python runtime_error ai_generated true

AssertionError: assert 1 == 2 # 使用 -p no:xdist 时通过,使用 -n auto 时失败

AssertionError: assert 1 == 2 # passes with -p no:xdist, fails with -n auto

ID: python/pytest-xdist-shared-state

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

版本兼容性

版本状态引入弃用备注
7.x active
8.x active

根因分析

测试共享全局状态(模块级缓存、单例、文件),在串行下安全,但在 pytest-xdist 的多个 worker 进程下产生竞态或持久化。

English

Tests share global state (module-level caches, singletons, files) that is safe serially but races or persists across worker processes under pytest-xdist.

generic

解决方案

  1. 90% 成功率
    @pytest.fixture(autouse=True)
    def reset_state():
        myapp.cache.clear()
        yield
        myapp.cache.clear()
  2. 88% 成功率
    def test_db(tmp_path, worker_id):
        if worker_id == 'master':
            db = tmp_path / 'db.sqlite'
        else:
            db = tmp_path / f'db_{worker_id}.sqlite'
        ...

无效尝试

常见但无效的做法:

  1. 70% 失败

    Masks the race condition; reruns may pass by luck and hide real bugs, and flaky plugin adds overhead.

  2. 95% 失败

    More workers means more contention, making the race more likely, not less.

  3. 85% 失败

    Slows tests and does not eliminate the race; still fails intermittently on slow CI machines.