5 个版本 (稳定)
1.2.2 | 2024 年 5 月 24 日 |
---|---|
1.2.0 | 2024 年 4 月 11 日 |
1.1.0 | 2024 年 2 月 29 日 |
1.0.0 | 2024 年 2 月 5 日 |
0.1.0 | 2023 年 11 月 6 日 |
#88 在 Cargo 插件
每月 464 次下载
115KB
2K SLoC
cargo-fixture
cargo fixture
是一个 cargo 扩展,它允许你在 cargo test
周围使用任意的 Rust 设置和清理代码。
它可以用来运行测试连接的网络服务器、启动 docker 容器、准备测试数据、检查程序的存在……或实际上任何可以从 Rust 代码中执行的操作。在 cargo test
完成后,可以手动释放或使用 RAII 守卫或闭包释放任何提供的资源。
可以使用环境变量、内存中的 K-V 存储或文件从 fixture 传递数据到测试。此外,还提供了定义串行测试的选项。
示例项目
安装
cargo install -f cargo-fixture
理由
虽然可以在测试本身中使用代码提供资源,但这通常迫使人们将许多测试用例组合成一个 #[test]
或需要使用各种技巧来同步测试。自定义测试框架目前支持不佳,不方便且存在限制(如没有输出捕获)。
此解决方案提供了与常规 cargo test
相同的体验,测试用例可以几乎以与通常相同的方式编写,并保持粒度。
入门
cargo fixture
命令与 cargo test
命令用法相同,区别在于它在运行 cargo test
前会启动一个 fixture。在 cargo test
运行期间,fixture 会继续运行,并在测试成功后被告知,并有时间进行清理。
cargo fixture
具有与 cargo test
相同的通用 CLI 语法,除了少数自己独有的标志外,它将所有参数都转发给它。
cargo fixture
还会构建带有特殊功能 _fixture
的代码,以便区分使用 fixture 的测试和常规测试。需要在 Cargo.toml
中定义此功能。
[features]
_fixture = []
fixture 是一个位于 tests
子目录的 Rust 程序,在 Cargo.toml
中声明为不属于常规(libtest)测试集。
[[test]]
name = "my_fixture"
test = false
harness = false
该文件应包含一个 main
函数。fixture 和测试通过 cargo-fixture
使用来自 cargo-fixture-lib 的客户端进行通信,底层使用 Unix 域套接字。库使用异步 I/O。
fixture 看起来像这样
async fn main() {
// Connect to the cargo fixture host
let mut fixture = FixtureClient::connect().await.unwrap();
// Prepare the environment...
// Let cargo fixture know tests can be run now, wait for result
let success = fixture.ready().await.unwrap();
eprintln!("Tests finished, success: {success}");
// Wrap up.
}
使用 fixture 环境的测试定义如下
#[with_fixture]
#[tokio::test]
async fn some_test(client: TestClient) {
// interact with whatever fixture has prepared for us.
// client can be used to obtain K-V data.
}
#[with_fixture]
宏标记测试在 _fixture
功能之外,因此当你运行普通的 cargo test
时,需要 fixture 的测试会被跳过!这样,你可以有一个庞大的 fixture,但仍然可以快速运行单元测试。
多个 fixture
使用 cargo fixture -F <name>
使用与默认(fixture
)不同的 fixture 程序。
解决 fixture 故障
-x
标志允许你用一个自定义命令替换 cargo test
命令。你可以使用这个来运行 shell 而不是 cargo test
。
cargo fixture -x sh
这将准备测试夹具,然后进入一个shell,在其中您可以检查夹具环境是否已正确准备,与之交互,甚至可以运行 cargo test
并在测试后与环境交互。
或者,可以使用简写形式 cargo fixture --shell
,它等价于 cargo fixture -x "$SHELL"
。
平台支持
异步运行时:[Tokio](https://tokio.rs/),[smol](https://docs.rs/smol)。
操作系统:Linux,Mac OS,Windows 10 或更高版本。
依赖项
~8–18MB
~254K SLoC