【问题标题】:How can I conditionally execute a module-level doctest based on a feature flag?如何根据功能标志有条件地执行模块级 doctest?
【发布时间】:2018-10-23 01:02:57
【问题描述】:

我正在为一个模块编写文档,该模块具有由 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]

在启用该功能的情况下运行会按预期运行两个 doctest:

$ 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? 很接近,但答案集中在随条件编译而变化的函数,而不是模块的文档。

【问题讨论】:

    标签: rust automated-tests documentation conditional-compilation


    【解决方案1】:

    我只看到一个解决方案:将#[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 的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2011-11-09
      • 1970-01-01
      相关资源
      最近更新 更多