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

- **ID:** `python/pytest-sqlalchemy-fixture-rollback`
- **领域:** python
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

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

## 无效尝试

- **** — This is a workaround that does not fix the underlying state leakage and may lead to other issues. (70% 失败率)
- **** — This is slow and may not be feasible for large test suites. (80% 失败率)
