How to test output to stdout

I'm writing a library that will print to stdout.

On the tests module, I would like to act like a user of this library, but assert that something is printed to stdout.

Is there a good way to do it?

2 Likes

Iā€™d recommend a test executable that runs itself with Command::output, like https://github.com/rust-lang/rust/blob/master/src/test/run-pass/command-exec.rs

If you're printing directly to stdout using println! you can use a tool like bats or cram, or maybe use std::process and capture the output, but I don't know if it is a good idea.

If you're passing to your functions a handle to stdout using trait bounds like, for example:

fn myfunc<W: Write>(writer: &mut W) {}

You can use std::io::Cursor to capture the output in your tests.

I'm using bats in another project and wanted to try it directly from rust this time.

@livioribeiro I'm gonna try your idea!

You can use gag to capture stdout. Unfortunately, I haven't gotten around to making it work on windows so you'll need to implement that if you want your tests to work on windows :smile:.

1 Like

If you're writing a library, you shouldn't be writing to stdout in the
first place.

Write to a generic stream instead.

...

On Mon, Mar 7, 2016 at 6:42 AM, Steven Allen users@rust-lang.org wrote:

stebalien https://users.rust-lang.org/users/stebalien
March 7

You can use gag https://crates.io/crates/gag to capture stdout.
Unfortunately, I haven't gotten around to making it work on windows so
you'll need to implement that if you want your tests to work on windows [image:
:smile:].

Visit Topic
https://users.rust-lang.org/t/how-to-test-output-to-stdout/4877/5 or
reply to this email to respond

To stop receiving notifications for this particular topic, click here
https://users.rust-lang.org/t/how-to-test-output-to-stdout/4877/unsubscribe.
To unsubscribe from these emails, change your user preferences
https://users.rust-lang.org/my/preferences

I was able to write a function that takes a writer. During tests I can pass a buffer, but on a normal run I can pass stdout. Handling this was just a little difficult but worth the effort.

Thank you!

1 Like