Programming Clojure by Alex Miller

Programming Clojure by Alex Miller

Author:Alex Miller
Language: eng
Format: epub
Tags: Pragmatic Bookshelf
Publisher: Pragmatic Bookshelf


When you invoke check, it generates 1000 sets of arguments that are valid according to the function’s :args spec. For each argument set, check invokes the function, then checks that the return value is valid according to the :ret spec and that the :fn spec is valid for the arguments and return value.

Let’s see how it works with a spec for the Clojure core function symbol, which takes a name and an optional namespace:

​ (doc symbol)

​ | -------------------------

​ | clojure.core/symbol

​ | ([name] [ns name])

​ | Returns a Symbol with the given namespace and name.

First we need to define the function spec:

src/examples/spec.clj

​ (s/fdef clojure.core/symbol

​ :args (s/cat :ns (s/? string?) :name string?)

​ :ret symbol?

​ :fn (​fn​ [{:keys [args ret]}]

​ (and (= (name ret) (:name args))

​ (= (namespace ret) (:ns args)))))

And then we can run the test as follows:

​ (stest/check ​'clojure.core/symbol​)

​ -> ({:sym clojure.core/symbol

​ :spec #object[clojure.spec.alpha$fspec_impl$reify__14282 ...],

​ :clojure.spec.test.check/ret {

​ :result true,

​ :num-tests 1000,

​ :seed 1485241441400}})

You can see from the output that stest/check ran 1000 tests on clojure.core/symbol and found no problems. When an error occurs, the test.check library goes the extra step of “shrinking” the error to the least complicated possible input that still fails. In complex tests, this is a crucial step to produce tractable input for reproduction and fixing.

One step that we glossed over is how spec generated 1000 random input arguments. While we haven’t mentioned it before, every spec is both a validator and a data generator for values that match the spec. Once we created a spec for the function arguments, check was able to use it to generate random arguments.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.