Skip to content

Instantly share code, notes, and snippets.

@jcf
Last active September 7, 2019 04:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcf/a1e3781b8c091a00c5d9 to your computer and use it in GitHub Desktop.
Save jcf/a1e3781b8c091a00c5d9 to your computer and use it in GitHub Desktop.
Measure slow clojure.test tests, and pretty print them
;; Make sure to require this file before you run your tests, and after any other
;; library that uses the same clojure.test hooks.
;;
;; NOTE: This doesn't work if you run your tests with `lein difftest`.
(ns example.test
(:require [clojure.pprint :refer [print-table]]
[clojure.test :refer [report with-test-out]]))
(def ^:private ^:const slow "in seconds"
0.1)
(def ^:private times
(atom {}))
(defn- add-test-end [{:keys [begin] :as m}]
(let [end (System/nanoTime)]
(assoc m :duration (- end begin) :end end)))
(defn- slow-test? [[_ {:keys [duration]}]]
(> (/ duration 1e9) slow))
(defn- report-time [[var {:keys [duration]}]]
(let [{:keys [ns name]} (meta var)]
{"Namespace" ns
"Function" name
"Duration / s" (format "%.3f" (/ duration 1e9))}))
(defmethod report :begin-test-var [{:keys [var]}]
(let [{:keys [ns name]} (meta var)]
(with-test-out (println " " (str ns "/" name))))
(swap! times assoc-in [var :begin] (System/nanoTime)))
(defmethod report :end-test-var [{:keys [var]}]
(swap! times update-in [var] add-test-end))
(defmethod report :summary [m]
(with-test-out
(let [slow-tests (filter slow-test? @times)]
(reset! times {})
(print-table (->> slow-tests
(sort-by (comp :duration last))
reverse
(map report-time))))
(println "\nRan" (:test m) "tests containing"
(+ (:pass m) (:fail m) (:error m)) "assertions.")
(println (:fail m) "failures," (:error m) "errors.")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment