Sub topic 3
Making tests safe to run in any shard
This chapter assumes you can run a test suite from the command line, read a CI YAML file, and write short Python or shell scripts. Sharding only helps if every shard can run its share of the tests without the others. A suite that passes on one machine can fail once it is split, because splitting removes things the tests quietly relied on.
What changes when you shard
Each shard runs in its own job, usually on its own machine. Three things that held on a single machine no longer hold:
- Order. Shard 2 never runs the tests that shard 1 ran earlier.
- Shared state. Files, databases and caches written by one test are not visible to tests in another shard.
- Membership. When files are added or timing data changes, a test can move to a different shard.
A test that depends on any of these is not independent. It may pass in one split and fail in the next, which makes failures look random.
Common sources of hidden coupling
| Coupling | Example | Fix |
|---|---|---|
| Order dependence | Test B uses a user created by test A | Have each test create its own data |
| Shared database | Two tests edit the same row | Use a separate schema or database per shard, and clean up after each test |
| Fixed ports | Two servers bind port 3000 | Use port 0 so the OS picks a free port |
| Shared files | Tests write to `/tmp/output.txt` | Use a unique temporary directory per test |
| Global state | A test changes an environment variable and never resets it | Restore it in teardown |
| External accounts | Tests sign in as the same user and change its settings | Create a unique user per test or per shard |
Jobs on separate machines do not collide on ports or local files. Collisions still happen when shards share an external resource, such as a staging database or a third-party test account. Those are the most common cause of failures that appear only after sharding.
Check independence before you shard
Run the suite in a different order from the normal one and see whether anything fails. Many runners can randomize order. In pytest, the pytest-randomly plugin does this, and a failing run prints the seed so you can reproduce it.
pip install pytest-randomly
pytest -p randomly # shuffled order, seed is printed
pytest -p "randomly" -p no:cacheprovider --randomly-seed=12345Then run a single file on its own. A test file that fails alone, but passes in the full run, relies on something another file sets up.
pytest tests/test_checkout.pyIf both checks pass, a shard boundary is unlikely to break the suite.
Give each test its own data
The simplest fix is to make every test create what it needs. This example uses pytest's tmp_path fixture, which provides a fresh directory for each test.
import json
def test_writes_report(tmp_path):
report = tmp_path / "report.json"
report.write_text(json.dumps({"ok": True}))
assert json.loads(report.read_text()) == {"ok": True}
def test_starts_with_no_report(tmp_path):
# This directory is new, so no file from the test above can exist here.
assert not (tmp_path / "report.json").exists()Neither test can see the other's file, so they pass in any order and in any shard.
For a database that all shards must reach, include the shard number in the database name. In GitHub Actions, the matrix value is available as ${{ matrix.shard }}:
env:
DB_NAME: app_test_${{ matrix.shard }}Each shard then writes to its own database, such as app_test_1 or app_test_2.
Work from the error message
When a test fails only in CI after you add shards, ask these questions in order:
- Does it pass when run alone? If not, it needs data it does not create.
- Does it pass in shuffled order? If not, it depends on an earlier test.
- Does it fail only when two shards run at once? If so, look for a shared external resource.
Exercise
A test passes in a full single-machine run but fails in shard 3 with "user not found". Another test in the same suite, which runs in shard 1, creates that user. What is the cause, and how do you fix it?
Show answer
The failing test depends on state created by a test in a different shard. Shard 3 never runs the test that creates the user. The fix is to have the failing test create its own user in a setup step or fixture, so it no longer depends on any other test.