Debian Codegraph @

src/_pytest/legacypath.py

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