Test Isolation Patterns: Stop Tests From Interfering With Each Other
A test that passes in isolation but fails when run alongside other tests is not a passing test — it's a liability. Tests that share state, depend on execution order, or leave side effects for other tests to trip over create a category of failures that's uniquely hard to debug: the test was fine, the code was fine, but the combination of both running in sequence produced unexpected behavior.
Test isolation means each test starts in a known state, does its work, and leaves nothing behind for the next test to inherit.
What Breaks Test Isolation
The most common culprits:
Shared database state — test A inserts a record, test B queries the same table and finds an unexpected row, test B fails. Or worse: test A's transaction is committed, test B reads the committed data, test A is rolled back — the database is clean but test B already ran against dirty data.
Shared in-memory state — global variables, singleton caches, module-level state that persists between tests. A cached authentication token from test A causes test B to skip auth setup, then test C — which expected auth to fail — passes incorrectly.
Filesystem side effects — test A writes a file, test B reads it, test C creates the same file and fails because it already exists. Temporary files left by tests accumulate in CI and cause intermittent failures.
External service state — test A creates a Stripe customer, test B searches for customers and finds an unexpected entry. Test A's webhook triggers asynchronously and fires during test B's execution.
Time-dependent behavior — test A sets system time to 2025-01-01, test B calculates duration from "now" and gets a wrong result because the clock was frozen.
Pattern 1: Database Transactions with Rollback
For integration tests that use a relational database, wrapping each test in a transaction and rolling back at the end is the gold standard:
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
@pytest.fixture
def db_session():
engine = create_engine('postgresql://localhost/testdb')
connection = engine.connect()
transaction = connection.begin()
Session = sessionmaker(bind=connection)
session = Session()
yield session
session.close()
transaction.rollback()
connection.close()Every test gets a fresh session. Any writes during the test are rolled back at teardown. The next test starts with the database in the same state it was in before the previous test ran.
For ORMs like Django, this pattern is built-in:
from django.test import TestCase
class OrderModelTests(TestCase):
# Django automatically wraps each test in a transaction
# and rolls back after each test
def test_create_order(self):
order = Order.objects.create(user_id=1, total=99.99)
self.assertEqual(Order.objects.count(), 1)
def test_list_orders_empty(self):
# Previous test's order was rolled back
self.assertEqual(Order.objects.count(), 0)The limitation: this doesn't work when your code explicitly commits transactions, or when you need to test behavior that spans multiple transactions. For those cases, use database reset instead.
Pattern 2: Database Reset Between Tests
When transaction rollback won't work, reset the database to a known state before each test:
@pytest.fixture(autouse=True)
def reset_database():
# Before each test
db.truncate_all_tables()
db.run_fixtures() # Load standard test data
yield
# After each test (optional cleanup)
# Not needed if next test also runs reset
# Or use a schema approach
@pytest.fixture(autouse=True)
def fresh_schema():
connection.execute("DROP SCHEMA test CASCADE")
connection.execute("CREATE SCHEMA test")
Base.metadata.create_all(connection)
yieldThis is slower than transaction rollback (requires actual writes and deletes), but handles all cases including tests that commit, tests that use multiple connections, and tests that trigger database triggers.
Pattern 3: Process Isolation for Global State
Language-level global state (module variables, singletons, class variables) doesn't respect database transaction boundaries. For tests that modify global state, process isolation is the reliable option:
Python — using pytest's forked mode:
pip install pytest-forked
# Run each test in a separate process
pytest --forkedThis is expensive (fork overhead), but guarantees complete isolation between tests that modify global state.
More commonly: explicit reset in fixtures:
import importlib
@pytest.fixture(autouse=True)
def reset_global_state():
# Reload the module to reset all module-level state
import myapp.cache
importlib.reload(myapp.cache)
yield
# Or explicitly reset known state variables
from myapp import config
config.reset_to_defaults()The explicit approach is faster and more targeted. It requires knowing what state can accumulate — which you discover through the flaky tests that reveal hidden shared state.
Pattern 4: Filesystem Isolation
Tests that read from or write to the filesystem need temporary directories that are created fresh for each test and cleaned up after:
Python with tmp_path:
def test_export_to_csv(tmp_path):
# tmp_path is a pytest fixture that provides a unique temporary directory
output_file = tmp_path / "export.csv"
export_data(output=str(output_file))
content = output_file.read_text()
assert 'user_id,name,email' in content
# tmp_path is automatically cleaned up after the testPython with tempfile:
import tempfile
import os
@pytest.fixture
def temp_dir():
with tempfile.TemporaryDirectory() as tmpdir:
yield tmpdir
# Directory is automatically deleted after the context manager exits
def test_file_processor(temp_dir):
input_file = os.path.join(temp_dir, 'input.json')
with open(input_file, 'w') as f:
json.dump({'key': 'value'}, f)
result = process_file(input_file)
assert result['processed'] is TrueNever write to absolute paths in tests (/tmp/test_output.csv) — this creates contention between parallel test runs and leaves files behind on failure.
Pattern 5: Time Isolation
Tests that depend on current time are inherently non-deterministic unless you control the clock:
Python with freezegun:
from freezegun import freeze_time
from datetime import datetime
@freeze_time("2025-01-15 12:00:00")
def test_order_expiry():
order = create_order(created_at=datetime(2025, 1, 15, 10, 0, 0))
assert order.is_expired() is False # 2 hours ago, not yet expired (24h window)
@freeze_time("2025-01-16 12:00:00")
def test_order_expired():
order = create_order(created_at=datetime(2025, 1, 15, 10, 0, 0))
assert order.is_expired() is True # 26 hours agoJavaScript with jest fake timers:
describe('session timeout', () => {
beforeEach(() => {
jest.useFakeTimers();
jest.setSystemTime(new Date('2025-01-15T12:00:00Z'));
});
afterEach(() => {
jest.useRealTimers();
});
it('expires session after 30 minutes', () => {
const session = createSession();
jest.advanceTimersByTime(31 * 60 * 1000); // Advance 31 minutes
expect(session.isExpired()).toBe(true);
});
});Always restore real timers in teardown. Leaving fake timers active causes any subsequent test that relies on real time to behave incorrectly.
Pattern 6: External Service Isolation
Tests that call external HTTP services should either mock those calls or use a local stub server:
Mock at the library level (requests-mock):
import requests_mock
def test_payment_gateway_decline(requests_mock):
requests_mock.post(
'https://api.stripe.com/v1/charges',
json={'error': {'code': 'card_declined'}},
status_code=402
)
with pytest.raises(PaymentDeclinedError):
charge_card(amount=100, card_token='tok_test')Stub server approach (for more complex scenarios):
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading
class StubStripeHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == '/v1/charges':
self.send_response(200)
self.end_headers()
self.wfile.write(b'{"id":"ch_test","status":"succeeded"}')
def log_message(self, *args):
pass # Suppress output
@pytest.fixture(scope='session')
def stub_stripe():
server = HTTPServer(('localhost', 0), StubStripeHandler)
port = server.server_address[1]
thread = threading.Thread(target=server.serve_forever)
thread.daemon = True
thread.start()
with patch.dict(os.environ, {'STRIPE_BASE_URL': f'http://localhost:{port}'}):
yield f'http://localhost:{port}'
server.shutdown()The stub server approach is more realistic than response-level mocking but still completely isolated from real external services.
Running Tests in Parallel
Good isolation enables parallel test execution, which is the primary payoff. When tests don't share state, you can run them concurrently:
# pytest-xdist for parallel execution
pip install pytest-xdist
pytest -n auto # Use all available CPU coresTests that looked isolated but share a database connection pool, a port number, or a temp directory path will fail when parallelized — making parallelization an excellent isolation detector.
For production monitoring that catches issues your isolated tests can't simulate, HelpMeTest provides continuous API health checks that run against live endpoints where real shared state, caches, and concurrent access reveal the issues your isolated test suite cannot.