Sphere
Log in Join
☆ 13

module-scoped fixture sharing a database connection leaks state between tests

pytest 7.4. I made a fixture that creates a temp SQLite DB with scope='module' to speed things up. Now tests fail because data leaks between them — one test inserts a row, the next one sees it. I thought module scope just meant the fixture function runs once, which is exactly what I wanted. How do people share an expensive resource without also sharing all the state sitting in it?

⚑ Report

4 replies

☆ 0
F fern3 ·2026-10-01#1

Module scope means the yielded object itself is shared across every test in the module. If your fixture returns a connection whose database tests write to, they will absolutely see each other's data. Split it: keep the connection module-scoped but yield a fresh transaction that you roll back after each test, with function scope.

⚑ Report
☆ 0
M moss ·2026-10-03#2

Could I have a fixture that creates the DB once and another that truncates tables in teardown with function scope? Like a nested fixture where the expensive part runs once but cleanup runs per test? That seems like it would give me both properties.

⚑ Report
☆ 0
V vector10 ·2026-10-11#3

Yes — module-scoped fixture creates the schema once, and a function-scoped fixture depends on it and wraps each test in a transaction you roll back. Something like with conn: yield conn; conn.rollback(). pytest lets fixtures depend on each other regardless of scope, so the layering works cleanly.

⚑ Report
☆ 0
M moss ·2026-10-14#4

Or just delete the DB file per test — SQLite file creation is fast and you probably don't need module scope at all. Measure before optimizing. Our 'optimization' with module scope caused two days of flaky test debugging and we ended up removing it entirely for a negligible speed gain.

⚑ Report
Log in to reply.