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

标签 rust

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

最佳答案

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

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".这通常用于仅在您想要运行测试时有条件地编译测试模块。

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

尝试运行:

#[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");
    }
}

输出将是:

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

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

关于rust - `#[cfg(test)]` 和 `#[cfg(feature = "test")]` 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72908829/

相关文章:

rust - Rust 中有 POD 类型的概念吗?

operator-overloading - 如何为不同的 RHS 类型和返回值重载运算符?

http - 如何在 Rust 中使用媒体文件正确格式化 HTTP 响应

rust - 如何引入带有宏的Rust枚举变量?

rust - 我可以创建一个指向堆栈对象的拥有指针吗

rust - 更新/重新初始化lazy_static中定义的var

java - Rust 中的消息摘要

rust - 删除 crate 功能

rust - 如何使用Cargo下载 crate 的文档?

rust - 我什么时候应该使用 usize vs i32, f32?