Skip to content

Instantly share code, notes, and snippets.

@AdamClements
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdamClements/33ef8d6ac9a65e9361ae to your computer and use it in GitHub Desktop.
Save AdamClements/33ef8d6ac9a65e9361ae to your computer and use it in GitHub Desktop.
Core async fake timeout
(defrecord FakeTimeout [current-time time-chans])
(defn timeout-fn
[{:keys [current-time time-chans]}]
(fn [time]
(let [ch (async/chan)]
(swap! time-chans merge-with into {(+ @current-time time) #{ch}})
(println time-chans)
ch)))
(defn fast-forward [{:keys [current-time time-chans]} elapsed]
(let [end-time (swap! current-time + elapsed)
affected (sort < (filter <= (keys @time-chans)))]
(doseq [timeindex affected]
(doseq [ch (get time-chans timeindex)] (async/close! ch))
(swap! time-chans dissoc timeindex))))
(defn fake-timeout-factory [] (->FakeTimeout (atom 0) (atom {})))
(def fakeout (fake-timeout-factory))
(with-redefs [async/timeout (timeout-fn fakeout)]
(async/go (async/<! (async/timeout 2000)) (println "Hi")))
;... Wait more than two seconds, expect no "Hi"
(fast-forward fakeout 3000)
; Expect "Hi" immediately
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment