Rust · Chapter 17 of 26
Testing
By the end of this chapter you can write unit tests with #[test], check results with assert!, assert_eq! and assert_ne! and their messages, test that code panics with #[should_panic(expected = ..)], write tests that return Result, keep tests next to the code in a #[cfg(test)] module, run them with cargo test (all of them, some of them by name, and with their printing shown), and write tests that fail when the code is wrong. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real programs
- 4 tasks
- Rust
- In the all labs plan
The first 2 chapters of Rust are free. This one comes with the all labs plan.
Why you need this
Neha pays 4,800 farmers every ten days from what amount works out, can by can, to the nearest paisa. Suppose someone tidies that function one evening and writes ml * per_litre / 1000, which drops the fraction instead of rounding it. Nothing crashes. Every slip still prints. But on Tuesday's pourings alone, 4,436 of the 9,864 accepted cans would earn a paisa less than the rate chart says: ₹44.36 in a day, about ₹440 over a ten-day payout, and a ledger that no longer matches the slips the farmers carry home. The 37 wrong amounts of 12 October were found by Neha, by hand, a day late.
So far you have checked your code by running main and reading what it printed. That works once, for the numbers you happened to try, on the day you wrote it. Nobody reads that output again after the next change, and nothing in main says what the right answer was. A test writes the right answer down next to the question, in code, and cargo test asks every question again in a second, after every change, before the box ever leaves the office.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
amount_tests.rs: tests that catch a wrong rounding
pay.rs holds the code under test. pay::amount(ml: u32, per_litre: u32) -> u64 is what a can earns in whole paise: ml times per_litre divided by 1000, rounded to the nearest paisa, with half a paisa rounding up (14542.4 paise is 14542, 14542.6 and 14542.5 are 14543).
In amount_tests.rs, write tests for amount, each a function marked #[test], using assert_eq! with a message.
The Check runs amount_tests.rs alone with pay.rs: every test must pass with the right amount, and at least one must fail with each of three broken ones: one that drops the fraction of a paisa (truncates), one that always rounds up, and one that rounds exactly half a paisa down. Each broken one is wrong only for some cans, so one test cannot catch all three.
- Task 2
parse_tests.rs: tests for parse errors
pay::parse_line(line: &str) -> Result<Can, String> reads one analyser line, time,farmer,kind,litres,fat,snf ("06:02:07,F10122,cow,4.88,4.2,8.6" is F10122's cow can of 4880 ml, fat 42, snf 86). A line it cannot read gives an Err with a message: an empty line is Err("empty line"); a line with the wrong number of fields is Err("6 fields expected, found 2") for 2 fields; a fat that is not a number, such as ERR, is Err("bad fat: ERR"). pay.rs lists every message.
In parse_tests.rs, write tests: a good line of your own, checking every field of the Can it gives; an empty line; a line cut short; and a line with ERR for fat and SNF, each compared with its whole Err. The good-line test must return Result<(), String> and use ? on parse_line.
The Check runs parse_tests.rs alone with pay.rs: every test must pass with the right parse_line, and at least one must fail with each of four broken ones: one that never says "empty line" (an empty line gives "6 fields expected, found 1"), one that does not count the fields (a cut-short line panics with index out of bounds), one that reads ERR as 0 for fat and SNF, and one that swaps fat and SNF on a good line.
- Task 3
can_tests.rs: a test that expects a panic
pay::Can::new(farmer: &str, kind: Kind, ml: u32, fat: u32, snf: u32) -> Can makes a can, and refuses a can of 0 ml with a panic whose message ends in "nothing was poured" ("a can of 0 ml from F10122: nothing was poured").
In can_tests.rs, write a test marked #[should_panic(expected = "...")] with text from that message, which makes a can of 0 ml; and a test that makes a can under a litre (750 ml, say) and checks its ml.
The Check runs can_tests.rs alone with pay.rs: every test must pass with the right Can::new, and at least one must fail with each of three broken ones: one that accepts 0 ml, one that panics at 0 ml with another message (attempt to divide by zero), and one that also refuses any can under one litre (1000 ml). It also looks for should_panic(expected in can_tests.rs.
- Task 4 · interview question
Interview: slip.rs, tests that live next to the code
slip.rs's slip_line uses rupees(paise: u64) -> String, a private helper: rupees(21084) is "₹210.84", rupees(5) is "₹0.05" and rupees(100) is "₹1.00". No other file can call it.
Write tests for rupees in the tests module at the end of slip.rs, and call rupees directly in at least one of them.
The Check takes your tests module (everything from the line #[cfg(test)] to the end of slip.rs), puts it under the right code and under three broken copies of rupees, and runs cargo test on each: every test must pass on the right one, and at least one must fail on each broken one: one that prints 5 paise as ₹0.5 (no zero in front), one that divides by 1000 instead of 100, and one that leaves out the ₹ sign. Keep the tests module at the end of the file, starting with the line #[cfg(test)].
Farhan will ask: why do Rust's unit tests live in the same file as the code, and what can they reach there that a test in another file cannot?
What you will learn
- #[test]: a function that cargo test runs and reports as ok or FAILED.
- assert!, assert_eq!, assert_ne!: fail a test, with a message that says why.
- #[should_panic(expected = "...")]: a test that passes only when the code panics with that message.
- Tests that return Result: use ? inside a test.
- #[cfg(test)] mod tests: tests that live next to the code, and can reach its private functions.
- cargo test: its output, one test by name, and -- --nocapture.
- A test must be able to fail: run it against broken code too.
More in Real programs
Build "Testing" yourself
DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Rust are free. This one comes with the all labs plan.