Cfg Test and Cargo Test a Missing Information

Oct 28, 2018 • 2 minutes to read

Table of contents

I’m currently working on a library and I want it battle tested. I don’t want to reach 100% code coverage but testing is part of the development workflow and moreover Rust natively provides testing and documentation facilities.

But, what’s the point about #[cfg(test)]?

As you may know, in Rust, you can write code in different ways. Either you put everything directly in your src folder within rs files (and where tests are written in the documentation and/or in a test module section) or you can have a dedicated and separated tests folder.

I enjoy both ways, having test in the documentation forces you to maintain a good documentation quality and makes you more confident about how the library works, but when I have to write more complicated tests I like to put them in tests folder.

I was using, for my lib, a file within src but I tag it with #[cfg(test)]:

mod socket;

mod tests;

I thought using mod tests in my tests folder would work, unfortunately I faced an importation error…

// Some random rs file in ./tests

use lib::tests::weird_function;

I was disappointed, in fact cfg(test) is telling the compiler to compile when it’s a test environment, but even with that it wasn’t working. So I asked about this error on IRC and here is what badboy answered me:

When using a separate tests folder, your crate (lib) is considered as a seperate crate and compile like any other people will use it. It means that every cfg(test) will not be compiled

This information is missing in rust-book for now and will be added soon (PR).

Hope this post might help someone.

comments powered by Disqus