Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...