Tests That Share State Pass or Fail Depending on Their Order

In progress Testing Python

A test is isolated when its result doesn't depend on which tests ran before it, after it or beside it. Tests that write to a shared database, global variable or file without resetting it break that: each passes alone, and the suite fails, or worse, fails only sometimes. Resetting the shared state before every test, automatically, is what makes results trustworthy.

How Pollution Happens

  • test_create_book adds a book to the database.
  • test_list_books expects exactly the five seeded books and finds six when it runs second.
  • Run alone, or in another order, both pass.

Test runners don't promise an order (plugins shuffle, parallel runs interleave), so the failure moves around and gets labelled "flaky".

Reset Before Every Test

@pytest.fixture(autouse=True)
def reset_db():
    curs.execute("DELETE FROM book")
    conn.commit()
    seed_db()

autouse=True runs the fixture before every test in scope without each test asking for it. Combined with an in-memory SQLite database, the reset is fast and leaves nothing on disk.

Other ways to get there:

  • wrap each test in a transaction and roll it back at the end (Django's TestCase does this);
  • give each test its own data (unique names, factories) instead of relying on a shared seed;
  • avoid module-level mutable globals in the code under test.

References

Review cards

Flashcard Why is it important to reset shared state before every test?

To ensure that each test runs in an isolated environment, and the result of a test does not depend on the state left by previous tests.

Flashcard How do you check that a test suite doesn't depend on test order?

Run it in random order (pytest-randomly or pytest-random-order) with several seeds. An isolated suite stays green.