How to reliably locate test data files from tests?


#1

I have some tests that load data files from the source tree. I’ve been building a path to them starting with PathBuf::from(file!()) and that seems to work well (example). However, I recently added a subcrate to my project, and when I try to run its tests using cargo test -p subcrate, this method fails, because file!() yields subcrate/src/foo.rs, but the cwd when running the tests is in subcrate.

Is there any way to reliably do this such that it works in the cargo test -p case? I know I could use include_bytes, but I have methods that take a Path and I’d like to write tests for them as well.


#2

Can you just assume the working directory is the crate/subcrate root? Or are there cases when it isn’t?

I’d also like an answer to this. Some of my tests will need to read and write resource files (in this case used only by the tests, so I shall probably place them in the tests directory).


#3

This works for the simple case, but it doesn’t work when running cargo test -p <subcrate>.


#4

I thought you said the cwd when running the tests is in the subcrate? So you should just be able to use Path::new("testdata/test.dmp"); and forget the file!() bit, surely?


#5

I typically use std::env::current_exe and build a path from there. (IIRC, I got the idea from Cargo’s tests.)


#6

If it doesn’t need to explicitly be a file, you can use the include_str! and include_bin! macros. The paths you pass them are always relative to the file you’re in. For example, https://github.com/sfackler/rust-security-framework/blob/master/security-framework/src/lib.rs#L107. The certificate file ends up in the test binary itself so it doesn’t matter where the test is run from.