Skip to content

Commit b7f2d7c

Browse files
authored
Fixed an issue where getpass.getuser() contained illegal characters for file directories (#8365)
* retry writing pytest-of dir when invalid chars are in directory name * add unit tests for getbasetemp() and changelog * patch _basetemp & _given_basetemp for testing basetemp() * Tweak changelog for #8317, tidy up comments
1 parent bbea18d commit b7f2d7c

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

changelog/8317.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed an issue where illegal directory characters derived from ``getpass.getuser()`` raised an ``OSError``.

src/_pytest/tmpdir.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,12 @@ def getbasetemp(self) -> Path:
115115
# use a sub-directory in the temproot to speed-up
116116
# make_numbered_dir() call
117117
rootdir = temproot.joinpath(f"pytest-of-{user}")
118-
rootdir.mkdir(exist_ok=True)
118+
try:
119+
rootdir.mkdir(exist_ok=True)
120+
except OSError:
121+
# getuser() likely returned illegal characters for the platform, use unknown back off mechanism
122+
rootdir = temproot.joinpath("pytest-of-unknown")
123+
rootdir.mkdir(exist_ok=True)
119124
basetemp = make_numbered_dir_with_cleanup(
120125
prefix="pytest-", root=rootdir, keep=3, lock_timeout=LOCK_TIMEOUT
121126
)

testing/test_tmpdir.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import pytest
1212
from _pytest import pathlib
1313
from _pytest.config import Config
14+
from _pytest.monkeypatch import MonkeyPatch
1415
from _pytest.pathlib import cleanup_numbered_dir
1516
from _pytest.pathlib import create_cleanup_lock
1617
from _pytest.pathlib import make_numbered_dir
@@ -445,3 +446,14 @@ def test(tmp_path):
445446
# running a second time and ensure we don't crash
446447
result = pytester.runpytest("--basetemp=tmp")
447448
assert result.ret == 0
449+
450+
451+
def test_tmp_path_factory_handles_invalid_dir_characters(
452+
tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch
453+
) -> None:
454+
monkeypatch.setattr("getpass.getuser", lambda: "os/<:*?;>agnostic")
455+
# _basetemp / _given_basetemp are cached / set in parallel runs, patch them
456+
monkeypatch.setattr(tmp_path_factory, "_basetemp", None)
457+
monkeypatch.setattr(tmp_path_factory, "_given_basetemp", None)
458+
p = tmp_path_factory.getbasetemp()
459+
assert "pytest-of-unknown" in str(p)

0 commit comments

Comments
 (0)