这是indexloc提供的服务,不要输入任何密码
Skip to content

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

@Nemo157

Description

@Nemo157

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-doctestsArea: Documentation tests, run by rustdocC-bugCategory: This is a bug.T-rustdocRelevant to the rustdoc team, which will review and decide on the PR/issue.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions