我正在尝试对这个简单的函数进行基于属性的测试:
(defn distinct-kw-keys
[maps]
(->> (map keys maps)
(flatten)
(filter keyword?)
(distinct)
(vec)))
。使用fdef
和check
:
(require '[clojure.spec.alpha :as s]
'[clojure.spec.test.alpha :as test])
(s/fdef distinct-kw-keys
:args (s/cat :maps (s/coll-of map?))
:ret (s/coll-of keyword?
:kind vector?
:distinct true))
(test/check `distinct-kw-keys)
调用test/check
在抛出OutOfMemoryError
一段时间后终止:
Exception in thread "Timer-1" Error printing return value (OutOfMemoryError) at clojure.test.check.generators/choose$fn (generators.cljc:260). Java heap space
等
我无法弄清楚这里有什么问题。功能和规格似乎工作正常,例如
(require '[clojure.spec.gen.alpha :as gen])
(s/valid?
(s/coll-of keyword?
:kind vector?
:distinct true)
(distinct-kw-keys
(gen/generate
(s/gen
(s/coll-of map?))))) ;; => true
它适用于我的机器(Macbook Pro 2015,16GB 内存),所以我无法重现您的问题。
要减少生成测试的数量,您可以编写:
(test/check `distinct-kw-keys {:clojure.spec.test.check/opts {:num-tests 1}})
使用换能器的函数变体,可能会稍微快一些:
(defn distinct-kw-keys
[maps]
(into []
(comp (mapcat keys)
(filter keyword?)
(distinct))
maps))
(test/check `distinct-kw-keys)
;;=> ({:spec #object[clojure.spec.alpha$fspec_impl$reify__2524 0x18025ced "clojure.spec.alpha$fspec_impl$reify__2524@18025ced"], :clojure.spec.test.check/ret {:result true, :pass? true, :num-tests 1000, :time-elapsed-ms 26488, :seed 1548072234986}, :sym user/distinct-kw-keys})