I would like to execute Rust's documentation tests written in the examples/ folder.
// examples/example.rs
//! ```rust
//! panic!();
//! ```
fn main() {}
I would expect cargo test --doc to panic, but the above documentation test is never run. When I define the same documentation test in src/lib.rs cargo test --doc panics as expected.
How do I run a documentation test which is defined in the examples/ folder?
Environment:
$ cargo --version
cargo 1.51.0 (43b129a20 2021-03-16)
$ rustc --version
rustc 1.51.0 (2fd73fabe 2021-03-23)
Documentation tests in Rust are only run for modules that are used in your library when built for cfg(doc). Also doctest = true in Cargo.toml is currently (Rust 1.51) unsupported for example sections.
One reason for this is that documentation tests are run as if they were executables that link to your library. For documentation tests on examples it is not clear how they should run. An executable linking to an example executable doesn't make much sense.
But there is a hacky workaround:
You can use the attribute path="…" to include the examples as modules in your library (e.g. in src/lib.rs) and combine this with the conditional compilation attribute cfg and doc(hidden) to only do this when generating documentation while not producing output for these modules in the result:
#[cfg(doc)]
#[doc(hidden)]
#[path = "../examples"]
mod examples {
mod example;
}
This causes documentation tests in examples/example.rs to be included when running cargo test --doc. If you want to import something from example.rs in your doctest you need to access the namespace using your_library::examples::example::… and add pub to the module declarations.
$ cargo test --doc
…
test src/../examples/example.rs - examples::example (line 2) ... FAILED
failures:
---- src/../examples/example.rs - examples::example (line 2) stdout ----
Test executable failed (exit code 101).
stderr:
thread 'main' panicked at 'explicit panic', src/../examples/example.rs:3:1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With