namespacexp
namespacexp

Reputation: 161

Is it possible to enable a rust feature only in test?

Say I have crate A, B and I want to share a test helper function helper() in crate A to crate B, so I use a feature test-utils:

#[cfg(feature="test-utils")]
pub fn helper(){

}

So the problem is since the helper function contains modification of sensitive data in A, I don't want this function to be compiled in production, such as cargo build --all-features.

Is there a way I can enable this feature only in test, and disable it in production?

Upvotes: 16

Views: 9996

Answers (1)

la Fleur
la Fleur

Reputation: 586

This is a requested feature of Cargo and is only possible using the version 2 resolver. If crate A has the function you mentioned, then crate B's Cargo.toml may contain

[package]
name = "B"
resolver = "2"

[features]
test-utils = []

[dependencies]
A = "*"

[dev-dependencies]
A = { version = "*", features = ["test-utils"] }
B = { path = ".", features = ["test-utils"] }

This would ensure that both crates are built with the test-utils feature only when testing them. I use to run

cargo build --release -vv
cargo test --release -vv

and make sure I really get the features I asked in both cases.

Upvotes: 15

Related Questions