Conceptcore
Mutation analysis
Also called mutation testing, program mutation, mutant, mutation score.
Mutation analysis plants small faults, called mutants, in copies of a program and runs the tests on each copy. The share of mutants that make a test fail measures how well the tests find faults.
- Applies to
- core-languages
Idea
A test suite can pass and still miss bugs. Mutation analysis measures how many bugs a suite can find, by planting bugs on purpose. A tool makes many copies of the program. Each copy, called a mutant, differs from the original by one small change, such as >= in place of >. The tool runs the suite on each mutant. If a test fails, the mutant is killed. If every test passes, the mutant lives: the suite cannot tell that program from the original.12
The idea rests on an observation by DeMillo, Lipton and Sayward. Programmers do not write programs at random. They write programs that are close to being correct, and each pass through the design brings the program closer.1 So a real fault is often a small change away from the correct program. The authors added a second claim, the coupling effect: test data that tells apart all programs that differ from a correct one by small errors also tells apart more complex errors. They called it an empirical principle that no one can prove.1 Later work calls the first claim the competent programmer hypothesis.2
The program below is the example from the 1978 paper. argmax returns the index of the first largest item in a list.1 Each mutant is a text replacement in the source, and exec compiles the changed text into a second function. The first suite has the three vectors of the paper, and the second adds one more.
SOURCE = """
def argmax(xs):
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
"""
# Each mutant makes one small change to the source text.
MUTANTS = [
("> to >=", "xs[i] > xs[best]", "xs[i] >= xs[best]"),
("> to <", "xs[i] > xs[best]", "xs[i] < xs[best]"),
("xs[i] to xs[best]", "xs[i] > xs[best]", "xs[best] > xs[best]"),
("start at 0", "range(1,", "range(0,"),
]
WEAK = [([1, 2, 3], 2), ([1, 3, 2], 1), ([3, 1, 2], 0)]
STRONG = WEAK + [([2, 2, 1], 0)]
def load(source):
namespace = {}
exec(source, namespace)
return namespace["argmax"]
def passes(argmax, suite):
return all(argmax(xs) == want for xs, want in suite)
assert passes(load(SOURCE), STRONG), "fix the program before mutating it"
print(f"{'mutant':<20}{'3 tests':<8}4 tests")
killed = {"weak": 0, "strong": 0}
for label, old, new in MUTANTS:
mutant = load(SOURCE.replace(old, new))
row = []
for name, suite in (("weak", WEAK), ("strong", STRONG)):
dead = not passes(mutant, suite)
killed[name] += dead
row.append("killed" if dead else "lived")
print(f"{label:<20}{row[0]:<8}{row[1]}")
total = len(MUTANTS)
print(f"{'killed':<20}{killed['weak']} of {total} {killed['strong']} of {total}")
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
The three tests have no repeated items, so > and >= give the same answer on each of them. The paper found the same gap in its data and added the vector (2, 2, 1).1 With the tie, the first of two equal items must win, and the >= mutant picks the second. The mutant start at 0 lives against both suites. Its extra first pass compares xs[0] with itself, which is never larger, so the mutant computes the same function as the original. The paper concluded that no test data could tell this mutant from MAX, and that test data which leaves only such mutants alive is adequate.1
A live mutant is a question for the programmer. The paper puts it in the voice of the mutation system: "The test data you've given me says it doesn't matter whether or not this test is for equality or inequality; why is that?"1 The answer is either one more test or a proof that the change does not matter.
Mutation analysis measures something that code coverage does not. Line and branch coverage record which code the tests run. They do not check that the tests can detect a fault in that code.3 A unit test that calls a function and checks nothing gives full coverage and kills no mutants. The pitfall "Coverage without checks" shows this.
How it works
Jia and Harman describe the process in five steps.2
- Make the mutants. A mutation operator is a rule that turns one piece of a program into another, such as
<into<=. The tool applies each operator at each place where it fits, and each application gives one mutant. - Run the original. The suite must pass on the original program. If it does not, the program has a known bug, and it must be fixed before mutation starts.
- Run each mutant. If the result of any test differs from the result on the original, the mutant is killed. Otherwise it lives. Jia and Harman also say "survived".
- Find the equivalent mutants. Some mutants differ in syntax from the original but compute the same function. No test can kill them. Program equivalence is undecidable, so no tool can find all of them, and a person must check the rest.
- Compute the score. The mutation score is the number of killed mutants divided by the number of mutants that are not equivalent. A score of 1 means that the suite detects every fault that the mutants stand for.
The operators decide which faults the score can see. PIT has a "conditionals boundary" operator, which swaps < with <= and > with >=, and a "negate conditionals" operator, which swaps == with !=, <= with >, and >= with <.4 mutmut adds 1 to integer literals, changes < to <=, and swaps break with continue.5 cargo-mutants replaces > with == or <, and it can replace a whole function body with a value of the return type, such as 0 or 1 for an unsigned integer.9
The program below makes mutants from the syntax tree, not from the text. It walks the tree of argmax and applies two of PIT's relational rules and the integer rule of mutmut. Each mutant starts from a fresh tree, so that only one change is active at a time.
import ast
SOURCE = """
def argmax(xs):
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
"""
WEAK = [([1, 2, 3], 2), ([1, 3, 2], 1), ([3, 1, 2], 0)]
STRONG = WEAK + [([2, 2, 1], 0)]
# Two relational rules from PIT's default operators.
RELATIONAL = {ast.Gt: [ast.GtE, ast.LtE], ast.Lt: [ast.LtE, ast.GtE]}
def mutations(tree):
"""Lists each (node, change) that the operators allow, in a fixed order."""
found = []
for node in ast.walk(tree):
if isinstance(node, ast.Compare):
for op in RELATIONAL.get(type(node.ops[0]), ()):
found.append((node, op))
elif isinstance(node, ast.Constant) and type(node.value) is int:
found.append((node, node.value + 1)) # mutmut's rule for integers
return found
def load(tree):
namespace = {}
exec(compile(ast.fix_missing_locations(tree), "<mutant>", "exec"), namespace)
return namespace["argmax"]
def passes(argmax, suite):
return all(argmax(xs) == want for xs, want in suite)
assert passes(load(ast.parse(SOURCE)), STRONG)
count = len(mutations(ast.parse(SOURCE)))
for k in range(count):
tree = ast.parse(SOURCE) # a fresh tree for each mutant
node, change = mutations(tree)[k]
before = ast.unparse(node)
if isinstance(node, ast.Compare):
node.ops = [change()]
else:
node.value = change
argmax = load(tree)
weak = "killed" if not passes(argmax, WEAK) else "lived"
strong = "killed" if not passes(argmax, STRONG) else "lived"
print(f"line {node.lineno - 1}: {before} -> {ast.unparse(node)}: 3 tests {weak}, 4 tests {strong}")
line 2: 0 -> 1: 3 tests killed, 4 tests killed
line 3: 1 -> 2: 3 tests killed, 4 tests killed
line 4: xs[i] > xs[best] -> xs[i] >= xs[best]: 3 tests lived, 4 tests killed
line 4: xs[i] > xs[best] -> xs[i] <= xs[best]: 3 tests killed, 4 tests killed
The operators made four mutants, and the fourth test kills all of them. They did not make the equivalent mutant start at 0, because the integer rule only adds 1. A different set of operators gives a different set of mutants and a different score for the same tests.
Where the change is made. A tool can change the source text, the syntax tree, or the compiled code. mutmut changes Python source.5 PIT changes the bytecode that the Java compiler made. Its documentation says that this is in general much faster and easier to add to a build, but that a bytecode change can be hard to describe as a change in the source.4 Mull is built on LLVM.10
One build for all mutants. In a compiled language, a separate build for each mutant costs a compile for each one. The mutant schema technique writes one program that holds every mutant, and a switch picks the active one at run time. The compile happens once.2 The examples for the compiled languages on this page use a schema: a global variable or a parameter selects the mutant.
States beyond killed and lived. Stryker uses more states. A mutant has "no coverage" when no test runs its code. A run that hits a timeout counts as detected, because an infinite loop would also stop a build. A mutant that ends in a compile error or a runtime error of the test runner is invalid and is not in the score. Stryker computes the score as detected mutants divided by valid mutants, times 100.6
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Library | |
| C++ | Library | |
| Java | Library | |
| C | Library | |
| C# | Library | |
| JavaScript | Library | |
| TypeScript | Library | |
| Go | Library | |
| Rust | Library | |
| Kotlin | Library | The Kotlin standard library and Gradle have no mutation tool. Alternative: PIT mutates JVM bytecode, and arcmutate, from the PIT team, extends it with support for Kotlin. |
| SQL | Does not apply | Queries are tested through the program or the database that runs them. |
| Bash | Idiom | Bash has no mutation tool. Alternative: A script that edits a copy of the source with sed, runs the tests and checks the exit status. |
| PowerShell | Idiom | PowerShell has no mutation tool in the language or its core modules. Alternative: A script that edits a copy of the source, runs the tests and checks the result. |
| HTML | Does not apply | Markup has no test suite to measure in this sense. |
| CSS | Does not apply | Style rules have no test suite to measure in this sense. |
| Regular expressions | Does not apply | A pattern is tested through the program that uses it. |
Mutation analysis is a tool, not a language feature. No tier 1 language has it in its standard toolchain. The examples write a small mutation harness in each language with the same four mutants of argmax, so the tables can be compared.
| Language | Verdict | Form |
|---|---|---|
| Python | library | mutmut, which mutates the source and runs pytest5 |
| JavaScript | library | StrykerJS7 |
| TypeScript | library | StrykerJS7 |
| Java | library | PIT, which mutates bytecode34 |
| C | library | Mull, built on LLVM10 |
| C++ | library | Mull10 |
| C# | library | Stryker.NET7 |
| Go | library | Gremlins11 |
| Rust | library | cargo-mutants, run as cargo mutants89 |
| Kotlin | library | PIT works on JVM bytecode; arcmutate, from the same team, extends PIT with support for Kotlin3 |
| PowerShell | idiom | a script that edits a copy of the source, runs the tests and checks the result |
| Bash | idiom | a script that edits a copy of the source, runs the tests and checks the exit status |
| SQL | n/a | queries are tested through the program or the database that runs them |
| Regex | n/a | a pattern is tested through the program that uses it |
| HTML/CSS | n/a | markup and style rules have no test suite to measure in this sense |
The languages differ in how a harness can make a mutant. Python and JavaScript can compile changed source text at run time, with exec and new Function. In the compiled languages, the examples build all mutants into one program.
The languages also differ in which mutants reach the tests. A type checker rejects some mutants before any test runs. Rust has no unary minus for usize, so that mutant does not compile, and cargo-mutants calls such a mutant "unviable".9 mutmut can use mypy or pyrefly to remove mutants that do not type check.5 In C and C++, a mutant can read past the end of an array. The read is undefined behavior, so the mutant may live or die by chance, unless a sanitizer stops it.
import io
import unittest
MUTANT = 0 # 0 runs the original code; 1 to 4 each switch on one change.
NAMES = {1: "> to >=", 2: "> to <", 3: "xs[i] to xs[best]", 4: "start at 0"}
def argmax(xs):
"""Returns the index of the first largest item of a non-empty list."""
best = 0
for i in range(0 if MUTANT == 4 else 1, len(xs)):
left = xs[best] if MUTANT == 3 else xs[i]
match MUTANT:
case 1:
bigger = left >= xs[best]
case 2:
bigger = left < xs[best]
case _:
bigger = left > xs[best]
if bigger:
best = i
return best
class Weak(unittest.TestCase):
def test_largest_last(self):
self.assertEqual(argmax([1, 2, 3]), 2)
def test_largest_in_middle(self):
self.assertEqual(argmax([1, 3, 2]), 1)
def test_largest_first(self):
self.assertEqual(argmax([3, 1, 2]), 0)
class Strong(Weak):
def test_tie_goes_to_first(self):
self.assertEqual(argmax([2, 2, 1]), 0)
def passes(case):
tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
result = unittest.TextTestRunner(stream=io.StringIO()).run(tests)
return result.wasSuccessful()
assert passes(Strong), "the original program must pass first"
print(f"{'mutant':<20}{'3 tests':<8}4 tests")
killed = {Weak: 0, Strong: 0}
for MUTANT, name in NAMES.items():
cells = []
for case in (Weak, Strong):
dead = not passes(case)
killed[case] += dead
cells.append("killed" if dead else "lived")
print(f"{name:<20}{cells[0]:<8}{cells[1]}")
print(f"{'killed':<20}{killed[Weak]} of 4 {killed[Strong]} of 4")
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. Python has no mutation tool in the standard library. mutmut is a mutation tool for Python, and it runs the tests with pytest.
- The program is a mutant schema: one copy of
argmaxholds every mutant, and the globalMUTANTpicks one. Thefor MUTANT, name in ...loop at module level assigns the global, soargmaxsees each value in turn. Stronginherits the three tests ofWeakand adds one. Aunittestrunner with aStringIOstream runs a suite quietly, andwasSuccessful()gives the verdict for one mutant.- The tie
[2, 2, 1]kills> to >=. No test can killstart at 0, because the extra pass comparesxs[0]with itself. mutmut can skip such a line with the comment# pragma: no mutate.
#include <array>
#include <cstddef>
#include <print>
#include <span>
#include <string_view>
#include <vector>
enum class Mutant { None, GtToGe, GtToLt, LeftToBest, StartAt0 };
// Each mutant is a separate instantiation; if constexpr drops the other branches.
template <Mutant M>
std::size_t argmax(std::span<const int> xs) {
std::size_t best = 0;
for (std::size_t i = M == Mutant::StartAt0 ? 0 : 1; i < xs.size(); ++i) {
int left = M == Mutant::LeftToBest ? xs[best] : xs[i];
bool bigger;
if constexpr (M == Mutant::GtToGe) {
bigger = left >= xs[best];
} else if constexpr (M == Mutant::GtToLt) {
bigger = left < xs[best];
} else {
bigger = left > xs[best];
}
if (bigger) {
best = i;
}
}
return best;
}
struct Case {
std::vector<int> xs;
std::size_t want;
};
template <Mutant M>
bool passes(std::span<const Case> suite) {
for (const Case& c : suite) {
if (argmax<M>(c.xs) != c.want) {
return false;
}
}
return true;
}
int main() {
const std::vector<Case> strong{{{1, 2, 3}, 2}, {{1, 3, 2}, 1}, {{3, 1, 2}, 0}, {{2, 2, 1}, 0}};
const std::span<const Case> weak = std::span(strong).first(3);
if (!passes<Mutant::None>(strong)) {
std::println("the original must pass first");
return 1;
}
struct Row {
std::string_view name;
bool (*passes)(std::span<const Case>);
};
const std::array<Row, 4> rows{{
{"> to >=", passes<Mutant::GtToGe>},
{"> to <", passes<Mutant::GtToLt>},
{"xs[i] to xs[best]", passes<Mutant::LeftToBest>},
{"start at 0", passes<Mutant::StartAt0>},
}};
std::println("{:<20}{:<8}4 tests", "mutant", "3 tests");
int weak_killed = 0, strong_killed = 0;
for (const Row& row : rows) {
const bool weak_dead = !row.passes(weak), strong_dead = !row.passes(strong);
weak_killed += weak_dead;
strong_killed += strong_dead;
std::println("{:<20}{:<8}{}", row.name, weak_dead ? "killed" : "lived", strong_dead ? "killed" : "lived");
}
std::println("{:<20}{} of 4 {} of 4", "killed", weak_killed, strong_killed);
}
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. The C++ standard library has no mutation tool. Mull mutates C and C++ programs through LLVM.
- The mutant is a template argument, not a run-time value.
argmax<Mutant::GtToGe>andargmax<Mutant::None>are two different functions, andif constexprdrops the branches that do not apply. This is close to what a tool does when it builds each mutant as a separate program, but the compiler runs only once. passes<Mutant::GtToGe>is an ordinary function, so its address fits in the tablerows. The loop then treats the mutants as data.std::span(strong).first(3)is the weak suite: a view of the first three cases, with no copy.
import java.util.ArrayList;
import java.util.List;
public class Main {
// The first two names are PIT mutators; the other two change a variable and a constant.
enum Mutant { NONE, CONDITIONALS_BOUNDARY, NEGATE_CONDITIONALS, COMPARE_BEST_TO_BEST, START_AT_0 }
record Case(int[] xs, int want) {}
static int argmax(int[] xs, Mutant m) {
int best = 0;
for (int i = m == Mutant.START_AT_0 ? 0 : 1; i < xs.length; i++) {
int left = m == Mutant.COMPARE_BEST_TO_BEST ? xs[best] : xs[i];
boolean bigger = switch (m) {
case CONDITIONALS_BOUNDARY -> left >= xs[best];
case NEGATE_CONDITIONALS -> left <= xs[best];
default -> left > xs[best];
};
if (bigger) {
best = i;
}
}
return best;
}
static boolean passes(Mutant m, List<Case> suite) {
return suite.stream().allMatch(c -> argmax(c.xs(), m) == c.want());
}
public static void main(String[] args) {
List<Case> weak = List.of(
new Case(new int[] {1, 2, 3}, 2),
new Case(new int[] {1, 3, 2}, 1),
new Case(new int[] {3, 1, 2}, 0));
List<Case> strong = new ArrayList<>(weak);
strong.add(new Case(new int[] {2, 2, 1}, 0));
if (!passes(Mutant.NONE, strong)) {
throw new AssertionError("the original must pass first");
}
System.out.printf("%-24s%-8s%s%n", "mutant", "3 tests", "4 tests");
int weakKilled = 0, strongKilled = 0;
for (Mutant m : Mutant.values()) {
if (m == Mutant.NONE) {
continue;
}
boolean weakDead = !passes(m, weak), strongDead = !passes(m, strong);
weakKilled += weakDead ? 1 : 0;
strongKilled += strongDead ? 1 : 0;
System.out.printf("%-24s%-8s%s%n", m, weakDead ? "killed" : "lived", strongDead ? "killed" : "lived");
}
System.out.printf("%-24s%d of 4 %d of 4%n", "killed", weakKilled, strongKilled);
}
}
mutant 3 tests 4 tests
CONDITIONALS_BOUNDARY lived killed
NEGATE_CONDITIONALS killed killed
COMPARE_BEST_TO_BEST killed killed
START_AT_0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. The JDK has no mutation tool. PIT is the common one for Java and the JVM.
- The first two mutants use PIT's rules.
CONDITIONALS_BOUNDARYturns>into>=.NEGATE_CONDITIONALSturns>into<=, not<, so this row differs from the Python table. Both rules are on by default in PIT. - PIT changes the bytecode that the compiler made, not the source. Its documentation says that this is in general much faster and easier to add to a build, but that a bytecode change can be hard to map back to a change in the source.
- The
switchexpression over the enum is the mutant schema. Adefaultbranch keeps the original>for the other mutants.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
enum { ORIGINAL, GT_TO_GE, GT_TO_LT, LEFT_TO_BEST, START_AT_0, COUNT };
static const char *const names[COUNT] = {"original", "> to >=", "> to <", "xs[i] to xs[best]", "start at 0"};
static int mutant = ORIGINAL;
/* Returns the index of the first largest item; n must be at least 1. */
static size_t argmax(const int *xs, size_t n) {
size_t best = 0;
for (size_t i = mutant == START_AT_0 ? 0 : 1; i < n; i++) {
int left = mutant == LEFT_TO_BEST ? xs[best] : xs[i];
bool bigger;
switch (mutant) {
case GT_TO_GE: bigger = left >= xs[best]; break;
case GT_TO_LT: bigger = left < xs[best]; break;
default: bigger = left > xs[best]; break;
}
if (bigger) {
best = i;
}
}
return best;
}
struct test { int xs[3]; size_t want; };
static const struct test suite[] = {{{1, 2, 3}, 2}, {{1, 3, 2}, 1}, {{3, 1, 2}, 0}, {{2, 2, 1}, 0}};
static bool passes(size_t tests) {
for (size_t t = 0; t < tests; t++) {
if (argmax(suite[t].xs, 3) != suite[t].want) {
return false;
}
}
return true;
}
int main(void) {
const size_t weak = 3, strong = 4; /* the strong suite adds the tie */
if (!passes(strong)) {
fprintf(stderr, "the original must pass first\n");
return 1;
}
printf("%-20s%-8s4 tests\n", "mutant", "3 tests");
int weak_killed = 0, strong_killed = 0;
for (mutant = GT_TO_GE; mutant < COUNT; mutant++) {
bool weak_dead = !passes(weak), strong_dead = !passes(strong);
weak_killed += weak_dead;
strong_killed += strong_dead;
printf("%-20s%-8s%s\n", names[mutant], weak_dead ? "killed" : "lived", strong_dead ? "killed" : "lived");
}
printf("%-20s%d of 4 %d of 4\n", "killed", weak_killed, strong_killed);
return 0;
}
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. The C standard library has no mutation tool. Mull is a mutation testing tool for C and C++ built on LLVM.
- The global
mutantand theswitchform the mutant schema. One build holds all the mutants, so the program compiles once. Theforloop inmainsets the global and runs both suites for each mutant. boolfrom<stdbool.h>converts to1or0when it is added to anint, soweak_killed += weak_deadcounts the kills.
In C, a mutant can make the program read past the end of an array. The read is undefined behavior. In a plain build the mutant below can give the right answers on all four tests and live. It did so on a Clang build without the sanitizer when this page was written. AddressSanitizer stops it at the first bad read, so a mutation run with the sanitizer kills it.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The mutant: the loop test i < n became i <= n. */
static size_t argmax(const int *xs, size_t n) {
size_t best = 0;
for (size_t i = 1; i <= n; i++) {
if (xs[i] > xs[best]) {
best = i;
}
}
return best;
}
int main(void) {
const int cases[][3] = {{1, 2, 3}, {1, 3, 2}, {3, 1, 2}, {2, 2, 1}};
for (size_t t = 0; t < 4; t++) {
int *xs = malloc(sizeof cases[t]); /* exactly three ints, as a caller would pass */
memcpy(xs, cases[t], sizeof cases[t]);
printf("argmax = %zu\n", argmax(xs, 3));
free(xs);
}
return 0;
}
- The mutant changes
i < nintoi <= n, the boundary rule that PIT and other tools apply to<. On the last pass it readsxs[3]. - Each test array is a heap copy of exactly three
intvalues, so the sanitizer sees the read as a heap buffer overflow. Without the sanitizer, the byte after the array decides the result, and a mutation run can report this mutant as lived on one machine and killed on another.
using System;
using System.Collections.Generic;
using System.Linq;
(int[] Xs, int Want)[] weak = [([1, 2, 3], 2), ([1, 3, 2], 1), ([3, 1, 2], 0)];
(int[] Xs, int Want)[] strong = [.. weak, ([2, 2, 1], 0)];
bool Passes(Mutant m, (int[] Xs, int Want)[] suite) =>
suite.All(c => Search.Argmax(c.Xs, m) == c.Want);
if (!Passes(Mutant.None, strong))
{
throw new InvalidOperationException("the original must pass first");
}
Console.WriteLine($"{"mutant",-20}{"3 tests",-8}4 tests");
int weakKilled = 0, strongKilled = 0;
foreach (var m in Enum.GetValues<Mutant>().Skip(1))
{
bool weakDead = !Passes(m, weak), strongDead = !Passes(m, strong);
weakKilled += weakDead ? 1 : 0;
strongKilled += strongDead ? 1 : 0;
Console.WriteLine($"{Search.Names[m],-20}{(weakDead ? "killed" : "lived"),-8}{(strongDead ? "killed" : "lived")}");
}
Console.WriteLine($"{"killed",-20}{weakKilled} of 4 {strongKilled} of 4");
enum Mutant { None, GtToGe, GtToLt, LeftToBest, StartAt0 }
static class Search
{
public static readonly Dictionary<Mutant, string> Names = new()
{
[Mutant.GtToGe] = "> to >=",
[Mutant.GtToLt] = "> to <",
[Mutant.LeftToBest] = "xs[i] to xs[best]",
[Mutant.StartAt0] = "start at 0",
};
// Returns the index of the first largest item of a non-empty array.
public static int Argmax(int[] xs, Mutant m)
{
int best = 0;
for (int i = m == Mutant.StartAt0 ? 0 : 1; i < xs.Length; i++)
{
int left = m == Mutant.LeftToBest ? xs[best] : xs[i];
bool bigger = m switch
{
Mutant.GtToGe => left >= xs[best],
Mutant.GtToLt => left < xs[best],
_ => left > xs[best],
};
if (bigger)
{
best = i;
}
}
return best;
}
}
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. .NET has no mutation tool in the SDK. Stryker.NET is the Stryker tool for C#.
- The
switchexpression on the enum is the mutant schema. The discard arm_keeps the original>for every other mutant. [.. weak, ([2, 2, 1], 0)]is a collection expression with a spread, so the strong suite is the weak suite plus the tie.- Stryker reports a mutant that does not compile as a compile error and leaves it out of the mutation score. A run of the tests that ends in a timeout counts as detected.
function argmax(xs) {
let best = 0;
for (let i = 1; i < xs.length; i++) {
if (xs[i] > xs[best]) best = i;
}
return best;
}
// Each mutant replaces one piece of the source text of argmax.
const MUTANTS = [
["> to >=", "xs[i] > xs[best]", "xs[i] >= xs[best]"],
["> to <", "xs[i] > xs[best]", "xs[i] < xs[best]"],
["xs[i] to xs[best]", "xs[i] > xs[best]", "xs[best] > xs[best]"],
["start at 0", "let i = 1", "let i = 0"],
];
const weak = [[[1, 2, 3], 2], [[1, 3, 2], 1], [[3, 1, 2], 0]];
const strong = [...weak, [[2, 2, 1], 0]];
const passes = (f, suite) => suite.every(([xs, want]) => f(xs) === want);
const load = (text) => new Function(`return (${text});`)();
const source = argmax.toString();
if (!passes(load(source), strong)) throw new Error("the original must pass first");
console.log("mutant".padEnd(20) + "3 tests".padEnd(8) + "4 tests");
const killed = { weak: 0, strong: 0 };
for (const [name, from, to] of MUTANTS) {
const mutant = load(source.replace(from, to));
const cells = [];
for (const [label, suite] of [["weak", weak], ["strong", strong]]) {
const dead = !passes(mutant, suite);
if (dead) killed[label]++;
cells.push(dead ? "killed" : "lived");
}
console.log(name.padEnd(20) + cells[0].padEnd(8) + cells[1]);
}
console.log("killed".padEnd(20) + `${killed.weak} of 4 ${killed.strong} of 4`);
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. JavaScript has no mutation tool in the language or in Node.js. StrykerJS mutates JavaScript and TypeScript.
toStringon a function defined in source returns the source text of the function.new Functioncompiles a changed copy at run time. So a JavaScript program can make its own mutants from text, as a mutation tool for a dynamic language does.- The output matches the Python table: the tie
[2, 2, 1]kills> to >=, andstart at 0lives because it is an equivalent mutant.
A function made by new Function sees only the global scope, not the module scope. Here argmax reads the module constant START, so the mutant code throws ReferenceError. The harness counts the exception as a failed test.
This code runs but gives a wrong answer on purpose.
const START = 1;
function argmax(xs) {
let best = 0;
for (let i = START; i < xs.length; i++) {
if (xs[i] > xs[best]) best = i;
}
return best;
}
const MUTANTS = [
["> to >=", "xs[i] > xs[best]", "xs[i] >= xs[best]"],
["> to <", "xs[i] > xs[best]", "xs[i] < xs[best]"],
["start at 0", "let i = START", "let i = 0"],
];
const weak = [[[1, 2, 3], 2], [[1, 3, 2], 1], [[3, 1, 2], 0]];
// Any exception counts as a failed test, so any exception kills the mutant.
const passes = (f, suite) => {
try {
return suite.every(([xs, want]) => f(xs) === want);
} catch {
return false;
}
};
const load = (text) => new Function(`return (${text});`)();
const source = argmax.toString();
for (const [name, from, to] of MUTANTS) {
const dead = !passes(load(source.replace(from, to)), weak);
console.log(`${name}: ${dead ? "killed" : "lived"}`);
}
> to >=: killed
> to <: killed
start at 0: lived
> to >=now shows as killed, though the weak suite has no tie. TheReferenceErrorkilled it, not a test.start at 0lives only because the mutation removed the reference toSTART.- The original code, loaded the same way, throws the same error. A harness that first runs the suite on the unchanged program finds this at once. Stryker puts a mutant that ends in a runtime error outside the mutation score, and does not count it as killed.
type Mutant = "none" | "> to >=" | "> to <" | "xs[i] to xs[best]" | "start at 0";
const MUTANTS: Exclude<Mutant, "none">[] = ["> to >=", "> to <", "xs[i] to xs[best]", "start at 0"];
function bigger(m: Mutant, a: number, b: number): boolean {
switch (m) {
case "> to >=":
return a >= b;
case "> to <":
return a < b;
case "none":
case "xs[i] to xs[best]":
case "start at 0":
return a > b;
default: {
const unreachable: never = m; // a new mutant name must be handled above
return unreachable;
}
}
}
// argmax with every mutant built in; m picks which one is active.
function argmax(xs: readonly number[], m: Mutant = "none"): number {
let best = 0;
for (let i = m === "start at 0" ? 0 : 1; i < xs.length; i++) {
const left = m === "xs[i] to xs[best]" ? xs[best] : xs[i];
if (bigger(m, left, xs[best])) best = i;
}
return best;
}
type Case = [xs: number[], want: number];
const weak: Case[] = [[[1, 2, 3], 2], [[1, 3, 2], 1], [[3, 1, 2], 0]];
const strong: Case[] = [...weak, [[2, 2, 1], 0]];
const passes = (m: Mutant, suite: Case[]): boolean => suite.every(([xs, want]) => argmax(xs, m) === want);
if (!passes("none", strong)) throw new Error("the original must pass first");
console.log("mutant".padEnd(20) + "3 tests".padEnd(8) + "4 tests");
const killed = { weak: 0, strong: 0 };
for (const m of MUTANTS) {
const weakDead = !passes(m, weak);
const strongDead = !passes(m, strong);
killed.weak += Number(weakDead);
killed.strong += Number(strongDead);
console.log(m.padEnd(20) + (weakDead ? "killed" : "lived").padEnd(8) + (strongDead ? "killed" : "lived"));
}
console.log("killed".padEnd(20) + `${killed.weak} of 4 ${killed.strong} of 4`);
mutant 3 tests 4 tests
> to >= lived killed
> to < killed killed
xs[i] to xs[best] killed killed
start at 0 lived lived
killed 2 of 4 3 of 4
- Verdict: library. TypeScript has no mutation tool of its own. StrykerJS mutates TypeScript as well as JavaScript.
- The mutant names form a union of string literal types. The
defaultbranch assignsmto a variable of typenever, so the type checker rejects the program if a name is added toMutantand not handled inbigger. argmaxtakes the mutant as a parameter, not as a global. Each call states which mutant it runs, so the tests of two mutants cannot interfere through shared state.- A type checker removes some mutants before any test runs. A mutant that returns a string where
numberis declared does not compile. A tool for a typed language must decide whether such a mutant counts at all; Stryker leaves compile errors out of the score.
package argmax
// Mutant picks the active change: "" runs the original code.
var Mutant string
// Argmax returns the index of the first largest item of a non-empty slice.
func Argmax(xs []int) int {
best := 0
start := 1
if Mutant == "start at 0" {
start = 0
}
for i := start; i < len(xs); i++ {
left := xs[i]
if Mutant == "xs[i] to xs[best]" {
left = xs[best]
}
var bigger bool
switch Mutant {
case "> to >=":
bigger = left >= xs[best]
case "> to <":
bigger = left < xs[best]
default:
bigger = left > xs[best]
}
if bigger {
best = i
}
}
return best
}
package argmax
import "testing"
var cases = []struct {
xs []int
want int
}{
{[]int{1, 2, 3}, 2},
{[]int{1, 3, 2}, 1},
{[]int{3, 1, 2}, 0},
{[]int{2, 2, 1}, 0}, // the tie; without it "> to >=" lives
}
func passes() bool {
for _, c := range cases {
if Argmax(c.xs) != c.want {
return false
}
}
return true
}
func TestMutants(t *testing.T) {
if !passes() {
t.Fatal("the original must pass first")
}
// A person checked this mutant and found no input that tells it apart.
equivalent := map[string]bool{"start at 0": true}
for _, m := range []string{"> to >=", "> to <", "xs[i] to xs[best]", "start at 0"} {
t.Run(m, func(t *testing.T) {
Mutant = m
defer func() { Mutant = "" }()
switch {
case !passes():
t.Log("killed")
case equivalent[m]:
t.Log("lived, marked equivalent")
default:
t.Error("lived: add a test that kills it")
}
})
}
}
=== RUN TestMutants
=== RUN TestMutants/>_to_>=
argmax_test.go:36: killed
=== RUN TestMutants/>_to_<
argmax_test.go:36: killed
=== RUN TestMutants/xs[i]_to_xs[best]
argmax_test.go:36: killed
=== RUN TestMutants/start_at_0
argmax_test.go:38: lived, marked equivalent
--- PASS: TestMutants ($TIME)
--- PASS: TestMutants/>_to_>= ($TIME)
--- PASS: TestMutants/>_to_< ($TIME)
--- PASS: TestMutants/xs[i]_to_xs[best] ($TIME)
--- PASS: TestMutants/start_at_0 ($TIME)
PASS
ok example $TIME
- Verdict: library.
go testhas coverage and fuzzing but no mutation testing. Gremlins is a mutation testing tool for Go. - The test turns the score into a gate. A mutant that lives and is not on the list of equivalent mutants fails the test with
t.Error. Delete the tie fromcasesand the subtest>_to_>=fails. t.Runnames each subtest after the mutant, and Go replaces the spaces in the name with_. Thedeferresets the package variable, so the next test sees the original code.- The map
equivalentrecords a judgment by a person. No tool can decide equivalence in general, so the list needs a review whenArgmaxchanges.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Mutant {
None,
GreaterToGreaterEq,
GreaterToEq,
LeftToBest,
StartAtZero,
}
/// Returns the index of the first largest item of a non-empty slice.
fn argmax(xs: &[i32], m: Mutant) -> usize {
let mut best = 0;
let start = if m == Mutant::StartAtZero { 0 } else { 1 };
for i in start..xs.len() {
let left = if m == Mutant::LeftToBest { xs[best] } else { xs[i] };
let bigger = match m {
Mutant::GreaterToGreaterEq => left >= xs[best],
Mutant::GreaterToEq => left == xs[best],
_ => left > xs[best],
};
if bigger {
best = i;
}
}
best
}
fn passes(m: Mutant, suite: &[(&[i32], usize)]) -> bool {
suite.iter().all(|&(xs, want)| argmax(xs, m) == want)
}
fn main() {
let weak: &[(&[i32], usize)] = &[(&[1, 2, 3], 2), (&[1, 3, 2], 1), (&[3, 1, 2], 0)];
let strong: Vec<(&[i32], usize)> = weak.iter().copied().chain([(&[2, 2, 1][..], 0)]).collect();
assert!(passes(Mutant::None, &strong), "the original must pass first");
let mutants = [Mutant::GreaterToGreaterEq, Mutant::GreaterToEq, Mutant::LeftToBest, Mutant::StartAtZero];
println!("{:<20}{:<8}4 tests", "mutant", "3 tests");
let (mut weak_killed, mut strong_killed) = (0, 0);
for m in mutants {
let weak_dead = !passes(m, weak);
let strong_dead = !passes(m, &strong);
weak_killed += weak_dead as u32;
strong_killed += strong_dead as u32;
let cell = |dead| if dead { "killed" } else { "lived" };
println!("{:<20}{:<8}{}", format!("{m:?}"), cell(weak_dead), cell(strong_dead));
}
println!("{:<20}{weak_killed} of 4 {strong_killed} of 4", "killed");
}
mutant 3 tests 4 tests
GreaterToGreaterEq lived killed
GreaterToEq killed killed
LeftToBest killed killed
StartAtZero lived lived
killed 2 of 4 3 of 4
- Verdict: library. Cargo has no mutation command. cargo-mutants adds
cargo mutants, which finds places where the code can change and no test fails. - The second mutant uses a rule of cargo-mutants, which replaces
>with==or<. Thematchon the enum is the mutant schema, and the compiler checks that each arm returns abool. - cargo-mutants also replaces a whole function body with a value of the return type. For
usizethe values are0and1. The tests above kill both:[1, 2, 3]wants2. - cargo-mutants skips functions marked
#[mutants::skip]and functions under#[cfg(test)].
A mutant that does not compile tells nothing about the tests. Rust has no unary minus for usize, so this mutant stops at the compiler.
This code does not compile, on purpose.
/// The mutant puts a unary minus in front of the result.
fn argmax(xs: &[i32]) -> usize {
let mut best = 0;
for i in 1..xs.len() {
if xs[i] > xs[best] {
best = i;
}
}
-best
}
fn main() {
println!("{}", argmax(&[1, 3, 2]));
}
- cargo-mutants calls such a mutant "unviable". It counts unviable mutants but does not print them by default. It deletes unary operators such as
-aand!a, but it does not replace them with other unary operators, because that gives too many unviable mutants, such as-false. - The type checker does part of the work of the tests here. In Python the same change runs, and the tests must catch the negative result.
Variations and related ideas
- Strong, weak and firm mutation. The method of DeMillo et al. compares the output of the whole program. This is strong mutation. Howden's weak mutation checks the state right after the mutated component runs, which is cheaper but can give a weaker test set. Firm mutation lies between the two.2
- Higher-order mutants. A higher-order mutant has more than one change. DeMillo et al. ran more than 22,000 higher-order mutants of Hoare's FIND on their seven test vectors. Only 19 of them passed, and those 19 were equivalent to FIND.1 Offutt found that test data which killed all first-order mutants killed over 99 percent of the second-order and third-order mutants.2
- Fewer mutants. Mutant sampling runs a random subset. In the studies of Wong and Mathur, a random 10 percent of mutants was only 16 percent less effective than the full set. Selective mutation uses fewer operators. Mathur suggested leaving out two of the 22 Mothra operators, ASR and SVR, which made about 30 to 40 percent of all mutants. Offutt et al. reported that this 2-selective mutation reached a mean score of 99.99 percent with 24 percent fewer mutants.2
- Generated inputs. A property-based test or a fuzz test makes many inputs, and an input such as the tie
[2, 2, 1]can come from a generator as well as from a person. Mutation analysis then measures the generator: a mutant that lives shows a kind of input it never makes. - Test-driven development. In test-driven development, each line of code exists to pass a test, so few mutants should live. The Gremlins README names support for the TDD process as one of its uses.11
Pitfalls
Coverage without checks
The suite below runs every line of argmax, and every assertion holds. It checks only that the result is a valid index. A coverage tool reports full line coverage, and the suite kills none of the mutants.
This code runs but gives a wrong answer on purpose.
import sys
SOURCE = """
def argmax(xs):
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
"""
MUTANTS = [
("> to >=", "xs[i] > xs[best]", "xs[i] >= xs[best]"),
("> to <", "xs[i] > xs[best]", "xs[i] < xs[best]"),
("xs[i] to xs[best]", "xs[i] > xs[best]", "xs[best] > xs[best]"),
("start at 0", "range(1,", "range(0,"),
]
INPUTS = [[1, 2, 3], [1, 3, 2], [3, 1, 2], [2, 2, 1]]
def load(source):
namespace = {}
exec(compile(source, "<argmax>", "exec"), namespace)
return namespace["argmax"]
def suite(argmax):
"""Runs argmax on each input but checks only that the index is valid."""
return all(0 <= argmax(xs) < len(xs) for xs in INPUTS)
lines = set()
def tracer(frame, event, arg):
if frame.f_code.co_name == "argmax" and event == "line":
lines.add(frame.f_lineno)
return tracer
sys.settrace(tracer)
assert suite(load(SOURCE))
sys.settrace(None)
print(f"lines of argmax run by the suite: {sorted(lines)}")
killed = sum(not suite(load(SOURCE.replace(old, new))) for _, old, new in MUTANTS)
print(f"mutants killed: {killed} of {len(MUTANTS)}")
lines of argmax run by the suite: [3, 4, 5, 6, 7]
mutants killed: 0 of 4
The output shows lines 3 to 7, which is the whole body. The PIT documentation calls a test with no assertions the most extreme case of this problem, and it notes that a suite can execute all branches of code that it tests only in part.3 The fix is to compare each result with the expected index, as the four tests in "Idea" do.
Equivalent mutants
A mutant that computes the same function as the original cannot be killed. It stays in the list of live mutants and lowers the score until a person marks it. The program below compares two mutants with argmax on every list of up to five items from the values 0 to 3.
from itertools import product
def argmax(xs):
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
def start_at_0(xs): # the mutant: range(1, ...) became range(0, ...)
best = 0
for i in range(0, len(xs)):
if xs[i] > xs[best]:
best = i
return best
def boundary(xs): # the mutant: > became >=
best = 0
for i in range(1, len(xs)):
if xs[i] >= xs[best]:
best = i
return best
inputs = [list(t) for n in range(6) for t in product(range(4), repeat=n)]
for mutant in (start_at_0, boundary):
differ = [xs for xs in inputs if mutant(xs) != argmax(xs)]
first = differ[0] if differ else None
print(f"{mutant.__name__}: differs on {len(differ)} of {len(inputs)} lists, first {first}")
start_at_0: differs on 0 of 1365 lists, first None
boundary: differs on 672 of 1365 lists, first [0, 0]
The search finds no difference for start_at_0 and finds one at once for boundary. A search like this is evidence, not proof. The proof here is short: the extra first pass compares xs[0] with xs[0], and > is false for equal values. In general no algorithm decides whether two programs are equivalent, so the check needs a person.2 For FIND, about 2 percent of the mutants were equivalent. The authors put this down to the long tuning of FIND, and estimated that production programs have well under 1 percent.1 Tools let the user skip code that makes equivalent mutants: mutmut reads the comment # pragma: no mutate, and cargo-mutants reads the attribute #[mutants::skip].59
Scores from different tools differ
The definition of the score decides its value. Jia and Harman divide by the mutants that are not equivalent.2 Stryker divides by the valid mutants, counts timeouts as detected, and leaves out compile errors and runtime errors.6 PIT gauges the quality of tests by the percentage of mutations killed.3 The operators also differ between tools. So a score of 80 percent from one tool and 80 percent from another do not say the same thing, and it is safer to compare a score with earlier runs of the same tool on the same code.
Errors that look like kills
A harness that counts every exception as a failed test can report a mutant as killed when the harness broke it. The JavaScript example shows a mutant that dies of a ReferenceError because the harness compiled it outside its module scope. Two rules prevent this. Run the suite on the unchanged program first, through the same harness.2 And keep errors apart from failed assertions, as Stryker does with its runtime error state.6
Mutants that do not stop
A mutant can turn a loop into one that never ends, for example by changing i += 1 into i -= 1. The harness needs a time limit for each run. mutmut sets the limit from the duration of the original tests, a constant and a multiplier.5 Stryker counts a timeout as detected.6
Cost
- Run time. The cost is about the number of mutants times the time of the tests that cover each one. Jia and Harman name the cost of running the large number of mutants as a problem that keeps mutation testing from being a practical technique.2 The Gremlins README says that a run on a large Go module can take hours.11
- Ways to cut it. PIT advises running mutation testing often but only on the code that changed.3 mutmut knows which tests to run for each mutant.5 A mutant schema saves the compile for each mutant, and sampling runs fewer mutants.2
- Human time. Each live mutant needs a decision: one more test or a mark as equivalent. More tests also mean more expected outputs to check by hand, which Jia and Harman call the human oracle problem.2
History
- 1971. Richard Lipton wrote a student report at Carnegie Mellon University, Fault Diagnosis of Computer Programs. Jia and Harman trace mutation testing back to it.2
- 1977. Richard Hamlet published Testing Programs with the Aid of a Compiler in IEEE Transactions on Software Engineering.2
- 1978. DeMillo, Lipton and Sayward published Hints on Test Data Selection. It described program mutation, dead and live mutants, equivalent mutants and the coupling effect, with the examples MAX, a triangle classifier and Hoare's FIND.1
- 1982. Budd and Angluin published the work that Jia and Harman cite for the undecidability of mutant equivalence.2
- 1989 and 1992. Offutt published studies of the coupling effect with first-order and higher-order mutants.2
- 1991. King and Offutt described the Mothra system for Fortran, which implemented the first formal set of mutation operators.2
- 1993. Untch, Offutt and Harrold presented mutant schemata at ISSTA.2
- 2011. Jia and Harman published their survey of the field in IEEE Transactions on Software Engineering.2
References
- Richard A. DeMillo, Richard J. Lipton and Frederick G. Sayward, Hints on Test Data Selection, Help for the Practicing Programmer, IEEE Computer 11(4), April 1978, pages 34 to 41, page 34 (programs close to being correct); page 35 (the coupling effect); page 36 (program mutation, dead and live mutants, equivalent mutants, adequate test data); page 37 (the MAX example); page 39 (FIND and its equivalent mutants); page 40 (higher-order mutants)
- Yue Jia and Mark Harman, An Analysis and Survey of the Development of Mutation Testing, IEEE Transactions on Software Engineering 37(5), 2011, pages 649 to 678, I Introduction; II.A Fundamental Hypotheses; II.B The Process of Mutation Analysis; II.C The Problems of Mutation Analysis; III.A.1 Mutant Sampling; III.B Execution Cost Reduction Techniques (strong, weak and firm mutation; mutant schema generation); IV Equivalent Mutant Detection Techniques; the reference list
- PIT Mutation Testing, home page, What is mutation testing?; What's wrong with line coverage?; How to use it?
- PIT, Mutation Operators, Overview (bytecode, default operators); Conditionals Boundary Mutator; Negate Conditionals Mutator
- mutmut, Python mutation tester, documentation, Install and run; Skipping via code comments; Filter generated mutants with type checker; Unstable configs (the timeout); Example mutations
- Stryker Mutator, Mutant states and metrics, Mutant states; Metrics
- Stryker Mutator, home page, the list of supported languages (JavaScript and TypeScript, C#, Scala)
- cargo-mutants, Welcome, the introduction
- cargo-mutants, Mutation patterns, Functions that are excluded from mutation; Replace function body with value; Binary operators; Unary operators
- Mull, README, the introduction; Citation
- Gremlins, a mutation testing tool for Go, README, the introduction; What is Mutation Testing
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag KWRP2X Edit this page History Report an error Markdown