python data_error ai_generated true

FileNotFoundError: [Errno 2] 没有那个文件或目录: '/tmp/pytest-of-root/pytest-12/test_write0/data.json'

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pytest-of-root/pytest-12/test_write0/data.json'

ID: python/pytest-tmp-path-not-shared

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

版本兼容性

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

根因分析

`tmp_path` 是 function 作用域且每个测试唯一;一个测试写入的文件在另一个测试中不可见,因为每个测试获得新的编号目录。

English

`tmp_path` is function-scoped and unique per test; a file written in one test is not visible in another because each test gets a fresh numbered directory.

generic

解决方案

  1. 90% 成功率
    Use `tmp_path_factory` for a session-scoped shared dir:
    @pytest.fixture(scope='session')
    def shared_data(tmp_path_factory):
        p = tmp_path_factory.mktemp('shared')
        (p / 'data.json').write_text('{}')
        return p
  2. 85% 成功率
    Or pass the path explicitly from the producing test to the consumer via a fixture dependency chain.

无效尝试

常见但无效的做法:

  1. 85% 失败

    Breaks isolation and parallel runs; tests collide and leave stale state.

  2. 60% 失败

    Parent is the per-run root shared by all tests in the session; writing there risks collisions under xdist.