删除给定的midje测试中的冗余代码

时间:2013-03-21 01:54:46

标签: clojure

在下面的代码中,有很多冗余代码,我在左侧执行相同的操作以获取所有这三个事实。在右侧,我也有同样的阻止。我该如何处理这种冗余?

(facts "Data is grouped by the given keys."
       (fact "The grouping keys are a subset of the :month/:day keys in data"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (subset? (set grouped-by-keys) (set months)))))
       (fact "All the grouping keys are distinct"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (apply distinct? grouped-by-keys))))
       (fact "All the distinct keys from data are present in grouping keys"
             (group-data data :day) => (fn [d]
                                           (let [months (map :day data)
                                                 grouped-by-keys (keys d)]
                                             (empty? (difference (set months) (set grouped-by-keys)))))))

1 个答案:

答案 0 :(得分:1)

宏可以提供帮助:

(defmacro day-facts [facts]
  (let [f (fn [[name expr]]
            `(~'fact ~name
                     (~'group-data ~'data :day) ~'=> (fn [~'d]
                                                       (let [~'months (map :day ~'data)
                                                             ~'grouped-by-keys (keys ~'d)]
                                                         ~expr))))]
    `(~'facts "Data is grouped by the given keys."
              ~@(map f facts))))


(day-facts [["The grouping keys are a subset of the :month/:day keys in data" (subset? (set grouped-by-keys) (set months))]
            ["All the grouping keys are distinct" (apply distinct? grouped-by-keys)]
            ["All the distinct keys from data are present in grouping keys" (empty? (difference (set months) (set grouped-by-keys)))]])