Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I locate resources for testing with Cargo?

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)?

like image 654
Léo Ercolanelli Avatar asked May 02 '15 15:05

Léo Ercolanelli


People also ask

What is cfg test in Rust?

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.

Does cargo run tests in parallel?

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.

How do you test a function in Rust?

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 .


1 Answers

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:

  • How can a Rust program access metadata from its Cargo package?
like image 187
Shepmaster Avatar answered Oct 24 '22 23:10

Shepmaster