Search code examples
clojurequickcheckproperty-based-testing

clojure.test.check generate two ints, one less than the other


I want to write a property like the following:

(prop/for-all [x (gen/nat)
               y (gen/nat)]
  (= (g x y) (f x y)))

However, the property only holds when x > y. What is the correct way to express that precondition for this property? (Better yet, how can I write this property such that y is generated as a natural number less than x?)


Solution

  • You can use the bind function to create a generator that depends on a previous value. I'm sure there has to be a cleaner way to do this.

    (def always-greater-than
      (gen/bind gen/nat
               (fn [v] (gen/tuple (gen/return (inc v))
                                  (gen/fmap #(mod % (inc v)) gen/nat)))))
    

    Example output:

    (gen/sample always-greater-than)
    ([1 0] [2 0] [1 0] [3 0] [1 0] [6 4] [7 6] [2 0] [3 2] [6 4])