Stdout redirection with dup2 + tempfile works in main.rs but fails in #[test] ā why?
ā Rust š 2025-05-29 š¤ surdeus šļø 10I'm working on a logging system in Rust where I want to capture the output of a macro that writes to
stdout(viaprintln!) and validate it in tests.To capture output, I'm using a
dup2+tempfile+libc::STDOUT_FILENOstrategy that redirectsstdoutto a temporary file. It works perfectly when invoked frommain.rs, but fails when the exact same code is run inside a#[test]function.
- Iām not using
io::set_output_capture- Even with
--nocapture,stdoutseems not to flow to the redirected output- My macro prints correctly, but the capture shows
""Has anyone else run into this? Is the test harness doing some internal redirection or buffering of
stdoutbefore mydup2has a chance to take effect?Here's a minimal example (with
main.rsandtests/test-main.rs) to reproduce.
Rust version: rustc 1.86.0 (05f9846f8 2025-03-31)
Appreciate any pointers. Thanks!
2 posts - 2 participants
š·ļø rust_feed