Tests That Share State Pass or Fail Depending on Their Order
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_bookadds a book to the database.test_list_booksexpects 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
TestCasedoes 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
- Software Testing MOC - hub for testing notes.
- Point the App at a Test Database Before It Imports Its Connection - the in-memory database the reset fixture works on.
- pytest documentation: Autouse fixtures - fixtures that run for every test.