Skip to content

Commit 9b8425a

Browse files
committed
Improve assert-throws? macro
Since `assert-throws?` throws an exception inside the try regardless of if the body throws, if the body *doesn't* throw, you get a sort of strange error message: ``` RuntimeException: Assert failed Expected message: exception! but got Assert failed Expected a <type pixie.stdlib.RuntimeException> exception: exception! ``` I fixed this, improved the messages a bit, and also added some extra arities for just checking that an expression throws, and also just checking the class of the exception, instead of always the class and the message.
1 parent 4121db2 commit 9b8425a

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

pixie/test.pxi

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,25 @@
6161
yr# ~y]
6262
(assert (= xr# yr#) (str (show '~x xr#) " != " (show '~y yr#)))))
6363

64-
(defmacro assert-throws? [klass msg body]
65-
`(try
66-
~body
67-
(assert false (str "Expected a " ~klass " exception: " ~msg))
68-
(catch e#
69-
(assert (= (type e#) ~klass)
70-
(str "Expected exception of class " ~klass " but got " (type e#)))
71-
(assert (= (ex-msg e#) ~msg)
72-
(str "Expected message: " ~msg " but got " (ex-msg e#))))))
64+
(defmacro assert-throws?
65+
([body]
66+
`(let [exn# (try (do ~body nil) (catch e# e#))]
67+
(assert (not (nil? exn#))
68+
(str "Expected " (pr-str (quote ~body)) " to throw an exception"))
69+
exn#))
70+
([klass body]
71+
`(let [exn# (assert-throws? ~body)]
72+
(assert (= (type exn#) ~klass)
73+
(str "Expected " (pr-str (quote ~body))
74+
" to throw exception of class " (pr-str ~klass)
75+
" but got " (pr-str (type exn#))))
76+
exn#))
77+
([klass msg body]
78+
`(let [exn# (assert-throws? ~klass ~body)]
79+
(assert (= (ex-msg exn#) ~msg)
80+
(str "Expected " (pr-str (quote ~body))
81+
" to throw exception with message " (pr-str ~msg)
82+
" but got " (pr-str (ex-msg exn#)))))))
7383

7484
(defmacro assert [x]
7585
`(let [x# ~x]

0 commit comments

Comments
 (0)