Skip to content

Commit

Permalink
feat(assert): adds new assert-like functionality to check malli schema
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonjckn committed Sep 11, 2023
1 parent 5da25bc commit 2814fad
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 2 deletions.
31 changes: 31 additions & 0 deletions src/malli/assert.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
(ns malli.assert
(:refer-clojure :exclude [assert])
(:require
[malli.core :as m]
[malli.dev.pretty :as pretty]
[malli.util :as mu]))

(def ^:dynamic *reporter* (pretty/thrower (pretty/-printer {:colors nil})))



(defmacro assert
"Assert that `x` validates against schema `?schema`, or throws ExceptionInfo.
The clojure.core/*assert* constant controls whether assertion are checked."
([?schema x]
(if *assert*
`(let [x# ~x]
(if (m/validate ~?schema x#)
x#
(*reporter* ::m/explain (mu/explain-data ~?schema x#))))
x)))


;; -----------------------------------------------------------------------------------------------------------
;; Developer Notes
;;
(comment
(set! *assert* true)
(assert int? "42")
(assert int? 42)
)
6 changes: 4 additions & 2 deletions src/malli/dev/virhe.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@

(defn -color [color body printer]
(let [colors (:colors printer -dark-colors)
color (get colors color (:error colors))]
color (get colors color (:error colors))]
#?(:cljs [:span body]
:clj [:span [:pass (str "\033[38;5;" color "m")] body [:pass "\u001B[0m"]])))
:clj (if color
[:span [:pass (str "\033[38;5;" color "m")] body [:pass "\u001B[0m"]]
[:span body]))))

;;
;; EDN
Expand Down
29 changes: 29 additions & 0 deletions test/malli/assert_test.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
(ns malli.assert-test
(:refer-clojure :exclude [assert])
(:require
[clojure.test :refer [deftest is]]
[malli.assert :refer [assert]]))


(set! *assert* true)

(deftest assert-throws-test
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert :int "42" )))
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert int? "42" )))
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert string? 42)))
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert int? nil)))
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert [:map [:a int?]] {:a "42"})))
(is (thrown? #?(:clj Exception, :cljs js/Error)
(assert ::invalid-schema 42))))

(deftest assert-checked-and-does-not-throw
(is (= 42 (assert :int 42 )))
(is (= 42 (assert int? 42 )))
(is (= "42" (assert string? "42")))
(is (= nil (assert any? nil)))
(is (= {:a 42} (assert [:map [:a int?]] {:a 42}))))

0 comments on commit 2814fad

Please sign in to comment.