How to test output to stdout


#1

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?


How to send a Writer into a thread?
#2

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


#3

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.


#4

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

@livioribeiro I’m gonna try your idea!


#5

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


#6

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


#7

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!