Jan Hudec
Jan Hudec

Reputation: 76376

Skipping unit tests or at least showing warnings from them

I need to test code that fetches and processes some data from standard C library. However, this data may not be installed at any particular system. So at the start of each test I detect whether the data is installed and skip the test.

It's easy to wrap the test in an if, but since the code that tests whether the test is possible may itself fail, I need to at least know that the tests were skipped. I know I can't simply use println! and I don't want to have to remember to pass --nocapture every time I test (and I want to see the warnings in the Travis log; Travis virtuals don't have all the data).

Upvotes: 0

Views: 552

Answers (1)

Shepmaster
Shepmaster

Reputation: 432109

A lesser-known fact is that println! uses the thread-local "standard out", which can be set to other output types. During tests, this is set to a capturing type. However, you can still get direct access to the true standard out and use that:

use std::io::{self,Write};

#[test]
fn a() {
    println!("Hi!"); // Will be captured / hidden by default
    write!(&mut io::stdout(), "Hello!").unwrap(); // Will be shown
}

Has output like:

running 1 test
Hello!test a ... ok

Upvotes: 7

Related Questions