1

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.

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Great thanks @leetwinski & @lee, not sure why I didn't thought about with-out-str. It works, but not with test-vars. I am looking at the clojure.test code and I am not sure why. I think it has something to do with *test-out* but I am not sure what. Any ideas?
You had it almost right, instead of *out* it should have been *test-out* which is a different one used by tests. Otherwise, the method was exactly the one to use. Thanks!
1

You can use with-out-str which intercepts printed values and collects them into a string:

(let [printed (with-out-str (test-vars))]
    ...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.