Skip to content

Instantly share code, notes, and snippets.

@prepor
Last active December 15, 2015 21:29
Show Gist options
  • Save prepor/5326359 to your computer and use it in GitHub Desktop.
Save prepor/5326359 to your computer and use it in GitHub Desktop.
Clojure pattern matching and tests. See https://github.com/clojure/core.match/wiki/Overview
(deftest match-t
(let [v {:foo 1 :bar 100}]
(is (match? v {:foo 1 :bar (_ :guard integer?)}))))
(import
'[java.util Date])
(defn timestamp
[]
(-> (Date.)
(.getTime)
(/ 1000)
int))
(defn like-timestamp?
[v]
(let [t (timestamp)]
(< (- t 10) v (+ t 10))))
(def user-tasks #{1 5})
(deftest match-complex-t
(let [result {:user 1
:projects ["mnemoniq"]
:tasks [1 5]
:created-at (timestamp)}]
(is (match? result ({:user (_ :guard integer?)
:projects (projects :guard [vector? #(= 1 (count %))])
:tasks tasks
:created-at (_ :guard like-timestamp?)}
:only [:user :projects :tasks :created-at])
(is (every? #(contains? user-tasks %) tasks))))))
(use '[clojure.core.match :only (match)])
(defmethod assert-expr 'match? [msg form]
(let [[_ value pattern & body] form]
`(let [result# (match ~value
~pattern (do ~@body :success)
:else :fail)]
(if (= :success result#)
(do-report {:type :pass, :message ~msg,
:expected '~form, :actual ~value})
(do-report {:type :fail, :message ~msg,
:expected '~form, :actual ~value}))
result#)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment