gpt4 book ai didi

rust - 当我无法更改打印的代码时,如何捕获 stdout/stderr 的内容?

转载 作者:行者123 更新时间:2023-12-05 02:29:26 26 4
gpt4 key购买 nike

我有一个无法修改的函数 foo,其中包含 println!eprintln! 代码。

fn foo() {
println!("hello");
}

调用该函数后,我必须测试它打印的内容,因此我想将 stdout/stderr 捕获到一个变量中。

最佳答案

我强烈建议不要这样做,但如果您每晚都在使用并且不介意使用似乎不太可能稳定的功能,则可以使用隐藏的功能直接捕获 stdout 和 stderr标准库:

#![feature(internal_output_capture)]

use std::sync::Arc;

fn foo() {
println!("hello");
eprintln!("world");
}

fn main() {
std::io::set_output_capture(Some(Default::default()));
foo();
let captured = std::io::set_output_capture(None);

let captured = captured.unwrap();
let captured = Arc::try_unwrap(captured).unwrap();
let captured = captured.into_inner().unwrap();
let captured = String::from_utf8(captured).unwrap();

assert_eq!(captured, "hello\nworld\n");
}

函数“无法更改”的情况非常罕见,因此我鼓励您这样做并改用依赖注入(inject)。例如,如果您能够编辑 foo 但不想更改其签名,请将所有代码移动到具有泛型的新函数中,您可以直接测试它:

use std::io::{self, Write};

fn foo() {
foo_inner(io::stdout(), io::stderr()).unwrap()
}

fn foo_inner(mut out: impl Write, mut err: impl Write) -> io::Result<()> {
writeln!(out, "hello")?;
writeln!(err, "world")?;
Ok(())
}

另见:

关于rust - 当我无法更改打印的代码时,如何捕获 stdout/stderr 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72185130/

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