'How do I import submodules in another submodule which are part of the tests/ directory?
My goal is to write a test-module(tests/) to an existing rust package.
my package directory tree looks similar to below example_package
example_package
|
├── Cargo.toml
├── src
│ ├── lib.rs
| ├── other_module.rs
│ ├── main.rs
└── tests
├── lib.rs
├── test1.rs
└── test_fixtures
├── mod.rs
├── test_fixture1.rs
└── test_fixture2.rs
Here
test-fixtures/- is the directory which has common test inputs used in actual testcases.test1.rs- is the actual testcase which importstest-fixtures/and tests a testcase.
But when I tried to import fixtures in test1.rs as below
//tried all below three different ways
use crate::test_fixtures;
//use self::test_fixtures;
//use super::test_fixtures;
The code fails at compile time.
--> tests/test1.rs:2:5
|
2 | use crate::test_fixtures;
| ^^^^^^^^^^^^^^^^^^^^ no `test_fixtures` in the root
What is the right way to import a submodule in another submodule which are part of tests/?
Code:
// tests$ cat lib.rs
pub mod test_fixtures;
pub mod test1;
// tests$ cat test_fixtures/mod.rs
pub mod test_fixture1;
pub mod test_fixture2;
// tests$ cat test_fixtures/test_fixture1.rs
pub fn test_fixture1() {
print!("test_fixture1");
}
// tests$ cat test_fixtures/test_fixture2.rs
pub fn test_fixture2() {
print!("test_fixture2");
}
// tests$ cat test1.rs
use crate::test_fixtures;
//use self::test_fixtures;
//use super::test_fixtures;
pub fn test1() {
println!("running test1");
}
Solution 1:[1]
??? tests
??? lib.rs
??? test1.rs
??? test_fixtures
??? mod.rs
??? test_fixture1.rs
??? test_fixture2.rs
The file structure presented makes an incorrect assumption. The tests folder is not a library crate. Adding a file named lib.rs inside the tests folder will not declare modules for use on all integration tests.
Instead, declare the common modules (such as test_fixtures) in each integration test file, or create a helper library which is shared by all of them.
See also:
Solution 2:[2]
Your tests/test1.rs file should look like this,
mod test_fixtures;
#[test]
fn test1() {
test_fixtures::test_fixture2
}
Notice, that you need to use mod to use the local module.
This tells the rust compiler to include a file named test_fixtures.rs or alternatively look for test_fixtures folder with mod.rs file in it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | E_net4 - Mr Downvoter |
| Solution 2 | Sandeep |
