Default current working directory for workspace and package

it seems that cargo test -p <package> uses package directory as the default working directory, while cargo run -p <package> uses workspace directory as the default dir. Is this expected?

More details:

I'm a new user of Rust workspace and encountered something confusing. Say my project has the following structure:

├── Cargo.lock
├── Cargo.toml
├── my_server
│   ├── Cargo.toml
│   └── src
│       ├──
│       ├── key.pem

In my_server/src/, I have a test function does the following to read the local file key.pem:

pub const KEY_FILE:  &'static str = "src/key.pem";

This works in I do cargo run from the package, i.e. my_server directory, but it fails when I do cargo run --bin in the workspace.

So looks like cargo run will have different default current directory depends on whether it starts in the workspace level or the package level. Is this expected?

The problem is that now I have a unit test function in my_server/src/ that also tries to read the same file using KEY_FILE, and this happens:

both running from the workspace directory:

cargo test -p my_server will find KEY_FILE.
cargo run -p my_server will not find KEY_FILE.

Is this a known issue? and any common practice to work around it?


I'm not sure at the cargo level, but unless you explicitly need to test file I/O, another option is to just include the data directly in your test with include_bytes!, which takes a path relative to the current file.

Another possibility is to construct your path at runtime relative to file!().

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.