capture_stdio/pipe/
stdout.rs

1//! Intercept [std::io::Stdout]
2
3use super::PipedFd;
4use crate::Capture;
5use os_pipe::PipeReader;
6use std::io::Error;
7
8/// Intercept stdout
9pub struct PipedStdout {
10    internal: PipedFd,
11}
12
13impl Capture for PipedStdout {
14    fn capture() -> Result<Self, Error> {
15        let internal = PipedFd::capture(1, false)?;
16        Ok(Self { internal })
17    }
18
19    fn restore(&mut self) {
20        self.internal.restore();
21    }
22}
23
24impl PipedStdout {
25    /// Get reader of pipe
26    pub fn get_reader(&mut self) -> &mut PipeReader {
27        &mut self.internal.reader
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use crate::pipe::stdout::PipedStdout;
34    use crate::Capture;
35    use std::io::{set_output_capture, BufRead, BufReader};
36
37    #[test]
38    fn test_stdout() {
39        // stdout is captured by testing
40        let original = set_output_capture(None);
41
42        let mut piped_stdout = PipedStdout::capture().unwrap();
43        let string = "Write something to stdout\n";
44        print!("{}", string);
45
46        set_output_capture(original);
47
48        let mut output = String::new();
49        let mut buf_reader = BufReader::new(piped_stdout.get_reader());
50        buf_reader.read_line(&mut output).unwrap();
51
52        assert_eq!(output, string);
53        piped_stdout.restore();
54    }
55}