`cargo run` and `cargo test` have different working directory in a cargo workspace

I have a cargo workspace with 3 different crates. In one of the crates, I have some tests which use std::env::current_dir() to get the current working directory.

The problem is that when I run cargo run, I get the workspace root folder as the working directory while with cargo test, I get the crate folder where I am running the tests as the working directory.
I want to get the workspace root folder using both commands when I call std::env::current_dir().

Does anyone know why this happens and what the simplest way to fix this is?

As to why it happens, well, it just uses the same current directory as what you called cargo with.

Ah yeah, the target folder is in the workspace root folder so the current working directory is that one, while the tests are run in the child crate, so the current working directory is the crate folder.

But do you know a good solution for this? How can I always get the workspace root folder?

I suppose you could try env!("CARGO_MANIFEST_DIR"), potentially concatenating the relative path for each crate. E.g. if you know your crates' Cargo.toml files are exactly one-level deep from the repo root, they can use:

concat!(env!("CARGO_MANIFEST_DIR"), "/..")

And canonicalize it if you like: Rust Playground

This of course is not portable. YMMV

1 Like

This worked for me, thank you for your help!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.