You will use
- A list of tuples as a table of cases
loop … in …inside a testassert … as "…"to label each check, andtest skipfor later
The whole program
//// Roman numerals, for clocks and chapter headings.
module roman
numerals() -> List(#(Int, String)) {
[
#(1000, "M"),
#(900, "CM"),
#(500, "D"),
#(400, "CD"),
#(100, "C"),
#(90, "XC"),
#(50, "L"),
#(40, "XL"),
#(10, "X"),
#(9, "IX"),
#(5, "V"),
#(4, "IV"),
#(1, "I")
]
}
/// `number` in Roman numerals. Zero and below have none.
to_roman(number: Int) -> String {
write(number, numerals())
}
write(number: Int, pairs: List(#(Int, String))) -> String {
match pairs {
[] -> ""
[#(value, letters), ..] if number >= value -> letters + write(
number - value,
pairs
)
[_, ..rest] -> write(number, rest)
}
}
module roman_test
import pooka/int
import roman
test "numbers become numerals" {
let cases = [
#(1, "I"),
#(4, "IV"),
#(9, "IX"),
#(14, "XIV"),
#(40, "XL"),
#(90, "XC"),
#(400, "CD"),
#(1987, "MCMLXXXVII"),
#(2026, "MMXXVI"),
#(3999, "MMMCMXCIX")
]
loop case in cases {
let #(number, expected) = case
assert roman.to_roman(number) == expected as int.to_string(number) + " should be " + expected
}
}
test "nothing has no numeral" {
loop number in [0, -1, -50] {
assert roman.to_roman(number) == "" as int.to_string(number)
}
}
test skip "numbers past 3999 need a bar over them" {
assert roman.to_roman(5000) == "V̄"
}
Run it
$ pooka test
Running tests...
• test module: roman_test
✓ numbers become numerals
✓ nothing has no numeral
- numbers past 3999 need a bar over them (skipped)
3 tests, 2 passed, 1 skipped
Get one row wrong, say #(1987, "MCMLXXXVI"), and the label tells you which:
$ pooka test
✗ numbers become numerals
assertion failed: 1987 should be MCMLXXXVI
expected "MCMLXXXVI"
got "MCMLXXXVII"
test/roman.spec.pooka:21
3 tests, 1 passed, 1 failed, 1 skipped
How it works
- The table is data. Each
#(number, expected)is a row. Adding a case means adding a line, not writing a test. - Label every check. Every row runs the same
assert, on the same line, so a line number alone cannot say which row failed. The label can. - The first failure stops the test. Later rows are not checked once one fails, so fix from the top.
test skipwaits patiently. A skipped test is still type-checked, so it cannot rot while it waits for numerals with bars over them.
Try next: add the reverse, from_roman, and test that every number from 1 to 3999 survives the round trip with one loop over list.range(1, 4000).