Force tests to use a library's feature flag

And on the heels of my last post regarding feature flags, I have a follow-up.

Say I have:

[dependencies]
serde = { version = "1.0", optional = true }

[dev-dependencies]
serde_json = "1.0"

and have successfully defined serde trait implementations for my types, but guarded by #[cfg(feature = "serde")]. In a tests/serde.rs I've got:

#[test]
fn serde_instances() {
    assert!(serde_json::from_str::<Kanji>("合").is_ok());
}

but the compiler complains that the Deserialize instance is missing. I realize that I can call cargo test --features=serde and get it to work, but is it possible to force the test suite to always assume that feature flag?

Please and thanks.

It's not quite the same, but the closest thing is the required-features field in Cargo.toml:

[[test]]
name = "serde"
required-features = ["serde"]

Now Cargo will build and run that test only when serde is enabled. So if you run cargo test --features serde (or cargo test --all-features), it will run, but otherwise it will be ignored.

Unfortunately, I don't think there's a way for a plain cargo test to automatically enable non-default features.

1 Like

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.