簡體   English   中英

如何用 Rust 個具有 doctests 的項目實現條件編譯?

[英]How would one achieve conditional compilation with Rust projects that have doctests?

我已經使用條件編譯來更改 function 的類型簽名,現在不能為兩種“功能”模式運行相同的 doctest,所以我需要一種方法來選擇退出 doctests。

我已經嘗試合並在正常測試中使用的#[cfg_attr(feature = "rss_loose", ignore)]///rust,ignore來制作///rust,cfg_attr(feature = "rss_loose", ignore)但這並沒有似乎不起作用。

只需編寫兩組不同的文檔和測試,它們將按原樣工作:

/// ```
/// assert_eq!(42, dt::foo());
/// ```
#[cfg(not(feature = "alternate"))]
pub fn foo() -> u8 { 42 }

/// ```
/// assert_eq!(true, dt::foo());
/// ```
#[cfg(feature = "alternate")]
pub fn foo() -> bool { true }
$ cargo test
   Compiling dt v0.1.0 (file:///private/tmp/dt)
     Running target/debug/dt-c3e297f8592542b5

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests dt

running 1 test
test foo_0 ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured
$ cargo test --features=alternate
   Compiling dt v0.1.0 (file:///private/tmp/dt)
     Running target/debug/dt-c3e297f8592542b5

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests dt

running 1 test
test foo_0 ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

至少從 Rust 1.55 版 2018 開始,可以使用如下注釋忽略文檔測試:

/// ```ignore
/// do_something();
/// ```

此外,每個文檔注釋行實際上都被翻譯成一個單獨的屬性,如下所示:

#[doc = " ```ignore"]
#[doc = " do_something();"]
#[doc = " ```"]

這意味着可以使用cfg_attr屬性有條件地替換說```ignore的行,其中一個只是說``` ,以激活測試:

#[cfg_attr(feature = "extra-doctests", doc = "```")]
#[cfg_attr(not(feature = "extra-doctests"), doc = "```ignore")]
/// do_something();
/// ```

當在啟用extra-doctests功能的情況下運行測試時,此 doc-test 將正常運行; 當此功能被禁用時,它將在日志中顯示為“已忽略”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM