4

I've used conditional compilation to change the type signature of a function, and now the same doctest can't be run for both "feature" modes, so I need a way to opt-out of the doctests.

I've tried merging #[cfg_attr(feature = "rss_loose", ignore)] used in normal tests and ///rust,ignore to make ///rust,cfg_attr(feature = "rss_loose", ignore) but this doesn't seem to work.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael Yoo
  • 489
  • 1
  • 6
  • 14
  • 1
    Does `#[cfg_attr]` works inside the doctest? You could then hide it with [`#`](https://doc.rust-lang.org/book/documentation.html#documentation-as-tests). – mcarton Jul 10 '16 at 14:11

2 Answers2

8

Just write two different sets of documentation and tests and it will all work as-is:

/// ```
/// 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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    Only problem with this was that I was trying to do this for a module documentation, so there were no two different functions to write docs for. But your method is a much better one. – Michael Yoo Jul 11 '16 at 11:36
5

At least as of Rust 1.55 edition 2018, a documentation test can be ignored with an annotation like the following:

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

Moreover, each documentation comment line is actually translated into an individual attribute, like so:

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

This means that the line saying ```ignore can be conditionally replaced, using the cfg_attr attribute, with one just saying ```, to activate the test:

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

When tests are run with the extra-doctests feature enabled, this doc-test will run normally; when this feature is disabled, it will appear as "ignored" in the log.

Hafydd
  • 146
  • 1
  • 2