Testing and QA · Intermediate · 30 min
Fix flaky tests and stop them coming back
By Padding · Updated 18 Nov 2026
Node.js 26 · Playwright 1.65.1 · Python 3 · pytest 9.2.0 · pytest-randomly 5.1.0 · pytest-xdist 3.8.0 · checked on node:26
You will reproduce six common causes of flaky tests in pytest and Playwright, fix each one, and finish with a quarantine rule and a written team policy that stop new flakes slipping in unseen.
On this page
A flaky test passes and fails on the same code. Nobody changed anything, the pipeline went red, someone pressed "re-run" and it went green. After a few weeks of that, the team stops believing red builds, and real bugs walk through.
Flakiness is rarely bad luck. It nearly always comes from a small set of causes, and each one can be made to fail on demand. In this tutorial you build a demo project with one deliberately flaky test per cause, make each one fail reliably, fix it, and prove the fix by running it many times:
- shared state between tests
- tests that depend on running in a certain order
- the real clock and the machine's time zone
- a network call to a service you do not control
- parallel workers writing to the same file
- a fixed sleep in a browser test
The Python examples use pytest with two plugins: pytest-randomly, which runs tests in a different order every time, and pytest-xdist, which runs them in parallel. The browser example uses Playwright's --repeat-each flag and its trace viewer. At the end you write down a team policy: a flaky test is quarantined with an owner and an expiry date, and it is never retried silently.
Step 1 · Set up the demo project
Make a throwaway folder with a Python virtual environment and pin the three test packages. Every command in this tutorial runs from this folder and calls the environment's Python directly, so you do not need to activate it.
mkdir -p ~/flaky-tests-demo/tests
cd ~/flaky-tests-demo
python3 -m venv .venv
.venv/bin/python -m pip install --quiet pytest==9.2.0 pytest-randomly==5.1.0 pytest-xdist==3.8.0
cat > pytest.ini <<'INI'
[pytest]
testpaths = tests
pythonpath = .
addopts = --strict-markers
INI
.venv/bin/python -m pytest --versionpythonpath = . lets the tests import modules that sit in the project folder. --strict-markers turns a mistyped marker name into an error, which matters for the quarantine marker you add at the end.
pytest-randomly switches itself on as soon as it is installed. From now on, every pytest run shuffles the test order and prints the seed it used.
Check it worked
The last command prints pytest 9.2.0. Run .venv/bin/python -m pytest once: with no tests yet it reports no tests ran, and the header has a line like Using --randomly-seed=2864137759 and a plugins: line that lists randomly-5.1.0 and xdist-3.8.0.
Step 2 · Catch shared state and order dependence
Here is a shopping cart kept in a module-level list. Every test in the same process sees the same list, which is the root of the problem.
cd ~/flaky-tests-demo
cat > cart.py <<'PY'
DELIVERY_FEE = 250
_items = [] # one list for the whole process, shared by every caller
def add(name, price):
_items.append({"name": name, "price": price})
def total():
return sum(item["price"] for item in _items)
def checkout():
return total() + DELIVERY_FEE
def clear():
_items.clear()
PY
cat > tests/test_cart.py <<'PY'
import cart
def test_new_cart_is_empty():
assert cart.total() == 0
def test_add_tea():
cart.add("Tea", 450)
assert cart.total() == 450
def test_checkout_charges_delivery():
# Leans on the tea that the test above left in the cart.
assert cart.checkout() == 450 + 250
PY
.venv/bin/python -m pytest -q -p no:randomly tests/test_cart.py-p no:randomly turns the plugin off for one run, so the tests run in file order. That is the order the author always saw, and in it all three pass. Two separate faults hide here: test_new_cart_is_empty only passes if it runs before anything adds to the cart, and test_checkout_charges_delivery only passes if test_add_tea ran first.
Now run the file up to ten times, each time in a fresh random order, and stop at the first failure:
cd ~/flaky-tests-demo
for run in 1 2 3 4 5 6 7 8 9 10; do
.venv/bin/python -m pytest tests/test_cart.py || break
doneOnly one of the six possible orders passes, so a failure usually shows up in the first run or two. When it does, the header of that run has a line like Using --randomly-seed=2864137759, which is the seed it used. To replay exactly that order, pass the seed back, or use the special value last, which reads the previous seed from pytest's cache:
.venv/bin/python -m pytest -q --randomly-seed=last tests/test_cart.pyA failure you can replay on demand is no longer flaky. It is an ordinary bug, and you can debug it like one.
Fix both faults. An autouse fixture empties the cart before and after every test, so no test inherits state. And the checkout test adds its own item, so it no longer depends on another test running first:
cd ~/flaky-tests-demo
cat > tests/test_cart.py <<'PY'
import pytest
import cart
@pytest.fixture(autouse=True)
def empty_cart():
cart.clear()
yield
cart.clear()
def test_new_cart_is_empty():
assert cart.total() == 0
def test_add_tea():
cart.add("Tea", 450)
assert cart.total() == 450
def test_checkout_charges_delivery():
cart.add("Tea", 450)
assert cart.checkout() == 700
PY
.venv/bin/python -m pytest -q --randomly-seed=last tests/test_cart.py
for run in 1 2 3 4 5 6 7 8 9 10; do
.venv/bin/python -m pytest tests/test_cart.py
doneThe better long-term fix is to get rid of the module-level list and pass a fresh cart object into each test through a fixture. The autouse reset is the quick, safe repair when the shared state lives in code you cannot change today.
Check it worked
The replay with --randomly-seed=last, the same order that failed before, now prints 3 passed. All ten random runs end with 3 passed, and each header shows a different Using --randomly-seed= value.
Step 3 · Stop depending on the real clock and time zone
This function dates receipts in UTC, which is the shop's rule. Its test compares the result with date.today(), which uses the machine's local time zone:
cd ~/flaky-tests-demo
cat > receipts.py <<'PY'
from datetime import datetime, timezone
def receipt_date():
"""Receipts are dated in UTC, whatever the shop's time zone."""
return datetime.now(timezone.utc).date().isoformat()
PY
cat > tests/test_receipts.py <<'PY'
from datetime import date
from receipts import receipt_date
def test_receipt_is_dated_today():
assert receipt_date() == date.today().isoformat()
PYOn a laptop in London the test passes most of the day. On a developer's laptop in Nairobi (three hours ahead of UTC) it fails between midnight and 3 am local time, and on a CI runner set to UTC it always passes. That is why such tests get blamed on "the CI being weird".
You do not have to wait for midnight. Run the test under three time zones, set for one command each with the TZ variable:
cd ~/flaky-tests-demo
for zone in UTC LINT-14 SST+11; do
echo "TZ=$zone"
TZ=$zone .venv/bin/python -m pytest -q tests/test_receipts.py || echo "failed with TZ=$zone"
done | tee tz.logLINT-14 and SST+11 are POSIX time zone strings, so they work without a time zone database. The sign is the reverse of what you might expect: LINT-14 is 14 hours ahead of UTC (the Line Islands in Kiribati) and SST+11 is 11 hours behind (American Samoa). They are 25 hours apart, so at any moment at least one of them is on a different date from UTC, and at least one run fails, whatever time you try it.
Fix the code so it accepts the current time as an argument, and give the tests fixed times that sit right on the boundary:
cd ~/flaky-tests-demo
cat > receipts.py <<'PY'
from datetime import datetime, timezone
def receipt_date(now=None):
"""Receipts are dated in UTC, whatever the shop's time zone."""
now = now or datetime.now(timezone.utc)
return now.astimezone(timezone.utc).date().isoformat()
PY
cat > tests/test_receipts.py <<'PY'
from datetime import datetime, timedelta, timezone
from receipts import receipt_date
NAIROBI = timezone(timedelta(hours=3))
def test_receipt_uses_the_utc_date():
late_evening = datetime(2026, 3, 1, 23, 30, tzinfo=timezone.utc)
assert receipt_date(late_evening) == "2026-03-01"
def test_early_morning_in_nairobi_is_still_yesterday_in_utc():
early_morning = datetime(2026, 3, 2, 1, 30, tzinfo=NAIROBI)
assert receipt_date(early_morning) == "2026-03-01"
PY
for zone in UTC LINT-14 SST+11; do
TZ=$zone .venv/bin/python -m pytest -q tests/test_receipts.py
doneThe tests now state the rule instead of restating the code, and they cover the exact case that used to fail. When you cannot add a parameter, for example in a large legacy module, a library such as time-machine can freeze or move the clock inside a test instead. Test time-dependent code with fake clocks covers that in depth.
Check it worked
Before the fix, tz.log shows at least one failed with TZ= line. After it, all three runs print 2 passed.
Step 4 · Take the network out of unit tests
Tests that call a real service fail whenever that service is slow, rate-limited or down, and they fail on patchy connections. On prepaid mobile data they also cost the developer money on every run. To see the effect without depending on anyone else's server, write a small stand-in for a currency-rates API that fails every third request, as overloaded services do:
cd ~/flaky-tests-demo
cat > rates_server.py <<'PY'
"""A stand-in for a currency-rates API that fails every third request."""
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
requests_seen = 0
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
global requests_seen
if self.path == "/health":
return self.reply(200, {"ok": True})
requests_seen += 1
if requests_seen % 3 == 0:
return self.reply(503, {"error": "try again later"})
self.reply(200, {"KES": 129.0, "NGN": 1480.0}) # made-up rates
def reply(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
HTTPServer(("127.0.0.1", 8765), Handler).serve_forever()
PY
cat > pricing.py <<'PY'
import json
import os
import urllib.request
RATES_URL = os.environ.get("RATES_URL", "http://127.0.0.1:8765/rates")
def fetch_rates():
with urllib.request.urlopen(RATES_URL, timeout=5) as response:
return json.load(response)
def price_in(currency, amount_usd):
return round(amount_usd * fetch_rates()[currency], 2)
PY
cat > tests/test_pricing.py <<'PY'
from pricing import price_in
def test_price_in_shillings():
assert price_in("KES", 10) == 1290.0
PYStart the server in your second terminal, from the same folder, and leave it running:
cd ~/flaky-tests-demo
python3 rates_server.pyBack in the first terminal, run the test six times:
cd ~/flaky-tests-demo
for run in 1 2 3 4 5 6; do
.venv/bin/python -m pytest -q tests/test_pricing.py > /dev/null && echo "run $run passed" || echo "run $run FAILED"
done | tee network.logA unit test should check your own logic: here, that the price is multiplied by the rate and rounded. Make the rate source a parameter, and pass a fake in the test:
cd ~/flaky-tests-demo
cat > pricing.py <<'PY'
import json
import os
import urllib.request
RATES_URL = os.environ.get("RATES_URL", "http://127.0.0.1:8765/rates")
def fetch_rates():
with urllib.request.urlopen(RATES_URL, timeout=5) as response:
return json.load(response)
def price_in(currency, amount_usd, fetch=fetch_rates):
return round(amount_usd * fetch()[currency], 2)
PY
cat > tests/test_pricing.py <<'PY'
from pricing import price_in
def fake_rates():
return {"KES": 129.0} # a made-up rate, fixed for the test
def test_price_in_shillings():
assert price_in("KES", 10, fetch=fake_rates) == 1290.0
def test_price_is_rounded_to_cents():
assert price_in("KES", 0.333, fetch=fake_rates) == 42.96
PYStop the server with Ctrl+C in the second terminal, then run the tests again. They pass with nothing listening, which proves they no longer touch the network:
cd ~/flaky-tests-demo
for run in 1 2 3 4 5 6; do
.venv/bin/python -m pytest -q tests/test_pricing.py
doneYou still want to know that the real API answers in the shape you expect. Keep that as a small, separate check that runs on a schedule and alerts someone, not inside the suite that blocks every merge.
Check it worked
Before the fix, network.log shows run 3 FAILED and run 6 FAILED and the other four runs passed. After it, all six runs print 2 passed with the server stopped.
Step 5 · Give parallel workers their own data
pytest-xdist runs tests in several processes at once, which makes a slow suite fast. It also exposes tests that write to a fixed path, a fixed database name or a fixed port. This test writes a report to one shared file, does some slower work, then reads the file back:
cd ~/flaky-tests-demo
cat > export.py <<'PY'
import csv
def write_report(rows, path):
with open(path, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["region", "order"])
writer.writerows(rows)
PY
cat > tests/test_export.py <<'PY'
import time
from pathlib import Path
import pytest
from export import write_report
REPORT = Path(__file__).parent.parent / "out" / "report.csv" # one file for every test
REGIONS = ["lagos", "nairobi", "accra", "kigali", "dakar", "kampala", "lusaka", "harare"]
@pytest.mark.parametrize("region", REGIONS)
def test_report_lists_the_region(region):
REPORT.parent.mkdir(exist_ok=True)
write_report([(region, n) for n in range(3)], REPORT)
time.sleep(0.5) # stands in for the slow part of a real test
lines = REPORT.read_text().splitlines()
assert lines[1].startswith(region)
PY
.venv/bin/python -m pytest -q tests/test_export.pyOne process at a time, all eight pass. Now run them across four workers:
.venv/bin/python -m pytest -n 4 tests/test_export.pySeveral tests fail: while one worker sleeps, another overwrites the file, so the first reads back the wrong region. Which tests fail changes from run to run, which is the mark of a race.
Fix it with pytest's tmp_path fixture, which gives every test its own new directory:
cd ~/flaky-tests-demo
cat > tests/test_export.py <<'PY'
import time
import pytest
from export import write_report
REGIONS = ["lagos", "nairobi", "accra", "kigali", "dakar", "kampala", "lusaka", "harare"]
@pytest.mark.parametrize("region", REGIONS)
def test_report_lists_the_region(region, tmp_path):
report = tmp_path / "report.csv"
write_report([(region, n) for n in range(3)], report)
time.sleep(0.5) # stands in for the slow part of a real test
lines = report.read_text().splitlines()
assert lines[1].startswith(region)
PY
rm -rf out
.venv/bin/python -m pytest -n 4 tests/test_export.pyThe same idea applies to anything shared. For a test database, use a name per worker: pytest-xdist provides a worker_id fixture (gw0, gw1 and so on, or master when it is not running in parallel) that you can build into the name, such as f"shop_test_{worker_id}". For servers, let the operating system pick a free port by binding to port 0.
Check it worked
The run with -n 4 ends with 8 passed, and near the top of the output there is a line something like 4 workers [8 items]. Run it a few more times: it passes every time.
Step 6 · Catch a fixed sleep with Playwright's --repeat-each
The most common flake in browser tests is a fixed wait: "click, wait one second, check". It passes when the app is fast and fails when it is slow. Add Playwright to the same folder. Pin the version so everyone, and CI, runs the same browser builds:
cd ~/flaky-tests-demo
cat > package.json <<'JSON'
{
"name": "flaky-tests-demo",
"private": true,
"type": "module",
"scripts": {
"test:e2e": "playwright test"
}
}
JSON
npm install --save-dev --save-exact @playwright/test@1.65.1
npx playwright install --with-deps chromiumOn Linux, --with-deps also installs the system libraries Chromium needs and may ask for your password. The browser download is large, so on prepaid data do it once on Wi-Fi; Playwright keeps it in a shared cache for later projects on the same version.
Write a page whose stock check takes anywhere from 0.3 to 1.7 seconds, like a real service on a busy day, a config that serves it with Python's built-in web server, and a test that waits a fixed second:
cd ~/flaky-tests-demo
mkdir -p site e2e
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Stock check</title>
</head>
<body>
<button id="check">Check stock</button>
<p id="status" role="status"></p>
<script>
document.getElementById('check').addEventListener('click', () => {
const status = document.getElementById('status');
status.textContent = 'Checking…';
const delay = 300 + Math.random() * 1400; // the stock service is sometimes slow
setTimeout(() => { status.textContent = 'In stock: 12'; }, delay);
});
</script>
</body>
</html>
HTML
cat > playwright.config.js <<'JS'
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
retries: 0,
use: {
baseURL: 'http://127.0.0.1:4321',
trace: 'retain-on-failure',
},
webServer: {
command: 'python3 -m http.server 4321 --bind 127.0.0.1 --directory site',
url: 'http://127.0.0.1:4321',
reuseExistingServer: !process.env.CI,
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
JS
cat > e2e/stock.spec.js <<'JS'
import { test, expect } from '@playwright/test';
test('shows the stock level', async ({ page }) => {
await page.goto('/');
await page.getByRole('button', { name: 'Check stock' }).click();
await page.waitForTimeout(1000);
expect(await page.getByRole('status').textContent()).toBe('In stock: 12');
});
JStrace: 'retain-on-failure' records a trace for every test and keeps it only when the test fails, which is exactly what you want while hunting a flake. Run the test once, then twenty times:
npx playwright test
npx playwright test --repeat-each=20The single run may pass or fail. Over twenty runs, roughly half fail, each with an error saying it expected In stock: 12 and received Checking…. --repeat-each is the tool to reach for whenever you suspect a test: a pass once proves little, a pass twenty or fifty times in a row is evidence.
Check it worked
The summary of the twenty runs lists both failed and passed tests, with the failures named shows the stock level and a repeat number in their output folder names.
Step 7 · Read the failure in the trace and fix the wait
Every failed repeat left a trace file:
cd ~/flaky-tests-demo
find test-results -name trace.zipOpen one in the trace viewer:
npx playwright show-trace "$(find test-results -name trace.zip | head -n 1)"The trace lists each action with a snapshot of the page before and after it. Select the 1000 ms wait and then the textContent call that follows it: the snapshot still shows Checking… in the status line, and the next screen shows the error. The test did not find a bug in the app. It looked too early. If you cannot open a window, for example on a remote machine, copy the zip to your laptop and drop it onto trace.playwright.dev, which opens it in the browser without uploading it.
Replace the sleep and the one-off read with a web-first assertion. expect(locator).toHaveText() keeps checking until the text matches or its timeout runs out, five seconds by default, so it waits as long as needed and no longer:
cd ~/flaky-tests-demo
cat > e2e/stock.spec.js <<'JS'
import { test, expect } from '@playwright/test';
test('shows the stock level', async ({ page }) => {
await page.goto('/');
await page.getByRole('button', { name: 'Check stock' }).click();
await expect(page.getByRole('status')).toHaveText('In stock: 12');
});
JS
npx playwright test --repeat-each=30The Playwright documentation itself says waitForTimeout is for debugging only. A search across your test folder for it, and for time.sleep in Python tests, is a quick way to find the next flake before it finds you.
Check it worked
find printed one or more paths ending in trace.zip. After the fix, the thirty repeats print 30 passed and the test-results folder has no traces left, because no test failed.
Step 8 · Write a quarantine rule and a team policy
Some flakes cannot be fixed the same day. The worst response is to rerun until green, and the second worst is to delete the test or skip it with a comment nobody reads. Quarantine is the middle ground: the test stops blocking merges, but it has a named owner, a ticket and an expiry date, and the build breaks when the date passes.
Add a quarantine marker in tests/conftest.py. Normal runs skip quarantined tests and show the owner and ticket in the skip reason. A marker with missing details, or an expired date, stops the whole run. --run-quarantined runs only the quarantined tests, as expected failures that do not break the build, so a nightly job can record how they behave:
cd ~/flaky-tests-demo
cat > tests/conftest.py <<'PY'
import datetime
import pytest
def pytest_addoption(parser):
parser.addoption(
"--run-quarantined",
action="store_true",
help="run only quarantined tests, without failing the run",
)
def pytest_configure(config):
config.addinivalue_line(
"markers",
"quarantine(owner, issue, expires): known flaky test, skipped until fixed",
)
def pytest_collection_modifyitems(config, items):
run_quarantined = config.getoption("--run-quarantined")
today = datetime.date.today()
expired = []
for item in items:
mark = item.get_closest_marker("quarantine")
if mark is None:
if run_quarantined:
item.add_marker(pytest.mark.skip(reason="not quarantined"))
continue
owner = mark.kwargs.get("owner")
issue = mark.kwargs.get("issue")
expires = mark.kwargs.get("expires")
if not (owner and issue and expires):
raise pytest.UsageError(f"{item.nodeid}: quarantine needs owner, issue and expires")
if datetime.date.fromisoformat(expires) < today:
expired.append(f"{item.nodeid} (owner {owner}, {issue}, expired {expires})")
elif run_quarantined:
item.add_marker(pytest.mark.xfail(reason=f"quarantined: {issue}", strict=False))
else:
item.add_marker(
pytest.mark.skip(reason=f"quarantined: {issue}, owner {owner}, until {expires}")
)
if expired:
raise pytest.UsageError("Quarantine expired, fix or delete: " + "; ".join(expired))
PYQuarantine a test with an expiry two weeks from today. The first command works out the date, so the example stays valid whenever you run it; on your own team you would type the date in:
cd ~/flaky-tests-demo
EXPIRES=$(python3 -c "import datetime; print(datetime.date.today() + datetime.timedelta(days=14))")
cat > tests/test_search.py <<PY
import random
import pytest
@pytest.mark.quarantine(owner="amina", issue="QA-142", expires="$EXPIRES")
def test_suggestions_are_ranked():
assert random.random() < 0.8 # stands in for a test that fails about one run in five
PY
.venv/bin/python -m pytest -q -rs
.venv/bin/python -m pytest -q --run-quarantined -rxX tests/test_search.pyNow see what happens when a quarantine runs out. Add a second quarantined test whose date has passed:
cd ~/flaky-tests-demo
cat > tests/test_expired_example.py <<'PY'
import pytest
@pytest.mark.quarantine(owner="tunde", issue="QA-98", expires="2026-01-01")
def test_old_flake():
assert True
PY.venv/bin/python -m pytest -qThe run stops before any test runs, with ERROR: Quarantine expired, fix or delete: and the test's ID, owner and ticket. Delete the example:
cd ~/flaky-tests-demo
rm tests/test_expired_example.py
.venv/bin/python -m pytest -qOn the Playwright side, retries in CI are acceptable only if they cannot hide anything. A test that fails and then passes on retry is reported as flaky; failOnFlakyTests turns that report into a failed run. Replace the config:
cd ~/flaky-tests-demo
cat > playwright.config.js <<'JS'
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
// Retries in CI collect a trace for a failure, and failOnFlakyTests
// makes any test that only passed on a retry fail the run.
retries: process.env.CI ? 2 : 0,
failOnFlakyTests: !!process.env.CI,
use: {
baseURL: 'http://127.0.0.1:4321',
trace: 'retain-on-failure',
},
webServer: {
command: 'python3 -m http.server 4321 --bind 127.0.0.1 --directory site',
url: 'http://127.0.0.1:4321',
reuseExistingServer: !process.env.CI,
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
JS
CI=1 npx playwright testLast, write the policy down where the team will find it, next to the tests. Keep it short enough that people read it:
cd ~/flaky-tests-demo
cat > FLAKY-TESTS.md <<'MD'
# Flaky tests: how we handle them
1. A flaky test is a bug, in the test or in the product. It gets a ticket the day it is seen.
2. Reproduce before you fix. Python: replay the order with --randomly-seed. Browser: run the
test with --repeat-each=20 and keep the trace.
3. If it cannot be fixed today, quarantine it with @pytest.mark.quarantine(owner=..., issue=...,
expires=...) or test.fixme() with the ticket in the title. Expiry is at most 14 days away.
4. An expired quarantine breaks the build. The owner fixes the test or deletes it, and says
which in the ticket.
5. Never retry silently. No rerun-until-green plugins on the main suite. Playwright retries in CI
only with failOnFlakyTests on, so a pass on retry still fails the run.
6. Quarantined tests run nightly with --run-quarantined. The owner reads the results.
7. A new or changed test passes 20 random orders (pytest) or --repeat-each=20 (Playwright)
before review.
8. No fixed sleeps in tests, no real network calls in unit tests, no shared files, ports or
database names between tests. Read the clock and the time zone from an argument or a fake.
MD
grep -c "^[0-9]\." FLAKY-TESTS.mdAgree the numbers with your team: two weeks and twenty repeats are sensible defaults, not laws. What matters is that every flaky test has a name next to it and a date by which it is gone.
Check it worked
The first quarantine run prints a skip line with quarantined: QA-142, owner amina, until and your date. The --run-quarantined run reports the test as xfailed or xpassed, and exits cleanly either way. The expired example stops the run with Quarantine expired, and after you delete it the normal run passes again. CI=1 npx playwright test prints 1 passed, and grep -c counts 8 rules.
Step 9 · Clean up
Remove the Chromium build this project downloaded, then the demo folder. Run npx playwright uninstall first, from inside the folder, because it needs the project's Playwright to know which browsers to remove:
cd ~/flaky-tests-demo
npx playwright uninstall
cd ~
rm -rf ~/flaky-tests-demoCheck it worked
ls ~/flaky-tests-demo reports that there is no such file or directory. Python, Node.js and any other projects' browsers are untouched. On Linux, the system libraries that npx playwright install --with-deps added with apt stay installed; they are shared packages, so remove them with apt only if you know nothing else needs them.
Next steps
- Build a larger browser suite with locators, mocked APIs and several browsers: write end-to-end browser tests with Playwright.
- Freeze and move time in tests without changing the code under test: test time-dependent code with fake clocks.
- Keep fixtures, markers and parallel runs tidy as the suite grows: organise a growing pytest suite.
- Go back over the basics of fixtures and assertions: 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