Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The Tests Are the Textbook

A first test

This test comes from jemage, a reader for structured data written for blind users. It is in tests/lines.rs.

#![allow(unused)]
fn main() {
#[test]
fn keys_keep_the_authors_order() {
    assert_eq!(
        lines(r#"{"zebra": 1, "apple": 2, "mango": 3}"#),
        ["object, 3 members", "zebra: 1", "apple: 2", "mango: 3"]
    );
}
}

The name states the rule: keys keep the author’s order. The input is one line of JSON with three keys, zebra, apple and mango. The expected output is what a blind reader hears, one line at a time, in the order the author wrote them. (r#"…"# is how Rust writes a string that contains quote marks.)

You don’t need the program’s source code to understand it. The test says what goes in and what comes out.

A second test

This one checks someone else’s code. serde_json is the most widely used JSON library in Rust, and this test, also from jemage, records what it does with the same kind of input. It is in tests/serde_pitfalls.rs.

The file it reads, 01_key_order.json, holds one line:

{"zebra": 1, "mango": 2, "apple": 3}
#![allow(unused)]
fn main() {
// Value stores objects in a BTreeMap: author's order is lost, keys come back
// sorted. With the `preserve_order` feature this test FAILS, correctly.
#[test]
fn key_order_is_sorted_not_preserved() {
    let v: Value = serde_json::from_slice(fixture!("01_key_order.json")).unwrap();
    let keys: Vec<&String> = v.as_object().unwrap().keys().collect();
    assert_eq!(
        keys,
        ["apple", "mango", "zebra"],
        "written as zebra, mango, apple"
    );
}
}

The first line of the test reads the file into serde_json’s general-purpose Value. The second collects the keys. The assertion says they come back as apple, mango, zebra: sorted, not in the order they were written.

Put the two tests side by side. The same three keys go in. jemage gives them back in the author’s order; serde_json sorts them. The library’s documentation does mention this, along with the preserve_order setting that changes it, but the test states it in one line and fails if it ever stops being true.

A third test

HTML has a rule many people never read. It sits in the tokenizer section of the HTML standard: anything that starts with <!, <?, or </ followed by something unexpected is treated as a comment, and that comment ends at the next >. The standard calls these bogus comments.

This test, from jemage’s HTML tokenizer, states the rule with five examples. It is in tests/html_tokenizer.rs.

#![allow(unused)]
fn main() {
#[test]
fn bogus_comments_are_comments_that_run_to_the_next_gt() {
    assert_eq!(
        pieces("<?xml version='1.0'?>x"),
        [(Comment, "<?xml version='1.0'?>"), (Text, "x")]
    );
    assert_eq!(pieces("<!foo>x"), [(Comment, "<!foo>"), (Text, "x")]);
    assert_eq!(pieces("</ x>y"), [(Comment, "</ x>"), (Text, "y")]);
    assert_eq!(pieces("<!foo"), [(Comment, "<!foo")]);
    assert_eq!(pieces("<!"), [(Comment, "<!")]);
}
}

pieces splits the input into labelled pieces. On the left of each line is the input; on the right, the pieces it should become. An XML declaration, <?xml ...?>, becomes a comment. So do <!foo> and </ x>. A bogus comment with no > at all takes everything to the end.

The rule explains something that looks like a bug. CDATA sections, <![CDATA[ ... ]]>, are an XML feature. In ordinary HTML, outside svg and math, a CDATA section starts with <!, so it is a bogus comment, and it ends at the first >, even when that > is inside the data. Run jemage on <p><![CDATA[ a > b ]]></p> and it reports:

Comment  "<![CDATA[ a >"
Text     " b ]]>"

The comment stops in the middle of the data, and the rest shows up as text. The test never mentions CDATA, but it is the rule that explains what happens to it. There is no CDATA test in the suite yet.

Summary

The three tests do three different jobs. The first teaches a rule of the program: keys keep the author’s order. The second records what a library actually does, which is not always what you’d assume. The third states a rule from a long public standard in five lines, and that rule explains a behaviour that otherwise looks like a bug. None of them needs the program’s source code to read.

Building one piece at a time, inside a test

Most of jemage was built this way: one small piece of behaviour, written as a test first, then the code to pass it. My opinion is that it’s the right way to work with a model, with some limits worth knowing.

The advantages:

  • One rule at a time. A test is small enough for a person to check by eye and for a model to get right. When it fails, it names the rule that broke.
  • The test is the spec. Its name says what should happen and its body says exactly what goes in and comes out. A year later, it still says so.
  • Cheap to change your mind. A test that pins the wrong behaviour can be rewritten in minutes, and the code follows.
  • It survives a rewrite. The code can be thrown away and regenerated; the tests decide whether the new version is right.
  • It checks other people’s code too. The serde_json test will fail the day the library changes, and that failure is a finding, not a bug.
  • Small context. A model working on one test and one function reads a few hundred lines, not the whole project.

The disadvantages:

  • Every piece can pass while the whole fails. Tests of single rules don’t show what happens when rules meet. jemage answers this with tests that run whole inputs: a full sample checked against a saved copy of the right output, and a test that glues random fragments of HTML together and checks that nothing is lost.
  • A test can be wrong. A model writes tests confidently, including wrong ones. Check them against something else: a second library, a real file, the standard itself.
  • It pins mistakes as firmly as rules. A test records current behaviour. If the behaviour was a mistake, the test now defends it. jemage marks these on purpose: one test is named known_gap_a_dotted_key_reads_like_a_path, so nobody mistakes it for a rule.
  • It only covers what someone thought of. The bogus-comment test explains CDATA, but there is still no CDATA test.
  • Helpers hide things. pieces makes the HTML tests short, and it also means the reader is trusting pieces.

On balance, I’d still build this way. The disadvantages are reasons to add a few whole-input tests and to check the tests themselves, not reasons to stop.

Divider: star and jewels. A thin horizontal band. A gold line with a dashed turquoise line above and below fades out toward both ends. At the centre is an eight-point gold star between two ruby and two turquoise jewels.