Skip to content

Instantly share code, notes, and snippets.

@ciniglio
Created October 3, 2014 15:19
Show Gist options
  • Save ciniglio/7c78d10a230d0dfd0f8d to your computer and use it in GitHub Desktop.
Save ciniglio/7c78d10a230d0dfd0f8d to your computer and use it in GitHub Desktop.
;; Taken from https://github.com/Prismatic/eng-practices/blob/master/clojure/20130821-testing-principles.md
(defmacro test-double
"Creates a test double of a function given a fully qualified function name.
Behaves like a function, and then stores arguments values in a map,
with key as the argument name"
([] `(gensym))
([fqfn] ; fully qualified function for argument naming
(let [args (first (:arglists (meta (resolve fqfn))))
args-count (count args)]
`(let [received-args# (repeatedly ~args-count #(atom nil))]
(reify
clojure.lang.IFn
(invoke [this# ~@args]
(doseq [[arg# received#] (map list ~args received-args#)]
(reset! received# arg#)))
clojure.lang.ILookup
(valAt [this# k# not-found#]
(-> (map (fn [arg# received#] [(keyword arg#) @received#]) '~args received-args#)
(#(into {} %))
(get k# not-found#)))
(valAt [this# k#] (.valAt this# k# nil)))))))
(test/deftest record-public-linkage-event-test
(let [mongo-datastore (test-double)
env :test
request {:cookies {"stage_p_public" {:value "foobar-cookie"}}}
user-id (rand-int 10)
event-body {:type "public-linkage" :key1 "val1" :public-id "foobar-cookie"}
event-log-double (test-double event-log/write-public-linkage-event)
expected-event {:type "public-linkage"
:key1 "val1"
:public-id "foobar-cookie"
:munged_public_id "foobar_cookie"
:user_id user-id}]
(with-redefs [event-log/write-public-linkage-event event-log-double]
(test/testing "event-log/write-public-linkage-event should be called with transformed event"
(record-public-linkage-event mongo-datastore env request user-id event-body)
(test/is (= mongo-datastore (:mongo-datastore event-log-double)))
(test/is (= expected-event (:event event-log-double)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment