Clojure规范-s/或单分支生成器



是否可以覆盖默认规范生成器,以便始终只为s/or复合规范的单个分支生成数据?

(s/def ::x
(s/or :x-a nat-int?
:x-b string?))
(gen/sample (s/gen ::x))
;; generate strings only

您可以使用s/with-gen提供自定义生成器:

(s/def ::x
(s/with-gen
(s/or :x-a nat-int?
:x-b string?)
#(s/gen string?)))
(gen/sample (s/gen ::x))
=> ("" "j" "e" "Jmi" "" "d" "bc" "ul" "H65P0ni" "OEDK")

您也可以只在采样时使用它,而无需修改基本::x规范:

(gen/sample (s/gen (s/with-gen ::x #(s/gen string?))))

还有其他规范函数接受覆盖的映射以达到相同的目的,例如s/exercise:

(s/exercise ::x 10 {::x #(s/gen string?)})
=>
(["" [:x-b ""]]
["" [:x-b ""]]
["" [:x-b ""]]
["" [:x-b ""]]
["13R0" [:x-b "13R0"]]
["7cT30" [:x-b "7cT30"]]
["uia0b" [:x-b "uia0b"]]
["" [:x-b ""]]
["bP" [:x-b "bP"]]
["4k2t6bW" [:x-b "4k2t6bW"]])

最新更新