Skip to content

Commit

Permalink
Merge pull request #123 from caioaao/devel
Browse files Browse the repository at this point in the history
with-redefs + wrap-with macros
  • Loading branch information
dchelimsky authored May 21, 2020
2 parents 5919a16 + 40bb113 commit 73ce48f
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/state_flow/labs/state.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
(ns state-flow.labs.state
"WARNING: This API is experimental and subject to changes."
(:refer-clojure :exclude [with-redefs])
(:require [cats.core :as m]
state-flow.api
[state-flow.core :as state-flow]
[state-flow.state :as state]))

(defmacro wrap-with
"WARNING: `wrap-with` usage is not recommended. Use only if you know what you're
doing and you are sure you can't achieve the same result without it.
Wraps the provided state-flow execution. `wrapper-fn` will be passed a
function that will run the flow when called."
[wrapper-fn flow]
`(m/do-let
[world# (state/get)
runner# (state-flow/runner)
:let [[ret# state#] (~wrapper-fn (fn [] (runner# ~flow world#)))]]
(state-flow.api/swap-state (constantly state#))
(state/return ret#)))

(defmacro with-redefs
"WARNING: `with-redefs` usage is not recommended. Use only if you know what you're
doing and you are sure you can't achieve the same result without it.
Wraps the provided state-flow execution with `clojure.core/with-redefs`
macro, e.g.
(defn now [] (java.util.Date.))
(def flow-with-trapped-time
(labs.state/with-redefs
[now (constantly #inst \"2018-01-01\")]
(flow \"a flow in 2018\"
...)))"
[bindings flow]
`(wrap-with
(fn [f#] (clojure.core/with-redefs ~bindings (f#)))
~flow))
39 changes: 39 additions & 0 deletions test/state_flow/labs/state_test.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
(ns state-flow.labs.state-test
(:require [clojure.test :as t :refer [deftest is testing]]
[matcher-combinators.test :refer [match?]]
[state-flow.core :as state-flow]
[state-flow.labs.state :as labs.state]
[state-flow.state :as state]))

(defn put2 [w] (assoc w :value 2))
(defn put3 [w] (assoc w :value 3))

(defn wrap-with-redefs [f]
(with-redefs [put2 put3]
(f)))

(defn called-it-callback [f]
(print "called it")
(f))

(deftest wrap-with-test
(testing "wrapper is called"
(is (= "called it"
(with-out-str
(-> (labs.state/wrap-with
(fn [f] (print "called it") (f))
(state/modify put2))
(state-flow/run {}))))))
(testing "flow runs successfully"
(is (match? [{} {:value 2}]
(-> (labs.state/wrap-with
(fn [f] (f))
(state/modify put2))
(state-flow/run {}))))))

(deftest with-redefs-test
(is (match?
[{} {:value 3}]
(-> (labs.state/with-redefs [put2 put3]
(state/modify put2))
(state-flow/run {})))))

0 comments on commit 73ce48f

Please sign in to comment.