She*_*ter 5 documentation automated-tests conditional-compilation rust
我正在编写模块的文档,该模块具有一些由Cargo功能标记控制的选项。我希望始终显示此文档,以便板条箱的使用者知道它可用,但是我仅在启用此功能时运行示例。
//! 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
}
Run Code Online (Sandbox Code Playgroud)
[package]
name = "featureful"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
[features]
solve_halting_problem = []
[dependencies]
Run Code Online (Sandbox Code Playgroud)
在启用该功能的情况下运行,将按预期运行两个doctest:
//! 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
}
Run Code Online (Sandbox Code Playgroud)
没有功能运行会出现错误:
[package]
name = "featureful"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
[features]
solve_halting_problem = []
[dependencies]
Run Code Online (Sandbox Code Playgroud)
无论 启用和禁用此功能,```ignore
和```no_run
修饰符均适用,因此它们似乎没有用。
一个具有doctest的Rust项目将如何实现条件编译?接近,但答案集中于随条件编译而变化的函数,而不是模块的文档。
我只看到一种解决方案:将其#[cfg]
放入测试中:
//! ```
//! #[cfg(feature = "solve_halting_problem")]
//! assert!(featureful::is_p_equal_to_np());
//! ```
Run Code Online (Sandbox Code Playgroud)
这将被视为测试,但是在未启用该功能时将为空。您可以将其与隐藏示例部分的功能以及可以将#[cfg]
属性放在整个块上的事实配对:
//! ```
//! # #[cfg(feature = "solve_halting_problem")] {
//! assert!(featureful::is_p_equal_to_np());
//! // Better double check
//! assert!(featureful::is_p_equal_to_np());
//! # }
//! ```
Run Code Online (Sandbox Code Playgroud)
注意,也许可以这样使用#![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
}
Run Code Online (Sandbox Code Playgroud)
禁用该功能后,它将无法运行测试,但会生成带有的文档cargo doc --features dox
。
归档时间: |
|
查看次数: |
286 次 |
最近记录: |