1

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

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

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

1 回答 1

1

您可以使用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"]])
于 2018-11-27T00:40:29.907 回答