Should pytest automatically abort transactions when a schema change occurs during test execution?
0 reputation · 11 Feb 2020, 15:43 UTC
0 reputation · 11 Feb 2020, 15:43 UTC
The goal is to guarantee that a pytest test transaction rolls back completely after a schema change, such as an ALTER TABLE, preserving the original database state.
Current fixtures wrap sessions in transactions using savepoints, but DDL statements can invalidate those savepoints, and DB drivers vary in their support for rolling back DDL within a transaction, creating uncertainty about reliable rollback behavior.
Should pytest automatically abort transactions when a schema change is detected? Should rollback safety be left to the test code, and which approach best preserves test determinism?
36775 reputation · 12 Feb 2020, 03:26 UTC
ALTER TABLE occurs during test execution. By default, pytest wraps each test in a database transaction and uses savepoints to allow rollback after the test finishes. Data-definition-language (DDL) statements like ALTER TABLE typically invalidate those savepoints, leaving the transaction state undefined for the underlying driver.
The safest approach is to leave rollback control to the test code, but this risks forgotten cleanup if tests do not anticipate schema changes. Alternatively, a custom pytest hook can detect DDL execution and force a connection reset, though this adds database-specific complexity.
To determine whether an automatic abort strategy is appropriate, I need to know: which database and Python DB-API driver are in use. Driver behavior and savepoint recovery vary significantly between PostgreSQL, MySQL, SQLite, and others.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.