Unable to import test module from another crate

I have folder structure like this:

crate1:
->src
    ->lib.rs
    ->tests.rs
    ->tests
       ->a.rs
       ->b.rs
->Cargo.toml

crate2:
->src
   ->lib.rs
->Cargo.toml

Under lib.rs of crate1, test module is already made as public:

// lib.rs
#[cfg(test)]
pub mod tests;

Now, under crate2, I am not able to import tests module from crate1:

// lib.rs (of crate2)
#[cfg(test)]
mod tests {
use crate1::tests; // This throws an error that unresolved import 'crates1::tests' , no 'tests' in the root
}

I have already added the crate1 as dependency to crate2's Cargo.toml. Infact, I am able to import other public functions defined in lib.rs (crate1). Not sure why importing tests module from crate1 results in the error.

PS: Crate1 is already written by someone else, I am just trying to import certain functions from crate1 into my own crate i.e crate2.

because the module is gated behind the test cfg flag.

compile time cfg flags are set per crate, the test cfg is NOT set for dependencies, even if you are building in debug mode.

1 Like

#[cfg(test)] is only set when compiling the #[test] tests within that crate into a test binary. It is not set when compiling a library that is merely being used by another test crate. When using the library from another crate, you can only use non-cfg(test) items.

Only use #[cfg(test)] for code that is used by the same crate’s #[test]s — not for anything else.

1 Like

I tried removing the line #[cfg(test)] from crate1's lib.rs ,but it still does not work.