Example
fn func_need_capture(){
println("hello")
}
Can I capture stdout for this test
#[test]
fn capture_test(){
.... //some code here
assert_eq(func_need_capture(),"hello"); // This's what I want to do
}
Example
fn func_need_capture(){
println("hello")
}
Can I capture stdout for this test
#[test]
fn capture_test(){
.... //some code here
assert_eq(func_need_capture(),"hello"); // This's what I want to do
}
No, this is not possible (other than by running the code in a subprocess). The output capturing hook that #[test] uses is private.
On Unix you should be able to do some platform specific things with reopening file descriptors. The basic idea would be to move the real stdout to another FD, and then open a pipe at stdout. You would connect that pipe back to yourself on another FD and use that to read from stdout.
Wouldn't work on Windows of course (maybe there is something similar?). And I don't know if that is considered UB or not by std.
It is quite unfortunate that this is not exposed by std.
The answer is that you just shouldn't be using println! in anything you want to test; use writeln in std - Rust instead. Make a parameter for where to write, then in the product code pass in stdout but in tests pass in a String or something.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.