Debian Codegraph @

src/_pytest/tmpdir.py

raw
1 # mypy: allow-untyped-defs
2 """Support for providing temporary directories to test functions."""
3
4 from __future__ import annotations
5
6 import atexit
7 from collections.abc import Generator
8 from contextlib import ExitStack
9 import dataclasses
10 import os
11 from pathlib import Path
12 import re
13 from shutil import rmtree
14 import stat
15 import tempfile
16 from typing import Any
17 from typing import final
18 from typing import Literal
19
20 from .pathlib import cleanup_dead_symlinks
21 from .pathlib import LOCK_TIMEOUT
22 from .pathlib import make_numbered_dir
23 from .pathlib import make_numbered_dir_with_cleanup
24 from .pathlib import rm_rf
25 from _pytest.compat import get_user_id
26 from _pytest.config import Config
27 from _pytest.config import ExitCode
28 from _pytest.config import hookimpl
29 from _pytest.config.argparsing import Parser
30 from _pytest.deprecated import check_ispytest
31 from _pytest.fixtures import fixture
32 from _pytest.fixtures import FixtureRequest
33 from _pytest.monkeypatch import MonkeyPatch
34 from _pytest.nodes import Item
35 from _pytest.reports import TestReport
36 from _pytest.stash import StashKey
37
38
39 tmppath_result_key = StashKey[dict[str, bool]]()
40 RetentionType = Literal["all", "failed", "none"]
41
42
43 @final
44 @dataclasses.dataclass
45 class TempPathFactory:
46 """Factory for temporary directories under the common base temp directory,
47 as discussed at :ref:`temporary directory location and retention`.
48 """
49
50 _given_basetemp: Path | None
51 # pluggy TagTracerSub, not currently exposed, so Any.
52 _trace: Any
53 _basetemp: Path | None
54 _retention_count: int
55 _retention_policy: RetentionType
56
57 def __init__(
58 self,
59 given_basetemp: Path | None,
60 retention_count: int,
61 retention_policy: RetentionType,
62 trace,
63 basetemp: Path | None = None,
64 *,
65 _ispytest: bool = False,
66 ) -> None:
67 check_ispytest(_ispytest)
68 if given_basetemp is None:
69 self._given_basetemp = None
70 else:
71 # Use os.path.abspath() to get absolute path instead of resolve() as it
72 # does not work the same in all platforms (see #4427).
73 # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012).
74 self._given_basetemp = Path(os.path.abspath(str(given_basetemp)))
75 self._trace = trace
76 self._retention_count = retention_count
77 self._retention_policy = retention_policy
78 self._basetemp = basetemp
79 # Register cleanups for session finish. Also called atexit as a last
80 # resort if sessionfinish for some reason doesn't happen.
81 self._exit_stack = ExitStack()
82
83 @classmethod
84 def from_config(
85 cls,
86 config: Config,
87 *,
88 _ispytest: bool = False,
89 ) -> TempPathFactory:
90 """Create a factory according to pytest configuration.
91
92 :meta private:
93 """
94 check_ispytest(_ispytest)
95 count = int(config.getini("tmp_path_retention_count"))
96 if count < 0:
97 raise ValueError(
98 f"tmp_path_retention_count must be >= 0. Current input: {count}."
99 )
100
101 policy = config.getini("tmp_path_retention_policy")
102 if policy not in ("all", "failed", "none"):
103 raise ValueError(
104 f"tmp_path_retention_policy must be either all, failed, none. Current input: {policy}."
105 )
106
107 return cls(
108 given_basetemp=config.option.basetemp,
109 trace=config.trace.get("tmpdir"),
110 retention_count=count,
111 retention_policy=policy,
112 _ispytest=True,
113 )
114
115 def _ensure_relative_to_basetemp(self, basename: str) -> str:
116 basename = os.path.normpath(basename)
117 if (self.getbasetemp() / basename).resolve().parent != self.getbasetemp():
118 raise ValueError(f"{basename} is not a normalized and relative path")
119 return basename
120
121 def mktemp(self, basename: str, numbered: bool = True) -> Path:
122 """Create a new temporary directory managed by the factory.
123
124 :param basename:
125 Directory base name, must be a relative path.
126
127 :param numbered:
128 If ``True``, ensure the directory is unique by adding a numbered
129 suffix greater than any existing one: ``basename="foo-"`` and ``numbered=True``
130 means that this function will create directories named ``"foo-0"``,
131 ``"foo-1"``, ``"foo-2"`` and so on.
132
133 :returns:
134 The path to the new directory.
135 """
136 basename = self._ensure_relative_to_basetemp(basename)
137 if not numbered:
138 p = self.getbasetemp().joinpath(basename)
139 p.mkdir(mode=0o700)
140 else:
141 p = make_numbered_dir(root=self.getbasetemp(), prefix=basename, mode=0o700)
142 self._trace("mktemp", p)
143 return p
144
145 def getbasetemp(self) -> Path:
146 """Return the base temporary directory, creating it if needed.
147
148 :returns:
149 The base temporary directory.
150 """
151 if self._basetemp is not None:
152 return self._basetemp
153
154 if self._given_basetemp is not None:
155 basetemp = self._given_basetemp
156 if basetemp.exists():
157 rm_rf(basetemp)
158 basetemp.mkdir(mode=0o700)
159 basetemp = basetemp.resolve()
160 else:
161 from_env = os.environ.get("PYTEST_DEBUG_TEMPROOT")
162 temproot = Path(from_env or tempfile.gettempdir()).resolve()
163 user = get_user() or "unknown"
164 # use a sub-directory in the temproot to speed-up
165 # make_numbered_dir() call
166 rootdir = temproot.joinpath(f"pytest-of-{user}")
167 try:
168 rootdir.mkdir(mode=0o700, exist_ok=True)
169 except OSError:
170 # getuser() likely returned illegal characters for the platform, use unknown back off mechanism
171 rootdir = temproot.joinpath("pytest-of-unknown")
172 rootdir.mkdir(mode=0o700, exist_ok=True)
173 # Because we use exist_ok=True with a predictable name, make sure
174 # we are the owners, to prevent any funny business (on unix, where
175 # temproot is usually shared).
176 # Also, to keep things private, fixup any world-readable temp
177 # rootdir's permissions. Historically 0o755 was used, so we can't
178 # just error out on this, at least for a while.
179 # Don't follow symlinks, otherwise we're open to symlink-swapping
180 # TOCTOU vulnerability.
181 # This check makes us vulnerable to a DoS - a user can `mkdir
182 # /tmp/pytest-of-otheruser` and then `otheruser` will fail this
183 # check. For now we don't consider it a real problem. otheruser can
184 # change their TMPDIR or --basetemp, and maybe give the prankster a
185 # good scolding.
186 uid = get_user_id()
187 if uid is not None:
188 stat_follow_symlinks = (
189 False if os.stat in os.supports_follow_symlinks else True
190 )
191 rootdir_stat = rootdir.stat(follow_symlinks=stat_follow_symlinks)
192 if stat.S_ISLNK(rootdir_stat.st_mode):
193 raise OSError(
194 f"The temporary directory {rootdir} is a symbolic link. "
195 "Fix this and try again."
196 )
197 if rootdir_stat.st_uid != uid:
198 raise OSError(
199 f"The temporary directory {rootdir} is not owned by the current user. "
200 "Fix this and try again."
201 )
202 if (rootdir_stat.st_mode & 0o077) != 0:
203 chmod_follow_symlinks = (
204 False if os.chmod in os.supports_follow_symlinks else True
205 )
206 rootdir.chmod(
207 rootdir_stat.st_mode & ~0o077,
208 follow_symlinks=chmod_follow_symlinks,
209 )
210 keep = self._retention_count
211 if self._retention_policy == "none":
212 keep = 0
213 basetemp = make_numbered_dir_with_cleanup(
214 prefix="pytest-",
215 root=rootdir,
216 keep=keep,
217 lock_timeout=LOCK_TIMEOUT,
218 mode=0o700,
219 register=self._exit_stack.callback,
220 )
221 # Ensure that the cleanup is called on exit (#1120 possibly?).
222 # But if the exit stack is closed manually (as it normally should),
223 # unregister the atexit to avoid pile up.
224 atexit.register(self._exit_stack.close)
225 self._exit_stack.callback(atexit.unregister, self._exit_stack.close)
226 assert basetemp is not None, basetemp
227 self._basetemp = basetemp
228 self._trace("new basetemp", basetemp)
229 return basetemp
230
231
232 def get_user() -> str | None:
233 """Return the current user name, or None if getuser() does not work
234 in the current environment (see #1010)."""
235 try:
236 # In some exotic environments, getpass may not be importable.
237 import getpass
238
239 return getpass.getuser()
240 except (ImportError, OSError, KeyError):
241 return None
242
243
244 def pytest_configure(config: Config) -> None:
245 """Create a TempPathFactory and attach it to the config object.
246
247 This is to comply with existing plugins which expect the handler to be
248 available at pytest_configure time, but ideally should be moved entirely
249 to the tmp_path_factory session fixture.
250 """
251 mp = MonkeyPatch()
252 config.add_cleanup(mp.undo)
253 _tmp_path_factory = TempPathFactory.from_config(config, _ispytest=True)
254 mp.setattr(config, "_tmp_path_factory", _tmp_path_factory, raising=False)
255
256
257 def pytest_addoption(parser: Parser) -> None:
258 parser.addini(
259 "tmp_path_retention_count",
260 help="How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.",
261 default="3",
262 # NOTE: Would have been better as an `int` but can't change it now.
263 type="string",
264 )
265
266 parser.addini(
267 "tmp_path_retention_policy",
268 help="Controls which directories created by the `tmp_path` fixture are kept around, based on test outcome. "
269 "(all/failed/none)",
270 type="string",
271 default="all",
272 )
273
274
275 @fixture(scope="session")
276 def tmp_path_factory(request: FixtureRequest) -> TempPathFactory:
277 """Return a :class:`pytest.TempPathFactory` instance for the test session."""
278 # Set dynamically by pytest_configure() above.
279 return request.config._tmp_path_factory # type: ignore
280
281
282 def _mk_tmp(request: FixtureRequest, factory: TempPathFactory) -> Path:
283 name = request.node.name
284 name = re.sub(r"[\W]", "_", name)
285 MAXVAL = 30
286 name = name[:MAXVAL]
287 return factory.mktemp(name, numbered=True)
288
289
290 @fixture
291 def tmp_path(
292 request: FixtureRequest, tmp_path_factory: TempPathFactory
293 ) -> Generator[Path]:
294 """Return a temporary directory (as :class:`pathlib.Path` object)
295 which is unique to each test function invocation.
296 The temporary directory is created as a subdirectory
297 of the base temporary directory, with configurable retention,
298 as discussed in :ref:`temporary directory location and retention`.
299 """
300 path = _mk_tmp(request, tmp_path_factory)
301 yield path
302
303 # Remove the tmpdir if the policy is "failed" and the test passed.
304 policy = tmp_path_factory._retention_policy
305 result_dict = request.node.stash[tmppath_result_key]
306
307 if policy == "failed" and result_dict.get("call", True):
308 # We do a "best effort" to remove files, but it might not be possible due to some leaked resource,
309 # permissions, etc, in which case we ignore it.
310 rmtree(path, ignore_errors=True)
311
312 del request.node.stash[tmppath_result_key]
313
314
315 def pytest_sessionfinish(session, exitstatus: int | ExitCode):
316 """After each session, remove base directory if all the tests passed,
317 the policy is "failed", and the basetemp is not specified by a user.
318 """
319 tmp_path_factory: TempPathFactory = session.config._tmp_path_factory
320 basetemp = tmp_path_factory._basetemp
321 if basetemp is None:
322 return
323
324 policy = tmp_path_factory._retention_policy
325 if (
326 exitstatus == 0
327 and policy == "failed"
328 and tmp_path_factory._given_basetemp is None
329 ):
330 if basetemp.is_dir():
331 # We do a "best effort" to remove files, but it might not be possible due to some leaked resource,
332 # permissions, etc, in which case we ignore it.
333 rmtree(basetemp, ignore_errors=True)
334
335 # Remove dead symlinks.
336 if basetemp.is_dir():
337 cleanup_dead_symlinks(basetemp)
338
339 # Run the numbered dirs and lock file cleanups registered on the ExitStack.
340 tmp_path_factory._exit_stack.close()
341
342
343 @hookimpl(wrapper=True, tryfirst=True)
344 def pytest_runtest_makereport(
345 item: Item, call
346 ) -> Generator[None, TestReport, TestReport]:
347 rep = yield
348 assert rep.when is not None
349 empty: dict[str, bool] = {}
350 item.stash.setdefault(tmppath_result_key, empty)[rep.when] = rep.passed
351 return rep