写入 std::io::stdout() 时输出不可见

问题描述 投票:0回答:1

我想使用一个实现

std::io::Write
的结构来输出内容。 我用
std::io::stdout()
来测试,但是即使缓冲区写入成功,我也看不到输出内容。

#[test]
fn show_test_2() {
    use std::io::Write;
    let mut buffer = std::io::stdout();
    match buffer.write(&"-----------------------".as_bytes()) {
        Ok(_) => println!("Buffer write success"),
        Err(_) => println!("Buffer write failed"),
    };
    println!("+++++++++++++++++++++++");
    assert!(false);
}

通过运行

cargo test --lib
,输出为:

test tests::show_test_2 ... FAILED

failures:

---- tests::show_test_2 stdout ----
Buffer write success
+++++++++++++++++++++++
thread 'tests::show_test_2' panicked at 'assertion failed: false', src\lib.rs:621:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

我的问题是:

  1. 为什么“------------------------”不在测试::show_test_2标准输出中?
  2. 正确的做法是什么?
debugging rust stdout
1个回答
1
投票

这似乎是一个已知问题:

问题是测试似乎重定向了

print
/
println
,但不是实际的
std::io::stdout()
功能。这个还是直接打印到控制台,没有被测试抓到。

不过,解决方案非常简单。使用

print!()
/
println!()
代替
std::io::stdout().write()

© www.soinside.com 2019 - 2024. All rights reserved.