How can I locate resources for testing with Cargo?

前端 未结 1 1585
无人共我
无人共我 2020-12-10 10:42

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 ca

相关标签:
1条回答
  • 2020-12-10 11:26

    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?
    0 讨论(0)
提交回复
热议问题