如何在属于 tests/ 目录的另一个子模块中导入子模块?

How do I import submodules in another submodule which are part of the tests/ directory?

我的目标是将 test-module(tests/) 写入现有的 rust 包。

我的包目录树看起来类似于下面 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

这里

但是当我尝试在 test1.rs 中导入 fixtures 时,如下所示

//tried all below three different ways
use crate::test_fixtures;
//use self::test_fixtures;
//use super::test_fixtures;

代码在编译时失败。

 --> tests/test1.rs:2:5
  |
2 | use crate::test_fixtures;
  |     ^^^^^^^^^^^^^^^^^^^^ no `test_fixtures` in the root

tests/ 的另一个子模块中导入一个子模块的正确方法是什么?

代码:

// 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");
    
}

这在本书的测试组织部分,Submodules in Integration Tests 小节中有记录:

As mentioned earlier, each file in the tests directory is compiled as its own separate crate.

[...]

After we’ve created tests/common/mod.rs, we can use it from any of the integration test files as a module. Here’s an example of calling the setup function from the it_adds_two test in tests/integration_test.rs:

use adder;

mod common;

#[test]
fn it_adds_two() {
    common::setup();
    assert_eq!(4, adder::add_two(2));
}

Note that the mod common; declaration is the same as the module declaration we demonstrated in Listing 7-21. Then in the test function, we can call the common::setup() function.

└── tests
    ├── lib.rs
    ├── test1.rs
    └── test_fixtures
        ├── mod.rs
        ├── test_fixture1.rs
        └── test_fixture2.rs

所提供的文件结构做出了错误的假设。 测试文件夹不是库 crate。在测试文件夹中添加名为 lib.rs 的文件将 不会 声明用于所有集成测试的模块。

相反,在每个集成测试文件中声明公共模块(例如test_fixtures),或者创建一个由所有模块共享的帮助程序库。

另请参阅:

您的 tests/test1.rs 文件应如下所示,

mod test_fixtures;

#[test]
fn test1() {
    test_fixtures::test_fixture2
}

请注意,您需要使用 mod 才能使用本地模块。

这告诉 Rust 编译器包含一个名为 test_fixtures.rs 的文件,或者寻找 test_fixtures 文件夹,里面有 mod.rs 个文件。