我希望在我的测试用例中模拟出现在另一个目录中的用户.我在项目根中有几个 case .

| examples/
|  | test1_dir/
|  | test2_dir/
| src/
|  |- main.rs
|  |- lib.rs
|  |- config.rs
|- Cargo.toml
|- Cargo.lock

config.rs内部,有两个测试用例,如下所示:

#[test]
fn config_find_file() {
  let original_dir = env::current_dir().unwrap();
  env::set_current_dir("examples/test1_dir").unwrap();

  // ... 

  env::set_current_dir(original_dir);
} 

#[test]
fn config_find_file_2() {
  let original_dir = env::current_dir().unwrap();
  env::set_current_dir("examples/test2_dir").unwrap();

  // ... 

  env::set_current_dir(original_dir);
} 

当我简单地用cargo test执行时,50%的时间都失败了.这是因为有时铁 rust 进入竞争状态并试图定位examples/test1_dir/examples/test2_dir.为了让它通过,我必须跑cargo test -- --test-threads=1.然而,我在这个项目中有多个测试,我不希望为所有这些测试运行一个线程.以下是我try 过的一些方法:

  1. Using Absolute Paths-尽管在try 查找要在其中的正确目录时这不会造成任何错误,但当出现在错误的目录中时,线程在测试中途切换环境文件夹并断言条件.
  2. Trying to tag tests-我可以跑cargo test --lib config -- --test-threads=1分.但是我不可能执行所有其他测试but配置测试,导致我定义的每个库都有过多的测试命令.

我应该如何处理这个问题?

推荐答案

有一个名为serial_test的 crate ,它提供proc宏#[serial].

使用这个宏的任何测试都将运行单线程,所有其他测试并行运行(这是cargo的默认设置).

例如,考虑以下4个测试.并行测试将并行运行,而串行测试将等待其他测试完成,然后一次只运行一个测试.

#[test]
fn test_parallel_one() {}

#[test]
fn test_parallel_two() {}

#[test]
#[serial]
fn test_serial_one() {}

#[test]
#[serial]
fn test_serial_another() {}

Rust相关问答推荐

如何使用字符串迭代器执行查找?

Arrow RecordBatch as Polars DataFrame

Rust TcpStream不能在读取后写入,但可以在不读取的情况下写入.为什么?

为什么铁 rust S似乎有内在的易变性?

无符号整数的Rust带符号差

为什么 `Deref` 没有在 `Cell` 上实现?

可选包装枚举的反序列化

Nom 解析器无法消耗无效输入

在描述棋盘时如何最好地使用特征与枚举

Rust 为什么被视为borrow ?

当在lambda中通过引用传递时,为什么会出现终身/类型不匹配错误?

全面的 Rust Ch.16.2 - 使用捕获和 const 表达式的 struct 模式匹配

如何在 Rust 中按 char 对字符串向量进行排序?

有没有办法通过命令获取 Rust crate 的可安装版本列表?

从嵌入式 Rust 中的某个时刻开始经过的时间

从 Axum IntoResponse 获取请求标头

&str 的编译时拆分是否可能?

在单独的线程上运行 actix web 服务器

Abortable:悬而未决的期货?

为什么我可以从读取的可变自引用中移出?