Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 6: Errors, modules, and tests

Objectives: LO-6.1, LO-6.2, LO-6.3
Prerequisites: the Module 6 reading, Lab 5, and busted, installed as setting up describes
Time: about 2 hours

You will sort the standard library’s failures into errors and nil results, write a function that classifies any failure, turn a script full of globals into a module, and write busted tests for it. The last check grades your tests the way the reading suggests: it breaks the module in four ways, and your tests must catch every one. As in the earlier labs, each check cell prints passed or fails with a message, and the checks fail until you finish their exercise.

Setup

Nothing in this lab is random. The first cell finds busted, which runs in a terminal process of its own, outside the notebook. If it prints not found, follow setting up before section 3. The second cell prints the Lua version, which should be Lua 5.4.

1. Errors and nil results

Run the next cell. It calls check_age from a chunk named caller, once with each error level, and prints the message pcall caught. Compare each message’s position with the level that made it, then change a level and run it again.

Level 1 names cell:3, the line in this cell that calls error. Level 2 names caller:1, the line that called check_age, which is the line to fix. Level 0 names no line.

Exercise L6.1 (LO-6.1, ★, about 10 minutes)

Each call below fails. Predict how: replace each "?" with "error" if it raises an error, or "nil" if it returns nil. Use the reading’s rule: a mistake in the calling code raises an error, and an expected failure returns nil.

Exercise L6.2 (LO-6.1, ★★, about 15 minutes)

Write classify(fn, ...), which calls fn with the remaining arguments in protected mode and returns exactly two values that say how the call went:

The call…classify returns
raised an error"error" and the error value
returned nil as its first result, or no results"failure" and the second result, the message, if any
returned anything else first, false included"ok" and the first result
Hint

table.pack(pcall(fn, ...)) keeps every result of the call, in order, after pcall’s own true or false.

pcall loses the stack the error came from; xpcall with debug.traceback keeps it. Run this cell and read the traceback from the top: the first line is the error, and the lines under it are the calls that led there, innermost first. The last two lines belong to lualab, which runs each cell inside an xpcall of its own; in a script run with lua, the list ends with the main chunk and [C]: in ?.

2. From a script to a module

This script reads sensor readings, one name=value per line, and prints how many were good, their mean, and how many lines were bad. It works, but every variable is global, and nothing in it can be reused or tested. Run it.

Exercise L6.3 (LO-6.2, LO-6.1, ★★, about 30 minutes)

Turn the script into the module scratch/readings.lua, by finishing the cell below. Running the cell writes the file. The module creates no globals, and returns a table with three functions:

  • readings.parse_line(line) returns the name and the value of a line name=value, where the name is letters, digits, and underscores, and the value is a number. For any other line, it returns nil and the message "bad line: " followed by the line.

  • readings.mean(values) returns the mean of a non-empty sequence of numbers. If values is empty or isn’t a table, it raises the error "mean: expected a non-empty list" at level 2.

  • readings.summary(text) returns a table { count = …, mean = …, bad = … } for the non-empty lines of text: the number of good lines, their mean, and the number of bad lines. When no line is good, mean is nil, and summary raises no error.

Which kind of failure should each function report, and why? The statement chooses for you; make sure you can say why.

Hint

Have summary call readings.parse_line and readings.mean, so that each rule lives in one place. Check for an empty list before calling mean.

The check adds ./scratch/?.lua to package.path, so that require("readings") finds your file, and clears package.loaded.readings, so that it loads the file as it is now. When you change the module, run its cell again to rewrite the file, then run the check.

Two more things to try before you go on. The next cell asks Lua where it would find the module, without loading it, then lists the module’s functions. Change the module’s cell, for example by adding a print at its top, rerun that cell, and run this one twice: once as it is, and once after uncommenting the line that clears the cache. Only the second run shows your print.

3. Tests with busted

Exercise L6.4 (LO-6.3, ★★★, about 35 minutes)

Finish the spec file scratch/readings_spec.lua in the cell below, and run the cell to write it. The first test is done for you. Add tests until every promise in Exercise L6.3’s statement is tested: each function’s normal results, the edges, and each failure, with its message.

The check runs your tests twice over. First against your module, where every test must pass. Then against four broken versions of it, each made by wrapping your module and changing one behavior; for each one, at least one of your tests must fail. The check names the broken versions your tests miss, but not how they are broken: work that out from what your tests don’t yet check.

Hint

Go through the statement of Exercise L6.3 sentence by sentence. Each sentence that says what a function returns or raises needs a test. assert.has_error(function() … end, "message") tests an error, and assert.are.same compares whole tables.

Run your tests on your module, and read busted’s report:

The check writes the four broken versions to scratch/broken/, runs your tests against each one, and reports which your tests caught.

Summary

  • The standard library raises errors for mistakes in the calling code and returns nil for failures the caller should expect, and classify can tell the two apart with pcall.

  • error(msg, 2) names the caller’s line, which is the line to fix.

  • A module is a file that returns a table and creates no globals; require finds it through package.path and keeps it in package.loaded, so a changed file needs the cache cleared.

  • busted runs describe and it blocks. A test suite is good when breaking the code makes it fail: tests of the normal case alone missed some of the broken versions.

Next, do the Module 6 practice, then finish PA3.