unit-testingrustrust-cargo

Rust test: Unused imports


Cargo identifies all imports in the tests module as unused, even though I am using them. Consider the following example:

pub fn f() {}

mod tests {
    use crate::a::f;

    #[test]
    fn test_f() {
        f();
    }
}

Compiling this with cargo build yields the following warning:

warning: unused import: `crate::a::f`
 --> src/a.rs:4:9
  |
4 |     use crate::a::f;
  |         ^^^^^^^^^^^

Removing the import naturally results in an error.

Rust by example uses import super::* for its unit tests, but in my example, I get the same warning:

warning: unused import: `super::*`
 --> src/a.rs:4:9
  |
4 |     use super::*;
  |         ^^^^^^^^

What's wrong here?

My Cargo.toml is:

[package]
name = "problem"
version = "0.0.1"
edition = "2021"

Solution

  • Your example is somewhat equivalent to

    mod a {
        pub fn f() {}
    
        // #[cfg(test)] // initially commented out
        mod tests {
            use crate::a::f; // or use super::*;
    
            #[test]
            fn test_f() {
                f();
            }
        }
    }
    
    fn main() {
        a::f();
    }
    

    The #[test] attribute tells that the test_f() is intended to be launched and analysed by cargo test.
    Thus, when not running cargo test, your tests module only contains the use declaration, as if test_f() did not exist at all; hence the warning.

    Introducing the #[cfg(test)] attribute on the tests module instructs the compiler that this whole module has to be considered only when cargo test is run.
    Thus, when not running cargo test, the situation is as your tests module did not exist at all, but when cargo test is run the tests module exists and the use declaration is useful because test_f() also exists and needs this use declaration.