clojuretest.check

Function generator in test.check


I want to make a generators for functions.

I've noticed that there are indeed generators for IFn values, but when the function domain is infinite (and since the values are strict), it's not generally practical for them to be used as generators for functions.

Does this functionality exist or would I have to implement it myself?


Solution

  • I think the answer depends on what sort of behavior you're expecting the function to have. In general you can use gen/let or gen/fmap to create arbitrary functions based on generated values. For example, you can generate a list of values and use it to construct a function that picks something from the list based on the hash of the input:

    (gen/let [rets (gen/not-empty (gen/vector gen/any))]
      (fn [x]
        (rets (mod (hash x) (count rets)))))