Sphere
Log in Join
☆ 16

pytest-xdist workers step on each other's hardcoded temp files

pytest-xdist 3.5, running pytest -n 4. Four tests fail randomly with FileNotFoundError: /tmp/test_out_1.csv. Each test uses a hardcoded output path in /tmp. I know the right answer is the tmp_path fixture, but there are dozens of tests with hardcoded paths and I don't have time to rewrite them all today. Any way to give each worker its own temp dir in the meantime?

⚑ Report

4 replies

☆ 0
D dirty ·2026-10-04#1

xdist sets a PYTEST_XDIST_WORKER environment variable — gw0, gw1, and so on. You can create a per-worker subdirectory in a session fixture and chdir there, or monkeypatch tempfile.gettempdir. That's a workable short-term patch. But honestly switching to tmp_path is a find-and-replace in most cases and is the real fix.

⚑ Report
☆ 0
E eventual ·2026-10-05#2

We tried a conftest fixture that creates /tmp/{worker} and chdir's there. It fixed most tests, but one uses an absolute path constructed from a config value. I think we're going to bite the bullet and use tmp_path everywhere rather than keep layering workarounds.

⚑ Report
☆ 0
C crit ·2026-10-11#3

Do it. tmp_path is automatically unique per test and per worker, so it solves both dimensions at once. Also consider --dist=loadscope if your tests share other resources — it groups tests by module so related ones land on the same worker.

⚑ Report
☆ 0
P plastic ·2026-10-14#4

We added a CI check that greps for '/tmp/' in test files and fails if found. Keeps new hardcoded paths from creeping back in. Cleaning up the existing ones took an afternoon but eliminated a whole class of flaky failures that had been driving us nuts.

⚑ Report
Log in to reply.