Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/tmpdir.py

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