python data_error ai_generated true

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) 重复键值违反唯一约束 "users_email_key"

sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "users_email_key"

ID: python/pytest-sqlalchemy-fixture-rollback

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2025-11-10首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

数据库 fixture 未在测试之间回滚事务,导致先前测试的数据持久化。

English

The database fixture does not roll back transactions between tests, causing data from previous tests to persist.

generic

解决方案

  1. 95% 成功率
    @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()
  2. 90% 成功率
    Use pytest-sqlalchemy's fixtures or factory_boy with a session that rolls back after each test.

无效尝试

常见但无效的做法:

  1. 70% 失败

    This is a workaround that does not fix the underlying state leakage and may lead to other issues.

  2. 80% 失败

    This is slow and may not be feasible for large test suites.