Debian Codegraph @

testing/test_tmpdir.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Callable
5 import dataclasses
6 import os
7 from pathlib import Path
8 import shutil
9 import stat
10 import sys
11 from typing import cast
12 import warnings
13
14 from _pytest import pathlib
15 from _pytest.config import Config
16 from _pytest.monkeypatch import MonkeyPatch
17 from _pytest.pathlib import cleanup_numbered_dir
18 from _pytest.pathlib import create_cleanup_lock
19 from _pytest.pathlib import make_numbered_dir
20 from _pytest.pathlib import maybe_delete_a_numbered_dir
21 from _pytest.pathlib import on_rm_rf_error
22 from _pytest.pathlib import register_cleanup_lock_removal
23 from _pytest.pathlib import rm_rf
24 from _pytest.pytester import Pytester
25 from _pytest.tmpdir import get_user
26 from _pytest.tmpdir import TempPathFactory
27 import pytest
28
29
30 def test_tmp_path_fixture(pytester: Pytester) -> None:
31 p = pytester.copy_example("tmpdir/tmp_path_fixture.py")
32 results = pytester.runpytest(p)
33 results.stdout.fnmatch_lines(["*1 passed*"])
34
35
36 @dataclasses.dataclass
37 class FakeConfig:
38 basetemp: str | Path
39
40 @property
41 def trace(self):
42 return self
43
44 def get(self, key):
45 return lambda *k: None
46
47 def getini(self, name):
48 if name == "tmp_path_retention_count":
49 return 3
50 elif name == "tmp_path_retention_policy":
51 return "all"
52 else:
53 assert False
54
55 @property
56 def option(self):
57 return self
58
59
60 class TestTmpPathHandler:
61 def test_mktemp(self, tmp_path: Path) -> None:
62 config = cast(Config, FakeConfig(tmp_path))
63 t = TempPathFactory.from_config(config, _ispytest=True)
64 tmp = t.mktemp("world")
65 assert str(tmp.relative_to(t.getbasetemp())) == "world0"
66 tmp = t.mktemp("this")
67 assert str(tmp.relative_to(t.getbasetemp())).startswith("this")
68 tmp2 = t.mktemp("this")
69 assert str(tmp2.relative_to(t.getbasetemp())).startswith("this")
70 assert tmp2 != tmp
71
72 def test_tmppath_relative_basetemp_absolute(
73 self, tmp_path: Path, monkeypatch: MonkeyPatch
74 ) -> None:
75 """#4425"""
76 monkeypatch.chdir(tmp_path)
77 config = cast(Config, FakeConfig("hello"))
78 t = TempPathFactory.from_config(config, _ispytest=True)
79 assert t.getbasetemp().resolve() == (tmp_path / "hello").resolve()
80
81
82 class TestConfigTmpPath:
83 def test_getbasetemp_custom_removes_old(self, pytester: Pytester) -> None:
84 mytemp = pytester.path.joinpath("xyz")
85 p = pytester.makepyfile(
86 """
87 def test_1(tmp_path):
88 pass
89 """
90 )
91 pytester.runpytest(p, f"--basetemp={mytemp}")
92 assert mytemp.exists()
93 mytemp.joinpath("hello").touch()
94
95 pytester.runpytest(p, f"--basetemp={mytemp}")
96 assert mytemp.exists()
97 assert not mytemp.joinpath("hello").exists()
98
99 def test_policy_none_delete_all(self, pytester: Pytester) -> None:
100 p = pytester.makepyfile(
101 """
102 def test_1(tmp_path):
103 assert 0 == 0
104 """
105 )
106 p_failed = pytester.makepyfile(
107 another_file_name="""
108 def test_1(tmp_path):
109 assert 0 == 1
110 """
111 )
112 pytester.makepyprojecttoml(
113 """
114 [tool.pytest.ini_options]
115 tmp_path_retention_policy = "none"
116 """
117 )
118
119 pytester.inline_run(p)
120 pytester.inline_run(p_failed)
121
122 root = pytester._test_tmproot
123 for child in root.iterdir():
124 base_dir = list(child.iterdir())
125 # Check the base dir itself is gone without depending on test results
126 assert base_dir == []
127
128 @pytest.mark.parametrize("policy", ['"failed"', '"all"'])
129 @pytest.mark.parametrize("count", [0, 1, 3])
130 def test_retention_count(self, pytester: Pytester, policy, count) -> None:
131 p = pytester.makepyfile(
132 """
133 def test_1(tmp_path):
134 assert 0 == 0
135 """
136 )
137 p_failed = pytester.makepyfile(
138 another_file_name="""
139 def test_1(tmp_path):
140 assert 0 == 1
141 """
142 )
143
144 pytester.makepyprojecttoml(
145 f"""
146 [tool.pytest.ini_options]
147 tmp_path_retention_policy = {policy}
148 tmp_path_retention_count = {count}
149 """
150 )
151
152 pytester.inline_run(p)
153 pytester.inline_run(p_failed)
154 pytester.inline_run(p)
155 pytester.inline_run(p_failed)
156 pytester.inline_run(p)
157 pytester.inline_run(p_failed)
158 pytester.inline_run(p)
159 pytester.inline_run(p_failed)
160
161 root = pytester._test_tmproot
162 for child in root.iterdir():
163 base_dir = filter(lambda x: not x.is_symlink(), child.iterdir())
164 assert len(list(base_dir)) == count
165
166 def test_policy_failed_removes_only_passed_dir(self, pytester: Pytester) -> None:
167 p = pytester.makepyfile(
168 """
169 def test_1(tmp_path):
170 assert 0 == 0
171 def test_2(tmp_path):
172 assert 0 == 1
173 """
174 )
175 pytester.makepyprojecttoml(
176 """
177 [tool.pytest.ini_options]
178 tmp_path_retention_policy = "failed"
179 """
180 )
181
182 pytester.inline_run(p)
183 root = pytester._test_tmproot
184
185 for child in root.iterdir():
186 base_dir = list(
187 filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())
188 )
189 assert len(base_dir) == 1
190 test_dir = list(
191 filter(
192 lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()
193 )
194 )
195 # Check only the failed one remains
196 assert len(test_dir) == 1
197 assert test_dir[0].name == "test_20"
198
199 def test_policy_failed_removes_basedir_when_all_passed(
200 self, pytester: Pytester
201 ) -> None:
202 p = pytester.makepyfile(
203 """
204 def test_1(tmp_path):
205 assert 0 == 0
206 """
207 )
208 pytester.makepyprojecttoml(
209 """
210 [tool.pytest.ini_options]
211 tmp_path_retention_policy = "failed"
212 """
213 )
214
215 pytester.inline_run(p)
216 root = pytester._test_tmproot
217 for child in root.iterdir():
218 # This symlink will be deleted by cleanup_numbered_dir **after**
219 # the test finishes because it's triggered by atexit.
220 # So it has to be ignored here.
221 base_dir = filter(lambda x: not x.is_symlink(), child.iterdir())
222 # Check the base dir itself is gone
223 assert len(list(base_dir)) == 0
224
225 # issue #10502
226 def test_policy_failed_removes_dir_when_skipped_from_fixture(
227 self, pytester: Pytester
228 ) -> None:
229 p = pytester.makepyfile(
230 """
231 import pytest
232
233 @pytest.fixture
234 def fixt(tmp_path):
235 pytest.skip()
236
237 def test_fixt(fixt):
238 pass
239 """
240 )
241 pytester.makepyprojecttoml(
242 """
243 [tool.pytest.ini_options]
244 tmp_path_retention_policy = "failed"
245 """
246 )
247
248 pytester.inline_run(p)
249
250 # Check if the whole directory is removed
251 root = pytester._test_tmproot
252 for child in root.iterdir():
253 base_dir = list(child.iterdir())
254 assert base_dir == []
255
256 # issue #10502
257 def test_policy_all_keeps_dir_when_skipped_from_fixture(
258 self, pytester: Pytester
259 ) -> None:
260 p = pytester.makepyfile(
261 """
262 import pytest
263
264 @pytest.fixture
265 def fixt(tmp_path):
266 pytest.skip()
267
268 def test_fixt(fixt):
269 pass
270 """
271 )
272 pytester.makepyprojecttoml(
273 """
274 [tool.pytest.ini_options]
275 tmp_path_retention_policy = "all"
276 """
277 )
278 pytester.inline_run(p)
279
280 # Check if the whole directory is kept
281 root = pytester._test_tmproot
282 for child in root.iterdir():
283 base_dir = list(
284 filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())
285 )
286 assert len(base_dir) == 1
287 test_dir = list(
288 filter(
289 lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()
290 )
291 )
292 assert len(test_dir) == 1
293
294
295 testdata = [
296 ("mypath", True),
297 ("/mypath1", False),
298 ("./mypath1", True),
299 ("../mypath3", False),
300 ("../../mypath4", False),
301 ("mypath5/..", False),
302 ("mypath6/../mypath6", True),
303 ("mypath7/../mypath7/..", False),
304 ]
305
306
307 @pytest.mark.parametrize("basename, is_ok", testdata)
308 def test_mktemp(pytester: Pytester, basename: str, is_ok: bool) -> None:
309 mytemp = pytester.mkdir("mytemp")
310 p = pytester.makepyfile(
311 f"""
312 def test_abs_path(tmp_path_factory):
313 tmp_path_factory.mktemp('{basename}', numbered=False)
314 """
315 )
316
317 result = pytester.runpytest(p, f"--basetemp={mytemp}")
318 if is_ok:
319 assert result.ret == 0
320 assert mytemp.joinpath(basename).exists()
321 else:
322 assert result.ret == 1
323 result.stdout.fnmatch_lines("*ValueError*")
324
325
326 def test_tmp_path_always_is_realpath(pytester: Pytester, monkeypatch) -> None:
327 # the reason why tmp_path should be a realpath is that
328 # when you cd to it and do "os.getcwd()" you will anyway
329 # get the realpath. Using the symlinked path can thus
330 # easily result in path-inequality
331 # XXX if that proves to be a problem, consider using
332 # os.environ["PWD"]
333 realtemp = pytester.mkdir("myrealtemp")
334 linktemp = pytester.path.joinpath("symlinktemp")
335 attempt_symlink_to(linktemp, str(realtemp))
336 monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(linktemp))
337 pytester.makepyfile(
338 """
339 def test_1(tmp_path):
340 assert tmp_path.resolve() == tmp_path
341 """
342 )
343 reprec = pytester.inline_run()
344 reprec.assertoutcome(passed=1)
345
346
347 def test_tmp_path_too_long_on_parametrization(pytester: Pytester) -> None:
348 pytester.makepyfile(
349 """
350 import pytest
351 @pytest.mark.parametrize("arg", ["1"*1000])
352 def test_some(arg, tmp_path):
353 tmp_path.joinpath("hello").touch()
354 """
355 )
356 reprec = pytester.inline_run()
357 reprec.assertoutcome(passed=1)
358
359
360 def test_tmp_path_factory(pytester: Pytester) -> None:
361 pytester.makepyfile(
362 """
363 import pytest
364 @pytest.fixture(scope='session')
365 def session_dir(tmp_path_factory):
366 return tmp_path_factory.mktemp('data', numbered=False)
367 def test_some(session_dir):
368 assert session_dir.is_dir()
369 """
370 )
371 reprec = pytester.inline_run()
372 reprec.assertoutcome(passed=1)
373
374
375 def test_tmp_path_fallback_tox_env(pytester: Pytester, monkeypatch) -> None:
376 """Test that tmp_path works even if environment variables required by getpass
377 module are missing (#1010).
378 """
379 monkeypatch.delenv("USER", raising=False)
380 monkeypatch.delenv("USERNAME", raising=False)
381 pytester.makepyfile(
382 """
383 def test_some(tmp_path):
384 assert tmp_path.is_dir()
385 """
386 )
387 reprec = pytester.inline_run()
388 reprec.assertoutcome(passed=1)
389
390
391 @pytest.fixture
392 def break_getuser(monkeypatch):
393 monkeypatch.setattr("os.getuid", lambda: -1)
394 # taken from python 2.7/3.4
395 for envvar in ("LOGNAME", "USER", "LNAME", "USERNAME"):
396 monkeypatch.delenv(envvar, raising=False)
397
398
399 @pytest.mark.usefixtures("break_getuser")
400 @pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
401 def test_tmp_path_fallback_uid_not_found(pytester: Pytester) -> None:
402 """Test that tmp_path works even if the current process's user id does not
403 correspond to a valid user.
404 """
405 pytester.makepyfile(
406 """
407 def test_some(tmp_path):
408 assert tmp_path.is_dir()
409 """
410 )
411 reprec = pytester.inline_run()
412 reprec.assertoutcome(passed=1)
413
414
415 @pytest.mark.usefixtures("break_getuser")
416 @pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
417 def test_get_user_uid_not_found():
418 """Test that get_user() function works even if the current process's
419 user id does not correspond to a valid user (e.g. running pytest in a
420 Docker container with 'docker run -u'.
421 """
422 assert get_user() is None
423
424
425 @pytest.mark.skipif(not sys.platform.startswith("win"), reason="win only")
426 def test_get_user(monkeypatch):
427 """Test that get_user() function works even if environment variables
428 required by getpass module are missing from the environment on Windows
429 (#1010).
430 """
431 monkeypatch.delenv("USER", raising=False)
432 monkeypatch.delenv("USERNAME", raising=False)
433 assert get_user() is None
434
435
436 class TestNumberedDir:
437 PREFIX = "fun-"
438
439 def test_make(self, tmp_path):
440 for i in range(10):
441 d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)
442 assert d.name.startswith(self.PREFIX)
443 assert d.name.endswith(str(i))
444
445 symlink = tmp_path.joinpath(self.PREFIX + "current")
446 if symlink.exists():
447 # unix
448 assert symlink.is_symlink()
449 assert symlink.resolve() == d.resolve()
450
451 def test_cleanup_lock_create(self, tmp_path):
452 d = tmp_path.joinpath("test")
453 d.mkdir()
454 lockfile = create_cleanup_lock(d)
455 with pytest.raises(OSError, match=r"cannot create lockfile in .*"):
456 create_cleanup_lock(d)
457
458 lockfile.unlink()
459
460 def test_lock_register_cleanup_removal(self, tmp_path: Path) -> None:
461 lock = create_cleanup_lock(tmp_path)
462
463 registry: list[Callable[..., None]] = []
464 register_cleanup_lock_removal(lock, register=registry.append)
465
466 (cleanup_func,) = registry
467
468 assert lock.is_file()
469
470 cleanup_func(original_pid="intentionally_different")
471
472 assert lock.is_file()
473
474 cleanup_func()
475
476 assert not lock.exists()
477
478 cleanup_func()
479
480 assert not lock.exists()
481
482 def _do_cleanup(self, tmp_path: Path, keep: int = 2) -> None:
483 self.test_make(tmp_path)
484 cleanup_numbered_dir(
485 root=tmp_path,
486 prefix=self.PREFIX,
487 keep=keep,
488 consider_lock_dead_if_created_before=0,
489 )
490
491 def test_cleanup_keep(self, tmp_path):
492 self._do_cleanup(tmp_path)
493 a, b = (x for x in tmp_path.iterdir() if not x.is_symlink())
494 print(a, b)
495
496 def test_cleanup_keep_0(self, tmp_path: Path):
497 self._do_cleanup(tmp_path, 0)
498 dir_num = len(list(tmp_path.iterdir()))
499 assert dir_num == 0
500
501 def test_cleanup_locked(self, tmp_path):
502 p = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)
503
504 create_cleanup_lock(p)
505
506 assert not pathlib.ensure_deletable(
507 p, consider_lock_dead_if_created_before=p.stat().st_mtime - 1
508 )
509 assert pathlib.ensure_deletable(
510 p, consider_lock_dead_if_created_before=p.stat().st_mtime + 1
511 )
512
513 def test_cleanup_ignores_symlink(self, tmp_path):
514 the_symlink = tmp_path / (self.PREFIX + "current")
515 attempt_symlink_to(the_symlink, tmp_path / (self.PREFIX + "5"))
516 self._do_cleanup(tmp_path)
517
518 def test_removal_accepts_lock(self, tmp_path):
519 dir = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)
520 create_cleanup_lock(dir)
521 maybe_delete_a_numbered_dir(dir)
522 assert dir.is_dir()
523
524
525 class TestRmRf:
526 def test_rm_rf(self, tmp_path):
527 adir = tmp_path / "adir"
528 adir.mkdir()
529 rm_rf(adir)
530
531 assert not adir.exists()
532
533 adir.mkdir()
534 afile = adir / "afile"
535 afile.write_bytes(b"aa")
536
537 rm_rf(adir)
538 assert not adir.exists()
539
540 def test_rm_rf_with_read_only_file(self, tmp_path):
541 """Ensure rm_rf can remove directories with read-only files in them (#5524)"""
542 fn = tmp_path / "dir/foo.txt"
543 fn.parent.mkdir()
544
545 fn.touch()
546
547 self.chmod_r(fn)
548
549 rm_rf(fn.parent)
550
551 assert not fn.parent.is_dir()
552
553 def chmod_r(self, path):
554 mode = os.stat(str(path)).st_mode
555 os.chmod(str(path), mode & ~stat.S_IWRITE)
556
557 def test_rm_rf_with_read_only_directory(self, tmp_path):
558 """Ensure rm_rf can remove read-only directories (#5524)"""
559 adir = tmp_path / "dir"
560 adir.mkdir()
561
562 (adir / "foo.txt").touch()
563 self.chmod_r(adir)
564
565 rm_rf(adir)
566
567 assert not adir.is_dir()
568
569 def test_on_rm_rf_error(self, tmp_path: Path) -> None:
570 adir = tmp_path / "dir"
571 adir.mkdir()
572
573 fn = adir / "foo.txt"
574 fn.touch()
575 self.chmod_r(fn)
576
577 # unknown exception
578 with pytest.warns(pytest.PytestWarning):
579 exc_info1 = (RuntimeError, RuntimeError(), None)
580 on_rm_rf_error(os.unlink, str(fn), exc_info1, start_path=tmp_path)
581 assert fn.is_file()
582
583 # we ignore FileNotFoundError
584 exc_info2 = (FileNotFoundError, FileNotFoundError(), None)
585 assert not on_rm_rf_error(None, str(fn), exc_info2, start_path=tmp_path)
586
587 # unknown function
588 with pytest.warns(
589 pytest.PytestWarning,
590 match=r"^\(rm_rf\) unknown function None when removing .*foo.txt:\n<class 'PermissionError'>: ",
591 ):
592 exc_info3 = (PermissionError, PermissionError(), None)
593 on_rm_rf_error(None, str(fn), exc_info3, start_path=tmp_path)
594 assert fn.is_file()
595
596 # ignored function
597 with warnings.catch_warnings(record=True) as w:
598 exc_info4 = PermissionError()
599 on_rm_rf_error(os.open, str(fn), exc_info4, start_path=tmp_path)
600 assert fn.is_file()
601 assert not [x.message for x in w]
602
603 exc_info5 = PermissionError()
604 on_rm_rf_error(os.unlink, str(fn), exc_info5, start_path=tmp_path)
605 assert not fn.is_file()
606
607
608 def attempt_symlink_to(path, to_path):
609 """Try to make a symlink from "path" to "to_path", skipping in case this platform
610 does not support it or we don't have sufficient privileges (common on Windows)."""
611 try:
612 Path(path).symlink_to(Path(to_path))
613 except OSError:
614 pytest.skip("could not create symbolic link")
615
616
617 def test_basetemp_with_read_only_files(pytester: Pytester) -> None:
618 """Integration test for #5524"""
619 pytester.makepyfile(
620 """
621 import os
622 import stat
623
624 def test(tmp_path):
625 fn = tmp_path / 'foo.txt'
626 fn.write_text('hello', encoding='utf-8')
627 mode = os.stat(str(fn)).st_mode
628 os.chmod(str(fn), mode & ~stat.S_IREAD)
629 """
630 )
631 result = pytester.runpytest("--basetemp=tmp")
632 assert result.ret == 0
633 # running a second time and ensure we don't crash
634 result = pytester.runpytest("--basetemp=tmp")
635 assert result.ret == 0
636
637
638 def test_tmp_path_factory_handles_invalid_dir_characters(
639 tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch
640 ) -> None:
641 monkeypatch.setattr("getpass.getuser", lambda: "os/<:*?;>agnostic")
642 # _basetemp / _given_basetemp are cached / set in parallel runs, patch them
643 monkeypatch.setattr(tmp_path_factory, "_basetemp", None)
644 monkeypatch.setattr(tmp_path_factory, "_given_basetemp", None)
645 p = tmp_path_factory.getbasetemp()
646 assert "pytest-of-unknown" in str(p)
647
648
649 @pytest.mark.skipif(not hasattr(os, "getuid"), reason="checks unix permissions")
650 def test_tmp_path_factory_create_directory_with_safe_permissions(
651 tmp_path: Path, monkeypatch: MonkeyPatch
652 ) -> None:
653 """Verify that pytest creates directories under /tmp with private permissions."""
654 # Use the test's tmp_path as the system temproot (/tmp).
655 monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(tmp_path))
656 tmp_factory = TempPathFactory(None, 3, "all", lambda *args: None, _ispytest=True)
657 basetemp = tmp_factory.getbasetemp()
658
659 # No world-readable permissions.
660 assert (basetemp.stat().st_mode & 0o077) == 0
661 # Parent too (pytest-of-foo).
662 assert (basetemp.parent.stat().st_mode & 0o077) == 0
663
664
665 @pytest.mark.skipif(not hasattr(os, "getuid"), reason="checks unix permissions")
666 def test_tmp_path_factory_fixes_up_world_readable_permissions(
667 tmp_path: Path, monkeypatch: MonkeyPatch
668 ) -> None:
669 """Verify that if a /tmp/pytest-of-foo directory already exists with
670 world-readable permissions, it is fixed.
671
672 pytest used to mkdir with such permissions, that's why we fix it up.
673 """
674 # Use the test's tmp_path as the system temproot (/tmp).
675 monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(tmp_path))
676 tmp_factory = TempPathFactory(None, 3, "all", lambda *args: None, _ispytest=True)
677 basetemp = tmp_factory.getbasetemp()
678
679 # Before - simulate bad perms.
680 os.chmod(basetemp.parent, 0o777)
681 assert (basetemp.parent.stat().st_mode & 0o077) != 0
682
683 tmp_factory = TempPathFactory(None, 3, "all", lambda *args: None, _ispytest=True)
684 basetemp = tmp_factory.getbasetemp()
685
686 # After - fixed.
687 assert (basetemp.parent.stat().st_mode & 0o077) == 0
688
689
690 @pytest.mark.skipif(
691 not hasattr(os, "getuid") or os.stat not in os.supports_follow_symlinks,
692 reason="checks unix permissions and symlinks",
693 )
694 def test_tmp_path_factory_doesnt_follow_symlinks(
695 tmp_path: Path, monkeypatch: MonkeyPatch
696 ) -> None:
697 """Verify that if a /tmp/pytest-of-foo directory is a symbolic link,
698 it is rejected (#13669, CVE-2025-71176)."""
699 attacker_controlled = tmp_path / "attacker_controlled"
700 attacker_controlled.mkdir()
701
702 # Use the test's tmp_path as the system temproot (/tmp).
703 monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(tmp_path))
704
705 # First just get the pytest-of-user path.
706 tmp_factory = TempPathFactory(None, 3, "all", lambda *args: None, _ispytest=True)
707 pytest_of_user = tmp_factory.getbasetemp().parent
708 # Just for safety in the test, before we nuke it.
709 assert "pytest-of-" in str(pytest_of_user)
710 shutil.rmtree(pytest_of_user)
711
712 pytest_of_user.symlink_to(attacker_controlled)
713
714 # This now tries to use the directory when it's a symlink.
715 tmp_factory = TempPathFactory(None, 3, "all", lambda *args: None, _ispytest=True)
716 with pytest.raises(OSError, match=r"temporary directory .* is a symbolic link"):
717 tmp_factory.getbasetemp()
718
719
720 def test_get_user_handles_getpass_oserror(monkeypatch: MonkeyPatch) -> None:
721 """Regression test: get_user() should return None when getpass.getuser()
722 raises OSError (Python 3.13+ behavior, #13835)."""
723 import getpass
724
725 def _raise_oserror():
726 raise OSError("No username set in the environment")
727
728 monkeypatch.setattr(getpass, "getuser", _raise_oserror)
729 assert get_user() is None