gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:30 26 4
gpt4 key购买 nike

我正在为一个模块编写文档,该模块具有一些由 Cargo 功能标志控制的选项。我想始终显示此文档,以便 crate 的消费者知道它可用,但我只需要在启用该功能时运行该示例。

库.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] 属性放在整个 block 上:

//! ```
//! # #[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 的文档。

关于rust - 如何根据功能标志有条件地执行模块级 doctest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50312190/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com