user1244932
user1244932

Reputation: 8092

How do I build code in a documentation test but not run it?

I have code in my documentation that can only be run if the user has some software on their machine. To emulate this, I add panic! to the sample code:

//!```rust
//!fn main() {
//!    panic!("Not run me");
//!}
//!```

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}

I want to check that the code in the comments can be compiled, but I do not want it to be run during cargo test. Right now, I get:

running 1 test
test src/lib.rs -  (line 1) ... FAILED

failures:

---- src/lib.rs -  (line 1) stdout ----
        thread 'rustc' panicked at 'test executable failed:

thread 'main' panicked at 'Not run me', <anon>:2
note: Run with `RUST_BACKTRACE=1` for a backtrace.

I read about doctest = false, but that disables not only the running of code in comments, but also syntax checking the code in comments.

How can I only disable running of code in comments, but still enable compilation of code in comments during cargo test?

Upvotes: 6

Views: 1055

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

There are several annotations you can use to change how the Rust code is processed. See the test documentation.

In your case it sounds like no_run is the one you'd want

//!```rust,no_run
//!fn main() {
//!    panic!("Not run me");
//!}
//!```

Alternatively you could use should_panic so Rust will run the code, but expect the panic. If it's code that won't actually compile, you can use ignore.

Upvotes: 9

Related Questions