How does one test optional features in Rust?
Asked Answered
O

2

10

I have a package I want to add an optional feature to. I've added an appropriate section to my Cargo.toml:

[features]
foo = []

I wrote an experimental test for the basic functionality of the cfg! macro:

#[test]
fn testing_with_foo() {
    assert!(cfg!(foo));
}

It looks as though I can activate features during testing via either of the options --features or --all-features:

(master *=) $ cargo help test
cargo-test 
Execute all unit and integration tests and build examples of a local package

USAGE:
    cargo test [OPTIONS] [TESTNAME] [-- <args>...]

OPTIONS:
    -q, --quiet                      Display one character per test instead of one line
        ...
        --features <FEATURES>...     Space-separated list of features to activate
        --all-features               Activate all available features

Neither cargo test --features foo testing_with_foo nor cargo test --all-features testing_with_foo works, though.

What is the proper way to do this?

Oldster answered 17/11, 2019 at 23:57 Comment(1)
Have you tried cargo test -- --features foo testing_with_foo (note the --).Higley
O
4

The solution is what @Jmb proposed: assert!(cfg!(feature = "foo"));. What it says in the Cargo Book

This can be tested in code via #[cfg(feature = "foo")].

allows one to confirm that conditional compilation works but doesn't provide a boolean value one can test against. If you want to branch based on the feature at runtime, you need cfg!.

Oldster answered 3/12, 2019 at 16:0 Comment(0)
F
3

Your test is incorrect. Quoting the Cargo book:

This can be tested in code via #[cfg(feature = "foo")].

Fraternity answered 18/11, 2019 at 3:35 Comment(3)
Or to be closer to what the OP wants: assert!(cfg!(feature = "foo"));Papyrus
Where exactly does it say this in the cargo book? I can't find it anywhere. 'This can be tested in code via #[cfg(feature = "foo")]'Execute
Link is a little outdated, you can check this - doc.rust-lang.org/cargo/reference/features.html.Fraternity

© 2022 - 2024 — McMap. All rights reserved.