Up to now you have checked programs by running them and reading the output. That works once, but it does not scale: after every change you would have to remember what each line should say and read it all again. An assertion writes the expectation into the program. assert_eq!(actual, expected) does nothing when the two values are equal and stops the program with a panic when they differ, printing both values. A success message after all the assertions then means every check passed.
The browser shows the panic message and marks the run as failed. You will use exactly this to prove the study planner's rules on Day 7.
Predict and run
Do all three assertions pass? What text will appear if they do?
fn qualifies(minutes: u32) -> bool {
minutes >= 20
}
fn main() {
assert_eq!(qualifies(19), false);
assert_eq!(qualifies(20), true);
assert_eq!(qualifies(21), true);
println!("Checks passed");
}Check your prediction
Checks passedAll three pass, so the program reaches the last line. Now replace >= with > and run. The second assertion fails and the program stops before the success message:
assertion `left == right` failed
left: false
right: trueleft is the first argument, the actual result of qualifies(20), and right is the expected value. The message also gives the line number of the failed assertion. Restore the rule.
Say what a check means
A bare left: false, right: true tells you what differed but not why it matters. Both assert_eq! and assert! accept a message after the values, written like a println! format string. assert!(condition) checks that something is true, which reads better than comparing with true. assert_ne! checks that two values differ.
fn label(minutes: u32) -> &'static str {
if minutes >= 60 { "long" } else { "short" }
}
fn main() {
let durations = vec![25, 60];
assert!(durations.len() == 2, "expected two sessions, found {}", durations.len());
assert_eq!(label(59), "short", "59 minutes is below the long limit");
assert_eq!(label(60), "long", "60 minutes counts as long");
assert_ne!(label(25), label(60));
println!("Label checks passed");
}Label checks passedWhen a check with a message fails, the message is the first thing in the report, so a reader knows which promise broke without opening the code. Change the second check to expect "long" for 59 and run it. The program stops with:
assertion `left == right` failed: 59 minutes is below the long limit
left: "short"
right: "long"assert_eq! puts your message on the same line as assertion ... failed, then prints the two values. assert! prints only your message: with a third duration in the vector, the first check stops the program with expected two sessions, found 3 and nothing else. Above either report, Rust prints the file and line of the failed check, after panicked at.
Pick cases that catch mistakes
An assertion only helps if a plausible bug would make it fail. For a rule with a limit, the bugs hide at the edges: > written instead of >=, a limit off by one, the wrong end of a range. Test each boundary value itself and one step past it on each side. For a range of 1 to 240 that means:
- 0 must be rejected, so a check that forgot the lower bound fails.
- 1 must be accepted, so
> 1instead of>= 1fails. - 240 must be accepted, so
< 240instead of<= 240fails. - 241 must be rejected, so a missing upper bound fails.
fn fits(minutes: u32) -> bool {
minutes >= 1 && minutes <= 240
}
fn main() {
assert!(!fits(0), "0 is too short");
assert!(fits(1), "1 is the shortest allowed");
assert!(fits(240), "240 is the longest allowed");
assert!(!fits(241), "241 is too long");
println!("Range checks passed");
}Range checks passed! means "not", so assert!(!fits(0)) passes when fits(0) is false. A middle value such as 100 would pass with almost any version of the rule, which makes it the least useful check of all.
Break it on purpose
After your checks pass, change the rule in a small, realistic way and run again. If nothing fails, your checks do not cover that mistake yet.
Practice
Your turn
Write checks for a cap of 60 minutes. Check 59, 60 and 61. After the checks pass, change the function temporarily so it always returns its input. Which check catches the mistake?
fn capped(minutes: u32) -> u32 {
if minutes > 60 {
60
} else {
minutes
}
}
fn main() {
// Add three assertions before the success message.
println!("Cap checks passed");
}Hint 1: the idea
At the limit the value stays the same. Above it the value becomes 60.
Hint 2: a first step
Start with assert_eq!(capped(59), 59);.
Worked solution
fn capped(minutes: u32) -> u32 {
if minutes > 60 {
60
} else {
minutes
}
}
fn main() {
assert_eq!(capped(59), 59);
assert_eq!(capped(60), 60);
assert_eq!(capped(61), 60);
println!("Cap checks passed");
}Cap checks passedOnly the 61-minute check catches a function that always returns its input, with left: 61 and right: 60; the other two pass by coincidence. A different slip, capping at 59 instead of 60, fails the 60-minute check first. Each boundary case guards against its own kind of slip, which is why you keep all three.
Completion is saved in this browser only. It does not measure mastery.