|
| 1 | +(ns clojure.core-test.bound-fn |
| 2 | + (:require [clojure.test :as t] |
| 3 | + [clojure.core-test.portability #?(:cljs :refer-macros :default :refer) [when-var-exists]])) |
| 4 | + |
| 5 | +(def ^:dynamic *x* :unset) |
| 6 | + |
| 7 | +(when-var-exists clojure.core/bound-fn |
| 8 | + (t/deftest test-bound-fn |
| 9 | + (t/testing "base case" |
| 10 | + (let [f (bound-fn [] *x*)] |
| 11 | + (t/is (= (f) :unset) "picks up dynamic vars") |
| 12 | + (binding [*x* :set] |
| 13 | + (t/is (= (f) :set) "And tracks their changes")))) |
| 14 | + |
| 15 | + (t/testing "Common cases" |
| 16 | + (binding [*x* :set] |
| 17 | + (let [f (bound-fn [] *x*)] |
| 18 | + (binding [*x* :set-again] |
| 19 | + (t/is (= (f) :set) "bound-fn stores values"))))) |
| 20 | + |
| 21 | + (t/testing "Infinite seqs" |
| 22 | + (binding [*x* (range)] |
| 23 | + (let [f (bound-fn [] *x*)] |
| 24 | + (binding [*x* (drop 50 (range))] |
| 25 | + (t/is (= (range 10) |
| 26 | + (take 10 (f)) |
| 27 | + (take 10 (f))) "infinite seqs work"))))) |
| 28 | + |
| 29 | + (t/testing "Nested cases" |
| 30 | + (binding [*x* :first!] |
| 31 | + (let [f (bound-fn [] *x*)] |
| 32 | + (binding [*x* :second!] |
| 33 | + (let [f (bound-fn [] [(f) *x*])] |
| 34 | + (t/is (= (f) [:first! :second!]) "Nested bound functions work as expected."))))) |
| 35 | + (let [f (fn [] (binding [*x* :inside-f] |
| 36 | + (bound-fn [] *x*)))] |
| 37 | + (binding [*x* :outside-f] |
| 38 | + (t/is (= ((f)) :inside-f) "bound-fn as result preserves initial bindings")))) |
| 39 | + |
| 40 | + (t/testing "Threaded/future cases" |
| 41 | + (let [f (bound-fn [] *x*)] |
| 42 | + (let [fut (future (f))] |
| 43 | + (binding [*x* :here] |
| 44 | + (t/is (= @fut :unset) "bound-fn stays bound even in other thread")))) |
| 45 | + (binding [*x* :caller] |
| 46 | + (let [f (future |
| 47 | + (binding [*x* :callee] |
| 48 | + (future (bound-fn [] *x*))))] |
| 49 | + (binding [*x* :derefer] |
| 50 | + (let [derefed-f @f] |
| 51 | + (t/is (= :callee (@derefed-f)) "Binding in futures preserved.")))))))) |
0 commit comments