Created
November 8, 2022 12:15
-
-
Save borkdude/1fc2bd73c77d094fb0577c9caf9684b3 to your computer and use it in GitHub Desktop.
Clojure deftest with arguments
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
;; {:deps {org.babashka/cli {:mvn/version "0.5.40"} | |
;; babashka/fs {:mvn/version "0.1.11"}}} | |
(ns test-args | |
{:clj-kondo/config '{:lint-as {test-args/deftest clojure.core/defn}}} | |
(:require | |
[babashka.cli :as cli] | |
[clojure.test :as t :refer [is]])) | |
(def ^:dynamic *test-args* (cli/parse-opts *command-line-args*)) | |
(defmacro deftest [name argvec & body] | |
`(clojure.core/defn | |
~(with-meta name {:test `(fn [] | |
(let [~argvec [*test-args*]] | |
~@body))}) | |
~'[m] | |
(binding [*test-args* ~'m] | |
(t/test-var (var ~name))))) | |
(deftest foo [{:keys [n] | |
:or {n 2}}] | |
(prn :n n) | |
(let [counter (atom 0)] | |
(dotimes [i n] | |
(swap! counter + i)) | |
(is (= @counter (reduce + (range n)))))) | |
(defn -main [& _] | |
(let [[fail error] (t/run-tests 'test-args)] | |
(when (pos? (+ fail error)) | |
(System/exit 1)))) | |
(comment | |
;; run test manually as normal function with arguments | |
(foo {:n 100}) | |
;; use test runner with test arguments bound to something else | |
(binding [*test-args* {:n 100}] | |
(t/run-tests 'test-args)) | |
;; globally change test constants | |
(alter-var-root #'*test-args* (constantly {:n 100})) | |
(t/run-tests 'test-args) | |
;; on the command line: | |
;; $ clojure -M -m test-args --n 125 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment