Skip to content

new: Don't add #[cfg(test)] mod tests {} by default #10531

Closed
@cgwalters

Description

@cgwalters

Problem

See discussion in https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/why.20mod.20test.3F

Having unit tests be under a separate module has no benefit for simple
unit tests. I had originally thought that #[test] functions were
still compiled even in non-test builds, but that's not true;
it seems that #[test] is implicitly also #[cfg(test)] - which
makes sense.

A separate module is really only necessary when one scales up a
test suite (e.g. adding types like structs that are only used by tests,
helper functions). But even then, one can add #[cfg(test)]
to these extra helpers to start.

But at that scale, there are also other potentially better ways
to handle things, such as moving the tests to an entirely separate
file which works better with incremental compilation.

There's also the philosophy that one should focus on integration,
not unit tests:
https://matklad.github.io/2021/02/27/delete-cargo-integration-tests.html

In short, there's lots of ways to handle tests; I think the book
should try to cover all the tradeoffs and advantages of these.

Injecting #[cfg(test)] mod test {} into every cargo new Rust
is a strong statement that this is a standard, but I think it shouldn't
be. Instead again, at non-trivial scale users should be referencing
the docs.

Note the docs will need to be updated after this, because it
does reference this explicitly. The documentation even says:

For now, let’s ignore the top two lines and focus on the function to see how it works.

Which to me is a strong indication that this is actually not useful
for every person new to Rust to see by default.

Proposed Solution

Don't add #[cfg(test)] mod test { ... } in cargo new by default, and change the book.

Notes

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: proposal for a feature. Before PR, ping rust-lang/cargo if this is not `Feature accepted`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions