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

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

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

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

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

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