test-case的ignore与regex特性:如何跳过测试用例并用正则断言

📅 2026/8/24 9:56:38
test-case的ignore与regex特性:如何跳过测试用例并用正则断言
test-case的ignore与regex特性如何跳过测试用例并用正则断言【免费下载链接】test-caseRust procedural macro attribute for adding test cases easily项目地址: https://gitcode.com/gh_mirrors/te/test-casetest-case是一款 Rust 过程宏procedural macro工具让你通过一行属性注解就能为函数生成带参数的测试用例。它的ignore 特性能方便地跳过某个测试用例regex 特性则能用正则表达式直接断言返回值。本文带你快速上手这两个实用功能少写样板代码让单元测试更整洁。一、快速准备安装 test-case在项目的 Cargo.toml 中把test-case加入开发依赖。如果你需要用正则断言记得开启with-regex特性该特性定义在 crates/test-case-macros/Cargo.toml 中[dev-dependencies] test-case { version 3, features [with-regex] }然后在测试模块中导入宏即可使用use test_case::test_case;二、用 ignore 跳过测试用例一行注解搞定当某个用例暂时无法通过例如依赖的外部接口还不稳定可以用ignore关键字让它被cargo test直接跳过而不是让整组测试变红。最简写法 —— 在期望值的位置写 ignore#[test_case(1 ignore)] #[test_case(2 ignore)] fn ignore_void(input: u8) { assert_eq!(input, 1) }运行cargo test后输出如下可以看到被跳过的用例标记为ignored不影响其他用例执行test ignore_void::_1_expects_inconclusiveempty ... ignored test ignore_void::_2_expects_inconclusiveempty ... ignored test result: ok. 0 passed; 0 failed; 9 ignored; 0 measured; 0 filtered out除了ignore还可以用等价的inconclusive关键字并支持附加注释说明跳过原因#[test_case(() ignore (); waiting for the API fix)] #[test_case(() inconclusive (); inconclusive test)] fn inconclusives(_: ()) { unreachable!() } 进阶技巧还能用方括号携带一条「跳过原因」运行测试时会直接展示出来方便后续排查#[test_case(() ignore[flaky network test] ())] fn descriptions(_: ()) {}最终cargo test中会显示为ignored, flaky network test原因一目了然。这套语法的解析与生成逻辑位于 crates/test-case-core/src/modifier.rs感兴趣可以对照阅读。完整示例见 tests/acceptance_cases/cases_can_be_ignored/src/lib.rs。三、用 regex 做正则断言只关心返回值的模式有时候你并不关心函数返回值的精确内容只要它「符合某个模式」就行。启用with-regex特性后test-case支持matching_regex关键字直接对返回值做正则断言。#[test_case(abcabc is matching_regex r#abc#)] #[test_case(abcabc201 is matching_regex r#\d#)] #[test_case(kumkwat it matches_regex r#^kumkwat$#)] fn regex_test(text: str) - str { text }几个使用要点别名matching_regex与matches_regex等价is与it也都是别名写法随意默认是部分匹配r#abc#表示返回值中「包含」匹配串即可abcabc会匹配成功要整串匹配就加锚点使用r#^kumkwat$#这样的正则锚点可以要求从头到尾完全匹配。正则断言的解析与代码生成实现在 crates/test-case-core/src/complex_expr.rs官方验收用例可参考 tests/acceptance_cases/cases_can_use_regex/src/lib.rs。四、新手常见坑避开这两类错误忘记开启with-regex特性编译时会直接报错with-regex feature is required to use matches-regex keyword。回到Cargo.toml加上features [with-regex]即可解决。正则写成非法模式如果正则本身有语法问题例如不完整的转义序列宏展开后的代码会报incomplete escape sequence之类的编译错误。建议先用r#...#原始字符串书写正则避免转义符打架。总结忽略用例#[test_case(参数 ignore[原因])]等价关键字inconclusive让cargo test跳过该用例并展示原因正则断言#[test_case(参数 is matching_regex r#模式#)]记得先开启with-regex特性两个特性都只需一行注解即可让参数化测试更灵活、更易维护。✅【免费下载链接】test-caseRust procedural macro attribute for adding test cases easily项目地址: https://gitcode.com/gh_mirrors/te/test-case创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考