`#[cfg(test)]` 和 `#[cfg(feature = "test")]` 有什么区别?

sav*_*ava 4 rust

我想了解#[cfg(test)]和之间的区别#[cfg(feature = "test")],最好通过示例来演示。

hkB*_*Bst 6

#[cfg(test)]test标记仅在启用配置选项时才编译的内容,而标记仅在启用配置选项#[cfg(feature = "test")]时才编译的内容。feature = "test"

运行时cargo test,发生的事情之一是rustc传递了--test“启用 test cfg 选项”的标志(除其他外)。这通常用于仅当您想要运行测试时有条件地编译测试模块。

功能是货物用于一般条件编译(和可选依赖项)的东西。

尝试运行:

#[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");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出将是:

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
Run Code Online (Sandbox Code Playgroud)

这表明假测试模块没有启用。