I'm on a project interacting with files, and I would like to use text files to test my work. However tests aren't run from the tests/
directory, and thus I cannot reliably find them when running cargo run
.
Does Cargo handle this by always running test from the root directory (which seems to be the case but I didn't find anything attesting it)?
The #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test , not when you run cargo build . This saves compile time when you only want to build the library and saves space in the resulting compiled artifact because the tests are not included.
The default behavior of the binary produced by cargo test is to run all the tests in parallel and capture output generated during test runs, preventing the output from being displayed and making it easier to read the output related to the test results.
At its simplest, a test in Rust is a function that's annotated with the test attribute. Attributes are metadata about pieces of Rust code; one example is the derive attribute we used with structs in Chapter 5. To change a function into a test function, add #[test] on the line before fn .
The environment variable CARGO_MANIFEST_DIR
can give you a stable base point to reference other files. Here, we assume that there's a resources/test
directory at the top level of the crate:
use std::path::PathBuf; fn main() { let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR")); d.push("resources/test"); println!("{}", d.display()); }
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With