Skip to content
Latchkey

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.email

Common 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

  1. Wrap each test in a SAVEPOINT/transaction that rolls back in teardown.
  2. Generate unique values per test (a factory sequence) instead of constants.
  3. 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →