Home / Companies / Mergify / Blog / Post Details
Content Deep Dive

pytest fixture teardown races: when yield-style cleanup eats itself

Blog post from Mergify

Post Details
Company
Date Published
Author
-
Word Count
1,120
Language
English
Hacker News Points
-
Summary

In Rémy Duthu's discussion about pytest fixture teardown races, the focus is on the issue that arises when session-scoped fixtures cause state inconsistencies, particularly in CI environments. The problem occurs when fixtures like seeded_users and admin, which share a database connection, are torn down in the reverse order of their setup, sometimes leading to unexpected deletions due to dependence on shared external resources. A naive defensive teardown can mitigate some visible failures but may still leave orphaned states. The recommended solution is to explicitly declare dependencies between fixtures to ensure proper teardown order, or to isolate fixtures by giving each its own connection. Additional solutions include using transactional fixtures for databases like PostgreSQL to handle rollbacks automatically, ensuring each test operates on a clean database state. Tools like Mergify can help detect these teardown race conditions by tagging tests sensitive to lifecycle issues, allowing for automated quarantine and smoother CI processes. The article also notes that fixture teardown races are part of broader patterns of flaky tests in pytest, often related to state not being cleaned up as expected.