#proc-macro #test-files #file-path #directory #test

test_each_file

为指定目录中的每个文件生成一个测试

9个不稳定版本 (3个重大更新)

0.3.3 2024年6月25日
0.3.2 2024年4月17日
0.3.0 2023年12月3日
0.2.0 2023年11月11日
0.0.2 2023年9月29日

#121过程宏

Download history 1107/week @ 2024-04-17 1314/week @ 2024-04-24 1837/week @ 2024-05-01 691/week @ 2024-05-08 1445/week @ 2024-05-15 995/week @ 2024-05-22 1656/week @ 2024-05-29 3621/week @ 2024-06-05 2891/week @ 2024-06-12 3007/week @ 2024-06-19 2322/week @ 2024-06-26 1656/week @ 2024-07-03 1683/week @ 2024-07-10 1736/week @ 2024-07-17 2203/week @ 2024-07-24 1780/week @ 2024-07-31

7,699 每月下载量
用于 3 crate

MIT 协议

15KB
227 代码行

测试每个文件

githubcrates-iodocs-rs

轻松为指定目录中的文件生成测试,实现全面测试。

以下是一个宏的简单示例

test_each_file! { in "./resources" => test }

fn test(content: &str) {
    // Make assertions on the `content` of the file here.
}

假设以下文件结构

- resources
  - a.txt
  - b.txt
  - extra
    - c.txt
- src
  - main.rs

宏展开为

#[test]
fn a() {
    // The macro actually uses an absolute path for `a.txt` behind the scenes
    test(include_str!("../resources/a.txt"))
}

#[test]
fn b() {
    test(include_str!("../resources/b.txt"))
}

mod extra {
    use super::*;

    #[test]
    fn c() {
        test(include_str!("../resources/extra/c.txt"))
    }
}

生成子模块

可以使用 as 关键字将测试自动插入模块中。例如

test_each_file! { in "./resources" as example => test }

这将把上面的测试包装在额外的 mod example { ... } 中。当在单个文件中多次使用 test_each_file! 时,此功能很有用,以防止生成的测试具有相同的名称。

文件分组

有时可能更希望编写一个测试,该测试以多个文件的内容作为输入。这种情况的一个常见用例是测试一个将给定输入(.in 文件)转换为输出(.out 文件)的函数。

test_each_file! { for ["in", "out"] in "./resources" => test }

fn test([input, output]: [&str; 2]) {
    // Make assertions on the content of the `input` and `output` files here.
}

`.in` 和 `.out` 文件都必须存在,并且位于同一目录中,如下所示

- resources
  - a.in
  - a.out
  - b.in
  - b.out
  - extra
    - c.in
    - c.out
- src
  - main.rs

请注意,`.in` 和 `.out` 在这里只是示例 - 可以提供任意类型的任意数量的唯一扩展名。

测试每个路径

存在一个类似的宏,用于传递给定目录中的所有路径。该宏的行为与 `test_each_file!` 相同,但它传递文件的路径而不是内容。通常,使用 `test_each_file!` 更好,因为它将文件包含在二进制文件中,而 `test_each_path!` 在运行时仍然需要路径。

test_each_path! { for ["in", "out"] in "./resources" => test }

fn test([input, output]: [&Path; 2]) {
    // Make assertions on the path of `input` and `output` here.
}

更多示例

对每个文件调用的表达式也可以是一个闭包,例如

test_each_file! { in "./resources" => |c: &str| assert!(c.contains("Hello World")) }

所有上述选项都可以组合,例如

test_each_file! { for ["in", "out"] in "./resources" as example => |[a, b]: [&str; 2]| assert_eq!(a, b) }

依赖项

~265–710KB
~17K SLoC