Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 983
namespacexp Avatar asked Jan 16 '26 21:01

namespacexp


1 Answers

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.

like image 106
la Fleur Avatar answered Jan 19 '26 12:01

la Fleur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!