Created
August 16, 2012 02:33
-
-
Save darkone23/3365864 to your computer and use it in GitHub Desktop.
A simple functional test-runner in clojure (unit tests only)
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 tryme.core) | |
(defn run-test | |
"Given a test sequence, runs the test and returns a result object" | |
[[name function input expected]] | |
(try | |
(let [actual (apply function input)] | |
(if (= expected actual) | |
{:type :success :name name} | |
{:type :failure :name name :expected expected :actual actual})) | |
(catch Exception exception | |
{:type :exception :name name :exception exception}))) | |
(defn format-test-result | |
"Takes in a test result, returns formatted lines of test output" | |
[{:keys [type name expected actual exception]}] | |
(case type | |
:success [(format "success(%s)" name)] | |
:failure (map format ["failure(%s)" | |
" expected: %s" | |
" actual : %s"] | |
[name expected actual]) | |
:exception (map format ["exception(%s)" | |
" message: %s"] | |
[name (.getMessage exception)]) | |
(throw (new RuntimeException (format "unknown result type %s" type))))) | |
(def formatted-testrun (comp format-test-result run-test)) | |
;; begin usage example -- let's test divide! | |
(def divide /) | |
;; define a few test cases... | |
(def test-cases | |
;; testname fn [args] expected | |
[["valid test" divide [6 3] 2] | |
["wrong expectation" divide [6 3] 1] | |
["cause exception" divide [6 0] 2]]) | |
;; we can get the results of our tests as result maps.. | |
(def our-test-results (map run-test test-cases)) | |
;; or we can get the results as formatted lines | |
(def our-result-lines (map formatted-testrun test-cases)) | |
;; or we can just flush our tests to stdout! | |
(doseq [line (mapcat formatted-testrun test-cases)] | |
(println line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment