Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Functional clojure.test
(require '[clojure.test :as test])
; Rewrite clojure.test to generate data structures instead of writing to
; stdout
(def ^:dynamic *results*
"Bound dynamically to an atom wrapping a vector of test report maps")
(defn add-name
"Given a testing report map, assoc's on a :name derived from the current
`clojure.test/testing` context."
(assoc m :name (test/testing-contexts-str)))
(defmulti ^:dynamic report :type)
(defmethod report :pass [m]
(swap! *results* conj (add-name m)))
(defmethod report :fail [m]
(swap! *results* conj (add-name m)))
(defmethod report :error [m]
(swap! *results* conj (add-name m)))
(defmethod report :default [_])
(defmacro tests
"Establishes a new testing context, and returns results of running the tests
as a data structure."
[& body]
`(binding [test/report report
*results* (atom [])]
(deref *results*)))
user=> (pprint (tests (testing "hi" (is (= 1 1)) (testing "nested" (is (= 1 2)) (is (/ 1 0))))))
[{:name "hi",
:type :pass,
:expected (= 1 1),
:actual (#<core$_EQ_ clojure.core$_EQ_@161e497c> 1 1),
:message nil}
{:name "hi nested",
:message nil,
:actual (not (= 1 2)),
:expected (= 1 2),
:type :fail,
:file "form-init3393983401854035175.clj",
:line 1}
{:name "hi nested",
:message nil,
#<ArithmeticException java.lang.ArithmeticException: Divide by zero>,
:expected (/ 1 0),
:type :error,
:file "",
:line 158}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.