gpt4 book ai didi

rust - 如何在测试中检查 std::process::exit() 的退出代码?

转载 作者:行者123 更新时间:2023-11-29 08:25:19 25 4
gpt4 key购买 nike

在 Rust 测试中,有没有一种方法可以检查调用 std::process::exit() 的函数?真的用特定的退出代码终止了进程吗?

人为的例子:

fn foo(n: i32) {
std::process::exit(n);
}

#[test]
fn exits_with_correct_exit_code() {
// How do I assert that the following call terminates
// the process with exit code 1?
foo(1);
}

最佳答案

你不能。 std::process:exit名字很好,但以防万一它所做的某个方面不清楚:

Terminates the current process with the specified exit code.

This function will never return and will immediately terminate the current process. The exit code is passed through to the underlying OS and will be available for consumption by another process.

Note that because this function never returns, and that it terminates the process, no destructors on the current stack or any other thread's stack will be run. If a clean shutdown is needed it is recommended to only call this function at a known point where there are no more destructors left to run.

运行测试时,每个测试都在单独的线程 中运行,但所有测试都在单个进程中运行。当该进程终止时,测试也会随之终止。

你可以尝试做一些复杂的递归测试:

#[test]
#[ignore]
fn real() {
std::process::exit(42)
}

#[test]
fn shim() {
let status = std::process::Command::new("/proc/self/exe")
.args(&["--ignored", "real"])
.status()
.expect("Unable to run program");

assert_eq!(Some(42), status.code());
}

这具有特定于平台的代码来查找当前进程,但它“有效”。


老实说,我会说代码超出了它的测试范围。您不应该测试 std::process::exit 是否按照它所说的去做。如果你真的需要断言一个函数是用一个参数调用的,那就是 mock object。是为了。

使用依赖注入(inject)提供一个闭包,捕获闭包中的值,并编写一个薄垫片:

fn foo_logic<F>(n: i32, f: F)
where F: FnOnce(i32)
{
f(n);
}

fn foo(n: i32) {
foo_logic(n, |n| std::process::exit(n));
}

#[test]
fn exits_with_correct_exit_code() {
let mut value = None;
foo_logic(1, |v| value = Some(v));
assert_eq!(Some(1), value);
}

您还可以考虑提取计算潜在错误代码的逻辑并直接对其进行测试。

关于rust - 如何在测试中检查 std::process::exit() 的退出代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43390971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com