rust icon indicating copy to clipboard operation
rust copied to clipboard

Cargo does not show ouput (e.g. stdout) from doctests with `--nocapture`

Open w1th0utnam3 opened this issue 5 months ago • 1 comments

Problem

As described in this closed issue: https://github.com/rust-lang/cargo/issues/1732, there is no output (e.g. stdout) printed from doctests ran through cargo (e.g. cargo test --doc -- --nocapture) even when explicitly providing the --nocapture flag. Unfortunately the previous issue was closed without being fully resolved as indicated by recent comments.

Support for --nocapture was added to rustdoc in this PR: https://github.com/rust-lang/rust/pull/86230

A PR to support this in cargo was proposed but it was never resolved: https://github.com/rust-lang/cargo/pull/9705

Steps

  1. cargo new --lib doc_testing
  2. Add the following code:
/// This function prints a message to the console.
///
/// ```rust
/// println!("Test");
/// doc_testing::test_function();
/// ```
pub fn test_function() {
    println!("This is a test function.");
}
  1. Run cargo test --doc -- --nocapture

I expect cargo to show the output of the two print statements, however the output is only:

cargo test --doc -- --nocapture
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.02s
   Doc-tests doc_testing

running 1 test
test src/lib.rs - test_function (line 3) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Possible Solution(s)

No response

Notes

No response

Version

cargo 1.87.0 (99624be96 2025-05-06)
release: 1.87.0
commit-hash: 99624be96e9d213b0e9b1e36451271f24e4a41d8
commit-date: 2025-05-06
host: aarch64-apple-darwin
libgit2: 1.9.0 (sys:0.20.0 vendored)
libcurl: 8.7.1 (sys:0.4.80+curl-8.12.1 system ssl:(SecureTransport) LibreSSL/3.3.6)
ssl: OpenSSL 3.4.1 11 Feb 2025
os: Mac OS 15.5.0 [64-bit]

w1th0utnam3 avatar Jun 10 '25 10:06 w1th0utnam3

Looking at cargo test --doc -- --nocapture, it appears we are passing the argument down to rustdoc to be process. We are doing so with --test-args --nocapture. That can cause issues for some CLI parsers, so to verify its being passed down correctly, I then ran cargo test --doc -- --quiet and rustdoc correctly handled that.

So this seems more like a rustdoc issue, so transferring this over.

epage avatar Jun 10 '25 13:06 epage

I'm going to close this as a duplicate of https://github.com/rust-lang/rust/issues/98550.

The solution for now is to use RUSTDOCFLAGS="-Zunstable-options --nocapture". The difference is whether or not this uses --test-args or to rustdoc directly. I don't know what the answer is for how this should actually work.

ehuss avatar Jun 10 '25 15:06 ehuss

Oh, sorry for reporting it again, I didn't find this issue from the other issues I mentioned.

w1th0utnam3 avatar Jun 11 '25 06:06 w1th0utnam3