Testing: Read testdata from subfolder

Hi,

I am trying to implement a test in rust which reads some testdata and compares the results of an algoritm with the testdata results. The testdata is in a subfolder next to the tested module.
I tried to use env::current_dir(), but the problem is it changes depending on the location how the test is started. When starting vom VSCode, the path is a different than when starting from console or when running the test instead of debugging.

Is there a reliable way to get a path to a file relative to the current source file or shall this be handled differently?

You can get the path for the current source file with file!.

You can get the path for your Cargo package (so you would go down from it instead of sideways) using env!("CARGO_MANIFEST_DIR").


Note that this is only suitable for tests or other things that run during development, not for general “resources”/“assets”, since the source code tree might be deleted or moved after the program is compiled.

If that might be your situation, or if you have only one or a few files, consider using include_bytes! or include_str! to ask the compiler to read and embed the file for you — this way you don't have to deal with file IO in your code, and the executable does not need the file when run at all, which is useful for non-test data files, as long as they are not so large that their size slows down the compilation and linking.

4 Likes

Thank you very much. This looks really promising.
It will be used only for testing, but nevertless thanks for the hint, maybe I need it in the future.