Reputation: 1111
I am looking for a way to determine if a function printed (using println
or anything similar).
What I am trying to determine is if test-vars
printed something or not.
The issue with this function is that it doesn't return anything, but only print things when errors got issues, but I want to know if it succeeded or not and the only way I see to know it is to check if it printed something or not.
Even better would be a way to "intercept" what is going to out and to put it in a variable.
After the comments from @lee and @leetwinski I tried the following:
(deftest test-1
(testing
(is (= 1 2))))
Then I tried to run that test using:
(let [printed (with-out-str (test-vars [#'test-1]))]
(print (str "Printed size: " (count printed))))
But here is what I got:
FAIL in (test-1) (form-init505699766276988020.clj:103)
expected: (= 1 2)
actual: (not (= 1 2))
Printed size: 0
nil
So, what test-vars
outputs has been outputted anyway. Then printed
was empty.
Upvotes: 1
Views: 595
Reputation: 17859
in addition to @Lee's answer: in general you could just rebind *out*
to any other writer you want:
temporary binding:
user> (binding [*out* (java.io.StringWriter.)]
(println 101)
(str *out*))
"101\n"
is just an analogue to with-out-str
thread-local binding:
user> (set! *out* (java.io.StringWriter.))
#object[java.io.StringWriter 0x575e6773 ""]
user> (println 123)
nil
user> (str *out*)
"123\n"
here we rebind the *out*
, for the current thread (and for all the threads, spawned from it, AFAIK).
Upvotes: 1
Reputation: 144136
You can use with-out-str
which intercepts printed values and collects them into a string:
(let [printed (with-out-str (test-vars))]
...)
Upvotes: 1