1
use std::io::{self, BufRead, Write};
2

            
3
/// Prints a prompt and reads a line of input.
4
9
pub fn prompt<R>(prompt_text: &str, mut reader: R) -> String
5
9
where
6
9
    R: BufRead,
7
{
8
9
    print!("{}", prompt_text);
9
9
    io::stdout().flush().expect("Failed to flush stdout.");
10
9
    let mut input = String::new();
11
9
    reader.read_line(&mut input).expect("Failed to read input.");
12
9
    input.trim().to_lowercase()
13
9
}
14

            
15
#[cfg(test)]
16
mod tests {
17
    use super::*;
18

            
19
    #[test]
20
3
    fn test_prompt() {
21
        // GIVEN a prompt with expected text
22
3
        let prompt_text = "Enter some text: ";
23
3
        let expected = "hello";
24
3
        let reader = std::io::Cursor::new(format!("{}\n", expected));
25

            
26
        // WHEN the user enters text
27
3
        let actual = prompt(prompt_text, reader);
28

            
29
        // THEN it should match the expected one
30
3
        assert_eq!(actual, expected);
31
3
    }
32
}