Skip to content

Prove the Planner’s Rules

The Course
•
24 min study

Running the planner with a few inputs and reading the output shows that it works today. It says nothing about tomorrow, after someone changes a comparison or reorders the checks. The project therefore has a second program, check.rs, that exercises every rule with assertions. It has its own main and uses the very same planner.rs as the application, through the same mod planner; line, so it tests the real code rather than a copy.

Run the planner checks Rust
mod planner; use planner::Planner; fn main() { let mut planner = Planner::new(); assert_eq!(planner.total_minutes(), 0); assert_eq!(planner.add_line(" Loops , 1 "), Ok(())); assert_eq!(planner.add_line("Borrowing,240"), Ok(())); assert_eq!(planner.sessions()[0].topic, "Loops"); assert_eq!(planner.sessions()[1].topic, "Borrowing"); assert_eq!(planner.total_minutes(), 241); for (input, message) in [ ("Review", "use topic,minutes"), (" ,20", "enter a topic"), ("Review,0", "use 1–240 minutes"), ("Review,241", "use 1–240 minutes"), ("Review,later", "enter a whole number"), ] { assert_eq!(planner.add_line(input), Err(message)); assert_eq!(planner.sessions().len(), 2); assert_eq!(planner.total_minutes(), 241); } for _ in 0..98 { assert_eq!(planner.add_line("Review,1"), Ok(())); } assert_eq!(planner.sessions().len(), 100); assert_eq!(planner.add_line("Review,1"), Err("planner is full")); assert_eq!(planner.sessions().len(), 100); assert_eq!(planner.total_minutes(), 339); println!("Planner checks passed"); } pub struct Session { pub topic: String, pub minutes: u32, } pub struct Planner { sessions: Vec<Session>, } impl Planner { pub fn new() -> Self { Self { sessions: Vec::new() } } pub fn add_line(&mut self, line: &str) -> Result<(), &'static str> { let (topic, minutes) = match line.split_once(',') { Some(pair) => pair, None => return Err("use topic,minutes"), }; let topic = topic.trim(); if topic.is_empty() { return Err("enter a topic"); } let minutes = match minutes.trim().parse::<u32>() { Ok(value) if value >= 1 && value <= 240 => value, Ok(_) => return Err("use 1–240 minutes"), Err(_) => return Err("enter a whole number"), }; if self.sessions.len() >= 100 { return Err("planner is full"); } self.sessions.push(Session { topic: String::from(topic), minutes, }); Ok(()) } pub fn sessions(&self) -> &[Session] { &self.sessions } pub fn total_minutes(&self) -> u32 { let mut total = 0; for session in &self.sessions { total += session.minutes; } total } }
Text
Planner checks passed

One line of output is the whole result: if any assertion failed, the run would stop with a panic before printing it.

What each group of checks proves

Open check.rs and read it top to bottom. It is organized around the planner's promises:

  • An empty planner totals 0. The first assertion runs before anything is added.
  • Both ends of the range are accepted. Loops , 1 and Borrowing,240 must return Ok(()). The first also has spaces, so it proves that both halves are trimmed.
  • Order and content are kept. The checks read sessions()[0].topic and sessions()[1].topic, so swapped or untrimmed topics fail.
  • Each error has its own message. A loop goes through five bad inputs, each paired with the exact Err message expected. assert_eq! can compare whole Result values, so a wrong message fails just like a wrong decision.
  • A rejection changes nothing. After every bad input, the length is still 2 and the total is still 241. This is the Day 6 checkpoint rule, checked for every kind of error.
  • The 100-session limit holds. for _ in 0..98 adds 98 more sessions, since 0..98 counts from 0 up to 97 and _ ignores the counter. The 101st request must fail with planner is full, leaving the length at 100.

Why break a working check

A check that has never failed might not be able to fail. It could test the wrong value, or test a case that passes with any version of the code. The way to find out is a mutation: change the code in a small, realistic way, run the checks, and confirm that one of them reports the problem. If they all still pass, you have found a gap.

Exercise

Make a check fail

In the editor above, find the upper duration limit in planner.rs. Change <= 240 to < 240. Run the checks, read the failure and explain what it proves. Restore the comparison and rerun before moving on.

Hint 1: the idea

Look for an input that was accepted before your change and is rejected after it.

Hint 2: a first step

Find the assertion for Borrowing,240 in check.rs, and compare its left and right values with the failure message.

Worked solution

The check for 240 minutes expects Ok(()). With the changed comparison the method returns Err("use 1–240 minutes"), so the assertion fails with that value as left and Ok(()) as right. This proves the checks would catch an off-by-one at the upper boundary. A check with 100 minutes could not have caught it. Restoring the inclusive comparison makes the case pass again.

Restore before you move on

The editor keeps your change until you reload the page. Rerun the checks after every mutation and only continue once you see Planner checks passed again.

Practice

Exercise

Close a gap

Two inputs are not checked yet: Review,-5 and Review, with nothing after the comma. Predict what add_line returns for each, then add both to the list of bad inputs in check.rs and run. Finally, try a mutation the new cases should catch: change Err(_) => return Err("enter a whole number") so it returns "use 1–240 minutes" instead.

Hint 1: the idea

A u32 cannot hold a minus sign, and an empty string is not a number, so both fail at the parsing step, not at the range check.

Hint 2: a first step

Each entry in the list is a pair: ("Review,-5", "enter a whole number"),.

Worked solution

Add these two pairs inside the list of bad inputs:

Rust
("Review,-5", "enter a whole number"),
("Review,", "enter a whole number"),

Both fail to parse, so add_line returns Err("enter a whole number"), and the loop also confirms the length and total stay unchanged. With the mutation, the run stops at the first case on that branch, Review,later, reporting left: Err("use 1–240 minutes"). A run always stops at the first failed assertion. Delete the Review,later pair for a moment and run again: your new cases now catch the mutation on their own. Put the pair back and restore planner.rs when you are done.

Was this article helpful?

Your response is saved on this device.