Skip to content

Instantly share code, notes, and snippets.

@ChrisDevo
Created March 17, 2016 17:16
Show Gist options
  • Save ChrisDevo/d77e08ca6f832a39727c to your computer and use it in GitHub Desktop.
Save ChrisDevo/d77e08ca6f832a39727c to your computer and use it in GitHub Desktop.
Using `is` in :pre assertion
;; 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