#async #scenario #operation #task #permutations

并发检查

测试并发场景的排列组合

2 个版本

0.1.0-alpha.22024年6月4日
0.1.0-alpha.12024年5月21日

并发 中排名 #252

MIT 许可证

47KB
1K SLoC

并发检查

并发检查 是一个 Rust 并发测试工具。它通过运行具有不同线程/任务交错的不同测试场景来帮助发现错误。

Crates.io Documentation Build status

用法

目前处于 alpha 版本,界面将很快改变,但理念保持不变。

将其添加到依赖项中

# Cargo.toml
[dependencies]
parcheck = { version = "0.1.0-alpha.2", git = "https://github.com/stepantubanov/parcheck.git" }

[dev-dependencies]
parcheck = { version = "0.1.0-alpha.2", features = ["enable"], git = "https://github.com/stepantubanov/parcheck.git" }

注意,enable 功能仅在 dev-dependecies 中启用。没有此功能,对 并发检查::task并发检查::operation 的调用将展开到底层 future,而不添加任何额外逻辑,因此对生产代码的影响应尽可能小。

为了控制代码,它必须通过调用 并发检查::task并发检查::operation 来进行配置。 "任务" 是执行线程(目前 并发检查 不支持任务内并发,但这即将到来)而 "操作" 是 并发检查 将控制的 future。具体来说,它将在确定性线性化计划中执行操作(当有多个任务运行时,只从其中一个任务中选择一个操作并允许它根据当前选择的计划执行,然后完成后,选择下一个操作,等等)。

async fn handle_http_request() {
    parcheck::task!("name_of_this_request", {
        async {
            // ... code that isn't controlled by parcheck

            let value = parcheck::operation!("name_of_operation", {
                // ... perform an async operation: execute an SQL query, send a message, set/get
                // in redis, etc.
                async {}
            }).await;

            // ... some other code that isn't controlled

            parcheck::operation!("name_of_next_operation", {
                // ... another operation, that will be controlled by parcheck
                async {}
            }).await;
        }
    }).await;
}

我们可以通过添加测试用例并通过 并发检查::runner 运行来测试此异步函数的两个并发执行的交错。

#[tokio::test]
async fn test_concurrent_scenarios() {
    parcheck::runner()
        .run(["name_of_this_request", "name_of_this_request"], || async {
            join!(
                handle_http_request(),
                handle_http_request(),
            );

            // ... assert that state after 2 concurrent requests is as expected
        }).await;
}

Runner 接受要测试的任务的名称,并在它们启动时(调用 并发检查::task)开始控制它们的执行。此测试将多次运行 2 个并发的 handle_http_request,每次操作的顺序都不同。如果代码在某个计划下崩溃,则 并发检查 将打印出该计划,并且可以用来重新创建它。

依赖项

~0–1.4MB
~24K SLoC