Debian Codegraph @

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

raw
1 # mypy: allow-untyped-defs
2 """Add backward compatibility support for the legacy py path type."""
3
4 import dataclasses
5 from pathlib import Path
6 import shlex
7 import subprocess
8 from typing import Final
9 from typing import final
10 from typing import List
11 from typing import Optional
12 from typing import TYPE_CHECKING
13 from typing import Union
14
15 from iniconfig import SectionWrapper
16
17 from _pytest.cacheprovider import Cache
18 from _pytest.compat import LEGACY_PATH
19 from _pytest.compat import legacy_path
20 from _pytest.config import Config
21 from _pytest.config import hookimpl
22 from _pytest.config import PytestPluginManager
23 from _pytest.deprecated import check_ispytest
24 from _pytest.fixtures import fixture
25 from _pytest.fixtures import FixtureRequest
26 from _pytest.main import Session
27 from _pytest.monkeypatch import MonkeyPatch
28 from _pytest.nodes import Collector
29 from _pytest.nodes import Item
30 from _pytest.nodes import Node
31 from _pytest.pytester import HookRecorder
32 from _pytest.pytester import Pytester
33 from _pytest.pytester import RunResult
34 from _pytest.terminal import TerminalReporter
35 from _pytest.tmpdir import TempPathFactory
36
37
38 if TYPE_CHECKING:
39 import pexpect
40
41
42 @final
43 class Testdir:
44 """
45 Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead.
46
47 All methods just forward to an internal :class:`Pytester` instance, converting results
48 to `legacy_path` objects as necessary.
49 """
50
51 __test__ = False
52
53 CLOSE_STDIN: "Final" = Pytester.CLOSE_STDIN
54 TimeoutExpired: "Final" = Pytester.TimeoutExpired
55
56 def __init__(self, pytester: Pytester, *, _ispytest: bool = False) -> None:
57 check_ispytest(_ispytest)
58 self._pytester = pytester
59
60 @property
61 def tmpdir(self) -> LEGACY_PATH:
62 """Temporary directory where tests are executed."""
63 return legacy_path(self._pytester.path)
64
65 @property
66 def test_tmproot(self) -> LEGACY_PATH:
67 return legacy_path(self._pytester._test_tmproot)
68
69 @property
70 def request(self):
71 return self._pytester._request
72
73 @property
74 def plugins(self):
75 return self._pytester.plugins
76
77 @plugins.setter
78 def plugins(self, plugins):
79 self._pytester.plugins = plugins
80
81 @property
82 def monkeypatch(self) -> MonkeyPatch:
83 return self._pytester._monkeypatch
84
85 def make_hook_recorder(self, pluginmanager) -> HookRecorder:
86 """See :meth:`Pytester.make_hook_recorder`."""
87 return self._pytester.make_hook_recorder(pluginmanager)
88
89 def chdir(self) -> None:
90 """See :meth:`Pytester.chdir`."""
91 return self._pytester.chdir()
92
93 def finalize(self) -> None:
94 return self._pytester._finalize()
95
96 def makefile(self, ext, *args, **kwargs) -> LEGACY_PATH:
97 """See :meth:`Pytester.makefile`."""
98 if ext and not ext.startswith("."):
99 # pytester.makefile is going to throw a ValueError in a way that
100 # testdir.makefile did not, because
101 # pathlib.Path is stricter suffixes than py.path
102 # This ext arguments is likely user error, but since testdir has
103 # allowed this, we will prepend "." as a workaround to avoid breaking
104 # testdir usage that worked before
105 ext = "." + ext
106 return legacy_path(self._pytester.makefile(ext, *args, **kwargs))
107
108 def makeconftest(self, source) -> LEGACY_PATH:
109 """See :meth:`Pytester.makeconftest`."""
110 return legacy_path(self._pytester.makeconftest(source))
111
112 def makeini(self, source) -> LEGACY_PATH:
113 """See :meth:`Pytester.makeini`."""
114 return legacy_path(self._pytester.makeini(source))
115
116 def getinicfg(self, source: str) -> SectionWrapper:
117 """See :meth:`Pytester.getinicfg`."""
118 return self._pytester.getinicfg(source)
119
120 def makepyprojecttoml(self, source) -> LEGACY_PATH:
121 """See :meth:`Pytester.makepyprojecttoml`."""
122 return legacy_path(self._pytester.makepyprojecttoml(source))
123
124 def makepyfile(self, *args, **kwargs) -> LEGACY_PATH:
125 """See :meth:`Pytester.makepyfile`."""
126 return legacy_path(self._pytester.makepyfile(*args, **kwargs))
127
128 def maketxtfile(self, *args, **kwargs) -> LEGACY_PATH:
129 """See :meth:`Pytester.maketxtfile`."""
130 return legacy_path(self._pytester.maketxtfile(*args, **kwargs))
131
132 def syspathinsert(self, path=None) -> None:
133 """See :meth:`Pytester.syspathinsert`."""
134 return self._pytester.syspathinsert(path)
135
136 def mkdir(self, name) -> LEGACY_PATH:
137 """See :meth:`Pytester.mkdir`."""
138 return legacy_path(self._pytester.mkdir(name))
139
140 def mkpydir(self, name) -> LEGACY_PATH:
141 """See :meth:`Pytester.mkpydir`."""
142 return legacy_path(self._pytester.mkpydir(name))
143
144 def copy_example(self, name=None) -> LEGACY_PATH:
145 """See :meth:`Pytester.copy_example`."""
146 return legacy_path(self._pytester.copy_example(name))
147
148 def getnode(self, config: Config, arg) -> Optional[Union[Item, Collector]]:
149 """See :meth:`Pytester.getnode`."""
150 return self._pytester.getnode(config, arg)
151
152 def getpathnode(self, path):
153 """See :meth:`Pytester.getpathnode`."""
154 return self._pytester.getpathnode(path)
155
156 def genitems(self, colitems: List[Union[Item, Collector]]) -> List[Item]:
157 """See :meth:`Pytester.genitems`."""
158 return self._pytester.genitems(colitems)
159
160 def runitem(self, source):
161 """See :meth:`Pytester.runitem`."""
162 return self._pytester.runitem(source)
163
164 def inline_runsource(self, source, *cmdlineargs):
165 """See :meth:`Pytester.inline_runsource`."""
166 return self._pytester.inline_runsource(source, *cmdlineargs)
167
168 def inline_genitems(self, *args):
169 """See :meth:`Pytester.inline_genitems`."""
170 return self._pytester.inline_genitems(*args)
171
172 def inline_run(self, *args, plugins=(), no_reraise_ctrlc: bool = False):
173 """See :meth:`Pytester.inline_run`."""
174 return self._pytester.inline_run(
175 *args, plugins=plugins, no_reraise_ctrlc=no_reraise_ctrlc
176 )
177
178 def runpytest_inprocess(self, *args, **kwargs) -> RunResult:
179 """See :meth:`Pytester.runpytest_inprocess`."""
180 return self._pytester.runpytest_inprocess(*args, **kwargs)
181
182 def runpytest(self, *args, **kwargs) -> RunResult:
183 """See :meth:`Pytester.runpytest`."""
184 return self._pytester.runpytest(*args, **kwargs)
185
186 def parseconfig(self, *args) -> Config:
187 """See :meth:`Pytester.parseconfig`."""
188 return self._pytester.parseconfig(*args)
189
190 def parseconfigure(self, *args) -> Config:
191 """See :meth:`Pytester.parseconfigure`."""
192 return self._pytester.parseconfigure(*args)
193
194 def getitem(self, source, funcname="test_func"):
195 """See :meth:`Pytester.getitem`."""
196 return self._pytester.getitem(source, funcname)
197
198 def getitems(self, source):
199 """See :meth:`Pytester.getitems`."""
200 return self._pytester.getitems(source)
201
202 def getmodulecol(self, source, configargs=(), withinit=False):
203 """See :meth:`Pytester.getmodulecol`."""
204 return self._pytester.getmodulecol(
205 source, configargs=configargs, withinit=withinit
206 )
207
208 def collect_by_name(
209 self, modcol: Collector, name: str
210 ) -> Optional[Union[Item, Collector]]:
211 """See :meth:`Pytester.collect_by_name`."""
212 return self._pytester.collect_by_name(modcol, name)
213
214 def popen(
215 self,
216 cmdargs,
217 stdout=subprocess.PIPE,
218 stderr=subprocess.PIPE,
219 stdin=CLOSE_STDIN,
220 **kw,
221 ):
222 """See :meth:`Pytester.popen`."""
223 return self._pytester.popen(cmdargs, stdout, stderr, stdin, **kw)
224
225 def run(self, *cmdargs, timeout=None, stdin=CLOSE_STDIN) -> RunResult:
226 """See :meth:`Pytester.run`."""
227 return self._pytester.run(*cmdargs, timeout=timeout, stdin=stdin)
228
229 def runpython(self, script) -> RunResult:
230 """See :meth:`Pytester.runpython`."""
231 return self._pytester.runpython(script)
232
233 def runpython_c(self, command):
234 """See :meth:`Pytester.runpython_c`."""
235 return self._pytester.runpython_c(command)
236
237 def runpytest_subprocess(self, *args, timeout=None) -> RunResult:
238 """See :meth:`Pytester.runpytest_subprocess`."""
239 return self._pytester.runpytest_subprocess(*args, timeout=timeout)
240
241 def spawn_pytest(
242 self, string: str, expect_timeout: float = 10.0
243 ) -> "pexpect.spawn":
244 """See :meth:`Pytester.spawn_pytest`."""
245 return self._pytester.spawn_pytest(string, expect_timeout=expect_timeout)
246
247 def spawn(self, cmd: str, expect_timeout: float = 10.0) -> "pexpect.spawn":
248 """See :meth:`Pytester.spawn`."""
249 return self._pytester.spawn(cmd, expect_timeout=expect_timeout)
250
251 def __repr__(self) -> str:
252 return f"<Testdir {self.tmpdir!r}>"
253
254 def __str__(self) -> str:
255 return str(self.tmpdir)
256
257
258 class LegacyTestdirPlugin:
259 @staticmethod
260 @fixture
261 def testdir(pytester: Pytester) -> Testdir:
262 """
263 Identical to :fixture:`pytester`, and provides an instance whose methods return
264 legacy ``LEGACY_PATH`` objects instead when applicable.
265
266 New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
267 """
268 return Testdir(pytester, _ispytest=True)
269
270
271 @final
272 @dataclasses.dataclass
273 class TempdirFactory:
274 """Backward compatibility wrapper that implements ``py.path.local``
275 for :class:`TempPathFactory`.
276
277 .. note::
278 These days, it is preferred to use ``tmp_path_factory``.
279
280 :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
281
282 """
283
284 _tmppath_factory: TempPathFactory
285
286 def __init__(
287 self, tmppath_factory: TempPathFactory, *, _ispytest: bool = False
288 ) -> None:
289 check_ispytest(_ispytest)
290 self._tmppath_factory = tmppath_factory
291
292 def mktemp(self, basename: str, numbered: bool = True) -> LEGACY_PATH:
293 """Same as :meth:`TempPathFactory.mktemp`, but returns a ``py.path.local`` object."""
294 return legacy_path(self._tmppath_factory.mktemp(basename, numbered).resolve())
295
296 def getbasetemp(self) -> LEGACY_PATH:
297 """Same as :meth:`TempPathFactory.getbasetemp`, but returns a ``py.path.local`` object."""
298 return legacy_path(self._tmppath_factory.getbasetemp().resolve())
299
300
301 class LegacyTmpdirPlugin:
302 @staticmethod
303 @fixture(scope="session")
304 def tmpdir_factory(request: FixtureRequest) -> TempdirFactory:
305 """Return a :class:`pytest.TempdirFactory` instance for the test session."""
306 # Set dynamically by pytest_configure().
307 return request.config._tmpdirhandler # type: ignore
308
309 @staticmethod
310 @fixture
311 def tmpdir(tmp_path: Path) -> LEGACY_PATH:
312 """Return a temporary directory path object which is unique to each test
313 function invocation, created as a sub directory of the base temporary
314 directory.
315
316 By default, a new base temporary directory is created each test session,
317 and old bases are removed after 3 sessions, to aid in debugging. If
318 ``--basetemp`` is used then it is cleared each session. See
319 :ref:`temporary directory location and retention`.
320
321 The returned object is a `legacy_path`_ object.
322
323 .. note::
324 These days, it is preferred to use ``tmp_path``.
325
326 :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.
327
328 .. _legacy_path: https://py.readthedocs.io/en/latest/path.html
329 """
330 return legacy_path(tmp_path)
331
332
333 def Cache_makedir(self: Cache, name: str) -> LEGACY_PATH:
334 """Return a directory path object with the given name.
335
336 Same as :func:`mkdir`, but returns a legacy py path instance.
337 """
338 return legacy_path(self.mkdir(name))
339
340
341 def FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH:
342 """(deprecated) The file system path of the test module which collected this test."""
343 return legacy_path(self.path)
344
345
346 def TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH:
347 """The directory from which pytest was invoked.
348
349 Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
350
351 :type: LEGACY_PATH
352 """
353 return legacy_path(self.startpath)
354
355
356 def Config_invocation_dir(self: Config) -> LEGACY_PATH:
357 """The directory from which pytest was invoked.
358
359 Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`,
360 which is a :class:`pathlib.Path`.
361
362 :type: LEGACY_PATH
363 """
364 return legacy_path(str(self.invocation_params.dir))
365
366
367 def Config_rootdir(self: Config) -> LEGACY_PATH:
368 """The path to the :ref:`rootdir <rootdir>`.
369
370 Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`.
371
372 :type: LEGACY_PATH
373 """
374 return legacy_path(str(self.rootpath))
375
376
377 def Config_inifile(self: Config) -> Optional[LEGACY_PATH]:
378 """The path to the :ref:`configfile <configfiles>`.
379
380 Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`.
381
382 :type: Optional[LEGACY_PATH]
383 """
384 return legacy_path(str(self.inipath)) if self.inipath else None
385
386
387 def Session_startdir(self: Session) -> LEGACY_PATH:
388 """The path from which pytest was invoked.
389
390 Prefer to use ``startpath`` which is a :class:`pathlib.Path`.
391
392 :type: LEGACY_PATH
393 """
394 return legacy_path(self.startpath)
395
396
397 def Config__getini_unknown_type(
398 self, name: str, type: str, value: Union[str, List[str]]
399 ):
400 if type == "pathlist":
401 # TODO: This assert is probably not valid in all cases.
402 assert self.inipath is not None
403 dp = self.inipath.parent
404 input_values = shlex.split(value) if isinstance(value, str) else value
405 return [legacy_path(str(dp / x)) for x in input_values]
406 else:
407 raise ValueError(f"unknown configuration type: {type}", value)
408
409
410 def Node_fspath(self: Node) -> LEGACY_PATH:
411 """(deprecated) returns a legacy_path copy of self.path"""
412 return legacy_path(self.path)
413
414
415 def Node_fspath_set(self: Node, value: LEGACY_PATH) -> None:
416 self.path = Path(value)
417
418
419 @hookimpl(tryfirst=True)
420 def pytest_load_initial_conftests(early_config: Config) -> None:
421 """Monkeypatch legacy path attributes in several classes, as early as possible."""
422 mp = MonkeyPatch()
423 early_config.add_cleanup(mp.undo)
424
425 # Add Cache.makedir().
426 mp.setattr(Cache, "makedir", Cache_makedir, raising=False)
427
428 # Add FixtureRequest.fspath property.
429 mp.setattr(FixtureRequest, "fspath", property(FixtureRequest_fspath), raising=False)
430
431 # Add TerminalReporter.startdir property.
432 mp.setattr(
433 TerminalReporter, "startdir", property(TerminalReporter_startdir), raising=False
434 )
435
436 # Add Config.{invocation_dir,rootdir,inifile} properties.
437 mp.setattr(Config, "invocation_dir", property(Config_invocation_dir), raising=False)
438 mp.setattr(Config, "rootdir", property(Config_rootdir), raising=False)
439 mp.setattr(Config, "inifile", property(Config_inifile), raising=False)
440
441 # Add Session.startdir property.
442 mp.setattr(Session, "startdir", property(Session_startdir), raising=False)
443
444 # Add pathlist configuration type.
445 mp.setattr(Config, "_getini_unknown_type", Config__getini_unknown_type)
446
447 # Add Node.fspath property.
448 mp.setattr(Node, "fspath", property(Node_fspath, Node_fspath_set), raising=False)
449
450
451 @hookimpl
452 def pytest_configure(config: Config) -> None:
453 """Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed."""
454 if config.pluginmanager.has_plugin("tmpdir"):
455 mp = MonkeyPatch()
456 config.add_cleanup(mp.undo)
457 # Create TmpdirFactory and attach it to the config object.
458 #
459 # This is to comply with existing plugins which expect the handler to be
460 # available at pytest_configure time, but ideally should be moved entirely
461 # to the tmpdir_factory session fixture.
462 try:
463 tmp_path_factory = config._tmp_path_factory # type: ignore[attr-defined]
464 except AttributeError:
465 # tmpdir plugin is blocked.
466 pass
467 else:
468 _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True)
469 mp.setattr(config, "_tmpdirhandler", _tmpdirhandler, raising=False)
470
471 config.pluginmanager.register(LegacyTmpdirPlugin, "legacypath-tmpdir")
472
473
474 @hookimpl
475 def pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None:
476 # pytester is not loaded by default and is commonly loaded from a conftest,
477 # so checking for it in `pytest_configure` is not enough.
478 is_pytester = plugin is manager.get_plugin("pytester")
479 if is_pytester and not manager.is_registered(LegacyTestdirPlugin):
480 manager.register(LegacyTestdirPlugin, "legacypath-pytester")