HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

How can I locate resources for testing with Cargo?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withlocatehowtestingforcancargoresources

Problem

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

Solution

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?

Code Snippets

use std::path::PathBuf;

fn main() {
    let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    d.push("resources/test");

    println!("{}", d.display());
}

Context

Stack Overflow Q#30003921, score: 101

Revisions (0)

No revisions yet.