Sub topic 13
Writing input code you can test
This chapter assumes you can write a Rust function with generics and trait bounds, use ? with Result, and run cargo test. It also assumes you have read the earlier chapters on read_line, lines(), and parse.
Why input code is hard to test
A function that calls io::stdin() directly depends on the terminal or pipe the test runner happens to have. A test cannot supply its own text, and running it would wait for input.
The fix is to move the stdin call to the edge of the program. The logic in the middle takes a reader as a parameter. In main, you pass it real standard input. In a test, you pass it a string.
The BufRead trait as the seam
BufRead is the trait that provides lines() and read_line. Three types you already know implement it:
StdinLock, which you get fromio::stdin().lock().&[u8], a byte slice. A string literal becomes one with.as_bytes().io::Cursor<T>, a wrapper that makes in-memory data readable.
A function with the bound R: BufRead works with all of them.
The testable version
use std::error::Error;
use std::io::{self, BufRead};
fn read_numbers<R: BufRead>(reader: R) -> Result<Vec<i32>, Box<dyn Error>> {
let mut numbers = Vec::new();
for line in reader.lines() {
let line = line?;
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
numbers.push(trimmed.parse::<i32>()?);
}
Ok(numbers)
}
fn main() -> Result<(), Box<dyn Error>> {
let numbers = read_numbers(io::stdin().lock())?;
println!("{numbers:?}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn skips_blank_lines() {
let data = "1\n2\n\n3\n";
assert_eq!(read_numbers(data.as_bytes()).unwrap(), vec![1, 2, 3]);
}
}Three points make this work.
read_numbersnever mentionsstdin. It only requiresBufRead, so the compiler generates a version for each reader type you pass.- Two different errors can occur.
line?can fail withio::Error, andparse::<i32>()?can fail withParseIntError. Both convert intoBox<dyn Error>, so one return type covers both. mainstays thin. It only connects real input to the logic and prints the result, so there is little left in it to test.
Run the test with cargo test. It finishes without waiting for a keyboard.
Testing the failure path
A good test suite also checks that bad input is rejected. Add this test inside the same tests module:
#[test]
fn rejects_non_numbers() {
let data = "1\nabc\n3\n";
assert!(read_numbers(data.as_bytes()).is_err());
}The function stops at the first line that fails to parse and returns the error, so the 3 is never read. If you want to check which error came back, compare its message:
#[test]
fn error_message_names_the_problem() {
let err = read_numbers("x\n".as_bytes()).unwrap_err();
assert_eq!(err.to_string(), "invalid digit found in string");
}Common mistakes
- Taking
Stdininstead of a generic reader. A parameter typedio::Stdincan never receive test data. Use aBufReadbound. - Printing inside the parsing function. Return values and let the caller print. Output is much harder to assert on than a returned
Vec. - Forgetting that
&stris not a reader. You must call.as_bytes(). Passing the&stritself will not compile. - Using
unwrapin the function under test. It hides the error type. ReturnResultand let the test decide.
Decision criteria
| Situation | Approach |
|---|---|
| Small script, run once | Call `stdin` directly in `main` |
| Parsing rules you want to verify | Generic `BufRead` function, as above |
| Need to test prompts too | Also take a `Write` parameter for output |
Exercise
Change read_numbers so that it also accepts several whitespace-separated numbers per line, such as "1 2\n3\n", and write a test that expects vec![1, 2, 3]. Which line of the function changes?
Show answer
Replace the single numbers.push(trimmed.parse::<i32>()?); with a loop over trimmed.split_whitespace() that parses and pushes each token: for token in trimmed.split_whitespace() { numbers.push(token.parse::<i32>()?); }. The blank-line check can stay, or be dropped, since split_whitespace yields nothing for an empty line. The test is assert_eq!(read_numbers("1 2\n3\n".as_bytes()).unwrap(), vec![1, 2, 3]);.