python data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-02-09First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

`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

中文

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

Workarounds

  1. 90% success
    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% success
    Or pass the path explicitly from the producing test to the consumer via a fixture dependency chain.

Dead Ends

Common approaches that don't work:

  1. 85% fail

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

  2. 60% fail

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