eri*_*cky 3 clojure clojure.spec
假设您有 a::givee
和 a ::giver
:
(s/def ::givee keyword?)
(s/def ::giver keyword?)
Run Code Online (Sandbox Code Playgroud)
形成一个unq/gift-pair
:
(s/def :unq/gift-pair (s/keys :req-un [::givee ::giver]))
Run Code Online (Sandbox Code Playgroud)
然后你有一个:unq/gift-history
which is a vector
of unq/gift-pair
:
(s/def :unq/gift-history (s/coll-of :unq/gift-pair :kind vector?))
Run Code Online (Sandbox Code Playgroud)
最后,假设您想替换以下内容:unq/gift-pair
之一vector
:
(defn set-gift-pair-in-gift-history [g-hist g-year g-pair]
(assoc g-hist g-year g-pair))
(s/fdef set-gift-pair-in-gift-history
:args (s/and (s/cat :g-hist :unq/gift-history
:g-year int?
:g-pair :unq/gift-pair)
#(< (:g-year %) (count (:g-hist %)))
#(> (:g-year %) -1))
:ret :unq/gift-history)
Run Code Online (Sandbox Code Playgroud)
一切正常:
(s/conform :unq/gift-history
(set-gift-pair-in-gift-history [{:givee :me, :giver :you} {:givee :him, :giver :her}] 1 {:givee :dog, :giver :cat}))
=> [{:givee :me, :giver :you} {:givee :dog, :giver :cat}]
Run Code Online (Sandbox Code Playgroud)
直到我尝试stest/check
这样做:
(stest/check `set-gift-pair-in-gift-history)
clojure.lang.ExceptionInfo: Couldn't satisfy such-that predicate after 100 tries.
java.util.concurrent.ExecutionException: clojure.lang.ExceptionInfo: Couldn't satisfy such-that predicate after 100 tries. {}
Run Code Online (Sandbox Code Playgroud)
我尝试使用s/int-in
限制向量计数(认为这可能是问题)但没有成功。
关于如何(stest/check `set-gift-pair-in-gift-history)
正确运行有什么想法吗?
谢谢。
问题在于向量的生成器和集合中的索引是独立/不相关的。随机向量和整数不满足这些条件:
#(< (:g-year %) (count (:g-hist %)))
#(> (:g-year %) -1)
Run Code Online (Sandbox Code Playgroud)
对于check
此函数,您可以提供一个自定义生成器来生成随机:unq/gift-history
向量,并根据该向量的大小为索引构建另一个生成器:
(s/fdef set-gift-pair-in-gift-history
:args (s/with-gen
(s/and
(s/cat :g-hist :unq/gift-history
:g-year int?
:g-pair :unq/gift-pair)
#(< (:g-year %) (count (:g-hist %)))
#(> (:g-year %) -1))
#(gen/let [hist (s/gen :unq/gift-history)
year (gen/large-integer* {:min 0 :max (max 0 (dec (count hist)))})
pair (s/gen :unq/gift-pair)]
[hist year pair]))
:ret :unq/gift-history)
Run Code Online (Sandbox Code Playgroud)
这是使用 test.check 的宏,它比/let
更方便,允许您使用看起来像常规 的代码来组合/组合生成器。自定义生成器返回函数参数向量。bind
fmap
let