Skip to content

cfg!(test) is always false in build.rs #15826

@elldritch

Description

@elldritch

Problem

cfg!(test) is always false in build.rs. This makes it hard for me to write build script logic that should only run on test builds. I would have expected that cfg!(test) is true in build.rs when I run cargo test, because this is what the cfg! documentation here suggests.

Steps

  1. Clone https://github.com/elldritch/cargo-cfg-test-release-repro
  2. Run cargo run, cargo run --release, cargo test -- --nocapture, and cargo test --release -- --nocapture.
  3. Observe that TEST_MODE=no is always outputted, even though cfg!(test) is true in the actual program itself.

Possible Solution(s)

My guess is that what's happening here is that the build script itself is not being built in "test mode", and therefore cfg!(test) is false in the build script. That... sort of makes sense? After all, we're not testing the build script. But if this is the intended behavior, then it surprised me, and I think it would be worth noting in the cfg.test documentation here. If this is intended behavior, I'm also not sure how I would write build script logic that should only run in test mode.

Notes

No response

Version

cargo 1.89.0 (c24e10642 2025-06-23)
release: 1.89.0
commit-hash: c24e1064277fe51ab72011e2612e556ac56addf7
commit-date: 2025-06-23
host: x86_64-unknown-linux-gnu
libgit2: 1.9.0 (sys:0.20.2 vendored)
libcurl: 8.12.1-DEV (sys:0.4.80+curl-8.12.1 vendored ssl:OpenSSL/3.5.0)
ssl: OpenSSL 3.5.0 8 Apr 2025
os: Arch Linux Rolling Release [64-bit]

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-build-scriptsArea: build.rs scriptsC-bugCategory: bugS-triageStatus: This issue is waiting on initial triage.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions