Skip to content

Instantly share code, notes, and snippets.

@thiagokokada
Last active January 13, 2025 13:24
Show Gist options
  • Save thiagokokada/fee513a7b8578c87c05469267c48e612 to your computer and use it in GitHub Desktop.
Save thiagokokada/fee513a7b8578c87c05469267c48e612 to your computer and use it in GitHub Desktop.
Babashka's test runner that dynamically discover the tests
#!/usr/bin/env bb
;; Inspired from https://book.babashka.org/#_running_tests
(require '[clojure.test :as t]
'[clojure.string :as string]
'[babashka.classpath :as cp]
'[babashka.fs :as fs])
(cp/add-classpath "src:test")
(defn test-file->test-ns
[file]
(as-> file $
(fs/components $)
(drop 1 $)
(mapv str $)
(string/join "." $)
(string/replace $ #"_" "-")
(string/replace $ #".clj$" "")
(symbol $)))
(def test-namespaces
(->> (fs/glob "test" "**/*_test.clj")
(mapv test-file->test-ns)))
(apply require test-namespaces)
(def test-results
(apply t/run-tests test-namespaces))
(def failures-and-errors
(let [{:keys [:fail :error]} test-results]
(+ fail error)))
(System/exit failures-and-errors)
@PEZ
Copy link

PEZ commented Dec 17, 2024

Thanks for sharing! I used this to build a CLI command for running tests with JVM Clojure:

(defn test-file->test-ns
  [file]
  (as-> file $
    (fs/components $)
    (drop 1 $)
    (mapv str $)
    (string/join "." $)
    (string/replace $ #"_" "-")
    (string/replace $ #"\.cljc?$" "")
    (str "'" $)))

(defn quoted-test-namespaces []
  (->> (fs/glob "test" "**/*_test.clj{,c}")
       (mapv test-file->test-ns)))

(defn ns->require-str [qns]
  (str "(require " qns ")"))

(defn ^:export run-tests-jvm! []
  (println "Running view tests with JVM Clojure...")
  (let [qnss (quoted-test-namespaces)
        command ["clojure" "-M:test" "-e"
                 (str "(require 'clojure.test)"
                      (string/join "\n" (map ns->require-str qnss))
                      "(clojure.test/run-tests " (string/join " " qnss) ")")]
        {:keys [err exit]} (apply p/shell command)]
    (when-not (zero? exit)
      (println err))))

@curist
Copy link

curist commented Jan 13, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment