ffff
ffff

Reputation: 3070

Trouble writing clojure spec for a schema

I have a schema of following structure

{:active? true|false
 :metric 90
 ....
}

The semantics here is that if :active? is false, then :metric should have a value of 0

Yes I can do the following

(s/keys :req-un [::active? ::metric] verify-structure) ;; verify-structure will test the above logic

But this doesn't help me with test data generation as its possible verify-structure can fail for all the generated data.

I guess I'll have to build a custom generator but I'm not sure how to generate dependent fields

Upvotes: 1

Views: 74

Answers (1)

Taylor Wood
Taylor Wood

Reputation: 16194

You could specify a custom generator like this:

(require '[clojure.test.check.generators :as gen])

(gen/let [active? gen/boolean
          metric (if active? (s/gen int?) (gen/return 0))]
  {:active? active? :metric metric})

(gen/sample *1)
({:active? true, :metric 0} {:active? true, :metric -1} ...)

gen/let is a macro that lets you use a familiar let-like syntax, but it expands to test.check fmap and bind calls which you could also use directly.

Once you have your custom generator, you can use s/with-gen to combine it with your spec, or pass it in an overrides map to spec functions that take generator overrides.

Upvotes: 2

Related Questions