
These days, nearly everyone has automated tests running in ci. It’s also popular to attempt to measure the effectiveness of the test suite, by seeing how well it covers the code under test. A low number for the measured test coverage means there is business logic that isn’t exercised by tests.
When people measure test coverage, they nearly always measure statement coverage or the more exhaustive branch coverage. Would you be surprised if I told you both are wrong? There is only one type of test coverage that tells us about gaps in the test suite, and it’s called mutation coverage. It’s rarely used.
Mutation coverage is bug detection rate
To compute the mutation coverage for a test suite, we generate large numbers of copies of the code under test. In each copy, we deliberately inject a small bug in the program logic. Here are examples of bugs we can create11 This is a very small list of examples. Others have made longer lists, plus you can retrieve more bugs from your git logs. Find small commits that fix bugs, and then use the reverse of that commit as a bug-producing tweak.:
- Change an operator for a related one, such as turning a + into a -, or a < into a >.
- Delete a method call.
- Change a plain = assignment to an incrementing += assignment, or an incrementing += into a multiplying *=.
- Replace a constant with another, e.g. turning 30 into 0, or the string "none" with "null".
- Modify parts of regexes (such as quantification operators, like swapping * and +, or by switching one character class for another one, like \w into \d.)
- Bypass a null check, or skip a check for the empty sequence.
- Replace a variable reference with another variable.
- Add code that modifies a value used in an expression. For example, if there’s a list reference, append an extra element to it, or reverse it.
- Return an error early in one of the branches of a function.
These injected bugs are called mutations, and the copy of the code with a deliberately injected bug is called a mutant. Once we have produced a mutant, we run the full test suite for it, and if the tests still pass, the mutant is known to have survived. A surviving mutant points to a gap in the tests, because we know there was a bug in the code (we just inserted it), and the tests still all passed.22 There’s a small imprecision here, because a mutation isn’t guaranteed to introduce a bug. Some mutations preserve the behaviour of the program (e.g. because they add an operation that is idempotent with one that was already there), and those mutations aren’t bugs. This means it’s probably unrealistic to aim for 100 % mutation coverage, but every real codebase I’ve tried mutation testing on has had less than something like 40 % mutation coverage, so there’s plenty of room for improvement.
Mutation coverage answers the question “how often does our test suite actually detect bugs?” I think it’s fairly obvious that mutation coverage is the criterion that matters for test coverage.
The expense splitting script
As a concrete example for this article, I want to use one of my favourite scripts of all time, written many years ago by Ward Cunningham. It takes a receipt of costs and expenses made by a group of friends, and works out who is owed how much, by whom, so that contributions are evened out. In less than 15 lines of awk, it parses and produces a text file format that serves as both data storage and convenient user interface.33 This article could have used anything else as an example, but I really want to show off this script. It’s exactly what we should strive toward when we make software. This is what great product decign is: do only what is needed, in a way that lets you get away with as little code as posible.
Keith makes a copy of the script
We’ll pretend someone named Keith has made a copy of this script to handle expenses incurred during a conference he visited with some colleagues. Because he’s a conscientious person, he took the time to add a few automated tests to it. To ensure no gaps in the testing, he measured branch coverage, which is more exhaustive than the more commonly used statement coverage.
Here are the test cases Keith came up with.
- Case 1: SUM adds preceding lines. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 1 apples │ 1.00 apples 2 pears │ 2.00 pears SUM │ 3.00
Case 1: SUM adds preceding lines.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
1 apples │ 1.00 apples
2 pears │ 2.00 pears
SUM │ 3.00
- Case 2: Multiplication and division works. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 10 3 │ 10.00 3 9 / 3 │ 9.00 / 3 SUM │ 33.00
Case 2: Multiplication and division works.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
10 * 3 │ 10.00 * 3
9 / 3 │ 9.00 / 3
SUM │ 33.00
- Case 3: The CR and DB operations negate the amount. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 70 salary │ 70.00 salary 29 CR rent │ 29.00 CR rent 22 DB food │ 22.00 DB food SUM │ 14.00
Case 3: The CR and DB operations negate the amount.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
70 salary │ 70.00 salary
29 CR rent │ 29.00 CR rent
22 DB food │ 22.00 DB food
SUM │ 14.00
- Case 4: Variables store sums and can be recalled. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 5 coffee │ 5.00 coffee COFFEE │ 5.00 │ 7 tea │ 7.00 tea COFFEE │ 5.00
Case 4: Variables store sums and can be recalled.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
5 coffee │ 5.00 coffee
COFFEE │ 5.00
│
7 tea │ 7.00 tea
COFFEE │ 5.00
With these test cases, Keith gets 100 % branch coverage, which implies he also has 100 % statement coverage, and since all tests pass, he assumes he successfully copied the script.
Unfortunately, once he tries using the script, he ends up with wildly incorrect numbers. That means his test suite has gaps and lets through invalid behaviour, despite the complete branch coverage. Mutation testing will reveal where the gaps are.
Mutation generation mechanisms
Some languages have tools that support a high level of automation for mutation testing:
- If we were working on a C# project, for example, we would be able to use Stryker.net.
- For both Java and C there are tools that apply mutations to the underlying jvm bytecode and llvm intermediate representation, respectively.
- There are some tree-sitter based tools as well, but they still need candidate mutations to be configured for each language.
I can’t find any ready-made solution for mutation testing in awk, which fits into a more general pattern: good tooling for mutation testing is rare.
We can, of course, generate mutations by hand. With the right interface, it wouldn’t even be that tedious.44 I’m picturing a hotkey in our editor that saves the current edit in a file as a mutant patch, and then restores the original file again so we can create the next mutant right away. We could easily create hundreds of mutants in a few minutes this way. Even with human-generated mutants, it’s possible the bottleneck is still running the test suite. I get tempted to create an Emacs minor mode that enqueues mutation patches in the background, and collects statistics that get refreshed into a grep buffer for surviving mutants … but that’s a project I can’t take the time for right now. But we could also have a language model generate the mutations for us. It might not do it as well as a human would, but the task is simple enough that even cheaper models are unlikely to mess it up too bad.
One of the benefits of creating mutants by hand – or generating them with language models – is that mutations can be made across languages in a single project. We can inject bugs into templates, browser frontend code, backend logic, model definitions, database queries, infrastructure configuration, etc. all through the same mechanism. We can cover the entire technology stack at once!
Generating mutants with language models
When I do this with language models, I supply instructions that tell the language model to
- Not read the tests, to reduce bias and prevent it from trying to be too clever. Mutation testing works even if the mutations are kind of dumb.
- Come up with N simple ways to edit the code that makes it wrong. I provide some examples of what that might be.55 I also ask for emphasis on mutations that seem like plausible mistakes. When the tests are fast to run, I think it’s better to get a larger set of dumb mutations, but when the tests are slow, higher quality mutations might be an edge. I don’t know. Someone should run the evals.
- Give each mutant a name based on the desired behaviour it breaks. This isn’t an important part of the process, but it’s a trick to make identification and triage easier later.
- Write each mutant as a patch against the current code, and store it in a temporary directory.
- Run a script called mutants.sh with the temporary directory and the command that runs the tests. The mutants.sh script loops through all mutant patches, and for each it applies it, runs the tests, checks for failure, then reverts the patch, and moves on to the next patch.
In the end we get a list of which mutants survived, i.e. which parts of the program logic were not covered by tests. Then we can get to work on adding test cases, or modifying existing test cases, to make sure those parts of the program logic are exercised too.66 A better-performing language model can also be used to help figure out why there are gaps, and propose changes to the test suite to close those gaps. This works reasonably well because the feedback and proofs are all mechanical; there is a specific command we can run to know whether we’ve closed all gaps. This works because mutant coverage is a metric that’s difficult to Goodhart. (No metric is immune, but the easiest way to fix mutant coverage problems is typically to do the right thing.)
Mutation coverage of Keith’s script
Keith learns about mutation testing, and decides to try it to find out where the bug in his copy of the script hides. He thinks of 21 mutants, of which seven survive. This means he measures a mutation coverage of 67 %. Despite the complete branch coverage of his test suite, the amount of program logic covered by tests is only around 2/3.
The following list shows the mutants that survive, i.e. the bugs that make it through his test suite. Note that there’s some overlap between them; I intentionally chose low-quality mutations for this article to illustrate that mutation coverage works even when you don’t spend a lot of effort on generating mutants. It’s a very powerful technique.
- Removing the starting anchor in the regex, i.e. deleting the leading ^ on the first line of the script.
- Removing the ending anchor in the regex, i.e. deleting the trailing $ on the first line of the script.
- Misspelling SUM in the special case condition, e.g. changing "SUM" to "TOTAL" in the second line of the script.
- Forgetting to zero the implicit sum when a variable is defined, i.e. removing the fifth line of the script.
- Changing != 0 to > 0 on the 12th line of the script.
- Removing the clause that resets the sum on a blank line, i.e. deleting the 20th line of the script.
- Changing NF == 0 to NF == 1 on the 20th line of the script.
Keith looks at these bugs, a little surprised that his tests let them through despite the complete branch coverage, and adds a few more test cases.
- Case 5: definitions reset the running total. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 5 coffee │ 5.00 coffee COFFEE │ 5.00 3 tea │ 3.00 tea SUM │ 8.00
Case 5: definitions reset the running total.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
5 coffee │ 5.00 coffee
COFFEE │ 5.00
3 tea │ 3.00 tea
SUM │ 8.00
- Case 6: blank lines reset the running total. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 5 coffee │ 5.00 coffee COFFEE │ 5.00 │ 3 tea │ 3.00 tea SUM │ 3.00
Case 6: blank lines reset the running total.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
5 coffee │ 5.00 coffee
COFFEE │ 5.00
│
3 tea │ 3.00 tea
SUM │ 3.00
- Case 7: single-number lines do not reset the running total. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 5 coffee │ 5.00 coffee COFFEE │ 5.00 4 │ 4.00 SUM │ 9.00
Case 7: single-number lines do not reset the running total.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
5 coffee │ 5.00 coffee
COFFEE │ 5.00
4 │ 4.00
SUM │ 9.00
- Case 8: the SUM variable is computed freshly in each reference. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 1 │ 1.00 SUM │ 1.00 2 │ 2.00 SUM │ 3.00
Case 8: the SUM variable is computed freshly in each reference.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
1 │ 1.00
SUM │ 1.00
2 │ 2.00
SUM │ 3.00
- Case 9: negative totals are formatted with two decimals. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 30 CR rent │ 30.00 CR rent SUM │ -30.00
Case 9: negative totals are formatted with two decimals.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
30 CR rent │ 30.00 CR rent
SUM │ -30.00
- Case 10: values with currency suffixes are numbers. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 12USD │ 12.00 SUM │ 12.00
Case 10: values with currency suffixes are numbers.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
12USD │ 12.00
SUM │ 12.00
- Case 11: variable names must be space delimited. ╭──────────────┬─────────────────────╮ │ INPUT │ EXPECTED OUTPUT │ ╰──────────────┼─────────────────────╯ 5 cookies │ 5.00 cookies FOOD: │ FOOD: SUM │ 5.00
Case 11: variable names must be space delimited.
╭──────────────┬─────────────────────╮
│ INPUT │ EXPECTED OUTPUT │
╰──────────────┼─────────────────────╯
5 cookies │ 5.00 cookies
FOOD: │ FOOD:
SUM │ 5.00
When Keith runs the expanded test suite, it immediately detects the bug in his script. Test case 6 fails, because it prints the final sum as 8.00 instead of the expected 3.00. This is the information Keith needs to find and fix the typo in his copy of the script:
--- a/skitrip.awk
+++ b/skitrip.awk
@@ -19,5 +19,5 @@ $2 == "/" {$1 /= $3}
$2 == "DB" {$1 = -$1}
$2 == "CR" {$1 = -$1}
-NF == 0 {sum == 0} # Implicit Summation
+NF == 0 {sum = 0} # Implicit Summation
{sum += $1}
With this, his script is a correct copy and works.
It is worth pointing out that this specific typo wasn’t one of the mutations he came up with. None of his mutations touched the buggy statement, but that’s also not necessary for mutation testing to work. Mutation testing reveals where bugs can still hide, regardless of what the specific bugs are. The test cases induced by mutation testing will reveal lots of different bugs that can hide in the same place as the surviving mutant.
Start mutation testing today
I think most people agree this is such an obvious way to measure test coverage. We ask literally the one question that matters: how many bugs are detected by our test suite? This is the same idea as the red phase in the tdd mantra of red–green–refactor: if we haven’t seen the tests fail for an incorrect implementation, how can we have any faith in their discriminatory power?77 With the data we get out of the mutation test, we can also grade the effectiveness of individual test cases in our test suite. Maybe some of them aren’t pulling their weight in killing mutants, and we could remove them without losing any power. When that allows us to remove expensive and/or slow test cases, that’s really nice.
Yet! I have never seen mutation testing used in the wild. Not once. I was introduced to it in university, and I, naïve at the time, assumed everyone used it. Then I got out into the workforce and realised people in the industry haven’t even heard of it.
At first I thought cost was the reason it’s unpopular. Both generating mutants (if done by a human), and running the test suite for each of them (if the tests are expensive and/or slow) can seem prohibitive. But on closer inspection, that can’t be the reason. With the right interface, it’s very cheap even for a human to generate a bunch of mutants. And while yes, running the full test suite is often expensive, mutation testing doesn’t require thousands of mutants to be useful.
Even if we can only afford to test one mutant per day, that’s still giving us data we wouldn’t have otherwise. Remember, before we test our first mutant, we have no information on how well our test suite actually detects bugs. That first mutant is the first time we get any information on the quality of our test suite! In terms of value of information, it doesn’t get much better than that.
And once we have tested one mutant, maybe we can upgrade to testing a new mutant once a day. When we have done that for a while, we can measure the cost of testing a mutant, pretend there’s a standard cost of not detecting a bug in the code, and together with our current mutation coverage, we get a specific figure for how many mutants it is economically defensible to test per day.
There’s really no reason to wait. Start mutation testing today. See where it takes you.