Full Byte Developer.

Run mutation testing to find tests that pass for the wrong reason

Mutation testing changes your code, runs your tests, and tells you which mutants survive.

Published here , updated · 3 sources

Coverage percentages count lines your tests touch. They do not prove those asserts would fail if the line lied. Mutation testing flips small pieces of production code, re-runs the suite, and reports every change the tests still greenlight [1][2]. A survivor is a soft spot in the suite, not a soft spot in the coverage badge.

One-minute setup

Install the runner and the test tool the project already uses:

bash
pip install mutmut pytest

mutmut 3.x reads pyproject.toml. Point it at source and tests [1][2]:

toml
[tool.mutmut]
source_paths = ["src/"]
pytest_add_cli_args_test_selection = ["tests/"]

Put a tiny module and a weak test beside it so you can see a survivor on purpose.

src/threshold.py:

python
def under_limit(value: int) -> bool:
    return value < 100

tests/test_threshold.py:

python
from threshold import under_limit

def test_under_limit_mid():
    assert under_limit(50) is True

The test proves mid-range behavior. It never checks the boundary at 100. That gap is what mutation testing is for.

Run the mutants and read the board

From the project root, with the package on PYTHONPATH if you are not using an installable layout:

bash
PYTHONPATH=src mutmut run
PYTHONPATH=src mutmut results

On this machine with mutmut 3.10.0, the run finished like this:

text
Running mutation testing
2/2  🎉 0 🫥 0  ⏰ 0  🤔 0  🙁 2  🔇 0  🧙 0
    threshold.x_under_limit__mutmut_1: survived
    threshold.x_under_limit__mutmut_2: survived

Both mutants survived. The suite stayed green after the code changed. Coverage on under_limit can still look fine because the mid-range assert executes the line.

Inspect a survivor:

bash
PYTHONPATH=src mutmut show threshold.x_under_limit__mutmut_1

Printed diff:

text
--- src/threshold.py
+++ src/threshold.py
@@ -1,2 +1,2 @@
 def under_limit(value: int) -> bool:
-    return value < 100
+    return value <= 100

The second survivor nudged the constant (< 100 to < 101). Same story: no assert noticed.

source value < 100 mutant value <= 100 pytest killed assert fails on mutant survived suite still green (gap)

Each mutant is one tiny source edit; pytest either catches the behavior shift or the survivor names a missing assert.

Close the hole the mutant found

Add a boundary assert, then re-run:

python
def test_under_limit_boundary():
    assert under_limit(99) is True
    assert under_limit(100) is False
bash
PYTHONPATH=src pytest -q
text
..                                                                       [100%]
2 passed in 0.01s

After that, the < to <= mutant should die because under_limit(100) would return True under the mutant and the new assert expects False. Re-run mutmut run and check mutmut results until the survivors you care about are gone or explicitly accepted [2][3].

What the operators are doing

Typical Python operators rewrite comparisons, arithmetic, and constants [1][2]. The point is not that every rewrite is a realistic bug. The point is that a suite which cannot tell < from <= will also miss many real boundary mistakes.

Survivors cluster where tests check happy paths only, assert on mocks instead of outcomes, or copy production formulas into the test so both sides mutate together. Fix the assert, not the mutant list.

Keep the cost from eating CI

Full-suite mutation on a large tree is expensive because each mutant pays for test time. Start with one critical module (source_paths), run nightly, or gate it on labeled PRs. mutmut's own docs treat path limits and selection args as the normal way to stay usable [2].

Do not treat a green coverage job as a substitute. Coverage asked "did we execute the line?". Mutation asks "would we notice if the line changed?".

Mistakes specific to mutmut and friends

  1. Old config keys (paths_to_mutate) on mutmut 3: the CLI flags you remember may be gone. Use source_paths and the pytest selection keys the current docs show [1][2].
  2. Package not importable: every mutant dies on ImportError and looks "killed." Confirm bare pytest passes first [3].
  3. Equivalent mutants chased forever: accept a short list with a note; spend time on survivors that flip a real branch.
  4. Test files or generated code in source_paths: point the tool at production modules only.

After the first clean run

Pick the module that guards money, auth, or data loss. Put mutmut on a schedule for that path. When a survivor shows up, write the missing assert before you argue about coverage targets.

Equivalent mutants and when to stop

Some survivors are "equivalent": the rewrite cannot change any output your program can produce. Changing x + 0 to x is the classic textbook case. mutmut will still list them if the operator fires [2]. Mark those with a short comment in the PR and move on. The productive survivors are the ones where a human can name a customer-visible bug the mutant represents.

A practical rule: if you can write an assert that kills the mutant without locking the implementation to one arithmetic spelling, write the assert. If every assert would only restate the exact expression under test, you are probably staring at an equivalent mutant.

Wire a nightly job without blocking every PR

Mutation testing belongs next to coverage, not in front of every push. A typical shape:

  1. PR CI runs unit tests and lint as today [3].
  2. Nightly (or weekly) CI runs mutmut run on src/billing/ or whichever path holds irreversible actions.
  3. The job fails when survivors appear in that path, or uploads mutmut results as an artifact for a human to triage.

Keep the mutated path small until the suite is fast enough. Expanding to the whole monorepo on day one is how teams disable the job within a week.

Compare coverage and mutation on the same function

For under_limit, coverage shows the return line ran under test_under_limit_mid. The < to <= mutant still uses that line and survives. Quote coverage for untested branches; quote survivors for untested boundaries.

A second survivor pattern: mocked outcomes

Another common soft spot looks like this. Production code computes a discount; the test only asserts that a mock was called with some args and never checks the returned money amount. Mutating the discount formula leaves the mock call intact, so the mutant survives. The fix is an assert on the numeric result (or on a persisted invoice field), not another mock expectation.

python
def discount(price: int, percent: int) -> int:
    return price - (price * percent // 100)

def test_discount_calls_helper(mocker):
    spy = mocker.spy(__name__, "discount")
    spy(200, 10)
    spy.assert_called_once()

That test can report 100% coverage on discount while a mutant that changes // 100 to // 101 still survives. Add:

python
def test_discount_ten_percent():
    assert discount(200, 10) == 180

Re-run mutmut on that module. Survivors that flip arithmetic should die once the assert pins the observable number [2][3].

What "killed" actually means in the report

A killed mutant means at least one test failed after the rewrite. It does not mean every test is strong. One strict boundary test can kill dozens of comparison mutants while a neighboring helper still has soft asserts. Read the survivor list by module, not as a single score. When the board shows mostly killed mutants in threshold.py and a pile of survivors in pricing.py, that is a map of where to write the next asserts.

A surviving mutant is a concrete gap, not a vibe about more tests. Write one assert that fails on the mutated operator, re-run the mutant, and confirm it flips to killed before you celebrate coverage again.

Send this to the friend who celebrates 100 percent coverage on a function that never hit its boundary.

A source code crystal being cloned into several slightly mutated copies, with teal test hammers knocking most mutants down into the floor while one surviving mutant still stands, rendered as unmarked geometric solids on a dark navy field with no typography or logos.
Mutation testing changes the code and runs the tests. A surviving mutant means a gap.

Keep this guide

By Full Byte Developer

Filed under Dev tools

Questions about this guide

What are mutation operators?

Small automatic edits to source: replace < with <=, nudge a constant, flip a boolean. Each edit is one mutant.

Is mutation testing slow?

Usually yes. Each mutant re-runs part of the suite. Limit paths, run on a schedule, or start with one module.

What does a surviving mutant mean?

Your tests still passed after the code changed. The suite did not notice that behavior shift.

Sources

  1. mutmut documentationmutmut.readthedocs.io
  2. pytest docsdocs.pytest.org

Next in this stack