The queue's most important promises are about what does not happen. A duplicate add must not replace a title. A second finish must not count a book twice. A bad command must not stop the run. Running the program with the sample input shows these promises held once, for one input. The check.rs entry point replays many inputs and checks every promise each time you run it, so a later change that breaks one is caught at once.
check.rs uses the same command, queue and app modules as the console entry; only the entry file differs. It has three groups of checks, each aimed at one layer.
check_parser calls parse directly with valid and malformed text and compares the typed results, including ParseError::ZeroId for finish 0 and InvalidId for a number one past u32::MAX. No queue is involved.
check_queue drives Queue methods directly. After every rejected call it checks both the returned error and the state that survived: the counts, and finally the full list of (id, title, status) triples in key order.
check_io replays fixtures through app::run into a Vec<u8> and compares entire transcripts, then proves the two I/O failures escape run: invalid UTF-8 in the input gives InvalidData, and a writer that always returns BrokenPipe gives that error back.
Run the checks
Run the queue checksRustmod app;
mod command;
mod queue;
use command::{Command, ParseError, parse};
use queue::{BookId, Queue, QueueError, Status};
use std::io::{self, Cursor, Write};
fn check_parser() {
let id = BookId::new(7).expect("positive ID");
assert_eq!(parse(" add\t7 Rust Patterns "), Ok(Command::Add { id, title: "Rust Patterns" }));
assert_eq!(parse("finish 7"), Ok(Command::Finish(id)));
assert_eq!(parse("list"), Ok(Command::List));
for (input, error) in [
("add 7", ParseError::MissingTitle),
("finish 0", ParseError::ZeroId),
("finish -1", ParseError::InvalidId),
("finish 4294967296", ParseError::InvalidId),
("list now", ParseError::ExtraArguments),
("remove 7", ParseError::UnknownCommand),
] {
assert_eq!(parse(input), Err(error));
}
}
fn check_queue() {
let id = BookId::new(7).expect("positive ID");
let earlier = BookId::new(3).expect("positive ID");
let missing = BookId::new(99).expect("positive ID");
let mut queue = Queue::default();
assert_eq!(queue.counts(), (0, 0));
assert_eq!(queue.add(id, " "), Err(QueueError::EmptyTitle));
assert_eq!(queue.counts(), (0, 0));
{
let input = String::from(" Rust Patterns ");
assert_eq!(queue.add(id, &input), Ok(()));
}
assert_eq!(queue.finish(id), Ok(()));
assert_eq!(queue.add(id, "Replacement"), Err(QueueError::DuplicateId));
assert_eq!(queue.finish(id), Err(QueueError::AlreadyFinished));
assert_eq!(queue.finish(missing), Err(QueueError::UnknownId));
assert_eq!(queue.add(earlier, "Traits"), Ok(()));
let books: Vec<_> = queue.books().map(|(id, book)| (id.get(), book.title(), book.status())).collect();
assert_eq!(books, vec![(3, "Traits", &Status::Pending), (7, "Rust Patterns", &Status::Finished)]);
assert_eq!(queue.counts(), (1, 1));
}
fn replay(input: &str) -> String {
let mut output = Vec::new();
app::run(Cursor::new(input.as_bytes()), &mut output).expect("fixture I/O");
String::from_utf8(output).expect("UTF-8 output")
}
struct FailingWriter;
impl Write for FailingWriter {
fn write(&mut self, _bytes: &[u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::BrokenPipe, "test writer"))
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn check_io() {
assert_eq!(replay("list"), "Reading queue\nPending: 0 | Finished: 0\n");
let transcript = replay("add 7 Rust\n\nadd 3 借用\nadd 7 Replacement\nfinish 3\nfinish 99\nlist");
assert_eq!(
transcript,
concat!(
"Added #7\n",
"Added #3\n",
"Line 4: ID is already in use\n",
"Finished #3\n",
"Line 6: book was not found\n",
"Reading queue\n",
"#3 [finished] 借用\n",
"#7 [pending] Rust\n",
"Pending: 1 | Finished: 1\n",
)
);
let read_error = app::run(Cursor::new([255_u8]), Vec::new()).expect_err("invalid UTF-8");
assert_eq!(read_error.kind(), io::ErrorKind::InvalidData);
let write_error = app::run(Cursor::new(b"list"), FailingWriter).expect_err("broken pipe");
assert_eq!(write_error.kind(), io::ErrorKind::BrokenPipe);
}
fn main() {
check_parser();
check_queue();
check_io();
println!("Reading queue checks passed");
}
use crate::command::{Command, parse};
use crate::queue::Queue;
use std::io::{self, BufRead, Write};
fn report(queue: &Queue, output: &mut impl Write) -> io::Result<()> {
writeln!(output, "Reading queue")?;
for (id, book) in queue.books() {
writeln!(output, "#{} [{}] {}", id.get(), book.status().label(), book.title())?;
}
let (pending, finished) = queue.counts();
writeln!(output, "Pending: {pending} | Finished: {finished}")
}
pub fn run(input: impl BufRead, mut output: impl Write) -> io::Result<()> {
let mut queue = Queue::default();
for (index, line) in input.lines().enumerate() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let number = index + 1;
let command = match parse(&line) {
Ok(command) => command,
Err(error) => {
writeln!(output, "Line {number}: {}", error.message())?;
continue;
}
};
match command {
Command::Add { id, title } => match queue.add(id, title) {
Ok(()) => writeln!(output, "Added #{}", id.get())?,
Err(error) => writeln!(output, "Line {number}: {}", error.message())?,
},
Command::Finish(id) => match queue.finish(id) {
Ok(()) => writeln!(output, "Finished #{}", id.get())?,
Err(error) => writeln!(output, "Line {number}: {}", error.message())?,
},
Command::List => report(&queue, &mut output)?,
}
}
output.flush()
}
use crate::queue::BookId;
#[derive(Debug, PartialEq, Eq)]
pub enum Command<'a> {
Add { id: BookId, title: &'a str },
Finish(BookId),
List,
}
#[derive(Debug, PartialEq, Eq)]
pub enum ParseError {
UnknownCommand,
InvalidId,
ZeroId,
MissingTitle,
ExtraArguments,
}
impl ParseError {
pub fn message(&self) -> &'static str {
match self {
Self::UnknownCommand => "use add, finish or list",
Self::InvalidId => "use a whole-number ID",
Self::ZeroId => "ID must be positive",
Self::MissingTitle => "enter a title",
Self::ExtraArguments => "list takes no arguments",
}
}
}
fn parse_id(text: &str) -> Result<BookId, ParseError> {
let value = text.parse::<u32>().map_err(|_| ParseError::InvalidId)?;
BookId::new(value).ok_or(ParseError::ZeroId)
}
pub fn parse(line: &str) -> Result<Command<'_>, ParseError> {
let line = line.trim();
let (verb, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let rest = rest.trim();
match verb {
"add" => {
let (id, title) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
let id = parse_id(id)?;
let title = title.trim();
if title.is_empty() {
return Err(ParseError::MissingTitle);
}
Ok(Command::Add { id, title })
}
"finish" => Ok(Command::Finish(parse_id(rest)?)),
"list" if !rest.is_empty() => Err(ParseError::ExtraArguments),
"list" => Ok(Command::List),
_ => Err(ParseError::UnknownCommand),
}
}
use std::collections::{BTreeMap, btree_map::Entry};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct BookId(u32);
impl BookId {
pub fn new(value: u32) -> Option<Self> {
if value == 0 {
None
} else {
Some(Self(value))
}
}
pub fn get(self) -> u32 {
self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum QueueError {
EmptyTitle,
DuplicateId,
UnknownId,
AlreadyFinished,
}
impl QueueError {
pub fn message(&self) -> &'static str {
match self {
Self::EmptyTitle => "enter a title",
Self::DuplicateId => "ID is already in use",
Self::UnknownId => "book was not found",
Self::AlreadyFinished => "book is already finished",
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Status {
Pending,
Finished,
}
impl Status {
pub fn label(&self) -> &'static str {
match self {
Self::Pending => "pending",
Self::Finished => "finished",
}
}
}
pub struct Book {
title: String,
status: Status,
}
impl Book {
pub fn title(&self) -> &str {
&self.title
}
pub fn status(&self) -> &Status {
&self.status
}
}
#[derive(Default)]
pub struct Queue {
books: BTreeMap<BookId, Book>,
}
impl Queue {
pub fn add(&mut self, id: BookId, title: &str) -> Result<(), QueueError> {
let title = title.trim();
if title.is_empty() {
return Err(QueueError::EmptyTitle);
}
match self.books.entry(id) {
Entry::Vacant(slot) => {
slot.insert(Book { title: String::from(title), status: Status::Pending });
Ok(())
}
Entry::Occupied(_) => Err(QueueError::DuplicateId),
}
}
pub fn finish(&mut self, id: BookId) -> Result<(), QueueError> {
let book = self.books.get_mut(&id).ok_or(QueueError::UnknownId)?;
if book.status == Status::Finished {
return Err(QueueError::AlreadyFinished);
}
book.status = Status::Finished;
Ok(())
}
pub fn books(&self) -> impl Iterator<Item = (&BookId, &Book)> {
self.books.iter()
}
pub fn counts(&self) -> (usize, usize) {
let finished = self.books.values().filter(|book| book.status == Status::Finished).count();
(self.books.len() - finished, finished)
}
}
Text
Reading queue checks passed
A passing run prints only one line, because every check is an assert! or assert_eq! that stays silent when it holds. Look at the inner block in check_queue: it adds a title from a String that is dropped right after. The later comparison still finds Rust Patterns, which proves the queue stored its own copy, as traced in the previous lesson.
A result and a state are separate promises
Why does check_queue check the stored records when it has already checked that the duplicate returned DuplicateId? Because a function can report the right error and still do the wrong thing. The standalone example below compares a correct add with one that overwrites the title first and only then reports the duplicate.
correct: result check true, state check trueoverwrites: result check true, state check false
Only the state check tells the two versions apart. The type annotation on versions is there so both functions can sit in one array as plain function pointers. In the real checks, the line comparing books against (7, "Rust Patterns", &Status::Finished) plays the role of state_ok.
Check what survived, not just what was returned
For every operation that can be rejected, assert two things: the error it returns, and the state afterward. A rejection that leaves the state unchanged is the actual promise; the error value is only the report.
Practice
Exercise
Make the duplicate check fail
In the checks playground above, find Entry::Occupied(_) => Err(QueueError::DuplicateId), in queue.rs. Temporarily replace it with Entry::Occupied(_) => Ok(()),. Predict which assertion fails first, then run and read the message. Restore the duplicate branch. Next, make the duplicate branch overwrite the title but still return DuplicateId, and predict which assertion catches that version instead.
Hint 1: the idea
The return value and the surviving state are two independent parts of the contract, and check_queue has an assertion for each.
Hint 2: a first step
Find the first assertion that calls queue.add(id, "Replacement"). Then find where the saved records are collected into books. For the overwrite, Entry::Occupied(mut slot) gives you slot.get_mut().
Worked solution
With Ok(()), the call queue.add(id, "Replacement") no longer returns DuplicateId, so its assert_eq! fails first; the message shows left: Ok(()) and right: Err(DuplicateId). The overwrite version looks like this:
It passes the return-value assertion, then fails the comparison of the collected books, whose output shows Replacement where Rust Patterns was expected. Each check catches a bug the other misses, so both are needed. Restore the original line before moving on.
Completion is saved in this browser only. It does not measure mastery.