What is the difference between `#[cfg(test)]` and `#[cfg(feature = "test")]`?

Viewed 80

I would like to understand the difference between #[cfg(test)] and #[cfg(feature = "test")], preferably demonstrated through examples.

1 Answers

#[cfg(test)] marks something to be compiled only when the test config option is enabled, while #[cfg(feature = "test")] marks something to be compiled only when the feature = "test" config option is enabled.

When running cargo test, one of the things that happens is that rustc is passed the --test flag which (among other things) "enables the test cfg option". This is usually used to conditionally compile the test module only when you want to run the tests.

Features are something that cargo uses for general conditional compilation (and optional dependencies).

Try running:

#[cfg(feature="test")]
mod fake_test {
    #[test]
    fn fake_test() {
        panic!("This function is NOT tested");
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn test() {
        panic!("This function is tested");
    }
}

Output will be:

running 1 test
test test::test ... FAILED

failures:

---- test::test stdout ----
thread 'test::test' panicked at 'This function is tested', src/lib.rs:13:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    test::test

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Which shows that the fake test module was not enabled.

Related