Suppress printing in Unit test

Let’s say I have a function that is just used to print some information on the screen, like:

function printStuff(x)
  print("Round(x=$(x)) = $(round(x,digits=2)) ")

As this function is used in a larger code base, I would like to add a test that checks that the function prints without any errors (e.g. that the function still works after a new Julia version is released).

I could add

@test printStuff(4.1123) == nothing

to my unit tests.

However, I would like to prevent the function from actually printing to the screen. Is there any way to do this?

You could use one of the new logging macros i.e. @info and then use @test_logs to test your function.


Could also turn printStuff(x) into printStuff(io::IO, x) (to match Base.print) and then use an IOBuffer (or devnull) in your tests, similar to

julia> buf = IOBuffer()
IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

julia> print(buf, "abcd")

julia> String(take!(buf))
1 Like

Another option is to use Suppressor.jl.


Echoing @pfitzseb, Suppressor.jl is designed for just this purpose, and recently got updated to also redirect the new logging macros. You can also capture the output and compare it to an expected result if you want to test what actually got printed.