Testing and QA · Advanced · 26 min
Run mutation testing on Python code with mutmut
By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · mutmut 3.8.1 · pytest 9.2.0 · uv 0.13
You will run mutmut 3.8 against a fully covered pricing module, read the mutants your pytest suite missed, kill them with sharper tests, set aside an equivalent mutant, and gate CI on a mutation score that only checks the modules you changed.
On this page
Line coverage tells you which lines ran while the tests ran. It does not tell you whether any test would notice if one of those lines were wrong. A test that calls a function and asserts nothing gives 100% coverage and catches nothing.
Mutation testing measures the second thing. The tool makes many small copies of your code, each with one deliberate bug: >= turned into >, 20_000 into 20001, or into and. Each copy is a mutant. It runs your tests against every mutant. If a test fails, the mutant is killed, which is what you want. If every test still passes, the mutant survived, and you have found a change to your code that your suite cannot see.
You will use mutmut, the most widely used mutation tester for Python, on a small shop module that works in minor units (kobo, pesewas, cents): a percentage discount, a delivery fee with weight bands and a free-delivery threshold, and a receipt formatter. The tests start at 100% line coverage and still let 15 of 33 mutants through. Boundary mistakes like these are the bugs that cost real money at a checkout, whether the order comes from a laptop or a low-end Android phone on prepaid data.
Step 1 · Create the project and a fully covered module
Make a throwaway project and add three development dependencies: pytest, mutmut and coverage.py. Each range allows patch releases and nothing newer:
mkdir -p ~/mutmut-demo
cd ~/mutmut-demo
uv init --no-package
rm main.py
uv add --dev "pytest>=9.2,<9.3" "mutmut>=3.8,<3.9" "coverage>=7.17,<7.18"
mkdir -p src/shop tests
touch src/shop/__init__.pyIf git is installed, uv init also makes the folder a git repository. You will use that later to choose which modules to mutate.
Write the code under test. Every amount is an integer number of minor units, so there is no floating-point money anywhere:
cat > src/shop/pricing.py <<'PY'
def apply_discount(subtotal, percent):
"""Return the subtotal after a percentage discount, in whole minor units."""
if percent < 0 or percent > 50:
raise ValueError("discount must be between 0 and 50 percent")
return subtotal - subtotal * percent // 100
def delivery_fee(subtotal, weight_g):
"""500 up to 2 kg, plus 100 for each started kilogram above that. Free from 20,000."""
if subtotal >= 20_000:
return 0
if weight_g <= 2_000:
return 500
extra_kg = (weight_g - 2_000 + 999) // 1_000
return 500 + extra_kg * 100
PY
cat > src/shop/receipt.py <<'PY'
def format_amount(minor):
"""Format minor units (kobo, cents, pesewas) as 1,234.50."""
return f"{minor // 100:,}.{minor % 100:02d}"
PYNow write the kind of tests many projects have: one happy-path example per behaviour, plus a check that a silly discount is refused:
cat > tests/test_pricing.py <<'PY'
import pytest
from shop.pricing import apply_discount, delivery_fee
def test_discount():
assert apply_discount(10_000, 10) == 9_000
def test_discount_too_big_is_refused():
with pytest.raises(ValueError):
apply_discount(10_000, 90)
def test_small_parcel():
assert delivery_fee(5_000, 1_000) == 500
def test_heavy_parcel():
assert delivery_fee(5_000, 4_500) == 800
def test_big_order_ships_free():
assert delivery_fee(25_000, 4_500) == 0
PY
cat > tests/test_receipt.py <<'PY'
from shop.receipt import format_amount
def test_thousands_and_minor_units():
assert format_amount(123_450) == "1,234.50"
def test_small_amount_keeps_two_digits():
assert format_amount(5) == "0.05"
PY
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
TOMLtestpaths matters more than usual here. mutmut writes a full copy of your project, tests included, into a mutants/ folder. Without testpaths, a bare pytest would collect both copies and stop with an error about duplicate test module names.
Check it worked
uv run coverage run --source=src -m pytest -q
uv run coverage reportpytest reports 7 passed, and the coverage table shows 100% for pricing.py, receipt.py and the total. By the usual measure, this suite is complete.
Step 2 · Tell mutmut what to mutate and how to test it
mutmut can guess where your code lives, but a src/ layout is clearer when you say so. Add a [tool.mutmut] table to pyproject.toml. In this file mutmut expects every path setting as a list:
cat >> pyproject.toml <<'TOML'
[tool.mutmut]
source_paths = ["src/"]
pytest_add_cli_args_test_selection = ["tests/"]
TOML
printf 'mutants/\n.coverage\n' >> .gitignoresource_pathsis the code mutmut changes. Tests are never mutated.pytest_add_cli_args_test_selectionis passed to pytest to choose which tests run against each mutant. It takes the same arguments you would type, so["tests/", "-m", "not slow"]would leave out slow tests.mutants/holds the mutated copy of the project and mutmut's results. It is rebuilt from your code, so it does not belong in git.
mutmut mutates code inside functions and methods. Module-level constants and class attributes outside a method are left alone. That is one reason this module keeps its thresholds inside the functions.
Check it worked
tail -4 pyproject.toml
grep -x "mutants/" .gitignoreYou see the [tool.mutmut] table with both settings, and mutants/ on its own line.
Step 3 · Run mutmut and read the counts
Start the run:
uv run mutmut runmutmut first generates the mutants, then runs your tests once without changes to record which tests touch which function, then checks that a deliberately broken run really fails. Only then does it start on the mutants. For each one it forks a fresh process, switches that one mutant on and runs only the tests that call the mutated function. That is why it is fast on a small project and still workable on a large one.
The progress line updates in place and ends like this:
33/33 🎉 18 🫥 0 ⏰ 0 🤔 0 🙁 15 🔇 0 🧙 0What the symbols count:
- 🎉 killed: at least one test failed. Good.
- 🙁 survived: every test passed with the bug in place. This is your to-do list.
- 🫥 no tests: no test calls the function at all.
- ⏰ timeout: the mutant made the tests far slower than normal, usually an endless loop. It counts as caught.
- 🤔 suspicious: slow, but not slow enough to call a timeout. Rerun it before you trust it.
- 🔇 skipped and 🧙 caught by type check: only appear when you configure skips or a type checker.
You can stop a long run with Ctrl+C and start it again later. mutmut picks up where it left off.
Check it worked
Save the counts to a file and read them:
uv run mutmut export-cicd-stats
cat mutants/mutmut-cicd-stats.jsonThe file reports "killed": 18, "survived": 15 and "total": 33. Your suite has 100% line coverage and still misses 15 of 33 small bugs, a mutation score of about 55%.
Step 4 · Read the survivors with mutmut results and show
List what got through:
uv run mutmut resultsEach line names one surviving mutant, as <module>.x_<function>__mutmut_<number>:
shop.pricing.x_apply_discount__mutmut_2: survived
shop.pricing.x_apply_discount__mutmut_3: survived
...
shop.pricing.x_delivery_fee__mutmut_13: survivedEvery survivor is in pricing.py. The two receipt tests killed all of format_amount's mutants, because they pin exact strings with odd values.
Look at one survivor as a diff against your source:
uv run mutmut show shop.pricing.x_apply_discount__mutmut_10
uv run mutmut show shop.pricing.x_delivery_fee__mutmut_1The first diff turns floor division into true division:
- return subtotal - subtotal * percent // 100
+ return subtotal - subtotal * percent / 100The test uses 10,000 and 10%, which divide exactly, so 9000.0 == 9000 and the test passes. A customer paying 999 would be charged 899.1, a fraction of a kobo that your accounts cannot hold. The second diff changes subtotal >= 20_000 to subtotal > 20_000, and no test places an order of exactly 20,000.
Run show on the rest and they fall into five groups:
apply_discount2 and 3 (percent <= 0,percent < 1): no test gives a 0% discount.apply_discount4 and 5 (percent >= 50,percent > 51): nothing tests 50% or 51%.apply_discount6, 7 and 8: the error message is replaced or changed, andpytest.raises(ValueError)does not look at it.delivery_fee1 and 2: the free-delivery threshold is never tested at 20,000.delivery_fee4, 5, 11, 12 and 13: the 2 kg boundary and the "started kilogram" rounding are never tested at 2,000 g, 2,001 g or 3,000 g.
On your own machine, mutmut browse gives the same information in an interactive terminal view: pick a mutant to see its diff, and press r to retest it after you change a test.
uv run mutmut browseThere is also mutmut apply <name>, which writes a mutant into your real source file so you can debug it. Commit your work first, because it really does change the file.
Check it worked
uv run mutmut results | wc -lThe count is 15, one line per survivor.
Step 5 · Kill the survivors with sharper tests
Each group above points at a test that is missing. Replace the pricing tests with a version that pins the limits, the exact error message, the rounding and every boundary:
cat > tests/test_pricing.py <<'PY'
import pytest
from shop.pricing import apply_discount, delivery_fee
def test_discount():
assert apply_discount(10_000, 10) == 9_000
def test_discount_rounds_down_to_whole_units():
assert apply_discount(999, 10) == 900
@pytest.mark.parametrize("percent", [0, 50])
def test_discount_limits_are_allowed(percent):
assert apply_discount(1_000, percent) == 1_000 - 10 * percent
@pytest.mark.parametrize("percent", [-1, 51, 90])
def test_discount_outside_limits_is_refused(percent):
with pytest.raises(ValueError, match="^discount must be between 0 and 50 percent$"):
apply_discount(10_000, percent)
def test_small_parcel():
assert delivery_fee(5_000, 1_000) == 500
def test_heavy_parcel():
assert delivery_fee(5_000, 4_500) == 800
def test_big_order_ships_free():
assert delivery_fee(25_000, 4_500) == 0
def test_free_delivery_starts_at_exactly_20000():
assert delivery_fee(19_999, 1_000) == 500
assert delivery_fee(20_000, 1_000) == 0
@pytest.mark.parametrize(
("weight_g", "fee"),
[(2_000, 500), (2_001, 600), (3_000, 600), (3_001, 700)],
)
def test_each_started_kilogram_above_2kg_costs_100(weight_g, fee):
assert delivery_fee(5_000, weight_g) == fee
PY
uv run pytest -qThe new tests read like a specification: the discount works at 0% and 50% and is refused just outside, rounding goes down to a whole unit, free delivery starts at exactly 20,000, and one gram over 2 kg costs another 100. Odd values such as 999 matter. Round numbers hide arithmetic mistakes.
Now rerun the mutants. A plain mutmut run is not enough here. mutmut caches results per function and only re-tests a function when its source changes. You changed the tests, not pricing.py, so it would report the old results. Name the mutants you want re-tested instead. Shell-style wildcards work, so this re-tests every mutant in the module:
uv run mutmut run "shop.pricing.*"
uv run mutmut resultsCheck it worked
pytest reports 17 passed. The rerun prints a 🎉 line for each re-tested mutant, and mutmut results now lists a single survivor:
shop.pricing.x_delivery_fee__mutmut_4: survivedStep 6 · Deal with an equivalent mutant
Look at the last survivor:
uv run mutmut show shop.pricing.x_delivery_fee__mutmut_4- if weight_g <= 2_000:
+ if weight_g < 2_000:You already test 2,000 g, so why does it live? Work through it: at exactly 2,000 g the mutant skips the early return and falls through to the formula, which gives (0 + 999) // 1_000, that is 0 extra kilograms, and a fee of 500. Both versions return 500 for every possible weight. This is an equivalent mutant: the code changed, but its behaviour did not, so no test can ever kill it.
You have two honest options:
- Simplify the code so the redundancy disappears. That is often the better fix, because an equivalent mutant can be a sign of a condition that does more than it needs to.
- Keep the code as it reads best, and tell mutmut not to mutate that line, with a comment saying why. Anyone who later sees the pragma knows it was a decision, not a way to hide a weak test.
Take the second option here, because the early return states the rule clearly. Rewrite pricing.py with the comment and the pragma:
cat > src/shop/pricing.py <<'PY'
def apply_discount(subtotal, percent):
"""Return the subtotal after a percentage discount, in whole minor units."""
if percent < 0 or percent > 50:
raise ValueError("discount must be between 0 and 50 percent")
return subtotal - subtotal * percent // 100
def delivery_fee(subtotal, weight_g):
"""500 up to 2 kg, plus 100 for each started kilogram above that. Free from 20,000."""
if subtotal >= 20_000:
return 0
# At exactly 2,000 g both branches return 500, so "<" here is an equivalent mutant.
if weight_g <= 2_000: # pragma: no mutate
return 500
extra_kg = (weight_g - 2_000 + 999) // 1_000
return 500 + extra_kg * 100
PY
uv run mutmut run "shop.pricing.x_delivery_fee*"
uv run mutmut export-cicd-stats# pragma: no mutate switches off every mutation on that line, including <= 2001, which your 2,001 g test was killing. Keep pragmas to the one line that needs it. mutmut also accepts # pragma: no mutate block for a whole indented block, and do_not_mutate_patterns in pyproject.toml for things such as log calls.
Run this function's mutants by name again. A comment-only change is not counted as a change to the function, so a plain mutmut run would keep the old result under a mutant number that now means something else.
Check it worked
uv run mutmut results | wc -l
grep -E '"(killed|survived|total)"' mutants/mutmut-cicd-stats.jsonThe first command prints 0: no survivors. The stats show "killed": 31, "survived": 0 and "total": 31, two fewer mutants than before because the pragma line no longer produces any.
Step 7 · Keep runs short as the code grows
Mutation testing is slow by nature: every mutant needs its own test run. Three habits keep it practical.
First, let the cache work for you while you develop. Commit the current state, then add a new function and its test:
git add -A
git commit -m "Pricing rules with mutation-tested tests"
cat >> src/shop/receipt.py <<'PY'
def receipt_line(name, minor):
"""One receipt line: the name on the left, the amount right-aligned, 32 characters wide."""
return f"{name:<20}{format_amount(minor):>12}"
PY
cat > tests/test_receipt.py <<'PY'
from shop.receipt import format_amount, receipt_line
def test_thousands_and_minor_units():
assert format_amount(123_450) == "1,234.50"
def test_small_amount_keeps_two_digits():
assert format_amount(5) == "0.05"
def test_receipt_line_is_32_characters():
line = receipt_line("Rice 5kg", 1_250_000)
assert line == "Rice 5kg 12,500.00"
assert len(line) == 32
PY
uv run mutmut run
uv run mutmut results --all true | grep receipt_lineThis time a plain mutmut run is right. receipt_line is new source, so mutmut tests its mutants and reuses the cached results for every function you did not touch.
Second, in CI there is no cache, because each job starts from a fresh checkout. There, ask git which source files changed and turn their paths into mutant name patterns. Save this as a script:
cat > mutate-changed.sh <<'SH'
#!/bin/sh
# Mutation-test only the modules under src/ that changed since a git ref (default: HEAD).
set -eu
base="${1:-HEAD}"
patterns=$(git diff --name-only "$base" -- 'src/*.py' | sed -e 's|^src/||' -e 's|\.py$|.*|' -e 's|/|.|g')
if [ -z "$patterns" ]; then
echo "No Python source under src/ changed since $base"
exit 0
fi
echo "Mutating: $patterns"
uv run mutmut run $patterns
SH
chmod +x mutate-changed.sh
./mutate-changed.shsrc/shop/receipt.py becomes the pattern shop.receipt.*, which matches every mutant in that module. In a pull request job, pass the base branch, for example ./mutate-changed.sh origin/main. git diff against a ref does not list files that have never been added to git, which is fine in CI, where everything is committed.
Third, cut the work per mutant when the suite is large. max_stack_depth in [tool.mutmut] stops a test from counting for functions it only reaches deep down the call stack, mutate_only_covered_lines = true skips lines no test executes, and mutmut run --max-children 2 limits parallel workers on a laptop with little memory.
Check it worked
The grep prints shop.receipt.x_receipt_line__mutmut_1: killed. The script's first line of output is Mutating: shop.receipt.*, so only the receipt module was considered.
Step 8 · Fail CI when the mutation score drops
mutmut exits with status 0 even when mutants survive, so a CI job needs its own rule. Write a short check that reads the stats file and fails below a minimum. It counts only mutants that were checked, because a run limited to changed modules leaves the rest "not checked":
cat > check_mutation_score.py <<'PY'
"""Fail when the mutation score in mutmut's CI stats is below a minimum percentage."""
import json
import sys
minimum = float(sys.argv[1]) if len(sys.argv) > 1 else 80.0
with open("mutants/mutmut-cicd-stats.json", encoding="utf-8") as f:
stats = json.load(f)
caught = stats["killed"] + stats["timeout"]
checked = caught + stats["survived"] + stats["no_tests"] + stats["suspicious"] + stats["segfault"]
if checked == 0:
sys.exit("No mutants were checked, so there is no score to compare.")
score = 100 * caught / checked
print(f"Mutation score {score:.1f}% ({caught} of {checked} mutants caught), minimum {minimum:.0f}%")
if score < minimum:
sys.exit(f"Mutation score is below {minimum:.0f}%")
PY
git add -A
git commit -m "Receipt lines, changed-module mutation runs and a score check"Now play the part of a teammate who adds a bulk discount to pricing.py without a test. Remove mutants/ first so the run starts from nothing, as it would in CI:
cat >> src/shop/pricing.py <<'PY'
def bulk_discount_percent(quantity):
"""10% off 100 or more of one item, 5% off 50 or more."""
if quantity >= 100:
return 10
if quantity >= 50:
return 5
return 0
PY
rm -rf mutants
./mutate-changed.sh
uv run mutmut export-cicd-stats
uv run python check_mutation_score.py 80 || echo "Mutation gate failed"The check prints Mutation score 79.4% (27 of 34 mutants caught), minimum 80%, then Mutation score is below 80% and exits with status 1, so the echo reports Mutation gate failed. The seven new mutants show as 🫥 no tests in mutmut results. Line coverage would have dropped too, but only by a few lines; the mutation score says plainly that a new rule ships unchecked.
Add the boundary tests and run the same three commands again:
cat > tests/test_bulk_discount.py <<'PY'
import pytest
from shop.pricing import bulk_discount_percent
@pytest.mark.parametrize(
("quantity", "percent"),
[(1, 0), (49, 0), (50, 5), (99, 5), (100, 10), (500, 10)],
)
def test_bulk_discount_bands(quantity, percent):
assert bulk_discount_percent(quantity) == percent
PY
rm -rf mutants
./mutate-changed.sh
uv run mutmut export-cicd-stats
uv run python check_mutation_score.py 80In GitHub Actions, the same scripts become a job. This file only runs on GitHub, so treat it as a starting point and adjust the Python and uv setup to match your other workflows:
# .github/workflows/mutation.yml
name: mutation
on: pull_request
jobs:
mutmut:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: astral-sh/setup-uv@v10
- run: uv sync
- run: ./mutate-changed.sh origin/${{ github.base_ref }}
- run: uv run mutmut export-cicd-stats
- run: uv run python check_mutation_score.py 80fetch-depth: 0 fetches the base branch so git diff can compare against it. If no source changed, the script exits early and the stats step has nothing to export, so for a real project add a condition that skips the last two steps in that case. Start the minimum where your project is today and raise it over time; a high number on day one mostly teaches people to add pragmas.
Check it worked
The full suite passes, and the check now prints Mutation score 100.0% (34 of 34 mutants caught), minimum 80% and exits with status 0.
Remove the demo project when you are done:
cd ~
rm -rf ~/mutmut-demoNext steps
mutmut or cosmic-ray
cosmic-ray (8.9 at the time of writing) is the other mature Python mutation tester, and the choice comes down to how you work. mutmut needs almost no setup, picks the tests to run per function, caches results and runs mutants in parallel on one machine, but it needs fork, so Windows users run it under WSL, and it only mutates code inside functions. cosmic-ray is configured with a TOML file that names the module path and any shell test command, so it is not tied to pytest. It keeps every result in a SQLite session file (cosmic-ray init, cosmic-ray baseline, cosmic-ray exec, then cr-report or cr-html), and it can spread the work across several machines with its HTTP distributor. Choose mutmut for day-to-day work on a pytest project, and look at cosmic-ray when a very large codebase needs a run shared across workers, or when your tests do not run under pytest.
- Compare the same ideas in JavaScript, with a break threshold built into the tool: measure test quality with mutation testing in JavaScript.
- Let a tool pick the boundary values for you: find edge cases with property-based testing in Hypothesis.
- Keep the suite tidy as the sharper tests pile up: organise a growing pytest suite.
- Go back over parametrize and the basics: test Python code with pytest.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials