如何根据功能标志有条件地执行模块级 doctest?

How can I conditionally execute a module-level doctest based on a feature flag?

我正在为一个模块编写文档,该模块具有一些由 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? 很接近,但答案集中在随条件编译而变化的 函数 上,而不是 模块 的文档.

我只看到一个解决方案:将 #[cfg] 放在测试中:

//! ```
//! #[cfg(feature = "solve_halting_problem")]
//! assert!(featureful::is_p_equal_to_np());
//! ```

这将被视为测试,但如果未启用该功能,它将为空。您可以将其与 hide portions of the example 的能力以及您也可以将 #[cfg] 属性放在整个块上的事实相结合:

//! ```
//! # #[cfg(feature = "solve_halting_problem")] {
//! assert!(featureful::is_p_equal_to_np());
//! // Better double check
//! assert!(featureful::is_p_equal_to_np());
//! # }
//! ```

请注意,也许您可​​以这样使用 #![feature(doc_cfg)]

/// This function is super useful
///
/// ```
/// assert!(featureful::is_p_equal_to_np());
/// ```
#[cfg(any(feature = "solve_halting_problem", feature = "dox"))]
#[doc(cfg(feature = "solve_halting_problem"))]
pub fn is_p_equal_to_np() -> bool {
    true
}

这不会 运行 禁用该功能时的测试,但会生成带有 cargo doc --features dox 的文档。

这也有效,而且我认为更干净:

//! This crate has common utility functions
//!
//! ```
//! assert_eq!(2, featureful::add_one(1));
//! ```
//!
#![cfg_attr(
    not(feature = "solve_halting_problem"),
    doc = "You may also want to use the feature flag `solve_halting_problem`:"
)]
#![cfg_attr(
    feature = "solve_halting_problem",
    doc = "This example works because the `solve_halting_problem` feature flag is enabled:"
)]
//!
#![cfg_attr(not(feature = "solve_halting_problem"), doc = "```ignore")]
#![cfg_attr(feature = "solve_halting_problem", doc = "```")]
//! assert!(featureful::is_p_equal_to_np());
//! ```