Enabling/disabling default crate features for integration tests


I added default features to one of my crates as below.

default = ["other_library"]

other_library = { version = "1.0.0", optional = true }

Of course every integration test in the tests folder now requires an extern crate other_library. Though as I use the feature for conditional compilation, some of the tests should be compiled with the feature disabled to test the according execution path.

I checked the reference and the book but couldn’t find a hint in that direction. I can enable compiler features with #![feature(...)], but is it possible to enable/disable crate features per integration test (especially default features)?


For testing you may need to specify cargo test --no-default-features.

For dependencies there’s other_library = { default-features = false }, but I suspect it’s not applicable here, since it refers to dependency’s features.


Thanks! That got me a little closer to the goal. When using @kornel’s approach above integration test needs to be compilable both with the default features and without them. Some use cases may not be applicable if the features are disabled so the test must be disabled as well. I decided to brake down the defaults per external libary as below.

#[cfg(other_library_integration)] extern crate other_library;

fn some_test_NOT_depending_on_feature() {

fn some_test_depending_on_feature() {

This approach works well if the feature is disabled. Unfortunately if I enable the feature with cargo test --features other_library_integration, the compilation fails complaining that extern crate other_library is missing. So probably the cfg attribute does not work on extern crate statements. Am I understanding that correctly?


in Cargo.toml make the dependency optional and enabled by the feature.

Crates are built regardless of extern crate statements, because cargo does it without seeing the source code.


Ahh, sorry seems like I made a completely different mistake. It should be #[cfg(feature = "other_library_integration")] and not #[cfg(other_library_integration)]. Interesting that the compiler does not warn if it doesn’t know the content of the cfg attribute to be a compiler feature or a package feature.

Thanks for the hints.