Sub topic 13
Writing input code you can test
This chapter assumes you know the basics of read_line, lines(), parse, and Result. It also assumes you can write a main that returns io::Result or Result<(), Box<dyn Error>>. The goal is to structure input code so a unit test can run it without a terminal.
Why input code is hard to test
A function that calls io::stdin() directly is tied to the real process input. A test runner does not give you a terminal to type into. Depending on how you run the tests, stdin is either empty or inherited from your shell, so the test either gets no data or hangs.
Here is the problem in code:
use std::io;
fn read_age() -> u32 {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("failed to read line");
input.trim().parse().expect("not a number")
}
fn main() {
println!("{}", read_age());
}You cannot call read_age from a test with a chosen input. You would need to spawn the whole program and pipe data into it. That works, but it is slow and awkward. A better approach is to separate two concerns:
- Where the bytes come from. Stdin in production, a string in tests.
- What the program does with them. Parsing, summing, validating.
The second concern holds the logic you want to test. The first concern should be a parameter.
The BufRead trait
BufRead is a standard library trait for readers that have an internal buffer. It provides read_line and lines(), the two methods you have used throughout this tutorial. Several types implement it:
| Type | Source of data |
|---|---|
| `StdinLock` | The process's standard input |
| `BufReader<File>` | A file on disk |
| `&[u8]` | A byte slice already in memory |
| `Cursor<Vec<u8>>` | An in-memory buffer with a read position |
The entry in the third row is the useful one for tests. A &[u8] is a BufRead, and "text".as_bytes() gives you one from a string literal. If your function accepts any BufRead, a test can pass a byte slice and production code can pass a locked stdin.
io::stdin() itself does not implement BufRead. Calling .lock() returns a StdinLock, which does. This is why earlier chapters locked stdin before calling lines().
Making the function generic
Take the reader as a type parameter with a BufRead bound:
use std::io::BufRead;
fn count_lines<R: BufRead>(reader: R) -> usize {
reader.lines().count()
}The function no longer mentions stdin. The type R is chosen by the caller, and the compiler generates code for each type used. You can also write the parameter as impl BufRead, which means the same thing here:
use std::io::BufRead;
fn count_lines(reader: impl BufRead) -> usize {
reader.lines().count()
}Both forms are fine. The R: BufRead form is useful when you need to name the type elsewhere in the signature, for example when two parameters must have the same reader type.
Choosing an error type
Reading and parsing can fail in different ways. lines() yields io::Result<String>, so each line can produce an io::Error. parse::<i32>() produces a ParseIntError. These are different types, so a single ? chain needs a common return type.
Box<dyn Error> is that common type. The ? operator converts any error that implements the Error trait into a boxed one. This is the same technique introduced in the previous chapter on mixed errors, and it is what makes the complete example below short.
A complete testable example
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 things to notice:
read_numbersknows nothing about stdin. It takes a reader and returns aVec.mainis a thin wrapper. It suppliesio::stdin().lock()and prints the result. There is almost no logic left in it to get wrong.- The test builds its input with
data.as_bytes(). No terminal, no pipe, and no files are involved.
Run the program and the tests with these commands:
printf '10\n20\n\n30\n' | cargo run
cargo testThe first command prints [10, 20, 30]. The second runs the unit test.
Testing the failure paths
Good input tests cover bad input as well as good input. Because read_numbers returns a Result, you can assert that it fails and inspect the message. Add these tests inside the same tests module:
#[test]
fn rejects_non_numbers() {
let data = "1\nabc\n3\n";
let err = read_numbers(data.as_bytes()).unwrap_err();
assert!(err.to_string().contains("invalid digit"));
}
#[test]
fn empty_input_gives_empty_vec() {
assert_eq!(read_numbers("".as_bytes()).unwrap(), Vec::<i32>::new());
}
#[test]
fn handles_missing_final_newline() {
assert_eq!(read_numbers("4\n5".as_bytes()).unwrap(), vec![4, 5]);
}
#[test]
fn trims_whitespace_around_numbers() {
assert_eq!(read_numbers(" 7 \n\t8\n".as_bytes()).unwrap(), vec![7, 8]);
}Each test checks a case that is easy to get wrong:
- Invalid text. The error message comes from
ParseIntError, whoseDisplayoutput for non-digits isinvalid digit found in string. - Empty input. End of input right away is not an error. The function returns an empty vector.
- No trailing newline.
lines()still yields the last line. Files and pipes often end without a newline. - Surrounding whitespace. The
trimcall handles spaces and tabs, not only the newline.
Because the tests run in memory, you can add dozens of these cases at no cost.
Testing the I/O error path
An in-memory slice never fails to read, so none of the tests above reach the line? branch. If you want to cover it, write a small reader that fails. A BufRead implementation needs Read as well, so you implement both:
use std::io::{self, BufRead, Read};
struct FailingReader;
impl Read for FailingReader {
fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::Other, "disk on fire"))
}
}
impl BufRead for FailingReader {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
Err(io::Error::new(io::ErrorKind::Other, "disk on fire"))
}
fn consume(&mut self, _amt: usize) {}
}
fn main() {
let result = FailingReader.lines().next();
println!("{:?}", result.map(|r| r.is_err()));
}This prints Some(true): the first item from lines() is an Err. In a real test suite you would pass FailingReader to read_numbers and assert that the result is an error. This level of testing is optional. Most programs get enough value from the parse-failure tests.
Going further: testing prompts
Programs that prompt the user also write output. The same idea applies to Write. Accept a generic writer and pass io::stdout() in production and a Vec<u8> in tests, since Vec<u8> implements Write:
use std::io::{self, BufRead, Write};
fn ask_age<R: BufRead, W: Write>(mut input: R, mut output: W) -> io::Result<Option<u32>> {
write!(output, "Enter your age: ")?;
output.flush()?;
let mut line = String::new();
if input.read_line(&mut line)? == 0 {
return Ok(None);
}
Ok(line.trim().parse().ok())
}
fn main() -> io::Result<()> {
let age = ask_age(io::stdin().lock(), io::stdout())?;
println!("{age:?}");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prompts_and_parses() {
let mut out = Vec::new();
let age = ask_age("42\n".as_bytes(), &mut out).unwrap();
assert_eq!(age, Some(42));
assert_eq!(String::from_utf8(out).unwrap(), "Enter your age: ");
}
#[test]
fn eof_gives_none() {
let mut out = Vec::new();
assert_eq!(ask_age("".as_bytes(), &mut out).unwrap(), None);
}
}Passing &mut out works because &mut W implements Write whenever W does. That lets the test keep ownership of the buffer and read it after the call.
Common mistakes
- Locking inside the function. If the function calls
io::stdin().lock()itself, it is no longer generic. Lock inmainand pass the result in. - Forgetting that
&[u8]is the reader. Passing aStringor&strdirectly fails to compile. Use.as_bytes(). - Putting logic in
main. Anything left inmaincannot be unit tested. Keep it to wiring. - Mixing a persistent prompt loop with a consumed reader.
lines()takes the reader by value. If you need to keep using the reader afterwards, pass&mut reader. This works because&mut RimplementsBufReadwhenRdoes. - Holding the stdin lock twice. Locking stdin in
mainand then callingio::stdin().read_lineelsewhere while the lock is held can block. Pass the locked handle down instead.
How the pieces fit together
Summary
- Accept
R: BufRead(orimpl BufRead) instead of callingio::stdin()inside your logic. - Return a
ResultwithBox<dyn Error>so I/O and parse errors share one type. - Keep
mainas a thin wrapper that suppliesio::stdin().lock(). - In tests, pass
str::as_bytes()for input and aVec<u8>for captured output. - Test the bad cases: invalid text, empty input, a missing final newline, and extra whitespace.
Exercise
Write a function sum_lines<R: BufRead>(reader: R) -> Result<i64, Box<dyn Error>> that adds up one integer per line, ignoring blank lines. Then write a test that checks "5\n-2\n\n10\n" gives 13, and a second test that checks "5\nx\n" returns an error.
Show answer
use std::error::Error; use std::io::BufRead; fn sumlines<R: BufRead>(reader: R) -> Result<i64, Box<dyn Error>> { let mut total = 0; for line in reader.lines() { let line = line?; let trimmed = line.trim(); if trimmed.isempty() { continue; } total += trimmed.parse::<i64>()?; } Ok(total) } #[cfg(test)] mod tests { use super::*; #[test] fn addslines() { asserteq!(sumlines("5\n-2\n\n10\n".asbytes()).unwrap(), 13); } #[test] fn badlineiserror() { assert!(sumlines("5\nx\n".asbytes()).iserr()); } }
Exercise
Why can a test pass "1\n2\n".as_bytes() to a function that expects R: BufRead, but not pass io::stdin() in the same position?
Show answer
A &[u8] implements BufRead, so it satisfies the bound. The Stdin handle returned by io::stdin() does not implement BufRead. You must call .lock() to get a StdinLock, which does.