Clojure 规范 - 测试检查 OutOfMemoryError

Clojure spec - test check OutOfMemoryError

我正在尝试对这个简单的函数进行基于 属性 的测试:

(defn distinct-kw-keys
  [maps]
  (->> (map keys maps)
       (flatten)
       (filter keyword?)
       (distinct)
       (vec)))

... 使用 fdefcheck:

(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})