0

How can I turn the stdout of stdout().into_raw_mode().unwrap() into a string so I can test it? Note: stdout().into_raw_mode().unwrap() is a RawTerminal<Stdout>.

use std::io::Write;

fn write_to_stdout(stdout: &mut impl Write) {
    write!(stdout, "Enter message: ").unwrap();
    stdout.flush().unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::stdout;
    use termion::raw::IntoRawMode;

    #[test]
    fn test_write_to_stdout() {
        let mut stdout = stdout().into_raw_mode().unwrap();

        write_to_stdout(&mut stdout);

        // output = ??

        assert!(output.contains("Enter message: "));
    }
}

Rust Playground

alexchenco
  • 53,565
  • 76
  • 241
  • 413

1 Answers1

1

The data you write to stdout will be retrieved by the terminal where you run your program, but you can't really read from stdout from within your own program.

What you can do is: In your test, write to something that you in fact can read from. Outside your test, you can then use the actual stdout writer.

use std::io::Write;

fn write_to_stdout(stdout: &mut impl Write) {
    write!(stdout, "Enter message: ").unwrap();
    stdout.flush().unwrap();
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::stdout;
    use termion::raw::IntoRawMode;

    #[test]
    fn test_write_to_stdout() {
        let mut fake_stdout = std::io::Cursor::new(Vec::new());

        write_to_stdout(&mut fake_stdout);

        let output = fake_stdout.into_inner();
        let output_str = String::from_utf8(output).expect("utf-8");

        assert!(output_str.contains("Enter message: "));
    }
}
Viktor W
  • 1,139
  • 6
  • 9