python
data_error
ai_generated
true
sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "users_email_key"
ID: python/pytest-sqlalchemy-fixture-rollback
80%Fix Rate
85%Confidence
0Evidence
2025-11-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
The database fixture does not roll back transactions between tests, causing data from previous tests to persist.
generic中文
数据库 fixture 未在测试之间回滚事务,导致先前测试的数据持久化。
Workarounds
-
95% success
@pytest.fixture(scope='function') def db_session(): connection = engine.connect() transaction = connection.begin() session = Session(bind=connection) yield session session.close() transaction.rollback() connection.close() -
90% success
Use pytest-sqlalchemy's fixtures or factory_boy with a session that rolls back after each test.
Dead Ends
Common approaches that don't work:
-
70% fail
This is a workaround that does not fix the underlying state leakage and may lead to other issues.
-
80% fail
This is slow and may not be feasible for large test suites.