Last active
March 6, 2019 10:51
-
-
Save bhb/57025b0b8c3b4f02db788940e9e20f30 to your computer and use it in GitHub Desktop.
Test helpers when using clojure.spec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns foo.test-helper | |
(:require [clojure.spec :as s] | |
[clojure.spec.test :as st] | |
[clojure.string :as str] | |
[clojure.test :refer :all] | |
[clojure.test.check.generators :as gen] | |
[clojure.test.check.random :refer [IRandom]] | |
[clojure.test.check.rose-tree :as rose])) | |
(defn instrument-all | |
"Fixture to instrument all functions" | |
[f] | |
(st/instrument) | |
(f)) | |
(defn check-asserts | |
"Fixture to check clojure.spec asserts" | |
[f] | |
(let [old-value (s/check-asserts?)] | |
(s/check-asserts true) | |
(f) | |
(s/check-asserts old-value))) | |
;; https://gist.github.com/alexanderkiel/931387c7a86c1879b2267ad064067af7/ | |
(defmethod assert-expr 'conform-var? [msg form] | |
;; Test if the var v conforms to it's spec. | |
(let [args (rest form)] | |
`(let [result# (clojure.spec.test/check ~@args {:clojure.spec.test.check/opts {:num-tests 25}})] | |
(if (true? (-> result# first :clojure.spec.test.check/ret :result)) | |
(do-report {:type :pass :message ~msg | |
:expected '~form :actual result#}) | |
(do-report {:type :fail :message ~msg | |
:expected '~form :actual result#})) | |
result#))) | |
(defmethod assert-expr 'conforms-to? [msg form] | |
(let [args (rest form)] | |
`(let [result# (s/valid? ~@args)] | |
(if result# | |
(do-report {:type :pass :message ~msg | |
:expected '~form :actual '~form}) | |
(do-report {:type :fail :message ~msg | |
:expected '~form :actual (s/explain-str ~@args)}))))) | |
(defrecord NonRandom [] | |
IRandom | |
(rand-long [_] 0) | |
(rand-double [_] 0) | |
(split [rng] [rng rng]) | |
(split-n [rng n] (repeat n rng))) | |
(defn make | |
"Creates a simple, reproducible instance of a spec" | |
[spec] | |
(rose/root (gen/call-gen (s/gen spec) (->NonRandom) 1))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment