Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Test automation · Fundamentals & Architecture · Chapter 03 / 06

Test automation learning path

Test data & isolation

Building data per test, uniqueness under parallel runs, factories, personas and cleanup.

Data isolation under parallel execution

Green sequentially and red in parallel almost always means shared data — isolate it, never retry it.

A suite that passes sequentially and fails under parallel execution, with the failures moving between tests from run to run, has a data problem rather than a timing one. The usual cause is that several workers act as the same user and mutate the same server-side state. There are three fixes, in order of preference. Isolating the data by giving each worker its own account keeps full parallelism and is the right answer whenever the backend can create accounts on demand — which makes a self-service test-data endpoint one of the highest-leverage things to ask a backend team for. Isolating the state through a per-test tenant or namespace is often better still for multi-tenant products. Serialising related tests onto one worker is correct but caps throughput, so it is a last resort rather than a first response. What is never a fix is a retry: the data was wrong, not late, and a retry converts a visible defect into an invisible one while making the pipeline slower.

Key points

  • Failures that move between tests under parallel execution are the signature of shared data
  • Prefer per-worker or per-test data isolation; serialising related tests caps your throughput
  • A retry is never the fix — the data was wrong, not late

Code

# The failure this fixture exists to prevent:
#
#   $ pytest tests -n 4
#   FAILED tests/services/test_cart_flow.py::test_add_item_to_empty_cart
#   FAILED tests/services/test_cart_flow.py::test_cart_total_is_sum_of_line_totals
#   3 failed, 148 passed        # sequentially: all green
#
# Four workers, one shared account, one shared server-side cart.

@pytest.fixture(scope="session")
def worker_account(base_url, worker_id) -> tuple[str, str]:
    """A dedicated account per xdist worker. Keeps full parallelism."""
    username = f"qa_{worker_id}_{uuid.uuid4().hex[:8]}"
    password = "Str0ng!Passw0rd"
    response = httpx.post(
        f"{base_url}/api/auth/register",
        json={"username": username, "password": password},
    )
    assert response.status_code == 201, f"Could not provision an account: {response.text}"
    return username, password

The registration endpoint was added to the demo app specifically so the suite could parallelise safely.

See it in the framework

  • Implementation · Worker-aware fixtures: conftest.py — live · reviewed
  • Used by · Data factories: framework/data/factories.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Adding a retry flag to make the pipeline green, which hides a genuine isolation defect indefinitely
  • Assuming a shared demo account is fine because it works today — it works until the second worker appears

Practice exercise

Run a suite you work with under four workers, ten times. If nothing fails, deliberately share one account between tests and reproduce the failure, then fix it three ways and rank them.

Uniqueness by construction

Every constrained field gets a worker-aware unique value; timestamps alone are not enough.

Any field with a uniqueness constraint needs a value that cannot collide, and the naive approach of appending a timestamp fails in exactly the situation you care about, because two workers can generate the same millisecond. A suffix that combines the worker identifier with a random component is collision-proof both across workers in one run and across repeated runs of the same worker, which matters when a previous run crashed and left records behind. Beyond mechanics there is a discipline about which values a test states explicitly. A test should specify only the fields the assertion actually depends on and let everything else be generated, because when a test names a value, a future reader has to check whether that value is load-bearing. One practical detail is worth internalising: always generate email addresses on domains reserved for testing, because using a real domain means your suite eventually sends mail to a stranger, and that is a mistake that only has to happen once.

Key points

  • Combine the worker identifier with a random component; timestamps alone can collide
  • Specify only the fields the assertion depends on and generate the rest
  • Generate email addresses on domains reserved for testing, never on a real one

Code

def unique_suffix() -> str:
    """Unique across xdist workers AND across reruns of the same worker."""
    worker = os.getenv("PYTEST_XDIST_WORKER", "gw0")
    return f"{worker}-{uuid.uuid4().hex[:8]}"


def unique_email(prefix: str = "qa") -> str:
    # .test is reserved by RFC 2606. Never generate on a real domain.
    return f"{prefix}+{unique_suffix()}@example.test"


# Specify only what the test is about; everything else is generated.
user = UserBuilder().with_email("boundary@example.test").build()

# Faker stays unseeded by default so variety keeps finding bugs, and is seeded
# only when reproducing a specific failure:
#   QA_FAKER_SEED=42 pytest -k the_failing_test

Worker identity plus randomness; a reserved domain; and a seed used only for reproduction.

See it in the framework

  • Implementation · Unique-suffix implementation: framework/data/factories.py — live · reviewed
  • Used by · Used by: conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • A timestamp-only suffix, which collides precisely when two workers run in step
  • Seeding the random generator globally for reproducibility, which reintroduces collisions across parallel workers

Practice exercise

Audit a suite for hardcoded usernames, emails and reference numbers. Replace each with a generated unique value and confirm the suite still passes under four workers.

Builders, factories and personas

Builders for readable overrides, model factories for valid instances, and a deliberately short persona list.

Three patterns cover almost all test data needs, and choosing between them is about what the test cares about. A builder is right when a test wants to override specific fields and read clearly while doing it; a fluent interface producing an immutable result keeps a test from mutating shared state accidentally. A factory derived from a model is right when the test needs a valid instance and genuinely does not care about the values, and because it is generated from the schema it cannot drift away from it. Personas are the third pattern and the one to use most sparingly: they are for the small number of accounts that genuinely must pre-exist, such as single-sign-on users or accounts with a verified payment method. Every persona is shared mutable state waiting to cause a parallel-execution failure, so keep the list short and restrict personas to read-only scenarios while any test that changes data uses a generated account.

Key points

  • Builders for readable, specific overrides; model factories for a valid instance you do not care about
  • Personas are for accounts that genuinely cannot be created per test — keep the list short
  • Use personas for read-only scenarios; anything that mutates data uses a generated account

Code

@dataclass
class UserBuilder:
    _username: str = field(default_factory=unique_username)
    _password: str = "Str0ng!Passw0rd"
    _email: str = field(default_factory=unique_email)

    def with_email(self, value: str) -> Self:
        self._email = value
        return self

    def build(self) -> UserData:          # frozen result, cannot be mutated
        return UserData(self._username, self._password, self._email)


class ProductFactory(ModelFactory[Product]):
    """Derived from the model, so it can never drift from the schema."""

    __model__ = Product


PERSONAS = {
    "standard": Persona("alice", "wonderland", "Ordinary shopper, read-only scenarios"),
}

Builder for specifics, factory for anything valid, persona only where pre-existing state is unavoidable.

See it in the framework

  • Implementation · Builders and factories: framework/data/factories.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • A growing persona list, which slowly recreates the shared-state problem the generated data solved
  • A builder returning a mutable object, so one test's change leaks into another through a shared default

Practice exercise

Count the shared accounts in a suite you work with. For each, decide whether it is genuinely unable to be created per test, and convert the ones that can be to generated data.

Cleanup strategies and their trade-offs

Clean before as well as after, keep cleanup idempotent, and never let a global reset near a parallel run.

Fixture teardown is the default cleanup mechanism and it has one important gap: it does not run when setup failed before the suspension point, so a crash mid-setup leaves state behind for the next run to inherit. Cleaning defensively at the start of a fixture as well as at the end makes a suite recoverable rather than merely tidy. Other strategies suit other situations. Generating uniquely named data and never cleaning it works well when data is cheap and namespaced, at the cost of a database that grows forever and eventually needs a scheduled sweeper that matches your naming prefix. Transaction rollback is elegant but only available when the tests share a database session with the application. A global reset endpoint is the one to be careful with, because it is fundamentally incompatible with parallel execution — each worker's reset destroys the other workers' live state. Whatever you choose, cleanup has to be idempotent, and its failure should never replace or hide the test's own result — if the test's assertions already passed or failed, that verdict is what matters, and a teardown exception shouldn't bury it under a confusing traceback. That's different from making cleanup failures invisible, though: pytest already reports a teardown exception as its own outcome, distinct from the test's pass or fail, and that visibility is doing real work — a cleanup step that silently swallows its own exceptions can leave contaminated state for the next test with nothing in the report to explain why. Treat a repeated cleanup failure as a signal about your test infrastructure's health, not noise to suppress.

Key points

  • Teardown after the suspension point does not run if setup raised — clean defensively at the start too
  • Cleanup must be idempotent; a teardown failure should surface (pytest reports it as its own outcome) rather than being silently swallowed and left to contaminate later tests
  • A global reset endpoint cannot coexist with parallel execution; keep it as a manual pre-run step

Code

@pytest.fixture
def shop_as_user(shop, worker_account):
    username, password = worker_account
    shop.login_as(username, password)

    shop.cart.clear()   # BEFORE: the previous run may have crashed mid-test
    yield shop
    shop.cart.clear()   # after


# What was REMOVED from this suite, and why the comment stayed behind:
#
#   @pytest.fixture(autouse=True, scope="session")
#   def _reset_sut(base_url):
#       httpx.post(f"{base_url}/api/testing/reset")
#
# "session" means once per WORKER. Under -n 4 each worker's reset wiped the
# other three workers' live sessions mid-run. Keep a global reset as a manual
# pre-run step only:  curl -X POST http://127.0.0.1:8000/api/testing/reset

Leaving the explanation next to the deleted code stops somebody re-adding it in six months.

See it in the framework

  • Implementation · Before/after cleanup: tests/services/conftest.py — live · reviewed
  • Used by · Web cleanup: tests/web/conftest.py — live · reviewed
  • Used by · Root fixtures: conftest.py — live · reviewed

Reviewed against commit f9ada16 (2026-08-14).

Common pitfalls

  • Swallowing a cleanup exception just to keep the test green, which hides the exact contamination that will make some later, unrelated-looking test fail for a reason nobody can trace
  • Relying on teardown alone, so one crashed run poisons every run after it until somebody cleans up by hand

Practice exercise

Find a fixture that only cleans up on teardown. Make its setup fail deliberately, observe the state left behind, then add defensive cleanup at the start and confirm the next run recovers.

Source registry

5 chapter references
pytest-xdist documentation

Parallel execution, worker identity and test distribution modes

pytest-dev · Official documentation
Source ↗
qa-automation-python reference framework

The runnable framework and demo application every lesson in this path is drawn from

sergiiiavt · Reference implementation
Source ↗
Eradicating Non-Determinism in Tests

Root causes of non-deterministic tests and how to remove rather than mask them

martinfowler.com · Industry article
Source ↗
Pydantic documentation

Model validation, strict configuration and settings management

Pydantic Services · Official documentation
Source ↗
pytest fixtures reference

Fixture scope, autouse, finalisation and the dependency graph

pytest-dev · Official reference
Source ↗