How to get the output of the function `print()`?

For example, I have a function:

greet() = print("Hello World!")

Now I want to test whether the output of this function is indeed ”Hello World!“. How can I realize this using the package Test? In other word, what should the SomeFunction() be in the following code:

using Test
out = SomeFunction(greet())
@test out == "Hello World!"

Does this make sense?

You should change your design:

greet(io) = print(io, "Hello world")
greet() = greet(stdout)

That way, you can pass an IO object to write into:

using Test
io = IOBuffer()
greet(io)
@test String(take!(io)) == "Hello world"
3 Likes

Perhaps redirect_stdout would work. Something like:

using Test
stream = IOBuffer()
redirect_stdout(greet(), stream)
@test take!(stream) == "Hello World!"
2 Likes

It tells:
ERROR: MethodError: no method matching (::Base.RedirectStdStream)(::Nothing, ::IOBuffer)

Oops, should be redirect_stdout(greet, stream)

:disappointed_relieved: It still reports error:
ERROR: MethodError: no method matching (::Base.RedirectStdStream)(::IOBuffer)

Thanks! This method does work, but it changes the original function.

Sorry, haven’t done this for a while.

using Test

greet() = print("Hello World!")

out = stdout
stream = redirect_stdout()

greet()

redirect_stdout(out)
@test String(readavailable(stream)) == "Hello World!"
1 Like

Worked. :+1:

Correct. If you want your function to be testable, then this is the way to do it. If you don’t want to (or cannot) change the function, you have to resort to a hack, e.g., what @screw_dog suggests, or using a Pipe:

try
    p = Pipe()
    redirect_stdout(greet, p)
    @test String(readavailable(p)) == "Hello world"
finally
    close(p)
end

EDIT: added close, thanks @mkitti!

2 Likes

I was just about to suggest that.

julia> function stdout_to_string(f)
           p = Pipe()
           redirect_stdout(f, p)
           str = String(readavailable(p))
           close(p)
           return str
       end
stdout_to_string (generic function with 1 method)

julia> stdout_to_string(greet)
"Hello World!"
2 Likes

Thanks to everyone! :handshake: :handshake: