我正在编写一个模块的文档,该模块有一些由Cargo功能标志控制的选项 . 我想总是显示这个文档,以便crate的消费者知道它可用,但我只需要在启用该功能时运行该示例 .
lib.rs
//! This crate has common utility functions
//!
//! ```
//! assert_eq!(2, featureful::add_one(1));
//! ```
//!
//! You may also want to use the feature flag `solve_halting_problem`:
//!
//! ```
//! assert!(featureful::is_p_equal_to_np());
//! ```
pub fn add_one(a: i32) -> i32 {
a + 1
}
#[cfg(feature = "solve_halting_problem")]
pub fn is_p_equal_to_np() -> bool {
true
}
Cargo.toml
[package]
name = "featureful"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
[features]
solve_halting_problem = []
[dependencies]
使用启用的功能运行会按预期运行两个doctests:
$ cargo test --features=solve_halting_problem
Doc-tests featureful
running 2 tests
test src/lib.rs - (line 7) ... ok
test src/lib.rs - (line 3) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
没有该功能运行有一个错误:
$ cargo test
Doc-tests featureful
running 2 tests
test src/lib.rs - (line 7) ... FAILED
test src/lib.rs - (line 3) ... ok
failures:
---- src/lib.rs - (line 7) stdout ----
error[E0425]: cannot find function `is_p_equal_to_np` in module `featureful`
--> src/lib.rs:8:21
|
4 | assert!(featureful::is_p_equal_to_np());
| ^^^^^^^^^^^^^^^^ not found in `featureful`
当启用或不启用功能时, ignore` 和
no_run` 修饰符都会应用,因此它们似乎没有用处 .
How would one achieve conditional compilation with Rust projects that have doctests?已关闭,但答案主要关注通过条件编译而不是模块文档更改的函数 .
1 回答
我只看到一个解决方案:把
#[cfg]
放在测试中:这将被视为测试,但在未启用该功能时它将为空 . 你可以将它与hide portions of the example的能力配对,并且你也可以将
#[cfg]
属性放在整个块上:作为一个注释,也许你可以像这样使用#![feature(doc_cfg)]:
禁用该功能时,这将不会运行测试,但这将生成带有
cargo doc --features dox
的文档 .