6

I've learned:

  • cargo test -- --nocapture which tells Cargo to show output instead of hiding output; I'm interested in seeing output for successful tests, not just failed tests.
  • env_logger crate which enables using an environment variable to set the log level.

I'm seeking any similar ways, and ideally any official reference guide that shows good ways to accomplish this.

trent
  • 25,033
  • 7
  • 51
  • 90
joelparkerhenderson
  • 34,808
  • 19
  • 98
  • 119
  • Cargo will show output if test fail, so generally no need to do that. Anyway your solution is ok. – Stargateur Jun 08 '20 at 16:33
  • Thanks both! I'll move the info from question to answer as you suggest. As with the other question, ideally please don't close, because this info took me +2 hours to figure out, and is non-obvious (IMHO) in the docs and various blog posts. – joelparkerhenderson Jun 08 '20 at 17:07
  • cargo --no-capture is easy to find, https://stackoverflow.com/questions/25106554/why-doesnt-println-work-in-rust-unit-tests – Stargateur Jun 08 '20 at 17:13

2 Answers2

3

The Rust book shows how to do this.

The relevant part of that section:

If we want to see printed values for passing tests as well, we can tell Rust to also show the output of successful tests with --show-output.

cargo test -- --show-output
2

Here's one solution that is working for me.

Cargo.toml dependency:

env_logger = "*"

Demo source code:

use log::*;

pub fn foo() -> bool {
    info!("hello world");
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use env_logger;
    #[test]
    fn test_foo() {
        env_logger::init();
        assert!(foo());
    }
}

Command:

RUST_LOG=info cargo test -- --nocapture   
joelparkerhenderson
  • 34,808
  • 19
  • 98
  • 119