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

时间:2018-11-27 00:31:02

标签: clojure clojure.spec test.check

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

(s/def ::x
  (s/or :x-a nat-int?
        :x-b string?))

(gen/sample (s/gen ::x))
;; generate strings only

1 个答案:

答案 0 :(得分:1)

您可以使用del提供自定义生成器:

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

出于相同的目的,还有其他规范函数接受 overrides 的映射,例如(gen/sample (s/gen (s/with-gen ::x #(s/gen string?))))

s/exercise