QA and Test Automation · Lab 7 of 35
Find and Fix a Flaky Test: Hands-On Lab on ShopRung
Take a ShopRung test suite that passes every time in its usual order, shuffle it and watch it fail, measure how often it fails, reproduce one failure exactly with its seed, find the cause (tests sharing state), fix it properly, and prove the fix. Plus the other common causes and a quarantine policy.
⏱ 45 minIntermediate💸 Free7 stepsJava + Python
Java 21 + Maven + JUnit 5.11Python 3.12 + pytest + pytest-randomly (second path)ShopRung
Overview video
What you will build
A checkout test suite for ShopRung in two versions:
- As first written: three tests that pass every time in the order they are written, and fail in most other orders. In Python, only 2 of 10 random orders passed; in Java, 1 of the 6 possible orders.
- Fixed: every test sets up its own data, so all orders pass: 10 of 10 seeds, and 60 of 60 when each test is repeated 20 times.
You also get a small flake_rate.py script that runs a suite many times in random orders and reports its pass rate and the seeds that failed.
Before you start
- The idea behind this lab: Flaky tests and Test reliability at scale.
- Java path: Your first Java test project. Python path: pytest basics, as in the pytest API lab.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Make the project
Java: Maven folders for tests and test resources. Python: a folder with tests and a virtual environment.
# Java
mkdir -p shoprung-flaky/src/test/java/dev/algorung/flaky shoprung-flaky/src/test/resources
# Python
mkdir -p shoprung-flaky-py/tests && cd shoprung-flaky-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir -p shoprung-flaky/src/test/java/dev/algorung/flaky shoprung-flaky/src/test/resources
# Python
mkdir -p shoprung-flaky-py/tests && cd shoprung-flaky-py && python3 -m venv .venv && source .venv/bin/activate# Java
mkdir shoprung-flaky\src\test\java\dev\algorung\flaky, shoprung-flaky\src\test\resources
# Python
mkdir shoprung-flaky-py\tests; cd shoprung-flaky-py; py -m venv .venv; .venv\Scripts\Activate.ps1 The project and a tiny ShopRung client
A build with JUnit only, and a helper that talks to ShopRung with the JDK's HTTP client.
Java: pom.xml needs only JUnit. Shop.java sends requests with java.net.http, so there is nothing else to install: post, get, reset and loginAlice (which pulls the token out of the response).
Python: requirements.txt adds two pytest plugins you will need: pytest-randomly, which shuffles the test order on every run and prints the seed it used, and pytest-repeat, which runs each test many times.
<?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-flaky</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>
</plugins>
</build>
</project> package dev.algorung.flaky;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/** A tiny ShopRung client: just enough HTTP for these tests, with the JDK only. */
final class Shop {
static final String BASE_URL = System.getProperty("baseUrl", "http://localhost:8080");
private static final HttpClient HTTP = HttpClient.newHttpClient();
private Shop() {}
static HttpResponse<String> post(String path, String token, String json) {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE_URL + path))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json == null ? "" : json));
if (token != null) b.header("Authorization", "Bearer " + token);
return send(b.build());
}
static HttpResponse<String> get(String path, String token) {
HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(BASE_URL + path));
if (token != null) b.header("Authorization", "Bearer " + token);
return send(b.build());
}
static void reset() {
post("/api/test/reset", null, null);
}
static String loginAlice() {
String body = post("/api/auth/login", null,
"{\"email\":\"alice@shoprung.test\",\"password\":\"Alice123!\"}").body();
return body.replaceAll(".*\"token\":\"([^\"]+)\".*", "$1");
}
private static HttpResponse<String> send(HttpRequest request) {
try {
return HTTP.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException | InterruptedException e) {
throw new IllegalStateException("ShopRung is not reachable at " + BASE_URL + ": start it with npm start", e);
}
}
} mvn test -DbaseUrl=...for another server.line 11- Puts ShopRung back to its seed data. Where you call it is the whole story of this lab.line 30
- Pulls the token out of the JSON without a JSON library.line 37
pytest==8.3.4
httpx==0.28.1
pytest-randomly==3.16.0
pytest-repeat==0.9.3 - Random order on every run, with a reproducible seed.line 3
--count=20runs each test 20 times.line 4
[pytest]
testpaths = tests
# pytest-randomly shuffles test order on every run and prints the seed; -p no:randomly turns it off. Python version of this step:
pip install -r requirements.txt Successfully installed ... pytest-randomly-3.16.0 pytest-repeat-0.9.3 ...
The suite as first written: always green
Three checkout tests that pass every time you run them in their usual order.
Create the test file below. It looks reasonable: reset ShopRung and log Alice in once for the whole class (or file), then three tests: add four notebooks ($50.00), apply SAVE10 (total $49.99), place the order (the cart empties).
Run it a few times. It passes every time, because the tests always run in the same order. Many real suites look exactly like this, and nobody notices the problem until the order changes: a new test is added, a framework is upgraded, or the suite is split across parallel workers.
Java note: JUnit's default order is fixed but not guaranteed to be top to bottom, so for this step run with the method-name order, which matches the numbers in the names.
package dev.algorung.flaky;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/** The checkout flow, as first written. Every test passes when they run top to bottom... */
class CheckoutFlowTest {
static String alice;
@BeforeAll
static void resetOnceAndLogIn() {
Shop.reset(); // ONCE for the whole class
alice = Shop.loginAlice();
}
@Test
void test1AddFourNotebooks() {
var r = Shop.post("/api/cart/items", alice, "{\"productId\":1,\"quantity\":4}");
assertTrue(r.body().contains("\"subtotalCents\":5000"), r.body());
}
@Test
void test2Save10AppliesAt50Dollars() {
var r = Shop.post("/api/cart/coupon", alice, "{\"code\":\"SAVE10\"}");
assertEquals(200, r.statusCode(), r.body());
assertTrue(r.body().contains("\"totalCents\":4999"), r.body());
}
@Test
void test3CheckoutEmptiesTheCart() {
var r = Shop.post("/api/orders", alice, null);
assertEquals(201, r.statusCode(), r.body());
assertTrue(Shop.get("/api/cart", alice).body().contains("\"itemCount\":0"));
}
} - Once for the whole class. Every test shares one cart.line 13
- Silently needs test1 to have run first.line 26
- Needs a full cart, which only test1 provides.line 33
"""The checkout flow, as first written. Every test passes when they run top to bottom..."""
import os
import httpx
import pytest
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
@pytest.fixture(scope="module")
def alice():
"""Reset ShopRung ONCE for the whole file, then log Alice in."""
httpx.post(f"{BASE_URL}/api/test/reset").raise_for_status()
token = httpx.post(f"{BASE_URL}/api/auth/login",
json={"email": "alice@shoprung.test", "password": "Alice123!"}).json()["token"]
with httpx.Client(base_url=BASE_URL, headers={"Authorization": f"Bearer {token}"}) as client:
yield client
def test_1_add_four_notebooks(alice):
r = alice.post("/api/cart/items", json={"productId": 1, "quantity": 4})
assert r.json()["subtotalCents"] == 5000
def test_2_save10_applies_at_50_dollars(alice):
r = alice.post("/api/cart/coupon", json={"code": "SAVE10"})
assert r.status_code == 200, r.json()["message"]
assert r.json()["totalCents"] == 4999
def test_3_checkout_empties_the_cart(alice):
r = alice.post("/api/orders")
assert r.status_code == 201, r.json()["message"]
assert alice.get("/api/cart").json()["itemCount"] == 0 - Once for the whole file. Every test shares one cart.line 10
- Silently needs test_1 to have run first.line 25
- Needs a full cart, which only test_1 provides.line 31
Python version of this step:
mvn test -Djunit.jupiter.testmethod.order.default=org.junit.jupiter.api.MethodOrderer\$MethodName [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q -p no:randomly ... [100%] 3 passed in 0.20s
Shuffle the order and watch it fail
Run the same tests in a random order, read the failures, and see they are not about checkout at all.
Java: create src/test/resources/junit-platform.properties (below). It makes JUnit run test methods in a random order, decided by a seed: the same seed always gives the same order. Python: pytest-randomly is already on; it prints the seed at the top of every run.
Run with seed 1. Now the checkout test runs before anything was added: Your cart is empty. SAVE10 runs before the notebooks: This coupon needs a subtotal of at least $50.00. Neither failure is a bug in ShopRung. The tests depend on each other.
# Run test methods in a random order, so hidden dependencies between tests show up.
junit.jupiter.testmethod.order.default = org.junit.jupiter.api.MethodOrderer$Random
# The seed decides the order. Change it (or pass -Djunit.jupiter.execution.order.random.seed=7) to try another
# order; keep a failing seed to reproduce the failure exactly.
junit.jupiter.execution.order.random.seed = 1 - A random order for every test class.line 2
- The seed. Keep the one that failed: it reproduces the exact order.line 5
mvn test [ERROR] CheckoutFlowTest.test3CheckoutEmptiesTheCart:... expected: <201> but was: <400>
{"error":"empty_cart","message":"Your cart is empty"}
[ERROR] CheckoutFlowTest.test2Save10AppliesAt50Dollars:... expected: <200> but was: <400>
... "This coupon needs a subtotal of at least $50.00"
[ERROR] Tests run: 3, Failures: 2 pytest -v --randomly-seed=1 Using --randomly-seed=1 ... tests/test_checkout_flow.py::test_3_checkout_empties_the_cart FAILED tests/test_checkout_flow.py::test_2_save10_applies_at_50_dollars FAILED tests/test_checkout_flow.py::test_1_add_four_notebooks PASSED ... E AssertionError: Your cart is empty E AssertionError: This coupon needs a subtotal of at least $50.00 2 failed, 1 passed in 0.22s
Measure the flakiness, and reproduce it
A pass rate across many orders, and one failing order you can replay exactly.
"It fails sometimes" is not a bug report. Measure it. In Python, flake_rate.py runs the suite 10 times with seeds 1 to 10 and prints how many runs passed and which seeds failed. On ShopRung this suite passed 2 of 10 runs.
In Java, there are only 3 tests, so there are only 6 possible orders; we ran all six against ShopRung and only 1 passed: the original order. Try a few seeds yourself with -Djunit.jupiter.execution.order.random.seed=N.
The seed is the reproduction recipe: pytest --randomly-seed=1 or the Java seed property gives the same failing order every time. Put it in the bug ticket.
"""Run the suite N times, each in a different random order, and report how often it passed.
Usage: python flake_rate.py 10
"""
import subprocess
import sys
runs = int(sys.argv[1]) if len(sys.argv) > 1 else 10
failed_seeds = []
for seed in range(1, runs + 1):
result = subprocess.run([sys.executable, "-m", "pytest", "-q", f"--randomly-seed={seed}"],
capture_output=True, text=True)
if result.returncode != 0:
failed_seeds.append(seed)
passed = runs - len(failed_seeds)
print(f"{passed}/{runs} runs passed ({100 * passed // runs}%)")
if failed_seeds:
print("failing seeds:", " ".join(map(str, failed_seeds)))
print(f"reproduce one with: pytest --randomly-seed={failed_seeds[0]}") - One full run per seed: a different order each time.line 10
- A failing seed replays the exact same order.line 20
Python version of this step:
mvn test -Djunit.jupiter.execution.order.random.seed=2
mvn test -Djunit.jupiter.execution.order.random.seed=3 Some seeds fail and some pass: the order changes, the code does not.
python flake_rate.py 10 2/10 runs passed (20%) failing seeds: 1 2 3 5 6 7 8 9 reproduce one with: pytest --randomly-seed=1
Fix the cause: each test owns its data
Reset before every test, and let each test arrange exactly what it needs.
The cause is shared state: one reset for the whole class, and tests that rely on what earlier tests left behind. The fix has two parts:
- Reset and log in before every test (
@BeforeEach, or a function-scoped fixture). - Each test arranges its own data. SAVE10 and checkout both need $50.00 in the cart, so they call
addFourNotebooks()themselves. A test reads top to bottom as a complete story.
Notice what we did not do: no retries, no sleeps, no @Order annotations to force the old order. Those hide the problem; this removes it. Rename the methods too: the numbers suggested an order that must not matter.
package dev.algorung.flaky;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.http.HttpResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** The checkout flow, fixed: every test sets up its own data, so any order works. */
class CheckoutFlowTest {
String alice;
@BeforeEach
void resetAndLogIn() {
Shop.reset(); // before EVERY test
alice = Shop.loginAlice();
}
/** Arrange: $50.00 in the cart. Each test that needs it calls it itself. */
private HttpResponse<String> addFourNotebooks() {
var r = Shop.post("/api/cart/items", alice, "{\"productId\":1,\"quantity\":4}");
assertEquals(200, r.statusCode(), r.body());
return r;
}
@Test
void addFourNotebooks_subtotalIs50Dollars() {
assertTrue(addFourNotebooks().body().contains("\"subtotalCents\":5000"));
}
@Test
void save10AppliesAt50Dollars() {
addFourNotebooks();
var r = Shop.post("/api/cart/coupon", alice, "{\"code\":\"SAVE10\"}");
assertEquals(200, r.statusCode(), r.body());
assertTrue(r.body().contains("\"totalCents\":4999"), r.body());
}
@Test
void checkoutEmptiesTheCart() {
addFourNotebooks();
var r = Shop.post("/api/orders", alice, null);
assertEquals(201, r.statusCode(), r.body());
assertTrue(Shop.get("/api/cart", alice).body().contains("\"itemCount\":0"));
}
} - Before EVERY test: known data in, known results out.line 14
- Arrange helper: each test calls it when it needs a full cart.line 21
- Arrange, act, assert, all inside the test.line 41
"""The checkout flow, fixed: every test sets up its own data, so any order works."""
import os
import httpx
import pytest
BASE_URL = os.getenv("BASE_URL", "http://localhost:8080")
@pytest.fixture
def alice():
"""For EVERY test: reset ShopRung, then log Alice in."""
httpx.post(f"{BASE_URL}/api/test/reset").raise_for_status()
token = httpx.post(f"{BASE_URL}/api/auth/login",
json={"email": "alice@shoprung.test", "password": "Alice123!"}).json()["token"]
with httpx.Client(base_url=BASE_URL, headers={"Authorization": f"Bearer {token}"}) as client:
yield client
def add_four_notebooks(client):
"""Arrange: $50.00 in the cart. Each test that needs it calls it itself."""
r = client.post("/api/cart/items", json={"productId": 1, "quantity": 4})
assert r.status_code == 200, r.text
return r
def test_add_four_notebooks(alice):
assert add_four_notebooks(alice).json()["subtotalCents"] == 5000
def test_save10_applies_at_50_dollars(alice):
add_four_notebooks(alice)
r = alice.post("/api/cart/coupon", json={"code": "SAVE10"})
assert r.status_code == 200, r.json()["message"]
assert r.json()["totalCents"] == 4999
def test_checkout_empties_the_cart(alice):
add_four_notebooks(alice)
r = alice.post("/api/orders")
assert r.status_code == 201, r.json()["message"]
assert alice.get("/api/cart").json()["itemCount"] == 0 - Function scope (the default): a reset and login for every test.line 11
- Arrange helper: each test calls it when it needs a full cart.line 20
- Arrange, act, assert, all inside the test.line 38
Python version of this step:
mvn test [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
pytest -q --randomly-seed=1 ... [100%] 3 passed in 0.36s
Prove the fix
Every order passes, and every test passes 20 times in a row.
One green run proves little for a flaky test. Run it the way it failed, many times: every seed, and every test repeated. In Python, all 10 seeds passed and --count=20 ran each test 20 times: 60 passed. In Java, all 6 of 6 orders now pass; check a few seeds, and use @RepeatedTest(20) on a test if you want repeats.
Keep random order switched on for good. It costs nothing and catches the next hidden dependency the day it is written.
mvn test -Djunit.jupiter.execution.order.random.seed=2
mvn test -Djunit.jupiter.execution.order.random.seed=3 [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS (every seed)
python flake_rate.py 10
pytest -q --count=20 10/10 runs passed (100%) ........................................................................ 60 passed in 6.98s
The other usual suspects, and a quarantine policy
Know the main causes of flakiness and what a team does while fixing them.
Shared state is the most common cause. The others you will meet:
- Timing: reading the page before it updates, fixed sleeps (see Waits and synchronization). Fix: wait for a condition.
- Time and dates: a test that uses today's date fails on the day a coupon expires, or at midnight. Fix: inject a clock (the mocks lab).
- Parallel runs: two workers using the same user. Fix: unique data per test (parallel episode).
- Environment: a slow or shared test server, a third-party sandbox that is down. Fix: mock what you do not own, check health first.
- Unordered results: asserting a list order the API never promised. Fix: sort, or compare as sets.
While a flaky test is being fixed, teams quarantine it: mark it (for example @Tag("quarantine") or @pytest.mark.quarantine), exclude it from the blocking run, keep running it separately, and give it an owner and a deadline. Automatic retries can be useful to keep the pipeline moving, but only if every retried pass is recorded and investigated: a retry that hides a flake also hides real intermittent bugs.
Check it works
The lab worked when both of these are true:
- The version from step 2 fails for most random orders (Python: about 2 of 10 seeds pass; Java: only the original order of the 6 passes), and a failing seed reproduces the same failure every time.
- The fixed version passes every seed you try, and 20 repeats of each test.
python flake_rate.py 10
# Java: mvn test with seeds 1, 2 and 3 10/10 runs passed (100%)
Troubleshooting
Python: the order does not change between runs.
pytest-randomly is not installed in the active environment, or you passed -p no:randomly. pip install -r requirements.txt inside the virtual environment.
Java: the order is the same for every seed.
Check the properties file is at src/test/resources/junit-platform.properties and the class name is org.junit.jupiter.api.MethodOrderer$Random.
Every test fails with a connection error.
ShopRung is not running. Start it with npm start, or pass the base URL.
The fixed suite still fails sometimes.
Look for state outside the test: another suite or a person using the same ShopRung at the same time. Each test run needs its own environment, or its own data.
What changes in production
- Teams track flakiness as a number: the pass rate of each test over many CI runs. Tools in CI dashboards flag tests that both pass and fail on the same commit.
- Random test order is switched on permanently in many codebases, with the seed printed in every log.
- Flaky tests are quarantined with an owner and a deadline, never just retried forever or deleted.
- Independent tests (own data, no order) are also what makes parallel runs and sharding possible, which is how big suites stay fast.
Interview angle
“A test passes locally and fails in CI one run in five. How do you handle it?”
First reproduce and measure: run it many times, in random order and in parallel like CI, and record the pass rate and a failing seed or log. Then find the cause from the evidence: shared state and order dependence, timing and missing waits, dates and time zones, parallel data collisions, or an unstable environment. Fix the cause (own data per test, condition-based waits, an injected clock, unique test data) instead of adding sleeps or retries, then prove it with many repeated runs. While it is being fixed, quarantine it with an owner so the pipeline stays trustworthy.
Clean up
The full project
Every file from this lab, as it is after the last step.