5 个稳定版本
| 1.0.5 | 2024 年 6 月 30 日 |
|---|---|
| 1.0.3 | 2023 年 3 月 4 日 |
| 1.0.2 | 2023 年 2 月 26 日 |
| 1.0.1 | 2023 年 2 月 12 日 |
| 1.0.0 |
|
在 Rust 模式 中排名 517
每月下载量 42
在 duplicate 中使用
46KB
1K SLoC
duplicate_macrotest
lib.rs:
宏扩展的测试框架。
类似于 trybuild,但允许您编写关于宏如何扩展的测试。
最小支持的 Rust 版本:1.34.0
宏扩展测试
一个最小的 duplicate_macrotest 设置如下所示
#[test]
pub fn pass() {
duplicate_macrotest::expand("tests/expand/*.rs");
// Alternatively,
duplicate_macrotest::expand_without_refresh("tests/expand/*.rs");
}
可以使用 cargo test 运行测试。此测试将针对匹配 glob 模式的每个源文件调用 cargo expand 命令,并将扩展结果与相应的 *.expanded.rs 文件进行比较。
如果不存在 *.expanded.rs 文件并且没有明确期望其存在(请参阅 expand_without_refresh),则将其创建(这就是更新测试的方法)。
可能的测试结果有
- 通过:扩展成功,结果与
.expanded.rs文件中的相同 - 失败:扩展与
.expanded.rs文件内容不同 - 刷新:不存在
.expanded.rs文件,但已创建 - 刷新失败:
.expanded.rs预期存在,但不存在。请参阅expand_without_refresh。
注意:当处理多个扩展测试文件时,建议指定通配符 (*.rs) 而不是对单个文件进行多次 expand 函数调用。对多个文件使用通配符会将它们组合在单个临时 crate 中,依赖关系将只构建一次。相比之下,对每个源文件调用 expand 函数将创建多个临时 crate,这会降低性能,因为每个临时 crate 都将构建依赖关系。
向 cargo expand 传递额外的参数
可以为 cargo expand 命令指定额外的参数。
为此,请使用以下带有 _args 后缀的函数
示例
pub fn pass() {
duplicate_macrotest::expand_args("tests/expand/*.rs", &["--features", "my-feature"]);
// Or
duplicate_macrotest::expand_without_refresh_args("tests/expand/*.rs", &["--features", "my-feature"]);
}
_args 函数将导致运行以下 cargo expand 命令
cargo expand --bin <test-name> --theme none --features my-feature
工作流程
首先,必须存在 cargo expand 工具。您可以通过 cargo 安装它。
cargo install cargo-expand
此工具需要 nightly 编译器才能工作,因此也必须安装。
cargo-expand 使用 rustfmt 格式化展开后的代码。强烈建议安装它,因为 test-project/ 和 test-procmacro-project/ 文件夹中的示例使用格式化后的展开代码进行比较。
设置测试项目
在提供过程或声明式宏的 crate 中,在 tests 目录下创建一个 expand 目录,并用不同的展开测试用例作为 Rust 源文件填充它。
然后创建一个 tests.rs 文件来运行测试
#[test]
pub fn pass() {
duplicate_macrotest::expand("tests/expand/*.rs");
// Or:
duplicate_macrotest::expand_without_refresh("tests/expand/*.rs");
}
然后您可以运行 cargo test,这将
- 展开与 glob 模式匹配的源文件中的宏
- 如果使用
expand函数- 第一次运行时,将在
expand目录下的每个测试用例中生成*.expanded.rs文件 - 在后续运行中,将测试用例的展开结果与相应的
*.expanded.rs文件的内容进行比较
- 第一次运行时,将在
- 如果使用
expand_without_refresh- 每次运行时,它都会将测试用例的展开结果与相应的
*.expanded.rs文件的内容进行比较。 - 如果找不到一个或多个
*.expanded.rs文件,则测试将失败。
- 每次运行时,它都会将测试用例的展开结果与相应的
更新 .expanded.rs
此操作仅适用于使用 expand 或 expand_args 函数的测试。
使用环境变量 MACROTEST=overwrite 运行测试,或删除 *.expanded.rs 文件并重新运行相应的测试。文件将自动创建;不建议手动编写。
依赖项
~1.2–2.2MB
~46K SLoC