python data_error ai_generated true

sqlite3.OperationalError:数据库已锁定

sqlite3.OperationalError: database is locked

ID: python/pytest-parallel-fixture-db-collision

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

版本兼容性

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

根因分析

多个 xdist 工作进程共享同一个 SQLite 文件(或同一 fixture 创建的数据库路径)并争用写锁。

English

Multiple xdist workers share the same SQLite file (or the same fixture-created DB path) and contend for write locks.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def db(tmp_path, worker_id):
        path = tmp_path / f"test-{worker_id}.db"
        conn = sqlite3.connect(path)
        yield conn
        conn.close()
  2. 90% 成功率
    # docker-compose with postgres
    # pytest.ini
    [pytest]
    addopts = -n auto
    # DATABASE_URL=postgresql://user:pass@localhost/test
  3. 88% 成功率
    pytestmark = pytest.mark.xdist_group(name="db")
    # run: pytest -n auto --dist=loadgroup

无效尝试

常见但无效的做法:

  1. 70% 失败

    Reduces but does not eliminate lock contention under load.

  2. 60% 失败

    Disables parallelism; CI time blows up.

  3. 85% 失败

    Autocommit increases contention rather than reducing it.