Unable to resolve symbol: thrown? - unit-testing

What is the proper way to do the following in clojure?
(ns todo.test.models.task
(:use [clojure.test]))
(deftest main-test
(is (thrown? Exception (throw Exception "stuff")))
(is (not (thrown? Exception (+ 2 3))))
)
First testcase runs fine but the whole snippet returns "Unable to resolve symbol: thrown?"

is is a macro that looks for the symbol thrown? in its body and build tests.
thrown? is not actually a function you can call. The default behaviour of is fails the test if an exception is thrown that was not beeing looked for, so you can just remove the (not (thrown? from the above example and get the result you are looking for.

thrown? is a special assertion that must show up after is, so you can't nest it in other expressions, so in the context of the is macro, the second assertion will not understand the symbol thrown?.
You could just say:
(deftest main-test
(is (thrown? Exception (throw (Exception. "stuff"))))
(is (= 5 (+ 2 3))))
If an exception is thrown in (+ 2 3), clojure.test will report 1 :error and 0 :fail and dump the stack trace.
Also note that your (throw Exception "stuff") is incorrect - you need to construct the Exception correctly inside the throw.

Use doseq if you want to do it for many statements:
(testing "bla"
(doseq [x [1 2 3 4]]
(my-dangerous-func! x)))

I know this is an old question but..
In addition to the above answers, if you really want a not-thrown? assertion, you can extend the is macro by adding your own e.g.
(defmethod assert-expr 'not-thrown? [msg form]
;; (is (not-thrown? c expr))
;; Asserts that evaluating expr does not throws an exception of class c.
;; Returns the exception thrown.
(let [klass (second form)
body (nthnext form 2)]
`(try ~#body
(do-report {:type :pass, :message ~msg,
:expected '~form, :actual nil})
(catch ~klass e#
(do-report {:type :fail, :message ~msg,
:expected '~form, :actual e#})
e#))))
This should then work as your original expectations
((deftest main-test
(is (thrown? Exception (throw (Exception. "stuff"))))
(is (not-thrown? Exception (+ 2 3)))))
However, please note that clojure.test will always report an error if an exception occurs in your function but if you have a special use-case for this, there you go.

Related

Does Clojure have a 'constantly' form that executes the body function at call-time?

I want to use constantly in a test to model a scenario that throws an Exception. Using the off-the-shelf constantly the body is evaluated when the code is read, not executed. I.e. I can't do this:
(def x (constantly (throw (Exception. "X"))))
(x 1 2 3)
Instead, the throw happens immediately.
This works:
(defn x [&] (throw (Exception. "X")))
But constantly is so handy and idiomatic, I wonder if there's a built-in equivalent that does this, maybe using a macro?
One alternative
#(throw (Exception. (str %&)))
constantly is a function not a macro like fn so you need to use (fn [& args]) to achieve this kind of operation.
constantly eagerly evaluates its parameters that's why it fails immediately.
It isn't built in, but it's easy to define. Let's call it defer:
(defmacro defer [exp]
(list 'fn ['& '_] exp))
Your example becomes
(def x (defer (throw (Exception. "X"))))
=> #'user/x
(x 1 2 3)
=> Exception X user/x (form-init7339591407440568822.clj:10)
This has no practical advantage over using the # reader form directly, as tap does, but it is what you asked for.
I changed the generated function to accept arguments, as the question called for. So it is no longer a thunk.
There are several ways to delay a computation in Clojure
The most obvious is delay:
(def x (delay (throw (ex-info "myException" {}))))
#x ;; exception is thrown
You could also use a lambda, similar to what would have to be done in other languages, or use laziness.
Given your code sample in the question, it looks like you are looking for something like this:
(defn x [& args]
(throw (ex-info "myException" {:args args})))
(try
(x 1 2 3)
(catch Exception e
(println "Exception! data is " (ex-data e))))
Note the use of ex-info and ex-data which could be useful to pass information.

How to wrap Exception in Clojure Macro?

I would like to wrap exception which has been thrown by system or user(does not matter) and force it to return some value.
I wrote macro for it but it does not work.
Macro:
(defmacro safe-fn
[form]
(try
`(do ~form)
(catch Throwable e
1)))
Usage: (safe-fn (throw (RuntimeException. "Try me!")))
Actual output: RuntimeException Try me! clojure-brave-and-true.core/eval2219 (form-init6122238559239237921.clj:1)
Desired output: 1
Macros are just functions that return code to be evaluated, so you could write safe-fn like this:
(defmacro safe-fn
[form]
`(try
~form
(catch Throwable ~'_
1)))
Example:
(safe-fn (throw (RuntimeException. "Try me!")))
;=> 1
See my answer to this question for more detail on macros, and specifically on using them to catch exceptions.
The macro with-exception-default from the Tupelo library does exactly what you want:
Default Value in Case of Exception
Sometimes you know an operation may result in an Exception, and you
would like to have the Exception converted into a default value. That
is when you need:
(with-exception-default default-val & body)
Evaluates body & returns its result. In the event of an exception the
specified default value is returned instead of the exception."
(with-exception-default 0
(Long/parseLong "12xy3"))
;=> 0
This feature is put to good use in tupelo.parse, where you will find
functions that work like this:
(parse-long "123") ; throws if parse error
;=> 123
(parse-long "1xy23" :default 666) ; returns default val if parse error
;=> 666

How to create a function that ignores any arguments and always throws an exception?

(constantly (throw (Exception. "Don't call me"))) is how I expected to do this, based on the Clojure docs for constantly:
(constantly x)
Returns a function that takes any number of arguments and returns x.
But when I try to use constantly to create a mock function that always throws, the exception gets thrown immediately, where I am trying to define the function. Is constantly supposed to evaluate it's body right away, and cache the result? Am I running into the equivalent of C's dreaded Undefined Behaviour (in this case, "all bets are off once you depend on side effects")?
user=> (constantly (throw (Exception. "but not right now")))
Exception but not right now user/eval8734 (form-init1747541642059004341.clj:1)
user=> (repeatedly (throw (Exception. "but not right now")))
Exception but not right now user/eval8736 (form-init1747541642059004341.clj:1)
What is the idiomatic way to create to mock a callback function in a test, so that it will throw an error if called?
constantly is a function; it evaluates its argument and then returns a function that will return that evaluated result. If you want to write a function that ignores all its arguments and evaluates some expression every time it is called, you can do something like this:
(fn [& _] (throw (Exception. "Don't call me")))
Example:
((fn [& _] (throw (Exception. "Don't call me"))) :foo :bar)
;=> java.lang.Exception: Don't call me
You could also write a macro to create functions that ignore their arguments:
(defmacro ignore-args [& exprs]
`(fn ~'[& _] ~#exprs))
Example:
((ignore-args (throw (Exception. "Don't call me"))) :foo :bar)
;=> java.lang.Exception: Don't call me
I'm not entirely sure how useful such a macro would be, though, because with any sort of descriptive name (ignore-args, in this case), it would take longer to type than (fn [& _] ,,,) and doesn't really convey more semantic meaning.
If you just want a function that always throws an exception, you can do this:
(defn blowup [& args] (throw (Exception. "I just blew up")))
If you're looking for a way to make those on demand, try this instead:
(defn explosives-factory [e] (fn [& args] (throw e)))
You can see it in practice here:
user=> (defn explosives-factory [e] (fn [&args] (throw e)))
#'user/explosives-factory
user=> (def blowup (explosives-factory (Exception. "Boom!")))
#'user/blowup
user=> (blowup 123)
Exception Boom! sun.reflect.NativeConstructorAccessorImpl.newInstance0 (NativeConstructorAccessorImpl.java:-2)

Can try and catch be in different (but nested) macros?

The try is in one macro, the catch in a second one that is called by the first. How to get the following to work?
(defmacro catch-me []
`(catch ~'Exception ~'ex
true))
(defmacro try-me []
`(try (+ 4 3)
(catch-me)))
Expanding try-me looks good:
(clojure.walk/macroexpand-all '(try-me))
yields
(try (clojure.core/+ 4 3) (catch Exception ex true))
but calling (try-me) yields:
"Unable to resolve symbol: catch in this context",
which, BTW, is also the message you would get in the REPL when using catch when not in a try.
UPDATE:
This is how I can get it to work (thanks, #Barmar), here you can see the actual context of my code:
(defmacro try-me [& body]
`(try
~#body
~#(for [[e msg] [[com.mongodb.MongoException$Network "Database unreachable."]
[com.mongodb.MongoException "Database problem."]
[Exception "Unknown error."]]]
`(catch ~e ~'ex
(common/site-layout
[:div {:id "errormessage"}
[:p ~msg]
[:p "Error is: " ~e]
[:p "Message is " ~'ex]])))))
but this is what I was hoping for (using a separate macro catch-me):
(defmacro try-me [& body]
`(try
~#body
(catch-me com.mongodb.MongoException$Network "Database unreachable.")
(catch-me com.mongodb.MongoException "Database problem.")
(catch-me Exception "Unknown error.")))
I think this would be easier to write / maintain.
Any ideas? I need syntax-quoting because I am passing parameters, that is why unfortunately Arthur's answer cannot be applied (or can it somehow?), but I didn't post my actual context until just now.
The reason you get that error is because the syntax for try is:
(try expr* catch-clause* finally-clause?)
This means that there can be any number of expr forms before the catch and finally clauses. try scans the exprs until it finds one that begins with catch or finally. It does this before expanding any macros, since it's just trying to figure out where the exprs and and the catch/finally clauses begin. It collects all the catch and finally clauses and establishes the appropriate error handling environment for them.
Once it does this, it executes all the expr forms normally. So it expands their macros, and then executes them. But catch is not a function or special form, it's just something that try looks for in the earlier step. So when it's executed normally, you get the same error as when you type it into the REPL.
What you should probably do is write a macro that you wrape around your entire code that expands into the try/catch expression that you want. Without an example of what you're trying to accomplish, it's hard to give a specific answer.
The short answer is YES, though nesting macros with special forms can lead to some double-quoting headaches like this one. It is necessarily to prevent the symbols from being evaluated at both levels of expansion:
user> (defmacro catch-me []
'(list 'catch 'Exception 'ex
'true))
user> (defmacro try-me []
`(try (+ 4 3)
~(catch-me)))
#'user/try-me
user> (try-me)
7
and to see that it catches the exception as well:
user> (defmacro try-me []
`(try (/ 4 0)
~(catch-me)))
#'user/try-me
user> (try-me)
true

How can I write a test to handle an expected exception?

How can I test for a function that throws an expected exception? Here is the function that throws the exception:
(defn seq-of-maps?
"Tests for a sequence of maps, and throws a custom exception if not."
[s-o-m]
(if-not (seq? s-o-m)
(throw (IllegalArgumentException. "s-o-m is not a sequence"))
(if-not (map? (first s-o-m))
(throw (IllegalArgumentException. "s-o-m is not a sequence of maps."))
true)))
I want to design a test like the following in which an exception is thrown and caught and then compared. The following does not work:
(deftest test-seq-of-maps
(let [map1 {:key1 "val1"}
empv []
s-o-m (list {:key1 "val1"}{:key2 "val2"})
excp1 (try
(seq-of-maps? map1)
(catch Exception e (.getMessage e)))]
(is (seq-of-maps? s-o-m))
(is (not (= excp1 "s-o-m is not a sequence")))))
I am getting these errors:
Testing util.test.core
FAIL in (test-seq-of-maps) (core.clj:27)
expected: (not (= excp1 "s-o-m is not a sequence"))
actual: (not (not true))
Ran 2 tests containing 6 assertions.
1 failures, 0 errors.
Obviously, I am missing something about writing tests. I am having trouble figuring that out. My project was set up with lein new, and I am running the tests with lein test.
Thanks.
The last assertion in your test is incorrect; it should be (is (= excp1 "s-o-m is not a sequence")) since map1 isn't a seq of maps.
Aside from that, it's probably clearer to use (is (thrown? ..)) or (is (thrown-with-msg? ...)) to check for thrown exceptions.
Example:
(t/is (thrown? java.lang.ClassCastException (s/valid? ::sut/int-value "x"))))
Note that you just write classname as a symbol. Use java.lang.Exception if you don't care about the exact Exception.