Compiler give warning on functions used in test only

I have test_utils in a module and I want to use those in tests across the different submodules. Although I use them in the testing, whenver I compile the code the it shows warnning regarding not used functions. Is there a place where I can put them and not having those warnings? or should I just use #[allow(dead_code)]

To illustrate, I have test_utils.rs

storage/test_utils.rs

pub const TEST_DIR: &str = "/tmp/test-rkv";
use std::fs;

pub fn setup() {
    fs::create_dir_all("/tmp/test").unwrap();
}

And I use that method in storage/data.rs

#[cfg(test)]
mod tests {
    use storage::test_utils::setup;
   #[test]
   fn sample() {
      setup();
   }
warning: function is never used: `setup`
  --> src/storage/test_utils.rs:10:1
   |
10 | fn setup() {
   | ^^^^^^^^^^
   |
   = note: #[warn(dead_code)] on by default

You could move the function into the tests module... because its the only place where it is needed!

The issue is when you do a normal compile the compiler doesn't even know the tests exist (the #[cfg(test)] attribute removes them early on in the compilation process), so all it sees is a setup() function which isn't used anywhere. Although probably not how you thought it'd behave, the dead code lint is actually doing its job correctly here.

If you need setup() to be in that particular module you can add a #[cfg(test)] attribute to it so the compiler only ever sees the function when you do cargo test. Otherwise you can tell the linter to ignore just that one setup() function by giving it a #[allow(dead_code)] attribute.

3 Likes