Created
March 17, 2016 17:16
-
-
Save ChrisDevo/d77e08ca6f832a39727c to your computer and use it in GitHub Desktop.
Using `is` in :pre assertion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Using `assert` in :pre doesn't work because `(assert true)` returns `nil`. | |
;; :pre expects a truthy value, not `nil`. | |
;; Even though `clojure.test/is` is technically 'test' code (which usually doesn't appear in production code), | |
;; in this case it provides the behavior I want (custom error messages when validating funtion arguments) | |
;; with little overhead. | |
;; Using `assert` | |
(defn my-fn [bool] | |
{:pre [(assert bool (format "Custom message returning modified value of bool: %s" (not bool)))]} | |
(println bool)) | |
; => #'my-ns.core/my-fn | |
(my-fn true) | |
; AssertionError Assert failed: (assert bool (format "Custom message returning modified value of bool: %s" (not bool))) my-ns.core/my-fn (form-init8676493359122491140.clj:1) | |
(my-fn false) | |
; AssertionError Assert failed: Custom message returning modified value of bool: true | |
; bool my-ns.core/my-fn (form-init8676493359122491140.clj:2) | |
;; Using `is` | |
(defn my-fn [bool] | |
{:pre [(clojure.test/is bool (format "Custom message returning modified value of bool: %s" (not bool)))]} | |
(println bool)) | |
; => #'my-ns.core/my-fn | |
(my-fn true) | |
true | |
; => nil | |
(my-fn false) | |
; FAIL in clojure.lang.PersistentList$EmptyList@1 (form-init8676493359122491140.clj:2) | |
; Custom message returning modified value of bool: true | |
; expected: bool | |
; actual: false | |
; AssertionError Assert failed: (clojure.test/is bool (format "Custom message returning modified value of bool: %s" (not bool))) my-ns.core/my-fn (form-init8676493359122491140.clj:1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment