legacypath.py 16 KB

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