Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't println! work in Rust unit tests?

Tags:

rust

println

I've implemented the following method and unit test:

use std::fs::File; use std::path::Path; use std::io::prelude::*;  fn read_file(path: &Path) {     let mut file = File::open(path).unwrap();     let mut contents = String::new();     file.read_to_string(&mut contents).unwrap();     println!("{}", contents); }  #[test] fn test_read_file() {     let path = &Path::new("/etc/hosts");     println!("{:?}", path);     read_file(path); } 

I run the unit test this way:

rustc --test app.rs; ./app 

I could also run this with

cargo test 

I get a message back saying the test passed but the println! is never displayed on screen. Why not?

like image 860
ruipacheco Avatar asked Aug 03 '14 16:08

ruipacheco


People also ask

How do you print a Rust test?

By default, output from print statements (e.g. println!, print!) will be eaten (not printed to stdout) by the Rust test harness. To see the output from print statements, run the tests with the nocapture flag. You must use the double, double hyphens with cargo test. It's not a typo.

What is Println in Rust?

In Rust, the println! is a macro defined in the std::fmt. It is used to handle printing dynamic information to the user. The println! is closely similar to the print! but appends a new line.

Why does Rust use Println?

println! is a macro in rust, that means that rust will rewrite the code for you at compile time.

Do Rust tests run in parallel?

Running Tests in Parallel or Consecutively When you run multiple tests, by default they run in parallel using threads, meaning they finish running faster and you get feedback quicker.


1 Answers

This happens because Rust test programs hide the stdout of successful tests in order for the test output to be tidy. You can disable this behavior by passing the --nocapture option to the test binary or to cargo test (but, in this case after -- – see below):

#[test] fn test() {     println!("Hidden output") } 

Invoking tests:

% rustc --test main.rs; ./main  running 1 test test test ... ok  test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured  % ./main --nocapture  running 1 test Hidden output test test ... ok  test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured  % cargo test -- --nocapture  running 1 test Hidden output test test ... ok  test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured 

If tests fail, however, their stdout will be printed regardless if this option is present or not.

like image 58
Vladimir Matveev Avatar answered Oct 18 '22 03:10

Vladimir Matveev