QA and Test Automation · Lab 8 of 35
Mutation Testing With PIT and mutmut: Find Weak Tests (Lab)
Measure how good tests really are: run mutation testing on ShopRung's pricing rules. Tests with 89% line coverage kill only 45 of 71 mutants; read the survivors, write the missing boundary tests, and reach 70 of 71. Then learn what an equivalent mutant is.
⏱ 50 minIntermediate💸 Free7 stepsJava + Python
Java 21 + Maven + JUnit 5.11 + PIT 1.17Python 3.12 + pytest + mutmut 3.9 (second path; macOS, Linux or WSL)
Overview video
What you will build
ShopRung's pricing rules from lab 4 with two versions of their tests, and the mutation reports that tell them apart:
- The first tests: 5 tests, all green, 89% line coverage. Mutation testing shows they kill only 45 of 71 mutants (63%): changing
>=to>on free shipping, or>to>=on the coupon expiry, goes unnoticed. - The improved tests: every rule checked on both sides of its edge. They kill 70 of 71. The last one is an equivalent mutant: a change that can never alter the result, so no test can kill it.
Java uses PIT, the standard mutation tool for the JVM, with an HTML report; Python uses mutmut.
Before you start
- Your first Java test project: this lab reuses its
PricingandCouponclasses (Python:pricing.py). - The idea behind this lab: Coverage and mutation testing. Boundary values: Test cases for a checkout.
- No ShopRung needed: mutation testing runs unit tests many times, so it works on code, not on a running shop.
Setup
S1Java 21 and Maven, or Python 3.12
Python path: mutmut 3 runs on macOS and Linux. On Windows, use WSL (Windows Subsystem for Linux).
java -version
mvn -v
# or
python3 --version S2Make the project
Java: Maven folders. Python: a src/shop package, tests, and a virtual environment.
# Java
mkdir -p shoprung-pricing/src/main/java/dev/algorung/shop shoprung-pricing/src/test/java/dev/algorung/shop
# Python
mkdir -p shoprung-pricing-py/src/shop shoprung-pricing-py/tests && cd shoprung-pricing-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir -p shoprung-pricing/src/main/java/dev/algorung/shop shoprung-pricing/src/test/java/dev/algorung/shop
# Python
mkdir -p shoprung-pricing-py/src/shop shoprung-pricing-py/tests && cd shoprung-pricing-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir shoprung-pricing\src\main\java\dev\algorung\shop, shoprung-pricing\src\test\java\dev\algorung\shop
# Python: use WSL, then the Linux commands The project, PIT and the pricing rules
A build with the mutation tool configured, and the code to mutate.
Mutation testing makes many small changes to your code, one at a time (each one is a mutant): >= becomes >, + becomes -, a return value becomes 0. For each mutant it runs your tests. If a test fails, the mutant is killed: your tests noticed. If all tests still pass, it survived: your tests would not notice that bug.
Java: pom.xml adds the PIT Maven plugin with its JUnit 5 plugin, set to mutate dev.algorung.shop and run the tests in the same package. Copy Pricing.java and Coupon.java from lab 4.
Python: pyproject.toml tells pytest where the code is and tells mutmut what to mutate. Copy pricing.py from lab 4 into src/shop.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>dev.algorung</groupId>
<artifactId>shoprung-pricing</artifactId>
<version>0.1.0</version>
<properties>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.11.4</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.2</version>
</plugin>
<!-- PIT: mutation testing. Run with: mvn test-compile org.pitest:pitest-maven:mutationCoverage -->
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>1.17.4</version>
<dependencies>
<dependency>
<groupId>org.pitest</groupId>
<artifactId>pitest-junit5-plugin</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
<configuration>
<targetClasses>
<param>dev.algorung.shop.*</param>
</targetClasses>
<targetTests>
<param>dev.algorung.shop.*</param>
</targetTests>
<outputFormats>
<param>HTML</param>
</outputFormats>
<timestampedReports>false</timestampedReports>
</configuration>
</plugin>
</plugins>
</build>
</project> - PIT: the standard mutation testing tool for Java.line 40
- Lets PIT run JUnit 5 tests.line 45
- Which code to mutate: never your tests.line 50
package dev.algorung.shop;
import java.time.LocalDate;
/**
* ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
* Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
*/
public final class Pricing {
public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
public static final long SHIPPING = 499; // $4.99
/** The four numbers a cart shows. */
public record Totals(long subtotal, long discount, long shipping, long total) {}
private Pricing() {}
/** 1250 becomes "$12.50" (PRICE-1). */
public static String money(long cents) {
if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
return String.format("$%d.%02d", cents / 100, cents % 100);
}
/** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
public static long shipping(long afterDiscount) {
if (afterDiscount == 0) return 0;
return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
}
/** Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8). */
public static Totals totals(long subtotal, Coupon coupon, LocalDate today) {
if (subtotal < 0) throw new IllegalArgumentException("subtotal must not be negative: " + subtotal);
long discount = 0;
if (coupon != null && coupon.problem(subtotal, today) == null) discount = coupon.discount(subtotal);
long shipping = shipping(subtotal - discount);
return new Totals(subtotal, discount, shipping, subtotal - discount + shipping);
}
} - A boundary. PIT will try
>here.line 27
package dev.algorung.shop;
import java.time.LocalDate;
import java.util.Locale;
/** ShopRung's three coupons (PRICE-2 to PRICE-7), with the same rules and messages as the shop. */
public enum Coupon {
SAVE10(true, 10, 5_000, null), // 10% off from $50.00
FLAT5(false, 500, 2_000, null), // $5.00 off from $20.00
WELCOME15(true, 15, 0, LocalDate.of(2025, 12, 31)); // expired
private final boolean percent;
private final long amount; // a percent, or cents
private final long minSubtotal; // cents
private final LocalDate expiresOn;
Coupon(boolean percent, long amount, long minSubtotal, LocalDate expiresOn) {
this.percent = percent;
this.amount = amount;
this.minSubtotal = minSubtotal;
this.expiresOn = expiresOn;
}
/** Finds a coupon by code. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7). */
public static Coupon of(String code) {
String c = code == null ? "" : code.trim().toUpperCase(Locale.ROOT);
for (Coupon coupon : values()) {
if (coupon.name().equals(c)) return coupon;
}
throw new IllegalArgumentException("No coupon called " + (c.isEmpty() ? "(empty)" : c));
}
/** Why this coupon cannot be used, or null when it can. */
public String problem(long subtotal, LocalDate today) {
if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
if (subtotal < minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
return null;
}
/** The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6). */
public long discount(long subtotal) {
if (percent) return (subtotal * amount + 50) / 100;
return Math.min(amount, subtotal); // a fixed amount never makes the total negative
}
} - Another boundary: is the last day valid?line 35
[project]
name = "shoprung-pricing"
version = "0.1.0"
requires-python = ">=3.12"
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
[tool.mutmut]
source_paths = ["src/shop/"]
tests_dir = ["tests/"] - Tests import
shopfromsrc.line 8 - What mutmut mutates.line 11
pytest==8.3.4
pytest-cov==6.0.0
mutmut==3.9.0 .venv/
mutants/
.coverage
__pycache__/ - mutmut works on a copy of your code in
mutants/.line 2
"""ShopRung money rules.""" """ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Python.
Every amount is whole cents in an int: $50.00 is 5000. No float, so no rounding surprises.
"""
from dataclasses import dataclass
from datetime import date
FREE_SHIPPING_FROM = 7_500 # $75.00, after the discount
SHIPPING = 499 # $4.99
@dataclass(frozen=True)
class Coupon:
code: str
percent: bool
amount: int # a percent, or cents
min_subtotal: int # cents
expires_on: date | None = None
COUPONS = {
"SAVE10": Coupon("SAVE10", True, 10, 5_000), # 10% off from $50.00
"FLAT5": Coupon("FLAT5", False, 500, 2_000), # $5.00 off from $20.00
"WELCOME15": Coupon("WELCOME15", True, 15, 0, date(2025, 12, 31)), # expired
}
@dataclass(frozen=True)
class Totals:
subtotal: int
discount: int
shipping: int
total: int
def money(cents: int) -> str:
"""1250 becomes "$12.50" (PRICE-1)."""
if cents < 0:
raise ValueError(f"cents must not be negative: {cents}")
return f"${cents // 100}.{cents % 100:02d}"
def shipping(after_discount: int) -> int:
"""$4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing."""
if after_discount == 0:
return 0
return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
def coupon(code: str | None) -> Coupon:
"""Finds a coupon. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7)."""
c = (code or "").strip().upper()
if c not in COUPONS:
raise ValueError(f"No coupon called {c or '(empty)'}")
return COUPONS[c]
def problem(c: Coupon, subtotal: int, today: date) -> str | None:
"""Why the coupon cannot be used, or None when it can."""
if c.expires_on and today > c.expires_on:
return "This coupon has expired"
if subtotal < c.min_subtotal:
return f"This coupon needs a subtotal of at least {money(c.min_subtotal)}"
return None
def discount(c: Coupon, subtotal: int) -> int:
"""The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6)."""
if c.percent:
return (subtotal * c.amount + 50) // 100
return min(c.amount, subtotal) # a fixed amount never makes the total negative
def totals(subtotal: int, c: Coupon | None, today: date) -> Totals:
"""Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8)."""
if subtotal < 0:
raise ValueError(f"subtotal must not be negative: {subtotal}")
off = discount(c, subtotal) if c and problem(c, subtotal, today) is None else 0
ship = shipping(subtotal - off)
return Totals(subtotal, off, ship, subtotal - off + ship) - A boundary. mutmut will try
>here.line 47
Python version of this step:
pip install -r requirements.txt Successfully installed ... mutmut-3.9.0 ... pytest-8.3.4 pytest-cov-6.0.0 ...
The first tests: green, and good coverage
Five tests that pass and cover most lines.
Create the test file below. It looks like many real test files: one test per function, each checking a typical value. Run it, and in Python also measure line coverage: 89%. By the usual standard this code is well tested.
Look closer before moving on: every value is far from an edge. Shipping is tested at $10.00 and $100.00, never at $75.00. SAVE10 at $100.00, never at $50.00.
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
/** The first tests: they pass, and coverage looks great. Are they any good? */
class PricingTest {
static final LocalDate TODAY = LocalDate.of(2026, 11, 30);
@Test
void money() {
assertEquals("$12.50", Pricing.money(1250));
}
@Test
void shipping() {
assertEquals(499, Pricing.shipping(1000));
assertEquals(0, Pricing.shipping(10000));
}
@Test
void save10() {
assertEquals(9000, Pricing.totals(10000, Coupon.of("SAVE10"), TODAY).total());
}
@Test
void flat5() {
assertEquals(500, Pricing.totals(3000, Coupon.of("FLAT5"), TODAY).discount());
}
@Test
void expiredCoupon() {
assertEquals(0, Pricing.totals(10000, Coupon.of("WELCOME15"), TODAY).discount());
}
} - Typical values: nowhere near the $75.00 edge.line 19
- $100.00: far above the $50.00 minimum.line 25
"""The first tests: they pass, and coverage looks great. Are they any good?"""
from datetime import date
from shop.pricing import coupon, money, shipping, totals
TODAY = date(2026, 11, 30)
def test_money():
assert money(1250) == "$12.50"
def test_shipping():
assert shipping(1000) == 499
assert shipping(10000) == 0
def test_save10():
t = totals(10000, coupon("SAVE10"), TODAY)
assert t.total == 9000
def test_flat5():
t = totals(3000, coupon("FLAT5"), TODAY)
assert t.discount == 500
def test_expired_coupon():
t = totals(10000, coupon("WELCOME15"), TODAY)
assert t.discount == 0 - Typical values: nowhere near the $75.00 edge.line 14
- $100.00: far above the $50.00 minimum.line 19
Python version of this step:
mvn test [INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q --cov=shop ..... [100%] src/shop/pricing.py 47 5 89% TOTAL 47 5 89% 5 passed
Run mutation testing
The real quality of the first tests: 45 of 71 mutants killed.
Run the mutation tool. It creates every mutant, runs the tests against each, and counts. This takes longer than a normal test run (seconds here, minutes on real projects), because the tests run once per mutant.
Python, real result: 71 mutants, 45 killed, 26 survived. A mutation score of 63%, from tests with 89% line coverage. Java: PIT prints a summary like the one below and writes an HTML report to target/pit-reports/index.html, where each line of code shows which mutants survived. Your exact Java numbers differ from Python's, because PIT makes different kinds of changes than mutmut.
Coverage only says a line ran during a test. Mutation testing asks whether any test would notice if that line were wrong.
mvn test-compile org.pitest:pitest-maven:mutationCoverage ================================================================================ - Statistics ================================================================================ >> Line Coverage (for mutated classes only): .../... (..%) >> Generated .. mutations Killed .. (..%) ... [INFO] BUILD SUCCESS
mutmut run 71/71 🎉 45 🫥 0 ⏰ 0 🤔 0 🙁 26 🔇 0 🧙 0
Read the survivors
Turn each surviving mutant into a missing test case.
Each survivor is a bug your tests would let through. List them and look at a few. In Python, mutmut results lists the survivors and mutmut show <name> prints one as a diff; in Java, open the HTML report and click a class. These are real survivors from the first tests:
# free shipping from exactly $75.00
- return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
+ return 0 if after_discount > FREE_SHIPPING_FROM else SHIPPING
# WELCOME15 is still valid on its last day
- if c.expires_on and today > c.expires_on:
+ if c.expires_on and today >= c.expires_on:
# $0.00 is a valid amount
- if cents < 0:
+ if cents <= 0:
# an empty or missing code
- c = (code or "").strip().upper()
+ c = (code or "XXXX").strip().upper()
# the error message is never checked
- raise ValueError(f"cents must not be negative: {cents}")
+ raise ValueError(None)
Each one names a test you did not write: shipping at exactly 7500, the coupon on 31 December 2025 and 1 January 2026, money(0), an empty coupon code, the exact error text. This is boundary value analysis, pointed at by a tool.
mutmut results
mutmut show shop.pricing.x_shipping__mutmut_7 shop.pricing.x_money__mutmut_1: survived
...
shop.pricing.x_shipping__mutmut_7: survived
...
- return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
+ return 0 if after_discount > FREE_SHIPPING_FROM else SHIPPING Kill them: tests on both sides of every edge
A test file where every rule is checked exactly on its boundaries.
Replace the test file. Each group comes from the survivors:
- money: 0, 5 and 100 cents, and the exact error for -1.
- shipping: 0, 1, 7499, 7500 and 7501.
- coupon codes: lower case, surrounding spaces, unknown, empty and missing, with the exact messages.
- SAVE10: 4999 refused, 5000 accepted. WELCOME15: valid on 31 December 2025, expired on 1 January 2026.
- discounts: half a cent rounds up (7495 → 750), less rounds down (7494 → 749), FLAT5 never goes below zero.
- totals: each path through the function, including an expired coupon and an empty cart, and the error for a negative subtotal.
package dev.algorung.shop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/** The tests after mutation testing: every rule checked on both sides of its edge. */
class PricingTest {
static final LocalDate TODAY = LocalDate.of(2026, 11, 30);
@ParameterizedTest
@CsvSource({"1250, $12.50", "5, $0.05", "0, $0.00", "100, $1.00"})
void money(long cents, String shown) {
assertEquals(shown, Pricing.money(cents));
}
@Test
void moneyRefusesNegativeAmounts() {
var e = assertThrows(IllegalArgumentException.class, () -> Pricing.money(-1));
assertEquals("cents must not be negative: -1", e.getMessage());
}
@ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
@CsvSource({"0, 0", "1, 499", "7499, 499", "7500, 0", "7501, 0"})
void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
assertEquals(expected, Pricing.shipping(afterDiscount));
}
@ParameterizedTest
@CsvSource({"SAVE10", "save10", "' Save10 '"})
void codesAreNotCaseSensitiveAndTrimmed(String code) {
assertEquals(Coupon.SAVE10, Coupon.of(code));
}
@ParameterizedTest
@CsvSource(value = {"NOPE, No coupon called NOPE", "'', No coupon called (empty)", "NULL, No coupon called (empty)"},
nullValues = "NULL")
void unknownCouponsAreRefused(String code, String message) {
var e = assertThrows(IllegalArgumentException.class, () -> Coupon.of(code));
assertEquals(message, e.getMessage());
}
@Test
void save10NeedsExactly50Dollars() {
assertEquals("This coupon needs a subtotal of at least $50.00", Coupon.SAVE10.problem(4_999, TODAY));
assertNull(Coupon.SAVE10.problem(5_000, TODAY));
}
@Test
void welcome15WorksOnItsLastDayAndNotTheDayAfter() {
assertNull(Coupon.WELCOME15.problem(4_000, LocalDate.of(2025, 12, 31)));
assertEquals("This coupon has expired", Coupon.WELCOME15.problem(4_000, LocalDate.of(2026, 1, 1)));
}
@ParameterizedTest(name = "{0} on {1} cents -> {2}")
@CsvSource({
"SAVE10, 5000, 500",
"SAVE10, 7495, 750", // 749.5 cents: half a cent rounds up
"SAVE10, 7494, 749", // 749.4 cents: rounds down
"FLAT5, 2000, 500",
"FLAT5, 300, 300", // a fixed amount never makes the total negative
})
void discounts(String code, long subtotal, long expected) {
assertEquals(expected, Coupon.of(code).discount(subtotal));
}
@ParameterizedTest(name = "{0} cents with {1} -> {2} off, {3} shipping, {4} total")
@CsvSource(value = {
"5000, SAVE10, 500, 499, 4999",
"4999, SAVE10, 0, 499, 5498", // just below: no discount
"8400, SAVE10, 840, 0, 7560", // free shipping after the discount
"8300, SAVE10, 830, 499, 7969", // 7470 after the discount: shipping charged
"2000, NULL, 0, 499, 2499",
"4000, WELCOME15, 0, 499, 4499", // expired on TODAY: no discount
"0, NULL, 0, 0, 0", // an empty cart costs nothing
}, nullValues = "NULL")
void totals(long subtotal, String code, long discount, long shipping, long total) {
Totals t = Pricing.totals(subtotal, code == null ? null : Coupon.of(code), TODAY);
assertEquals(new Totals(subtotal, discount, shipping, total), t);
}
@Test
void totalsRefuseNegativeSubtotals() {
var e = assertThrows(IllegalArgumentException.class, () -> Pricing.totals(-1, null, TODAY));
assertEquals("subtotal must not be negative: -1", e.getMessage());
}
} - Kills
>=→>on free shipping.line 30 - The last valid day, and the day after: kills mutants on the expiry check.line 57
- Exactly half a cent: checks the rounding direction.line 64
- Checking the message kills mutants that change it.line 26
- The empty cart: kills
<→<=on the subtotal check.line 81
"""The tests after mutation testing: every rule checked on both sides of its edge."""
from datetime import date
import pytest
from shop.pricing import coupon, discount, money, problem, shipping, totals
TODAY = date(2026, 11, 30)
@pytest.mark.parametrize("cents, shown", [(1250, "$12.50"), (5, "$0.05"), (0, "$0.00"), (100, "$1.00")])
def test_money(cents, shown):
assert money(cents) == shown
def test_money_refuses_negative_amounts():
with pytest.raises(ValueError, match="cents must not be negative: -1"):
money(-1)
@pytest.mark.parametrize("after_discount, expected", [
(0, 0), (1, 499), (7_499, 499), (7_500, 0), (7_501, 0),
])
def test_shipping_is_free_from_75_dollars(after_discount, expected):
assert shipping(after_discount) == expected
@pytest.mark.parametrize("code", ["SAVE10", "save10", " Save10 "])
def test_codes_are_not_case_sensitive_and_trimmed(code):
assert coupon(code).code == "SAVE10"
@pytest.mark.parametrize("code, message", [("NOPE", "No coupon called NOPE"), ("", "No coupon called (empty)"),
(None, "No coupon called (empty)")])
def test_unknown_coupons_are_refused(code, message):
with pytest.raises(ValueError, match=message.replace("(", r"\(").replace(")", r"\)")):
coupon(code)
@pytest.mark.parametrize("subtotal, expected_problem", [
(4_999, "This coupon needs a subtotal of at least $50.00"),
(5_000, None),
])
def test_save10_needs_50_dollars(subtotal, expected_problem):
assert problem(coupon("SAVE10"), subtotal, TODAY) == expected_problem
@pytest.mark.parametrize("today, expected_problem", [
(date(2025, 12, 31), None), # the last valid day
(date(2026, 1, 1), "This coupon has expired"), # the day after
])
def test_welcome15_expiry_edge(today, expected_problem):
assert problem(coupon("WELCOME15"), 4_000, today) == expected_problem
@pytest.mark.parametrize("code, subtotal, expected", [
("SAVE10", 5_000, 500),
("SAVE10", 7_495, 750), # 749.5 cents: half a cent rounds up
("SAVE10", 7_494, 749), # 749.4 cents: rounds down
("FLAT5", 2_000, 500),
("FLAT5", 300, 300), # a fixed amount never makes the total negative
])
def test_discounts(code, subtotal, expected):
assert discount(coupon(code), subtotal) == expected
@pytest.mark.parametrize("subtotal, code, expected", [
(5_000, "SAVE10", (5_000, 500, 499, 4_999)),
(4_999, "SAVE10", (4_999, 0, 499, 5_498)), # just below: no discount
(8_400, "SAVE10", (8_400, 840, 0, 7_560)), # free shipping after the discount
(8_300, "SAVE10", (8_300, 830, 499, 7_969)), # 7470 after discount: shipping charged
(2_000, None, (2_000, 0, 499, 2_499)),
(4_000, "WELCOME15", (4_000, 0, 499, 4_499)), # expired on TODAY: no discount
(0, None, (0, 0, 0, 0)), # an empty cart costs nothing
])
def test_totals(subtotal, code, expected):
t = totals(subtotal, coupon(code) if code else None, TODAY)
assert (t.subtotal, t.discount, t.shipping, t.total) == expected
def test_totals_refuses_negative_subtotals():
with pytest.raises(ValueError, match="subtotal must not be negative"):
totals(-1, None, TODAY) - Kills
>=→>on free shipping.line 22 - The last valid day of WELCOME15.line 49
- Exactly half a cent: checks the rounding direction.line 58
- The empty cart: kills
<→<=on the subtotal check.line 74
Python version of this step:
mvn test [INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q -p no:randomly ................................. [100%] 33 passed in 0.03s
Run it again, and meet an equivalent mutant
70 of 71 killed, and a survivor that cannot be killed.
Run mutation testing again. Python: 70 of 71 killed. One survivor is left:
- return (subtotal * c.amount + 50) // 100
+ return (subtotal * c.amount + 51) // 100
Try to write a test that kills it, and you cannot. For +51 to round differently from +50, subtotal × percent would have to end in 49. ShopRung's percentages are 10 and 15, so that product always ends in 0 or 5. No input can ever show the difference. This is an equivalent mutant: the code changed, but its behaviour did not. Every mutation tool produces some; you note them and move on. That is why teams aim for a high mutation score, not 100%.
mvn test-compile org.pitest:pitest-maven:mutationCoverage
open target/pit-reports/index.html >> Generated .. mutations Killed .. (9.%) ... [INFO] BUILD SUCCESS
mutmut run
mutmut results 71/71 🎉 70 🫥 0 ⏰ 0 🤔 0 🙁 1 🔇 0 🧙 0
shop.pricing.x_discount__mutmut_4: survived Using mutation testing at work
Where it pays off, and how to keep it affordable.
- Pick the code: business rules like pricing, permissions and calculations, where a small mistake costs money. Not glue code or UI.
- Run it incrementally: PIT has an incremental mode and a Git integration that mutates only changed code; mutmut caches results. Full runs nightly, changed code per pull request.
- Use the score as a signal, not a target: a falling score on a pull request means new code arrived without real tests. Reviewers open the report instead of arguing about coverage.
- In interviews and reviews, mutation testing is the clearest answer to "coverage is 90%, but are the tests good?".
Check it works
Compare the two runs. With the first tests, many mutants survive (Python: 45 of 71 killed). With the improved tests, all but the equivalent mutant are killed (Python: 70 of 71). If a mutant you expected to kill still survives, mutmut show or the PIT report tells you which line and which change: write the test that would notice it.
mvn test-compile org.pitest:pitest-maven:mutationCoverage
# or: mutmut run 71/71 🎉 70 🫥 0 ⏰ 0 🤔 0 🙁 1 🔇 0 🧙 0
Troubleshooting
PIT: No mutations found.
targetClasses does not match your package. It must be dev.algorung.shop.* (or your own package).
PIT: tests are not found or the run fails at the start.
Run mvn test first: PIT needs a green suite. Check the pitest-junit5-plugin dependency is inside the PIT plugin, not in the project's dependencies.
mutmut: "Running forced fail test" fails.
mutmut checks the tests can fail at all. Run pytest alone first and fix any import error (the pythonpath = ["src"] line).
mutmut on Windows.
mutmut 3 needs a Unix-like system. Use WSL, or take the Java path.
Mutation testing takes too long.
Limit it to the classes that matter (targetClasses, source_paths), keep unit tests fast, and run full mutation tests nightly.
What changes in production
- Teams apply mutation testing to critical business logic, not the whole codebase.
- PIT runs incrementally on changed code in pull requests; full runs happen nightly, with the HTML report as a CI artifact.
- Survivors become review comments ("this boundary is untested"), and equivalent mutants are noted and excluded.
- Mutation score complements coverage: coverage finds code no test runs, mutation testing finds code no test really checks.
Interview angle
“Coverage is 90%. How do you know whether the tests are any good?”
Coverage only shows lines were executed. Mutation testing shows whether tests notice changes: a tool like PIT or mutmut makes small changes such as >= to >, runs the tests against each, and reports which mutants survived. Each survivor is a missing assertion or boundary case. On pricing rules I have seen 89% line coverage kill only 63% of mutants; adding boundary tests at the exact edges took it to all but one, which was an equivalent mutant that cannot change behaviour. I run it on critical logic, incrementally in CI.
Practice
These run in your browser and check your answer.
Kill the mutant
This shipping function is correct. A mutation tool changed >= to >, and the tests below the starter did not notice. Write kills_mutant() so it returns True only if the given function behaves correctly at the edge: call it with 7500 and check the result is 0.
def kills_mutant(shipping):
# this check is too far from the edge to notice the mutant
return shipping(10_000) == 0
Hint
Test exactly at the boundary: shipping(7_500).
The full project
Every file from this lab, as it is after the last step.