How pytest module-scoped fixtures silently share mutable state across tests
A technical article on DEV Community highlights a common pytest pitfall where fixtures set to 'scope=module' share the same object across all tests in a module rather than providing each test its own copy. This means if one test mutates a shared dict or object, subsequent tests receive the already-modified version, causing hard-to-trace failures that only appear when tests run in certain orders. The author recommends three fixes: dropping the scope to the default function level, keeping expensive shared setup while handing each test a deep copy, or using an immutable type like MappingProxyType so mutations raise an immediate error. The article also suggests installing the pytest-randomly plugin to shuffle test execution order in CI, which helps surface order-dependent failures early. The core advice is to treat scope widening as a performance optimisation — only justified when the shared object is proven to be read-only.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in