rust-lang / rust-lang/rust

`cfg(test)` is not set within the test code while compiling doctests

Open
#148,942 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-doctests C-bug T-rustdoc
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

//! ```rust
//! assert!(cfg!(test));
//! ```

I expected to see this happen: the test passes.

Instead, this happened:

thread 'main' panicked at src/lib.rs:3:1:
assertion failed: cfg!(test)

Very similar to #45599, which I think got a bit confused by a cfg(doctest) being added to the crate the doctests are being generated from. This is about the crate that contains the doctest source code and is being executed (where neither cfg(test) or cfg(doctest) are set). As mentioned in that issue doctests are treated as integration tests, and the same code as an integration test passes:

> cat tests/foo.rs
#[test]
fn test() {
    assert!(cfg!(test))
}

> cargo test --test foo -q

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

This is niche, but has usecases, such as having an example in README.md that you include_str! to run as a doctest and needing different behavior when tested vs. copied by a user to try out.

Meta

Tested on 1.80-edition-2021 + 1.90-edition-2024 + nightly.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the minimal doctest with cargo test on the reported stable and nightly toolchains, then compare it with the integration-test example in the issue. Trace how doctests are compiled and determine how test configuration should behave there; done means the doctest assertion passes without breaking ordinary doctest execution.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.