5 个不稳定版本
| 0.3.0 | 2024 年 5 月 16 日 |
|---|---|
| 0.2.1 | 2024 年 3 月 2 日 |
| 0.2.0 | 2024 年 1 月 4 日 |
| 0.1.1 | 2023 年 2 月 4 日 |
| 0.1.0 | 2023 年 2 月 4 日 |
#211 in 文件系统
2,443 每月下载次数
12KB
51 行
dir-test 提供一个宏,用于从目录中的文件生成单个测试用例。
使用方法
将以下依赖项添加到您的 Cargo.toml。
[dev-dependencies]
dir-test = "0.1"
基本使用
use dir_test::{dir_test, Fixture};
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/fixtures",
glob: "**/*.txt",
)]
fn mytest(fixture: Fixture<&str>) {
// The file content and the absolute path of the file are available as follows.
let content = fixture.content();
let path = fixture.path();
// Write your test code here.
// ...
}
假设您的 crate 如下,则上述代码生成两个测试用例 mytest__foo() 和 mytest__fixtures_a_bar()。
my-crate/
├─ fixtures/
│ ├─ foo.txt
│ ├─ fixtures_a/
│ │ ├─ bar.txt
├─ src/
│ ├─ ...
│ ├─ lib.rs
├─ Cargo.toml
├─ README.md
🔽
#[test]
fn mytest__foo() {
mytest(fixture);
}
#[test]
fn mytest__fixtures_a_bar() {
mytest(fixture);
}
注意:由于当前过程宏系统的限制,dir 参数必须指定为绝对路径。请考虑使用环境变量,dir-test crate 内部解析环境变量。
自定义加载器
您可以指定一个自定义加载器函数来从文件路径加载文件内容。加载器将传递 &'static str 文件路径,并可以返回任意类型。
use dir_test::{dir_test, Fixture};
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/fixtures",
glob: "**/*.txt",
loader: std::fs::read_to_string,
)]
fn test(fixture: Fixture<std::io::Result<String>>) {
let content = fixture.content().unwrap();
// ...
}
如果没有指定加载器函数,则默认内容类型为 &'static str。
自定义测试名称
可以通过指定 postfix 参数来自定义测试名称。将 postfix 追加到测试名称中。
use dir_test::{dir_test, Fixture};
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/fixtures",
glob: "**/*.txt",
postfix: "custom", // `_custom` is appended to the test name.
)]
fn test(fixture: Fixture<std::io::Result<String>>) {
// ...
}
测试属性
可以通过 dir_test_attr 属性指定测试属性。在 dir_test_attr 内部的属性应用于所有生成的测试。
use dir_test::{dir_test, Fixture};
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/fixtures",
glob: "**/*.txt",
)]
#[dir_test_attr(
#[wasm_bindgen_test]
#[cfg(target_family = "wasm")]
)]
fn wasm_test(fixture: Fixture<std::io::Result<String>>) {
// ...
}
注意:必须在 dir_test 之后指定 dir_test_attr 属性。
返回类型
测试可以有返回类型,允许在测试中使用 [Result<T, E>] 类型。请参阅相关书籍链接 此处。
use dir_test::{dir_test, Fixture};
#[dir_test(
dir: "$CARGO_MANIFEST_DIR/fixtures",
glob: "**/*.txt",
)]
fn test(fixture: Fixture<&str>) -> std::io::Result<()> {
// ...
}
依赖项
~1.5MB
~36K SLoC