我使用条件编译来更改函数的类型签名,现在不能为两种“功能”模式运行相同的 doctest,所以我需要一种方法来选择退出 doctest。
我已经尝试合并#[cfg_attr(feature = "rss_loose", ignore)]
用于正常测试和///rust,ignore
制作///rust,cfg_attr(feature = "rss_loose", ignore)
,但这似乎不起作用。
只需编写两套不同的文档和测试,它就会按原样工作:
/// ```
/// assert_eq!(42, dt::foo());
/// ```
#[cfg(not(feature = "alternate"))]
pub fn foo() -> u8 { 42 }
/// ```
/// assert_eq!(true, dt::foo());
/// ```
#[cfg(feature = "alternate")]
pub fn foo() -> bool { true }
$ cargo test
Compiling dt v0.1.0 (file:///private/tmp/dt)
Running target/debug/dt-c3e297f8592542b5
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
Doc-tests dt
running 1 test
test foo_0 ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
$ cargo test --features=alternate
Compiling dt v0.1.0 (file:///private/tmp/dt)
Running target/debug/dt-c3e297f8592542b5
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured
Doc-tests dt
running 1 test
test foo_0 ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
至少从 Rust 1.55 2018 版开始,可以使用如下注释忽略文档测试:
/// ```ignore
/// do_something();
/// ```
此外,每个文档注释行实际上都被翻译成一个单独的属性,如下所示:
#[doc = " ```ignore"]
#[doc = " do_something();"]
#[doc = " ```"]
这意味着说这行```ignore
可以有条件地替换,使用属性cfg_attr
,一个只是说```
,来激活测试:
#[cfg_attr(feature = "extra-doctests", doc = "```")]
#[cfg_attr(not(feature = "extra-doctests"), doc = "```ignore")]
/// do_something();
/// ```
在extra-doctests
启用该功能的情况下运行测试时,此 doc-test 将正常运行;当此功能被禁用时,它将在日志中显示为“已忽略”。