pytester.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. # mypy: allow-untyped-defs
  2. """(Disabled by default) support for testing pytest and pytest plugins.
  3. PYTEST_DONT_REWRITE
  4. """
  5. from __future__ import annotations
  6. import collections.abc
  7. from collections.abc import Callable
  8. from collections.abc import Generator
  9. from collections.abc import Iterable
  10. from collections.abc import Sequence
  11. import contextlib
  12. from fnmatch import fnmatch
  13. import gc
  14. import importlib
  15. from io import StringIO
  16. import locale
  17. import os
  18. from pathlib import Path
  19. import platform
  20. import re
  21. import shutil
  22. import subprocess
  23. import sys
  24. import traceback
  25. from typing import Any
  26. from typing import Final
  27. from typing import final
  28. from typing import IO
  29. from typing import Literal
  30. from typing import overload
  31. from typing import TextIO
  32. from typing import TYPE_CHECKING
  33. from weakref import WeakKeyDictionary
  34. from iniconfig import IniConfig
  35. from iniconfig import SectionWrapper
  36. from _pytest import timing
  37. from _pytest._code import Source
  38. from _pytest.capture import _get_multicapture
  39. from _pytest.compat import NOTSET
  40. from _pytest.compat import NotSetType
  41. from _pytest.config import _PluggyPlugin
  42. from _pytest.config import Config
  43. from _pytest.config import ExitCode
  44. from _pytest.config import hookimpl
  45. from _pytest.config import main
  46. from _pytest.config import PytestPluginManager
  47. from _pytest.config.argparsing import Parser
  48. from _pytest.deprecated import check_ispytest
  49. from _pytest.fixtures import fixture
  50. from _pytest.fixtures import FixtureRequest
  51. from _pytest.main import Session
  52. from _pytest.monkeypatch import MonkeyPatch
  53. from _pytest.nodes import Collector
  54. from _pytest.nodes import Item
  55. from _pytest.outcomes import fail
  56. from _pytest.outcomes import importorskip
  57. from _pytest.outcomes import skip
  58. from _pytest.pathlib import bestrelpath
  59. from _pytest.pathlib import make_numbered_dir
  60. from _pytest.reports import CollectReport
  61. from _pytest.reports import TestReport
  62. from _pytest.tmpdir import TempPathFactory
  63. from _pytest.warning_types import PytestFDWarning
  64. if TYPE_CHECKING:
  65. import pexpect
  66. pytest_plugins = ["pytester_assertions"]
  67. IGNORE_PAM = [ # filenames added when obtaining details about the current user
  68. "/var/lib/sss/mc/passwd"
  69. ]
  70. def pytest_addoption(parser: Parser) -> None:
  71. parser.addoption(
  72. "--lsof",
  73. action="store_true",
  74. dest="lsof",
  75. default=False,
  76. help="Run FD checks if lsof is available",
  77. )
  78. parser.addoption(
  79. "--runpytest",
  80. default="inprocess",
  81. dest="runpytest",
  82. choices=("inprocess", "subprocess"),
  83. help=(
  84. "Run pytest sub runs in tests using an 'inprocess' "
  85. "or 'subprocess' (python -m main) method"
  86. ),
  87. )
  88. parser.addini(
  89. "pytester_example_dir", help="Directory to take the pytester example files from"
  90. )
  91. def pytest_configure(config: Config) -> None:
  92. if config.getvalue("lsof"):
  93. checker = LsofFdLeakChecker()
  94. if checker.matching_platform():
  95. config.pluginmanager.register(checker)
  96. config.addinivalue_line(
  97. "markers",
  98. "pytester_example_path(*path_segments): join the given path "
  99. "segments to `pytester_example_dir` for this test.",
  100. )
  101. class LsofFdLeakChecker:
  102. def get_open_files(self) -> list[tuple[str, str]]:
  103. if sys.version_info >= (3, 11):
  104. # New in Python 3.11, ignores utf-8 mode
  105. encoding = locale.getencoding()
  106. else:
  107. encoding = locale.getpreferredencoding(False)
  108. out = subprocess.run(
  109. ("lsof", "-Ffn0", "-p", str(os.getpid())),
  110. stdout=subprocess.PIPE,
  111. stderr=subprocess.DEVNULL,
  112. check=True,
  113. text=True,
  114. encoding=encoding,
  115. ).stdout
  116. def isopen(line: str) -> bool:
  117. return line.startswith("f") and (
  118. "deleted" not in line
  119. and "mem" not in line
  120. and "txt" not in line
  121. and "cwd" not in line
  122. )
  123. open_files = []
  124. for line in out.split("\n"):
  125. if isopen(line):
  126. fields = line.split("\0")
  127. fd = fields[0][1:]
  128. filename = fields[1][1:]
  129. if filename in IGNORE_PAM:
  130. continue
  131. if filename.startswith("/"):
  132. open_files.append((fd, filename))
  133. return open_files
  134. def matching_platform(self) -> bool:
  135. try:
  136. subprocess.run(("lsof", "-v"), check=True)
  137. except (OSError, subprocess.CalledProcessError):
  138. return False
  139. else:
  140. return True
  141. @hookimpl(wrapper=True, tryfirst=True)
  142. def pytest_runtest_protocol(self, item: Item) -> Generator[None, object, object]:
  143. lines1 = self.get_open_files()
  144. try:
  145. return (yield)
  146. finally:
  147. if hasattr(sys, "pypy_version_info"):
  148. gc.collect()
  149. lines2 = self.get_open_files()
  150. new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}
  151. leaked_files = [t for t in lines2 if t[0] in new_fds]
  152. if leaked_files:
  153. error = [
  154. f"***** {len(leaked_files)} FD leakage detected",
  155. *(str(f) for f in leaked_files),
  156. "*** Before:",
  157. *(str(f) for f in lines1),
  158. "*** After:",
  159. *(str(f) for f in lines2),
  160. f"***** {len(leaked_files)} FD leakage detected",
  161. "*** function {}:{}: {} ".format(*item.location),
  162. "See issue #2366",
  163. ]
  164. item.warn(PytestFDWarning("\n".join(error)))
  165. # used at least by pytest-xdist plugin
  166. @fixture
  167. def _pytest(request: FixtureRequest) -> PytestArg:
  168. """Return a helper which offers a gethookrecorder(hook) method which
  169. returns a HookRecorder instance which helps to make assertions about called
  170. hooks."""
  171. return PytestArg(request)
  172. class PytestArg:
  173. def __init__(self, request: FixtureRequest) -> None:
  174. self._request = request
  175. def gethookrecorder(self, hook) -> HookRecorder:
  176. hookrecorder = HookRecorder(hook._pm)
  177. self._request.addfinalizer(hookrecorder.finish_recording)
  178. return hookrecorder
  179. def get_public_names(values: Iterable[str]) -> list[str]:
  180. """Only return names from iterator values without a leading underscore."""
  181. return [x for x in values if x[0] != "_"]
  182. @final
  183. class RecordedHookCall:
  184. """A recorded call to a hook.
  185. The arguments to the hook call are set as attributes.
  186. For example:
  187. .. code-block:: python
  188. calls = hook_recorder.getcalls("pytest_runtest_setup")
  189. # Suppose pytest_runtest_setup was called once with `item=an_item`.
  190. assert calls[0].item is an_item
  191. """
  192. def __init__(self, name: str, kwargs) -> None:
  193. self.__dict__.update(kwargs)
  194. self._name = name
  195. def __repr__(self) -> str:
  196. d = self.__dict__.copy()
  197. del d["_name"]
  198. return f"<RecordedHookCall {self._name!r}(**{d!r})>"
  199. if TYPE_CHECKING:
  200. # The class has undetermined attributes, this tells mypy about it.
  201. def __getattr__(self, key: str): ...
  202. @final
  203. class HookRecorder:
  204. """Record all hooks called in a plugin manager.
  205. Hook recorders are created by :class:`Pytester`.
  206. This wraps all the hook calls in the plugin manager, recording each call
  207. before propagating the normal calls.
  208. """
  209. def __init__(
  210. self, pluginmanager: PytestPluginManager, *, _ispytest: bool = False
  211. ) -> None:
  212. check_ispytest(_ispytest)
  213. self._pluginmanager = pluginmanager
  214. self.calls: list[RecordedHookCall] = []
  215. self.ret: int | ExitCode | None = None
  216. def before(hook_name: str, hook_impls, kwargs) -> None:
  217. self.calls.append(RecordedHookCall(hook_name, kwargs))
  218. def after(outcome, hook_name: str, hook_impls, kwargs) -> None:
  219. pass
  220. self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)
  221. def finish_recording(self) -> None:
  222. self._undo_wrapping()
  223. def getcalls(self, names: str | Iterable[str]) -> list[RecordedHookCall]:
  224. """Get all recorded calls to hooks with the given names (or name)."""
  225. if isinstance(names, str):
  226. names = names.split()
  227. return [call for call in self.calls if call._name in names]
  228. def assert_contains(self, entries: Sequence[tuple[str, str]]) -> None:
  229. __tracebackhide__ = True
  230. i = 0
  231. entries = list(entries)
  232. # Since Python 3.13, f_locals is not a dict, but eval requires a dict.
  233. backlocals = dict(sys._getframe(1).f_locals)
  234. while entries:
  235. name, check = entries.pop(0)
  236. for ind, call in enumerate(self.calls[i:]):
  237. if call._name == name:
  238. print("NAMEMATCH", name, call)
  239. if eval(check, backlocals, call.__dict__):
  240. print("CHECKERMATCH", repr(check), "->", call)
  241. else:
  242. print("NOCHECKERMATCH", repr(check), "-", call)
  243. continue
  244. i += ind + 1
  245. break
  246. print("NONAMEMATCH", name, "with", call)
  247. else:
  248. fail(f"could not find {name!r} check {check!r}")
  249. def popcall(self, name: str) -> RecordedHookCall:
  250. __tracebackhide__ = True
  251. for i, call in enumerate(self.calls):
  252. if call._name == name:
  253. del self.calls[i]
  254. return call
  255. lines = [f"could not find call {name!r}, in:"]
  256. lines.extend([f" {x}" for x in self.calls])
  257. fail("\n".join(lines))
  258. def getcall(self, name: str) -> RecordedHookCall:
  259. values = self.getcalls(name)
  260. assert len(values) == 1, (name, values)
  261. return values[0]
  262. # functionality for test reports
  263. @overload
  264. def getreports(
  265. self,
  266. names: Literal["pytest_collectreport"],
  267. ) -> Sequence[CollectReport]: ...
  268. @overload
  269. def getreports(
  270. self,
  271. names: Literal["pytest_runtest_logreport"],
  272. ) -> Sequence[TestReport]: ...
  273. @overload
  274. def getreports(
  275. self,
  276. names: str | Iterable[str] = (
  277. "pytest_collectreport",
  278. "pytest_runtest_logreport",
  279. ),
  280. ) -> Sequence[CollectReport | TestReport]: ...
  281. def getreports(
  282. self,
  283. names: str | Iterable[str] = (
  284. "pytest_collectreport",
  285. "pytest_runtest_logreport",
  286. ),
  287. ) -> Sequence[CollectReport | TestReport]:
  288. return [x.report for x in self.getcalls(names)]
  289. def matchreport(
  290. self,
  291. inamepart: str = "",
  292. names: str | Iterable[str] = (
  293. "pytest_runtest_logreport",
  294. "pytest_collectreport",
  295. ),
  296. when: str | None = None,
  297. ) -> CollectReport | TestReport:
  298. """Return a testreport whose dotted import path matches."""
  299. values = []
  300. for rep in self.getreports(names=names):
  301. if not when and rep.when != "call" and rep.passed:
  302. # setup/teardown passing reports - let's ignore those
  303. continue
  304. if when and rep.when != when:
  305. continue
  306. if not inamepart or inamepart in rep.nodeid.split("::"):
  307. values.append(rep)
  308. if not values:
  309. raise ValueError(
  310. f"could not find test report matching {inamepart!r}: "
  311. "no test reports at all!"
  312. )
  313. if len(values) > 1:
  314. raise ValueError(
  315. f"found 2 or more testreports matching {inamepart!r}: {values}"
  316. )
  317. return values[0]
  318. @overload
  319. def getfailures(
  320. self,
  321. names: Literal["pytest_collectreport"],
  322. ) -> Sequence[CollectReport]: ...
  323. @overload
  324. def getfailures(
  325. self,
  326. names: Literal["pytest_runtest_logreport"],
  327. ) -> Sequence[TestReport]: ...
  328. @overload
  329. def getfailures(
  330. self,
  331. names: str | Iterable[str] = (
  332. "pytest_collectreport",
  333. "pytest_runtest_logreport",
  334. ),
  335. ) -> Sequence[CollectReport | TestReport]: ...
  336. def getfailures(
  337. self,
  338. names: str | Iterable[str] = (
  339. "pytest_collectreport",
  340. "pytest_runtest_logreport",
  341. ),
  342. ) -> Sequence[CollectReport | TestReport]:
  343. return [rep for rep in self.getreports(names) if rep.failed]
  344. def getfailedcollections(self) -> Sequence[CollectReport]:
  345. return self.getfailures("pytest_collectreport")
  346. def listoutcomes(
  347. self,
  348. ) -> tuple[
  349. Sequence[TestReport],
  350. Sequence[CollectReport | TestReport],
  351. Sequence[CollectReport | TestReport],
  352. ]:
  353. passed = []
  354. skipped = []
  355. failed = []
  356. for rep in self.getreports(
  357. ("pytest_collectreport", "pytest_runtest_logreport")
  358. ):
  359. if rep.passed:
  360. if rep.when == "call":
  361. assert isinstance(rep, TestReport)
  362. passed.append(rep)
  363. elif rep.skipped:
  364. skipped.append(rep)
  365. else:
  366. assert rep.failed, f"Unexpected outcome: {rep!r}"
  367. failed.append(rep)
  368. return passed, skipped, failed
  369. def countoutcomes(self) -> list[int]:
  370. return [len(x) for x in self.listoutcomes()]
  371. def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> None:
  372. __tracebackhide__ = True
  373. from _pytest.pytester_assertions import assertoutcome
  374. outcomes = self.listoutcomes()
  375. assertoutcome(
  376. outcomes,
  377. passed=passed,
  378. skipped=skipped,
  379. failed=failed,
  380. )
  381. def clear(self) -> None:
  382. self.calls[:] = []
  383. @fixture
  384. def linecomp() -> LineComp:
  385. """A :class: `LineComp` instance for checking that an input linearly
  386. contains a sequence of strings."""
  387. return LineComp()
  388. @fixture(name="LineMatcher")
  389. def LineMatcher_fixture(request: FixtureRequest) -> type[LineMatcher]:
  390. """A reference to the :class: `LineMatcher`.
  391. This is instantiable with a list of lines (without their trailing newlines).
  392. This is useful for testing large texts, such as the output of commands.
  393. """
  394. return LineMatcher
  395. @fixture
  396. def pytester(
  397. request: FixtureRequest, tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch
  398. ) -> Pytester:
  399. """
  400. Facilities to write tests/configuration files, execute pytest in isolation, and match
  401. against expected output, perfect for black-box testing of pytest plugins.
  402. It attempts to isolate the test run from external factors as much as possible, modifying
  403. the current working directory to ``path`` and environment variables during initialization.
  404. It is particularly useful for testing plugins. It is similar to the :fixture:`tmp_path`
  405. fixture but provides methods which aid in testing pytest itself.
  406. """
  407. return Pytester(request, tmp_path_factory, monkeypatch, _ispytest=True)
  408. @fixture
  409. def _sys_snapshot() -> Generator[None]:
  410. snappaths = SysPathsSnapshot()
  411. snapmods = SysModulesSnapshot()
  412. yield
  413. snapmods.restore()
  414. snappaths.restore()
  415. @fixture
  416. def _config_for_test() -> Generator[Config]:
  417. from _pytest.config import get_config
  418. config = get_config()
  419. yield config
  420. config._ensure_unconfigure() # cleanup, e.g. capman closing tmpfiles.
  421. # Regex to match the session duration string in the summary: "74.34s".
  422. rex_session_duration = re.compile(r"\d+\.\d\ds")
  423. # Regex to match all the counts and phrases in the summary line: "34 passed, 111 skipped".
  424. rex_outcome = re.compile(r"(\d+) (\w+)")
  425. @final
  426. class RunResult:
  427. """The result of running a command from :class:`~pytest.Pytester`."""
  428. def __init__(
  429. self,
  430. ret: int | ExitCode,
  431. outlines: list[str],
  432. errlines: list[str],
  433. duration: float,
  434. ) -> None:
  435. try:
  436. self.ret: int | ExitCode = ExitCode(ret)
  437. """The return value."""
  438. except ValueError:
  439. self.ret = ret
  440. self.outlines = outlines
  441. """List of lines captured from stdout."""
  442. self.errlines = errlines
  443. """List of lines captured from stderr."""
  444. self.stdout = LineMatcher(outlines)
  445. """:class:`~pytest.LineMatcher` of stdout.
  446. Use e.g. :func:`str(stdout) <pytest.LineMatcher.__str__()>` to reconstruct stdout, or the commonly used
  447. :func:`stdout.fnmatch_lines() <pytest.LineMatcher.fnmatch_lines()>` method.
  448. """
  449. self.stderr = LineMatcher(errlines)
  450. """:class:`~pytest.LineMatcher` of stderr."""
  451. self.duration = duration
  452. """Duration in seconds."""
  453. def __repr__(self) -> str:
  454. return (
  455. f"<RunResult ret={self.ret!s} "
  456. f"len(stdout.lines)={len(self.stdout.lines)} "
  457. f"len(stderr.lines)={len(self.stderr.lines)} "
  458. f"duration={self.duration:.2f}s>"
  459. )
  460. def parseoutcomes(self) -> dict[str, int]:
  461. """Return a dictionary of outcome noun -> count from parsing the terminal
  462. output that the test process produced.
  463. The returned nouns will always be in plural form::
  464. ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
  465. Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
  466. """
  467. return self.parse_summary_nouns(self.outlines)
  468. @classmethod
  469. def parse_summary_nouns(cls, lines) -> dict[str, int]:
  470. """Extract the nouns from a pytest terminal summary line.
  471. It always returns the plural noun for consistency::
  472. ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====
  473. Will return ``{"failed": 1, "passed": 1, "warnings": 1, "errors": 1}``.
  474. """
  475. for line in reversed(lines):
  476. if rex_session_duration.search(line):
  477. outcomes = rex_outcome.findall(line)
  478. ret = {noun: int(count) for (count, noun) in outcomes}
  479. break
  480. else:
  481. raise ValueError("Pytest terminal summary report not found")
  482. to_plural = {
  483. "warning": "warnings",
  484. "error": "errors",
  485. }
  486. return {to_plural.get(k, k): v for k, v in ret.items()}
  487. def assert_outcomes(
  488. self,
  489. passed: int = 0,
  490. skipped: int = 0,
  491. failed: int = 0,
  492. errors: int = 0,
  493. xpassed: int = 0,
  494. xfailed: int = 0,
  495. warnings: int | None = None,
  496. deselected: int | None = None,
  497. ) -> None:
  498. """
  499. Assert that the specified outcomes appear with the respective
  500. numbers (0 means it didn't occur) in the text output from a test run.
  501. ``warnings`` and ``deselected`` are only checked if not None.
  502. """
  503. __tracebackhide__ = True
  504. from _pytest.pytester_assertions import assert_outcomes
  505. outcomes = self.parseoutcomes()
  506. assert_outcomes(
  507. outcomes,
  508. passed=passed,
  509. skipped=skipped,
  510. failed=failed,
  511. errors=errors,
  512. xpassed=xpassed,
  513. xfailed=xfailed,
  514. warnings=warnings,
  515. deselected=deselected,
  516. )
  517. class SysModulesSnapshot:
  518. def __init__(self, preserve: Callable[[str], bool] | None = None) -> None:
  519. self.__preserve = preserve
  520. self.__saved = dict(sys.modules)
  521. def restore(self) -> None:
  522. if self.__preserve:
  523. self.__saved.update(
  524. (k, m) for k, m in sys.modules.items() if self.__preserve(k)
  525. )
  526. sys.modules.clear()
  527. sys.modules.update(self.__saved)
  528. class SysPathsSnapshot:
  529. def __init__(self) -> None:
  530. self.__saved = list(sys.path), list(sys.meta_path)
  531. def restore(self) -> None:
  532. sys.path[:], sys.meta_path[:] = self.__saved
  533. @final
  534. class Pytester:
  535. """
  536. Facilities to write tests/configuration files, execute pytest in isolation, and match
  537. against expected output, perfect for black-box testing of pytest plugins.
  538. It attempts to isolate the test run from external factors as much as possible, modifying
  539. the current working directory to :attr:`path` and environment variables during initialization.
  540. """
  541. __test__ = False
  542. CLOSE_STDIN: Final = NOTSET
  543. class TimeoutExpired(Exception):
  544. pass
  545. def __init__(
  546. self,
  547. request: FixtureRequest,
  548. tmp_path_factory: TempPathFactory,
  549. monkeypatch: MonkeyPatch,
  550. *,
  551. _ispytest: bool = False,
  552. ) -> None:
  553. check_ispytest(_ispytest)
  554. self._request = request
  555. self._mod_collections: WeakKeyDictionary[Collector, list[Item | Collector]] = (
  556. WeakKeyDictionary()
  557. )
  558. if request.function:
  559. name: str = request.function.__name__
  560. else:
  561. name = request.node.name
  562. self._name = name
  563. self._path: Path = tmp_path_factory.mktemp(name, numbered=True)
  564. #: A list of plugins to use with :py:meth:`parseconfig` and
  565. #: :py:meth:`runpytest`. Initially this is an empty list but plugins can
  566. #: be added to the list.
  567. #:
  568. #: When running in subprocess mode, specify plugins by name (str) - adding
  569. #: plugin objects directly is not supported.
  570. self.plugins: list[str | _PluggyPlugin] = []
  571. self._sys_path_snapshot = SysPathsSnapshot()
  572. self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
  573. self._request.addfinalizer(self._finalize)
  574. self._method = self._request.config.getoption("--runpytest")
  575. self._test_tmproot = tmp_path_factory.mktemp(f"tmp-{name}", numbered=True)
  576. self._monkeypatch = mp = monkeypatch
  577. self.chdir()
  578. mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self._test_tmproot))
  579. # Ensure no unexpected caching via tox.
  580. mp.delenv("TOX_ENV_DIR", raising=False)
  581. # Discard outer pytest options.
  582. mp.delenv("PYTEST_ADDOPTS", raising=False)
  583. # Ensure no user config is used.
  584. tmphome = str(self.path)
  585. mp.setenv("HOME", tmphome)
  586. mp.setenv("USERPROFILE", tmphome)
  587. # Do not use colors for inner runs by default.
  588. mp.setenv("PY_COLORS", "0")
  589. @property
  590. def path(self) -> Path:
  591. """Temporary directory path used to create files/run tests from, etc."""
  592. return self._path
  593. def __repr__(self) -> str:
  594. return f"<Pytester {self.path!r}>"
  595. def _finalize(self) -> None:
  596. """
  597. Clean up global state artifacts.
  598. Some methods modify the global interpreter state and this tries to
  599. clean this up. It does not remove the temporary directory however so
  600. it can be looked at after the test run has finished.
  601. """
  602. self._sys_modules_snapshot.restore()
  603. self._sys_path_snapshot.restore()
  604. def __take_sys_modules_snapshot(self) -> SysModulesSnapshot:
  605. # Some zope modules used by twisted-related tests keep internal state
  606. # and can't be deleted; we had some trouble in the past with
  607. # `zope.interface` for example.
  608. #
  609. # Preserve readline due to https://bugs.python.org/issue41033.
  610. # pexpect issues a SIGWINCH.
  611. def preserve_module(name):
  612. return name.startswith(("zope", "readline"))
  613. return SysModulesSnapshot(preserve=preserve_module)
  614. def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:
  615. """Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`."""
  616. pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True) # type: ignore[attr-defined]
  617. self._request.addfinalizer(reprec.finish_recording)
  618. return reprec
  619. def chdir(self) -> None:
  620. """Cd into the temporary directory.
  621. This is done automatically upon instantiation.
  622. """
  623. self._monkeypatch.chdir(self.path)
  624. def _makefile(
  625. self,
  626. ext: str,
  627. lines: Sequence[Any | bytes],
  628. files: dict[str, str],
  629. encoding: str = "utf-8",
  630. ) -> Path:
  631. items = list(files.items())
  632. if ext is None:
  633. raise TypeError("ext must not be None")
  634. if ext and not ext.startswith("."):
  635. raise ValueError(
  636. f"pytester.makefile expects a file extension, try .{ext} instead of {ext}"
  637. )
  638. def to_text(s: Any | bytes) -> str:
  639. return s.decode(encoding) if isinstance(s, bytes) else str(s)
  640. if lines:
  641. source = "\n".join(to_text(x) for x in lines)
  642. basename = self._name
  643. items.insert(0, (basename, source))
  644. ret = None
  645. for basename, value in items:
  646. p = self.path.joinpath(basename).with_suffix(ext)
  647. p.parent.mkdir(parents=True, exist_ok=True)
  648. source_ = Source(value)
  649. source = "\n".join(to_text(line) for line in source_.lines)
  650. p.write_text(source.strip(), encoding=encoding)
  651. if ret is None:
  652. ret = p
  653. assert ret is not None
  654. return ret
  655. def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:
  656. r"""Create new text file(s) in the test directory.
  657. :param ext:
  658. The extension the file(s) should use, including the dot, e.g. `.py`.
  659. :param args:
  660. All args are treated as strings and joined using newlines.
  661. The result is written as contents to the file. The name of the
  662. file is based on the test function requesting this fixture.
  663. :param kwargs:
  664. Each keyword is the name of a file, while the value of it will
  665. be written as contents of the file.
  666. :returns:
  667. The first created file.
  668. Examples:
  669. .. code-block:: python
  670. pytester.makefile(".txt", "line1", "line2")
  671. pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
  672. To create binary files, use :meth:`pathlib.Path.write_bytes` directly:
  673. .. code-block:: python
  674. filename = pytester.path.joinpath("foo.bin")
  675. filename.write_bytes(b"...")
  676. """
  677. return self._makefile(ext, args, kwargs)
  678. def makeconftest(self, source: str) -> Path:
  679. """Write a conftest.py file.
  680. :param source: The contents.
  681. :returns: The conftest.py file.
  682. """
  683. return self.makepyfile(conftest=source)
  684. def makeini(self, source: str) -> Path:
  685. """Write a tox.ini file.
  686. :param source: The contents.
  687. :returns: The tox.ini file.
  688. """
  689. return self.makefile(".ini", tox=source)
  690. def maketoml(self, source: str) -> Path:
  691. """Write a pytest.toml file.
  692. :param source: The contents.
  693. :returns: The pytest.toml file.
  694. .. versionadded:: 9.0
  695. """
  696. return self.makefile(".toml", pytest=source)
  697. def getinicfg(self, source: str) -> SectionWrapper:
  698. """Return the pytest section from the tox.ini config file."""
  699. p = self.makeini(source)
  700. return IniConfig(str(p))["pytest"]
  701. def makepyprojecttoml(self, source: str) -> Path:
  702. """Write a pyproject.toml file.
  703. :param source: The contents.
  704. :returns: The pyproject.ini file.
  705. .. versionadded:: 6.0
  706. """
  707. return self.makefile(".toml", pyproject=source)
  708. def makepyfile(self, *args, **kwargs) -> Path:
  709. r"""Shortcut for .makefile() with a .py extension.
  710. Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting
  711. existing files.
  712. Examples:
  713. .. code-block:: python
  714. def test_something(pytester):
  715. # Initial file is created test_something.py.
  716. pytester.makepyfile("foobar")
  717. # To create multiple files, pass kwargs accordingly.
  718. pytester.makepyfile(custom="foobar")
  719. # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
  720. """
  721. return self._makefile(".py", args, kwargs)
  722. def maketxtfile(self, *args, **kwargs) -> Path:
  723. r"""Shortcut for .makefile() with a .txt extension.
  724. Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting
  725. existing files.
  726. Examples:
  727. .. code-block:: python
  728. def test_something(pytester):
  729. # Initial file is created test_something.txt.
  730. pytester.maketxtfile("foobar")
  731. # To create multiple files, pass kwargs accordingly.
  732. pytester.maketxtfile(custom="foobar")
  733. # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
  734. """
  735. return self._makefile(".txt", args, kwargs)
  736. def syspathinsert(self, path: str | os.PathLike[str] | None = None) -> None:
  737. """Prepend a directory to sys.path, defaults to :attr:`path`.
  738. This is undone automatically when this object dies at the end of each
  739. test.
  740. :param path:
  741. The path.
  742. """
  743. if path is None:
  744. path = self.path
  745. self._monkeypatch.syspath_prepend(str(path))
  746. def mkdir(self, name: str | os.PathLike[str]) -> Path:
  747. """Create a new (sub)directory.
  748. :param name:
  749. The name of the directory, relative to the pytester path.
  750. :returns:
  751. The created directory.
  752. :rtype: pathlib.Path
  753. """
  754. p = self.path / name
  755. p.mkdir()
  756. return p
  757. def mkpydir(self, name: str | os.PathLike[str]) -> Path:
  758. """Create a new python package.
  759. This creates a (sub)directory with an empty ``__init__.py`` file so it
  760. gets recognised as a Python package.
  761. """
  762. p = self.path / name
  763. p.mkdir()
  764. p.joinpath("__init__.py").touch()
  765. return p
  766. def copy_example(self, name: str | None = None) -> Path:
  767. """Copy file from project's directory into the testdir.
  768. :param name:
  769. The name of the file to copy.
  770. :return:
  771. Path to the copied directory (inside ``self.path``).
  772. :rtype: pathlib.Path
  773. """
  774. example_dir_ = self._request.config.getini("pytester_example_dir")
  775. if example_dir_ is None:
  776. raise ValueError("pytester_example_dir is unset, can't copy examples")
  777. example_dir: Path = self._request.config.rootpath / example_dir_
  778. for extra_element in self._request.node.iter_markers("pytester_example_path"):
  779. assert extra_element.args
  780. example_dir = example_dir.joinpath(*extra_element.args)
  781. if name is None:
  782. func_name = self._name
  783. maybe_dir = example_dir / func_name
  784. maybe_file = example_dir / (func_name + ".py")
  785. if maybe_dir.is_dir():
  786. example_path = maybe_dir
  787. elif maybe_file.is_file():
  788. example_path = maybe_file
  789. else:
  790. raise LookupError(
  791. f"{func_name} can't be found as module or package in {example_dir}"
  792. )
  793. else:
  794. example_path = example_dir.joinpath(name)
  795. if example_path.is_dir() and not example_path.joinpath("__init__.py").is_file():
  796. shutil.copytree(example_path, self.path, symlinks=True, dirs_exist_ok=True)
  797. return self.path
  798. elif example_path.is_file():
  799. result = self.path.joinpath(example_path.name)
  800. shutil.copy(example_path, result)
  801. return result
  802. else:
  803. raise LookupError(
  804. f'example "{example_path}" is not found as a file or directory'
  805. )
  806. def getnode(self, config: Config, arg: str | os.PathLike[str]) -> Collector | Item:
  807. """Get the collection node of a file.
  808. :param config:
  809. A pytest config.
  810. See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
  811. :param arg:
  812. Path to the file.
  813. :returns:
  814. The node.
  815. """
  816. session = Session.from_config(config)
  817. assert "::" not in str(arg)
  818. p = Path(os.path.abspath(arg))
  819. config.hook.pytest_sessionstart(session=session)
  820. res = session.perform_collect([str(p)], genitems=False)[0]
  821. config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
  822. return res
  823. def getpathnode(self, path: str | os.PathLike[str]) -> Collector | Item:
  824. """Return the collection node of a file.
  825. This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
  826. create the (configured) pytest Config instance.
  827. :param path:
  828. Path to the file.
  829. :returns:
  830. The node.
  831. """
  832. path = Path(path)
  833. config = self.parseconfigure(path)
  834. session = Session.from_config(config)
  835. x = bestrelpath(session.path, path)
  836. config.hook.pytest_sessionstart(session=session)
  837. res = session.perform_collect([x], genitems=False)[0]
  838. config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
  839. return res
  840. def genitems(self, colitems: Sequence[Item | Collector]) -> list[Item]:
  841. """Generate all test items from a collection node.
  842. This recurses into the collection node and returns a list of all the
  843. test items contained within.
  844. :param colitems:
  845. The collection nodes.
  846. :returns:
  847. The collected items.
  848. """
  849. session = colitems[0].session
  850. result: list[Item] = []
  851. for colitem in colitems:
  852. result.extend(session.genitems(colitem))
  853. return result
  854. def runitem(self, source: str) -> Any:
  855. """Run the "test_func" Item.
  856. The calling test instance (class containing the test method) must
  857. provide a ``.getrunner()`` method which should return a runner which
  858. can run the test protocol for a single item, e.g.
  859. ``_pytest.runner.runtestprotocol``.
  860. """
  861. # used from runner functional tests
  862. item = self.getitem(source)
  863. # the test class where we are called from wants to provide the runner
  864. testclassinstance = self._request.instance
  865. runner = testclassinstance.getrunner()
  866. return runner(item)
  867. def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder:
  868. """Run a test module in process using ``pytest.main()``.
  869. This run writes "source" into a temporary file and runs
  870. ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
  871. for the result.
  872. :param source: The source code of the test module.
  873. :param cmdlineargs: Any extra command line arguments to use.
  874. """
  875. p = self.makepyfile(source)
  876. values = [*list(cmdlineargs), p]
  877. return self.inline_run(*values)
  878. def inline_genitems(self, *args) -> tuple[list[Item], HookRecorder]:
  879. """Run ``pytest.main(['--collect-only'])`` in-process.
  880. Runs the :py:func:`pytest.main` function to run all of pytest inside
  881. the test process itself like :py:meth:`inline_run`, but returns a
  882. tuple of the collected items and a :py:class:`HookRecorder` instance.
  883. """
  884. rec = self.inline_run("--collect-only", *args)
  885. items = [x.item for x in rec.getcalls("pytest_itemcollected")]
  886. return items, rec
  887. def inline_run(
  888. self,
  889. *args: str | os.PathLike[str],
  890. plugins=(),
  891. no_reraise_ctrlc: bool = False,
  892. ) -> HookRecorder:
  893. """Run ``pytest.main()`` in-process, returning a HookRecorder.
  894. Runs the :py:func:`pytest.main` function to run all of pytest inside
  895. the test process itself. This means it can return a
  896. :py:class:`HookRecorder` instance which gives more detailed results
  897. from that run than can be done by matching stdout/stderr from
  898. :py:meth:`runpytest`.
  899. :param args:
  900. Command line arguments to pass to :py:func:`pytest.main`.
  901. :param plugins:
  902. Extra plugin instances the ``pytest.main()`` instance should use.
  903. :param no_reraise_ctrlc:
  904. Typically we reraise keyboard interrupts from the child run. If
  905. True, the KeyboardInterrupt exception is captured.
  906. """
  907. from _pytest.unraisableexception import gc_collect_iterations_key
  908. # (maybe a cpython bug?) the importlib cache sometimes isn't updated
  909. # properly between file creation and inline_run (especially if imports
  910. # are interspersed with file creation)
  911. importlib.invalidate_caches()
  912. plugins = list(plugins)
  913. finalizers = []
  914. try:
  915. # Any sys.module or sys.path changes done while running pytest
  916. # inline should be reverted after the test run completes to avoid
  917. # clashing with later inline tests run within the same pytest test,
  918. # e.g. just because they use matching test module names.
  919. finalizers.append(self.__take_sys_modules_snapshot().restore)
  920. finalizers.append(SysPathsSnapshot().restore)
  921. # Important note:
  922. # - our tests should not leave any other references/registrations
  923. # laying around other than possibly loaded test modules
  924. # referenced from sys.modules, as nothing will clean those up
  925. # automatically
  926. rec = []
  927. class PytesterHelperPlugin:
  928. @staticmethod
  929. def pytest_configure(config: Config) -> None:
  930. rec.append(self.make_hook_recorder(config.pluginmanager))
  931. # The unraisable plugin GC collect slows down inline
  932. # pytester runs too much.
  933. config.stash[gc_collect_iterations_key] = 0
  934. plugins.append(PytesterHelperPlugin())
  935. ret = main([str(x) for x in args], plugins=plugins)
  936. if len(rec) == 1:
  937. reprec = rec.pop()
  938. else:
  939. class reprec: # type: ignore
  940. pass
  941. reprec.ret = ret
  942. # Typically we reraise keyboard interrupts from the child run
  943. # because it's our user requesting interruption of the testing.
  944. if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc:
  945. calls = reprec.getcalls("pytest_keyboard_interrupt")
  946. if calls and calls[-1].excinfo.type == KeyboardInterrupt:
  947. raise KeyboardInterrupt()
  948. return reprec
  949. finally:
  950. for finalizer in finalizers:
  951. finalizer()
  952. def runpytest_inprocess(
  953. self, *args: str | os.PathLike[str], **kwargs: Any
  954. ) -> RunResult:
  955. """Return result of running pytest in-process, providing a similar
  956. interface to what self.runpytest() provides."""
  957. syspathinsert = kwargs.pop("syspathinsert", False)
  958. if syspathinsert:
  959. self.syspathinsert()
  960. instant = timing.Instant()
  961. capture = _get_multicapture("sys")
  962. capture.start_capturing()
  963. try:
  964. try:
  965. reprec = self.inline_run(*args, **kwargs)
  966. except SystemExit as e:
  967. ret = e.args[0]
  968. try:
  969. ret = ExitCode(e.args[0])
  970. except ValueError:
  971. pass
  972. class reprec: # type: ignore
  973. ret = ret
  974. except Exception:
  975. traceback.print_exc()
  976. class reprec: # type: ignore
  977. ret = ExitCode(3)
  978. finally:
  979. out, err = capture.readouterr()
  980. capture.stop_capturing()
  981. sys.stdout.write(out)
  982. sys.stderr.write(err)
  983. assert reprec.ret is not None
  984. res = RunResult(
  985. reprec.ret, out.splitlines(), err.splitlines(), instant.elapsed().seconds
  986. )
  987. res.reprec = reprec # type: ignore
  988. return res
  989. def runpytest(self, *args: str | os.PathLike[str], **kwargs: Any) -> RunResult:
  990. """Run pytest inline or in a subprocess, depending on the command line
  991. option "--runpytest" and return a :py:class:`~pytest.RunResult`."""
  992. new_args = self._ensure_basetemp(args)
  993. if self._method == "inprocess":
  994. return self.runpytest_inprocess(*new_args, **kwargs)
  995. elif self._method == "subprocess":
  996. return self.runpytest_subprocess(*new_args, **kwargs)
  997. raise RuntimeError(f"Unrecognized runpytest option: {self._method}")
  998. def _ensure_basetemp(
  999. self, args: Sequence[str | os.PathLike[str]]
  1000. ) -> list[str | os.PathLike[str]]:
  1001. new_args = list(args)
  1002. for x in new_args:
  1003. if str(x).startswith("--basetemp"):
  1004. break
  1005. else:
  1006. new_args.append(
  1007. "--basetemp={}".format(self.path.parent.joinpath("basetemp"))
  1008. )
  1009. return new_args
  1010. def parseconfig(self, *args: str | os.PathLike[str]) -> Config:
  1011. """Return a new pytest :class:`pytest.Config` instance from given
  1012. commandline args.
  1013. This invokes the pytest bootstrapping code in _pytest.config to create a
  1014. new :py:class:`pytest.PytestPluginManager` and call the
  1015. :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
  1016. instance.
  1017. If :attr:`plugins` has been populated they should be plugin modules
  1018. to be registered with the plugin manager.
  1019. """
  1020. import _pytest.config
  1021. new_args = [str(x) for x in self._ensure_basetemp(args)]
  1022. config = _pytest.config._prepareconfig(new_args, self.plugins)
  1023. # we don't know what the test will do with this half-setup config
  1024. # object and thus we make sure it gets unconfigured properly in any
  1025. # case (otherwise capturing could still be active, for example)
  1026. self._request.addfinalizer(config._ensure_unconfigure)
  1027. return config
  1028. def parseconfigure(self, *args: str | os.PathLike[str]) -> Config:
  1029. """Return a new pytest configured Config instance.
  1030. Returns a new :py:class:`pytest.Config` instance like
  1031. :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
  1032. hook.
  1033. """
  1034. config = self.parseconfig(*args)
  1035. config._do_configure()
  1036. return config
  1037. def getitem(
  1038. self, source: str | os.PathLike[str], funcname: str = "test_func"
  1039. ) -> Item:
  1040. """Return the test item for a test function.
  1041. Writes the source to a python file and runs pytest's collection on
  1042. the resulting module, returning the test item for the requested
  1043. function name.
  1044. :param source:
  1045. The module source.
  1046. :param funcname:
  1047. The name of the test function for which to return a test item.
  1048. :returns:
  1049. The test item.
  1050. """
  1051. items = self.getitems(source)
  1052. for item in items:
  1053. if item.name == funcname:
  1054. return item
  1055. assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}"
  1056. def getitems(self, source: str | os.PathLike[str]) -> list[Item]:
  1057. """Return all test items collected from the module.
  1058. Writes the source to a Python file and runs pytest's collection on
  1059. the resulting module, returning all test items contained within.
  1060. """
  1061. modcol = self.getmodulecol(source)
  1062. return self.genitems([modcol])
  1063. def getmodulecol(
  1064. self,
  1065. source: str | os.PathLike[str],
  1066. configargs=(),
  1067. *,
  1068. withinit: bool = False,
  1069. ):
  1070. """Return the module collection node for ``source``.
  1071. Writes ``source`` to a file using :py:meth:`makepyfile` and then
  1072. runs the pytest collection on it, returning the collection node for the
  1073. test module.
  1074. :param source:
  1075. The source code of the module to collect.
  1076. :param configargs:
  1077. Any extra arguments to pass to :py:meth:`parseconfigure`.
  1078. :param withinit:
  1079. Whether to also write an ``__init__.py`` file to the same
  1080. directory to ensure it is a package.
  1081. """
  1082. if isinstance(source, os.PathLike):
  1083. path = self.path.joinpath(source)
  1084. assert not withinit, "not supported for paths"
  1085. else:
  1086. kw = {self._name: str(source)}
  1087. path = self.makepyfile(**kw)
  1088. if withinit:
  1089. self.makepyfile(__init__="#")
  1090. self.config = config = self.parseconfigure(path, *configargs)
  1091. return self.getnode(config, path)
  1092. def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:
  1093. """Return the collection node for name from the module collection.
  1094. Searches a module collection node for a collection node matching the
  1095. given name.
  1096. :param modcol: A module collection node; see :py:meth:`getmodulecol`.
  1097. :param name: The name of the node to return.
  1098. """
  1099. if modcol not in self._mod_collections:
  1100. self._mod_collections[modcol] = list(modcol.collect())
  1101. for colitem in self._mod_collections[modcol]:
  1102. if colitem.name == name:
  1103. return colitem
  1104. return None
  1105. def popen(
  1106. self,
  1107. cmdargs: Sequence[str | os.PathLike[str]],
  1108. stdout: int | TextIO = subprocess.PIPE,
  1109. stderr: int | TextIO = subprocess.PIPE,
  1110. stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
  1111. **kw,
  1112. ):
  1113. """Invoke :py:class:`subprocess.Popen`.
  1114. Calls :py:class:`subprocess.Popen` making sure the current working
  1115. directory is in ``PYTHONPATH``.
  1116. You probably want to use :py:meth:`run` instead.
  1117. """
  1118. env = os.environ.copy()
  1119. env["PYTHONPATH"] = os.pathsep.join(
  1120. filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
  1121. )
  1122. kw["env"] = env
  1123. if stdin is self.CLOSE_STDIN:
  1124. kw["stdin"] = subprocess.PIPE
  1125. elif isinstance(stdin, bytes):
  1126. kw["stdin"] = subprocess.PIPE
  1127. else:
  1128. kw["stdin"] = stdin
  1129. popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
  1130. if stdin is self.CLOSE_STDIN:
  1131. assert popen.stdin is not None
  1132. popen.stdin.close()
  1133. elif isinstance(stdin, bytes):
  1134. assert popen.stdin is not None
  1135. popen.stdin.write(stdin)
  1136. return popen
  1137. def run(
  1138. self,
  1139. *cmdargs: str | os.PathLike[str],
  1140. timeout: float | None = None,
  1141. stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
  1142. ) -> RunResult:
  1143. """Run a command with arguments.
  1144. Run a process using :py:class:`subprocess.Popen` saving the stdout and
  1145. stderr.
  1146. :param cmdargs:
  1147. The sequence of arguments to pass to :py:class:`subprocess.Popen`,
  1148. with path-like objects being converted to :py:class:`str`
  1149. automatically.
  1150. :param timeout:
  1151. The period in seconds after which to timeout and raise
  1152. :py:class:`Pytester.TimeoutExpired`.
  1153. :param stdin:
  1154. Optional standard input.
  1155. - If it is ``CLOSE_STDIN`` (Default), then this method calls
  1156. :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and
  1157. the standard input is closed immediately after the new command is
  1158. started.
  1159. - If it is of type :py:class:`bytes`, these bytes are sent to the
  1160. standard input of the command.
  1161. - Otherwise, it is passed through to :py:class:`subprocess.Popen`.
  1162. For further information in this case, consult the document of the
  1163. ``stdin`` parameter in :py:class:`subprocess.Popen`.
  1164. :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int
  1165. :returns:
  1166. The result.
  1167. """
  1168. __tracebackhide__ = True
  1169. cmdargs = tuple(os.fspath(arg) for arg in cmdargs)
  1170. p1 = self.path.joinpath("stdout")
  1171. p2 = self.path.joinpath("stderr")
  1172. print("running:", *cmdargs)
  1173. print(" in:", Path.cwd())
  1174. with p1.open("w", encoding="utf8") as f1, p2.open("w", encoding="utf8") as f2:
  1175. instant = timing.Instant()
  1176. popen = self.popen(
  1177. cmdargs,
  1178. stdin=stdin,
  1179. stdout=f1,
  1180. stderr=f2,
  1181. )
  1182. if popen.stdin is not None:
  1183. popen.stdin.close()
  1184. def handle_timeout() -> None:
  1185. __tracebackhide__ = True
  1186. timeout_message = f"{timeout} second timeout expired running: {cmdargs}"
  1187. popen.kill()
  1188. popen.wait()
  1189. raise self.TimeoutExpired(timeout_message)
  1190. if timeout is None:
  1191. ret = popen.wait()
  1192. else:
  1193. try:
  1194. ret = popen.wait(timeout)
  1195. except subprocess.TimeoutExpired:
  1196. handle_timeout()
  1197. f1.flush()
  1198. f2.flush()
  1199. with p1.open(encoding="utf8") as f1, p2.open(encoding="utf8") as f2:
  1200. out = f1.read().splitlines()
  1201. err = f2.read().splitlines()
  1202. self._dump_lines(out, sys.stdout)
  1203. self._dump_lines(err, sys.stderr)
  1204. with contextlib.suppress(ValueError):
  1205. ret = ExitCode(ret)
  1206. return RunResult(ret, out, err, instant.elapsed().seconds)
  1207. def _dump_lines(self, lines, fp):
  1208. try:
  1209. for line in lines:
  1210. print(line, file=fp)
  1211. except UnicodeEncodeError:
  1212. print(f"couldn't print to {fp} because of encoding")
  1213. def _getpytestargs(self) -> tuple[str, ...]:
  1214. return sys.executable, "-mpytest"
  1215. def runpython(self, script: os.PathLike[str]) -> RunResult:
  1216. """Run a python script using sys.executable as interpreter."""
  1217. return self.run(sys.executable, script)
  1218. def runpython_c(self, command: str) -> RunResult:
  1219. """Run ``python -c "command"``."""
  1220. return self.run(sys.executable, "-c", command)
  1221. def runpytest_subprocess(
  1222. self, *args: str | os.PathLike[str], timeout: float | None = None
  1223. ) -> RunResult:
  1224. """Run pytest as a subprocess with given arguments.
  1225. Any plugins added to the :py:attr:`plugins` list will be added using the
  1226. ``-p`` command line option. Additionally ``--basetemp`` is used to put
  1227. any temporary files and directories in a numbered directory prefixed
  1228. with "runpytest-" to not conflict with the normal numbered pytest
  1229. location for temporary files and directories.
  1230. :param args:
  1231. The sequence of arguments to pass to the pytest subprocess.
  1232. :param timeout:
  1233. The period in seconds after which to timeout and raise
  1234. :py:class:`Pytester.TimeoutExpired`.
  1235. :returns:
  1236. The result.
  1237. """
  1238. __tracebackhide__ = True
  1239. p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
  1240. args = (f"--basetemp={p}", *args)
  1241. for plugin in self.plugins:
  1242. if not isinstance(plugin, str):
  1243. raise ValueError(
  1244. f"Specifying plugins as objects is not supported in pytester subprocess mode; "
  1245. f"specify by name instead: {plugin}"
  1246. )
  1247. args = ("-p", plugin, *args)
  1248. args = self._getpytestargs() + args
  1249. return self.run(*args, timeout=timeout)
  1250. def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:
  1251. """Run pytest using pexpect.
  1252. This makes sure to use the right pytest and sets up the temporary
  1253. directory locations.
  1254. The pexpect child is returned.
  1255. """
  1256. basetemp = self.path / "temp-pexpect"
  1257. basetemp.mkdir(mode=0o700)
  1258. invoke = " ".join(map(str, self._getpytestargs()))
  1259. cmd = f"{invoke} --basetemp={basetemp} {string}"
  1260. return self.spawn(cmd, expect_timeout=expect_timeout)
  1261. def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:
  1262. """Run a command using pexpect.
  1263. The pexpect child is returned.
  1264. """
  1265. pexpect = importorskip("pexpect", "3.0")
  1266. if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
  1267. skip("pypy-64 bit not supported")
  1268. if not hasattr(pexpect, "spawn"):
  1269. skip("pexpect.spawn not available")
  1270. logfile = self.path.joinpath("spawn.out").open("wb")
  1271. child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout)
  1272. self._request.addfinalizer(logfile.close)
  1273. return child
  1274. class LineComp:
  1275. def __init__(self) -> None:
  1276. self.stringio = StringIO()
  1277. """:class:`python:io.StringIO()` instance used for input."""
  1278. def assert_contains_lines(self, lines2: Sequence[str]) -> None:
  1279. """Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.
  1280. Lines are matched using :func:`LineMatcher.fnmatch_lines <pytest.LineMatcher.fnmatch_lines>`.
  1281. """
  1282. __tracebackhide__ = True
  1283. val = self.stringio.getvalue()
  1284. self.stringio.truncate(0)
  1285. self.stringio.seek(0)
  1286. lines1 = val.split("\n")
  1287. LineMatcher(lines1).fnmatch_lines(lines2)
  1288. class LineMatcher:
  1289. """Flexible matching of text.
  1290. This is a convenience class to test large texts like the output of
  1291. commands.
  1292. The constructor takes a list of lines without their trailing newlines, i.e.
  1293. ``text.splitlines()``.
  1294. """
  1295. def __init__(self, lines: list[str]) -> None:
  1296. self.lines = lines
  1297. self._log_output: list[str] = []
  1298. def __str__(self) -> str:
  1299. """Return the entire original text.
  1300. .. versionadded:: 6.2
  1301. You can use :meth:`str` in older versions.
  1302. """
  1303. return "\n".join(self.lines)
  1304. def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]:
  1305. if isinstance(lines2, str):
  1306. lines2 = Source(lines2)
  1307. if isinstance(lines2, Source):
  1308. lines2 = lines2.strip().lines
  1309. return lines2
  1310. def fnmatch_lines_random(self, lines2: Sequence[str]) -> None:
  1311. """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`)."""
  1312. __tracebackhide__ = True
  1313. self._match_lines_random(lines2, fnmatch)
  1314. def re_match_lines_random(self, lines2: Sequence[str]) -> None:
  1315. """Check lines exist in the output in any order (using :func:`python:re.match`)."""
  1316. __tracebackhide__ = True
  1317. self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name)))
  1318. def _match_lines_random(
  1319. self, lines2: Sequence[str], match_func: Callable[[str, str], bool]
  1320. ) -> None:
  1321. __tracebackhide__ = True
  1322. lines2 = self._getlines(lines2)
  1323. for line in lines2:
  1324. for x in self.lines:
  1325. if line == x or match_func(x, line):
  1326. self._log("matched: ", repr(line))
  1327. break
  1328. else:
  1329. msg = f"line {line!r} not found in output"
  1330. self._log(msg)
  1331. self._fail(msg)
  1332. def get_lines_after(self, fnline: str) -> Sequence[str]:
  1333. """Return all lines following the given line in the text.
  1334. The given line can contain glob wildcards.
  1335. """
  1336. for i, line in enumerate(self.lines):
  1337. if fnline == line or fnmatch(line, fnline):
  1338. return self.lines[i + 1 :]
  1339. raise ValueError(f"line {fnline!r} not found in output")
  1340. def _log(self, *args) -> None:
  1341. self._log_output.append(" ".join(str(x) for x in args))
  1342. @property
  1343. def _log_text(self) -> str:
  1344. return "\n".join(self._log_output)
  1345. def fnmatch_lines(
  1346. self, lines2: Sequence[str], *, consecutive: bool = False
  1347. ) -> None:
  1348. """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`).
  1349. The argument is a list of lines which have to match and can use glob
  1350. wildcards. If they do not match a pytest.fail() is called. The
  1351. matches and non-matches are also shown as part of the error message.
  1352. :param lines2: String patterns to match.
  1353. :param consecutive: Match lines consecutively?
  1354. """
  1355. __tracebackhide__ = True
  1356. self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive)
  1357. def re_match_lines(
  1358. self, lines2: Sequence[str], *, consecutive: bool = False
  1359. ) -> None:
  1360. """Check lines exist in the output (using :func:`python:re.match`).
  1361. The argument is a list of lines which have to match using ``re.match``.
  1362. If they do not match a pytest.fail() is called.
  1363. The matches and non-matches are also shown as part of the error message.
  1364. :param lines2: string patterns to match.
  1365. :param consecutive: match lines consecutively?
  1366. """
  1367. __tracebackhide__ = True
  1368. self._match_lines(
  1369. lines2,
  1370. lambda name, pat: bool(re.match(pat, name)),
  1371. "re.match",
  1372. consecutive=consecutive,
  1373. )
  1374. def _match_lines(
  1375. self,
  1376. lines2: Sequence[str],
  1377. match_func: Callable[[str, str], bool],
  1378. match_nickname: str,
  1379. *,
  1380. consecutive: bool = False,
  1381. ) -> None:
  1382. """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
  1383. :param Sequence[str] lines2:
  1384. List of string patterns to match. The actual format depends on
  1385. ``match_func``.
  1386. :param match_func:
  1387. A callable ``match_func(line, pattern)`` where line is the
  1388. captured line from stdout/stderr and pattern is the matching
  1389. pattern.
  1390. :param str match_nickname:
  1391. The nickname for the match function that will be logged to stdout
  1392. when a match occurs.
  1393. :param consecutive:
  1394. Match lines consecutively?
  1395. """
  1396. if not isinstance(lines2, collections.abc.Sequence):
  1397. raise TypeError(f"invalid type for lines2: {type(lines2).__name__}")
  1398. lines2 = self._getlines(lines2)
  1399. lines1 = self.lines[:]
  1400. extralines = []
  1401. __tracebackhide__ = True
  1402. wnick = len(match_nickname) + 1
  1403. started = False
  1404. for line in lines2:
  1405. nomatchprinted = False
  1406. while lines1:
  1407. nextline = lines1.pop(0)
  1408. if line == nextline:
  1409. self._log("exact match:", repr(line))
  1410. started = True
  1411. break
  1412. elif match_func(nextline, line):
  1413. self._log(f"{match_nickname}:", repr(line))
  1414. self._log(
  1415. "{:>{width}}".format("with:", width=wnick), repr(nextline)
  1416. )
  1417. started = True
  1418. break
  1419. else:
  1420. if consecutive and started:
  1421. msg = f"no consecutive match: {line!r}"
  1422. self._log(msg)
  1423. self._log(
  1424. "{:>{width}}".format("with:", width=wnick), repr(nextline)
  1425. )
  1426. self._fail(msg)
  1427. if not nomatchprinted:
  1428. self._log(
  1429. "{:>{width}}".format("nomatch:", width=wnick), repr(line)
  1430. )
  1431. nomatchprinted = True
  1432. self._log("{:>{width}}".format("and:", width=wnick), repr(nextline))
  1433. extralines.append(nextline)
  1434. else:
  1435. msg = f"remains unmatched: {line!r}"
  1436. self._log(msg)
  1437. self._fail(msg)
  1438. self._log_output = []
  1439. def no_fnmatch_line(self, pat: str) -> None:
  1440. """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``.
  1441. :param str pat: The pattern to match lines.
  1442. """
  1443. __tracebackhide__ = True
  1444. self._no_match_line(pat, fnmatch, "fnmatch")
  1445. def no_re_match_line(self, pat: str) -> None:
  1446. """Ensure captured lines do not match the given pattern, using ``re.match``.
  1447. :param str pat: The regular expression to match lines.
  1448. """
  1449. __tracebackhide__ = True
  1450. self._no_match_line(
  1451. pat, lambda name, pat: bool(re.match(pat, name)), "re.match"
  1452. )
  1453. def _no_match_line(
  1454. self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str
  1455. ) -> None:
  1456. """Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``.
  1457. :param str pat: The pattern to match lines.
  1458. """
  1459. __tracebackhide__ = True
  1460. nomatch_printed = False
  1461. wnick = len(match_nickname) + 1
  1462. for line in self.lines:
  1463. if match_func(line, pat):
  1464. msg = f"{match_nickname}: {pat!r}"
  1465. self._log(msg)
  1466. self._log("{:>{width}}".format("with:", width=wnick), repr(line))
  1467. self._fail(msg)
  1468. else:
  1469. if not nomatch_printed:
  1470. self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat))
  1471. nomatch_printed = True
  1472. self._log("{:>{width}}".format("and:", width=wnick), repr(line))
  1473. self._log_output = []
  1474. def _fail(self, msg: str) -> None:
  1475. __tracebackhide__ = True
  1476. log_text = self._log_text
  1477. self._log_output = []
  1478. fail(log_text)
  1479. def str(self) -> str:
  1480. """Return the entire original text."""
  1481. return str(self)