Skip to content

Instantly share code, notes, and snippets.

@wwiill
Last active October 15, 2020 01:43
Show Gist options
  • Save wwiill/17c34d827c33782b1b2f3ca50e14b5e0 to your computer and use it in GitHub Desktop.
Save wwiill/17c34d827c33782b1b2f3ca50e14b5e0 to your computer and use it in GitHub Desktop.
Generative testing with test.check

Generative testing in Clojure with test.check

Youtube talk by Reid Draper: https://www.youtube.com/watch?v=JMhNINPo__g

sample

Returns samples from a given generator

(gen/sample gen/boolean)

vector

Generator for vectors of a given element type

(gen/sample
  (gen/vector gen/int))

any-printable

return

Return a constant value (like constantly)

(gen/sample
  (gen/return :foo))

choose

Choose a value from 5 to 10 inclusive

(gen/sample 
  (gen/choose 5 10))

elements

Choose a random element from a given list of values

(gen/sample
  (gen/elements [:clojure :haskell]))

one-of

Choose among supplied generators

(gen/sample
  (gen/one-of [gen/boolean gen/int]))

frequency

Apply a frequency to which generator to choose

(gen/sample 
  (gen/frequency
    [[5 (gen/return :weekday)]
     [2 (gen/return :weekend)]]))

such-that

Filter the generated values

(gen/sample
  (gen/such-that #(not= 0 %) gen/int))

fmap

Apply a function to every value generated. i.e. transform the generated value.

(gen/sample
  (gen/fmap odd? gen/int))

bind

Take a generated value and create a new generator from it

(gen/sample
  (gen/bind
    ;; generate a value - a non-empty vector of ints
    (gen/not-empty (gen/vector gen/int))
    ;; a new generator that returns a tuple based on the vector value generated
    #(gen/tuple (gen/return %)
                (gen/elements %))))

Shrinking

Walk the shrink tree as long as the test continues to fail, reducing to the smallest failing value.

Testing

(defspec
  my-test-property
  100 ;; how many iterations to do
  (prop/for-all
    [a gen/int]
    ...))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment