|
| 1 | +(ns clojure.core-test.binding |
| 2 | + (:require [clojure.test :as t] |
| 3 | + [clojure.core-test.portability :as p])) |
| 4 | + |
| 5 | +(p/when-var-exists clojure.core/binding |
| 6 | + (def ^:dynamic *x* :unset) |
| 7 | + (def ^:dynamic *y* nil) |
| 8 | + (defn ^:dynamic *f* [x] (inc x)) |
| 9 | + |
| 10 | + (defn test-fn [] *x*) |
| 11 | + |
| 12 | + (t/deftest test-binding |
| 13 | + ;; base-case with no overrides |
| 14 | + (t/is (= *x* :unset) "Unset is :unset") |
| 15 | + (t/is (= (*f* 1) 2) "fn call") |
| 16 | + |
| 17 | + ;; common cases |
| 18 | + (t/is (binding [*x* :set] (= *x* :set)) "Can bind dynamic var.") |
| 19 | + (t/is (binding [*x* :set] (= (test-fn) :set)) "Binding for indirect reference.") |
| 20 | + (t/is (binding [*x* nil] (= (test-fn) nil)) "Dynamic vars are nullable.") |
| 21 | + (t/is (binding [*f* dec] (= (*f* 1) 0)) "Can bind functions.") |
| 22 | + |
| 23 | + ;; infinite seqs |
| 24 | + (binding [*x* (range)] |
| 25 | + (t/is (= '(0 1 2 3) (take 4 (test-fn))) "Infinite range") |
| 26 | + (t/is (= '(0 1 2 3) (take 4 (test-fn))) "Immutability")) |
| 27 | + |
| 28 | + ;; Nested cases |
| 29 | + (binding [*x* :first!] |
| 30 | + (let [layer-1 (fn [] (test-fn))] |
| 31 | + (binding [*x* :second!] |
| 32 | + (t/is (= :second! (layer-1) (test-fn)) "Value is determined at call-site")))) |
| 33 | + (binding [*y* *x*] |
| 34 | + (t/is (= *y* :unset) "Dynamic reference is by value at binding.") |
| 35 | + (binding [*x* :layer-2] |
| 36 | + (t/is (= *y* :unset) "Dynamic reference does not update.")) |
| 37 | + (binding [*y* *x* |
| 38 | + *x* :set-later] |
| 39 | + (t/is (= *y* :unset) "Bind vars are applied in sequence."))) |
| 40 | + (let [f (fn [] (binding [*x* :inside-f] (test-fn)))] |
| 41 | + (binding [*x* :outside-f] |
| 42 | + (t/is (= (test-fn) :outside-f)) |
| 43 | + (t/is (= (f) :inside-f) "Nested in func-call"))) |
| 44 | + (binding [*y* (binding [*x* :bad] (test-fn))] |
| 45 | + (t/is (= *y* :bad) "Binding in a binding vector")) |
| 46 | + |
| 47 | + ;; Threading/future/delay cases |
| 48 | + (let [f (delay (test-fn))] |
| 49 | + (binding [*x* :here] |
| 50 | + (t/is (= @f :here) "Delayed functions inherit there bindings when forced")) |
| 51 | + (t/is (= @f :here) "And value persists outside binding expression")) |
| 52 | + (Thread/sleep 1) |
| 53 | + (let [f (future (test-fn))] |
| 54 | + (binding [*x* :now-here] |
| 55 | + (t/is (= @f :unset) "Thread context is separate from joining thread"))) |
| 56 | + (binding [*x* :outer] |
| 57 | + (let [f (future (test-fn))] |
| 58 | + (binding [*x* :inner] |
| 59 | + (t/is (= @f :outer) "Thread context preserves binding context.")))) |
| 60 | + (binding [*x* :caller] |
| 61 | + (let [f (future |
| 62 | + (binding [*x* :callee] |
| 63 | + (future (test-fn))))] |
| 64 | + (binding [*x* :derefer] |
| 65 | + (let [derefed-f @f] |
| 66 | + (t/is (= :callee @derefed-f) "Binding in futures preserved."))))))) |
0 commit comments