13个版本 (7个重大更新)
0.8.4 | 2024年5月24日 |
---|---|
0.8.1 | 2024年3月21日 |
#50 in 过程宏
每月587次下载
用于 enumcapsulate
81KB
2K SLoC
tryexpand
类似于 trybuild,但它允许您测试声明性或过程宏的展开方式。
文档
请参阅docs.rs上的文档。
需求
tryexpand
需要已安装cargo-expand。
使用
安装
通过运行以下命令将tryexpand
添加到您的项目作为开发依赖项:
cargo install --dev tryexpand
编写测试
然后在您的crate的tests/
目录下,创建包含对tryexpand::expand()
的调用的tests.rs
文件,并在tests/expand/pass/
、tests/expand/checked_pass/
和tests/expand/fail/
目录中填充相应的Rust源文件。
通过
tryexpand
测试套件的基类是tryexpand::expand()
函数,您向其传递文件路径列表(或glob模式)。
#[test]
pub fn pass() {
tryexpand::expand(
["tests/expand/pass/*.rs"]
).expect_pass();
// or its short-hand (by default `.expect_pass()` is implied):
tryexpand::expand(
["tests/expand/pass/*.rs"]
);
}
默认情况下,tryexpand::expand()
断言匹配的测试文件成功展开。
失败
如果您想编写宏展开诊断测试,则需要添加对.expect_fail()
的调用
#[test]
pub fn fail() {
tryexpand::expand(
["tests/expand/fail/*.rs"]
).expect_fail();
}
命令行参数
此外,您还可以指定要传递给cargo expand
的参数
#[test]
tryexpand::expand(
// ...
)
// ...
.args(["--features", "test-feature"])
.expect_pass();
命令行环境变量
以及用于设置环境变量的 cargo expand
tryexpand::expand(
// ...
)
// ...
.envs([("MY_ENV", "my env var value")])
.expect_pass();
cargo check
您还可以使用 tryexpand
对扩展后的代码进行类型检查(即 cargo check
)
tryexpand::expand(
// ...
)
// ...
.and_check()
.expect_pass();
cargo run
或者您可以让 tryexpand
为您运行扩展后的代码(即 cargo run
)
tryexpand::expand(
// ...
)
// ...
.and_run()
.expect_pass();
cargo test
或者您可以让 tryexpand
为您运行扩展代码的包含的单元测试(如果有的话)(即 cargo test
)
tryexpand::expand(
// ...
)
// ...
.and_run_tests()
.expect_pass();
运行测试
可以使用以下方式运行测试
cargo test
虽然可以并行运行测试,但建议顺序运行它们
cargo test -- --test-threads=1
出于调试目的,您可能希望查看所有测试的输出,而不仅仅是失败的测试
cargo test -- --no-capture
每个 tryexpand
测试将调用 cargo expand
命令(以及任何可选的后续命令:cargo check
,cargo run
,cargo test
)在每个与glob模式匹配的源文件上,并将扩展结果与相应的 *.out.rs
,*.out.txt
或 *.err.txt
快照文件进行比较。
如果提供了环境变量 TRYEXPAND=overwrite
(例如 $ TRYEXPAND=overwrite cargo test
),则将创建或覆盖快照文件。快照文件应纳入版本控制。
不推荐手动编写快照文件。
性能考虑
当与多个扩展测试文件一起工作时,建议指定通配符(*.rs
)而不是对单个文件进行多次 expand
函数调用。
对于多个文件使用通配符将它们分组到单个临时crate中,该crate的依赖项将只构建一次。相比之下,对每个源文件调用 expand
函数将创建多个临时crate,这将降低性能,因为每个临时crate都将构建依赖项。
参考 tests/macro-tests 和 tests/proc-macro-tests。
可靠性考虑
由于每个 rustc/cargo 发布版本可能会对生成的诊断信息进行更改,因此建议使用 固定的 工具链 运行 tryexpand
测试,例如。
cargo +1.76.0 test <OPTIONS>
调试
TRYEXPAND_KEEP_ARTIFACTS
对于您的测试中每个类似 expand()
的方法调用,会在 $CARGO_TARGET_DIR/target/tests/
生成一个临时且具有唯一名称的 Rust 项目。默认情况下,这些项目在测试完成后将被删除(无论结果如何)。如果您想查看实际被展开的代码/项目,可以提供 TRYEXPAND_KEEP_ARTIFACTS=1
(例如,$ TRYEXPAND_KEEP_ARTIFACTS=1 cargo test
),并且 tryexpand
将跳过清理。
TRYEXPAND_TRUNCATE_OUTPUT
默认情况下,tryexpand
会截断超过 100 行的控制台输出。如果您希望暂时改变这种行为,可以提供 TRYEXPAND_TRUNCATE_OUTPUT=0
(例如,$ TRYEXPAND_TRUNCATE_OUTPUT=0 cargo test
),并且 tryexpand
将产生完整的控制台输出。
贡献
请阅读 CONTRIBUTING.md 了解我们的 行为准则,
以及向我们提交拉取请求的流程。
版本控制
我们使用 SemVer 进行版本控制。有关可用的版本,请参阅 此存储库的标签。
许可
此项目采用 MIT 或 Apache-2.0 许可 – 请参阅 LICENSE-MIT.md/LICENSE-APACHE.md 文件以获取详细信息。
来源
依赖项
~4–6MB
~110K SLoC