fn f() -> u32 {
0
}
fn main() {
#[cfg(test)]
mod tests {
use super::f;
#[test]
fn test_f() {
assert_eq!(f(), 1);
}
}
}
This code compiles fine.
Running “cargo test” skips the test case “test_f”.
Moving the test case outside of main fixes the issue and we get an expected error message.
Questions:
Why is having a test case in the “main” a bad idea?
Why is there no warning or error message when compiling the code?
Here is a YouTube video recording of the "problem" - https://youtu.be/FyAhU2xavfU
kpreid
October 7, 2024, 3:09pm
2
Such tests cannot be run because inner functions like that cannot be named by anything outside of main
, including the test harness.
There is supposed to be a warning — Make test harness lint about unnnameable tests. by cjgillot · Pull Request #114414 · rust-lang/rust · GitHub — but you're not getting a warning. So, this is a bug. It seems that it is because of the mod
being involved. I have filed a bug report:
opened 03:07PM - 07 Oct 24 UTC
A-diagnostics
T-compiler
### Code
```rust
fn _outer_function() {
mod tests {
#[test]
… fn inner_test() {}
}
}
```
### Current output
```text
warning: function `inner_test` is never used
--> src/lib.rs:4:12
|
4 | fn inner_test() {}
| ^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
```
### Desired output
```text
warning: cannot test inner items
--> src/lib.rs:3:9
|
3 | #[test]
| ^^^^^^^
|
= note: `#[warn(unnameable_test_items)]` on by default
= note: this warning originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)
```
### Rationale and extra context
The desired warning is produced if `mod tests` is removed so that the `inner_test()` is directly in the function. The warning should be produced in both cases, since both cases are tests that will not be run.
The warning was last changed in #114414.
### Rust Version
Stable 1.81.0 and nightly 1.83.0-nightly (2024-10-05 9096f4fafa2ac2d771f8)
4 Likes
system
Closed
January 5, 2025, 3:09pm
3
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.