Python "sqlalchemy.exc.IntegrityError: UNIQUE constraint failed" in CI
sqlalchemy.exc.IntegrityError wraps a database constraint violation. A UNIQUE constraint failed in tests usually means a row with the same key was inserted twice because the test database state was not reset between tests.
What this error means
A test fails with "sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.email" when inserting fixture data.
pytest
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: users.emailCommon causes
Shared database state across tests
A prior test inserted the same unique value and the data was not rolled back or torn down.
Hard-coded fixture values reused by multiple tests
Several tests insert the identical email/slug without isolation, colliding on the unique index.
How to fix it
Isolate each test in a rolled-back transaction
- Wrap each test in a SAVEPOINT/transaction that rolls back in teardown.
- Generate unique values per test (a factory sequence) instead of constants.
- Recreate or truncate tables between tests if rollback is not feasible.
Python
@pytest.fixture
def session(engine):
conn = engine.connect()
txn = conn.begin()
s = Session(bind=conn)
yield s
s.close()
txn.rollback()
conn.close()How to prevent it
- Latchkey managed runners auto-retry genuinely transient infra failures, but constraint collisions from shared state are deterministic and must be fixed with proper test isolation.
- Roll back the DB transaction after each test.
- Use factory sequences for unique fields.
Related guides
Python "sqlalchemy.orm.exc.DetachedInstanceError" in CIFix "DetachedInstanceError: Instance is not bound to a Session" in CI - a SQLAlchemy object was accessed afte…
Python "factory_boy DjangoModelFactory not registered" in CIFix factory_boy errors where a DjangoModelFactory is not wired up in CI - the factory is unregistered with py…
Python "redis.exceptions.ConnectionError" in CIFix "redis.exceptions.ConnectionError: Error connecting to Redis" in CI - the redis-py client could not reach…