pytester.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  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. The type of items to add to the list depends on
  567. #: the method using them so refer to them for details.
  568. self.plugins: list[str | _PluggyPlugin] = []
  569. self._sys_path_snapshot = SysPathsSnapshot()
  570. self._sys_modules_snapshot = self.__take_sys_modules_snapshot()
  571. self._request.addfinalizer(self._finalize)
  572. self._method = self._request.config.getoption("--runpytest")
  573. self._test_tmproot = tmp_path_factory.mktemp(f"tmp-{name}", numbered=True)
  574. self._monkeypatch = mp = monkeypatch
  575. self.chdir()
  576. mp.setenv("PYTEST_DEBUG_TEMPROOT", str(self._test_tmproot))
  577. # Ensure no unexpected caching via tox.
  578. mp.delenv("TOX_ENV_DIR", raising=False)
  579. # Discard outer pytest options.
  580. mp.delenv("PYTEST_ADDOPTS", raising=False)
  581. # Ensure no user config is used.
  582. tmphome = str(self.path)
  583. mp.setenv("HOME", tmphome)
  584. mp.setenv("USERPROFILE", tmphome)
  585. # Do not use colors for inner runs by default.
  586. mp.setenv("PY_COLORS", "0")
  587. @property
  588. def path(self) -> Path:
  589. """Temporary directory path used to create files/run tests from, etc."""
  590. return self._path
  591. def __repr__(self) -> str:
  592. return f"<Pytester {self.path!r}>"
  593. def _finalize(self) -> None:
  594. """
  595. Clean up global state artifacts.
  596. Some methods modify the global interpreter state and this tries to
  597. clean this up. It does not remove the temporary directory however so
  598. it can be looked at after the test run has finished.
  599. """
  600. self._sys_modules_snapshot.restore()
  601. self._sys_path_snapshot.restore()
  602. def __take_sys_modules_snapshot(self) -> SysModulesSnapshot:
  603. # Some zope modules used by twisted-related tests keep internal state
  604. # and can't be deleted; we had some trouble in the past with
  605. # `zope.interface` for example.
  606. #
  607. # Preserve readline due to https://bugs.python.org/issue41033.
  608. # pexpect issues a SIGWINCH.
  609. def preserve_module(name):
  610. return name.startswith(("zope", "readline"))
  611. return SysModulesSnapshot(preserve=preserve_module)
  612. def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:
  613. """Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`."""
  614. pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True) # type: ignore[attr-defined]
  615. self._request.addfinalizer(reprec.finish_recording)
  616. return reprec
  617. def chdir(self) -> None:
  618. """Cd into the temporary directory.
  619. This is done automatically upon instantiation.
  620. """
  621. self._monkeypatch.chdir(self.path)
  622. def _makefile(
  623. self,
  624. ext: str,
  625. lines: Sequence[Any | bytes],
  626. files: dict[str, str],
  627. encoding: str = "utf-8",
  628. ) -> Path:
  629. items = list(files.items())
  630. if ext is None:
  631. raise TypeError("ext must not be None")
  632. if ext and not ext.startswith("."):
  633. raise ValueError(
  634. f"pytester.makefile expects a file extension, try .{ext} instead of {ext}"
  635. )
  636. def to_text(s: Any | bytes) -> str:
  637. return s.decode(encoding) if isinstance(s, bytes) else str(s)
  638. if lines:
  639. source = "\n".join(to_text(x) for x in lines)
  640. basename = self._name
  641. items.insert(0, (basename, source))
  642. ret = None
  643. for basename, value in items:
  644. p = self.path.joinpath(basename).with_suffix(ext)
  645. p.parent.mkdir(parents=True, exist_ok=True)
  646. source_ = Source(value)
  647. source = "\n".join(to_text(line) for line in source_.lines)
  648. p.write_text(source.strip(), encoding=encoding)
  649. if ret is None:
  650. ret = p
  651. assert ret is not None
  652. return ret
  653. def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:
  654. r"""Create new text file(s) in the test directory.
  655. :param ext:
  656. The extension the file(s) should use, including the dot, e.g. `.py`.
  657. :param args:
  658. All args are treated as strings and joined using newlines.
  659. The result is written as contents to the file. The name of the
  660. file is based on the test function requesting this fixture.
  661. :param kwargs:
  662. Each keyword is the name of a file, while the value of it will
  663. be written as contents of the file.
  664. :returns:
  665. The first created file.
  666. Examples:
  667. .. code-block:: python
  668. pytester.makefile(".txt", "line1", "line2")
  669. pytester.makefile(".ini", pytest="[pytest]\naddopts=-rs\n")
  670. To create binary files, use :meth:`pathlib.Path.write_bytes` directly:
  671. .. code-block:: python
  672. filename = pytester.path.joinpath("foo.bin")
  673. filename.write_bytes(b"...")
  674. """
  675. return self._makefile(ext, args, kwargs)
  676. def makeconftest(self, source: str) -> Path:
  677. """Write a conftest.py file.
  678. :param source: The contents.
  679. :returns: The conftest.py file.
  680. """
  681. return self.makepyfile(conftest=source)
  682. def makeini(self, source: str) -> Path:
  683. """Write a tox.ini file.
  684. :param source: The contents.
  685. :returns: The tox.ini file.
  686. """
  687. return self.makefile(".ini", tox=source)
  688. def getinicfg(self, source: str) -> SectionWrapper:
  689. """Return the pytest section from the tox.ini config file."""
  690. p = self.makeini(source)
  691. return IniConfig(str(p))["pytest"]
  692. def makepyprojecttoml(self, source: str) -> Path:
  693. """Write a pyproject.toml file.
  694. :param source: The contents.
  695. :returns: The pyproject.ini file.
  696. .. versionadded:: 6.0
  697. """
  698. return self.makefile(".toml", pyproject=source)
  699. def makepyfile(self, *args, **kwargs) -> Path:
  700. r"""Shortcut for .makefile() with a .py extension.
  701. Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting
  702. existing files.
  703. Examples:
  704. .. code-block:: python
  705. def test_something(pytester):
  706. # Initial file is created test_something.py.
  707. pytester.makepyfile("foobar")
  708. # To create multiple files, pass kwargs accordingly.
  709. pytester.makepyfile(custom="foobar")
  710. # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.
  711. """
  712. return self._makefile(".py", args, kwargs)
  713. def maketxtfile(self, *args, **kwargs) -> Path:
  714. r"""Shortcut for .makefile() with a .txt extension.
  715. Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting
  716. existing files.
  717. Examples:
  718. .. code-block:: python
  719. def test_something(pytester):
  720. # Initial file is created test_something.txt.
  721. pytester.maketxtfile("foobar")
  722. # To create multiple files, pass kwargs accordingly.
  723. pytester.maketxtfile(custom="foobar")
  724. # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.
  725. """
  726. return self._makefile(".txt", args, kwargs)
  727. def syspathinsert(self, path: str | os.PathLike[str] | None = None) -> None:
  728. """Prepend a directory to sys.path, defaults to :attr:`path`.
  729. This is undone automatically when this object dies at the end of each
  730. test.
  731. :param path:
  732. The path.
  733. """
  734. if path is None:
  735. path = self.path
  736. self._monkeypatch.syspath_prepend(str(path))
  737. def mkdir(self, name: str | os.PathLike[str]) -> Path:
  738. """Create a new (sub)directory.
  739. :param name:
  740. The name of the directory, relative to the pytester path.
  741. :returns:
  742. The created directory.
  743. :rtype: pathlib.Path
  744. """
  745. p = self.path / name
  746. p.mkdir()
  747. return p
  748. def mkpydir(self, name: str | os.PathLike[str]) -> Path:
  749. """Create a new python package.
  750. This creates a (sub)directory with an empty ``__init__.py`` file so it
  751. gets recognised as a Python package.
  752. """
  753. p = self.path / name
  754. p.mkdir()
  755. p.joinpath("__init__.py").touch()
  756. return p
  757. def copy_example(self, name: str | None = None) -> Path:
  758. """Copy file from project's directory into the testdir.
  759. :param name:
  760. The name of the file to copy.
  761. :return:
  762. Path to the copied directory (inside ``self.path``).
  763. :rtype: pathlib.Path
  764. """
  765. example_dir_ = self._request.config.getini("pytester_example_dir")
  766. if example_dir_ is None:
  767. raise ValueError("pytester_example_dir is unset, can't copy examples")
  768. example_dir: Path = self._request.config.rootpath / example_dir_
  769. for extra_element in self._request.node.iter_markers("pytester_example_path"):
  770. assert extra_element.args
  771. example_dir = example_dir.joinpath(*extra_element.args)
  772. if name is None:
  773. func_name = self._name
  774. maybe_dir = example_dir / func_name
  775. maybe_file = example_dir / (func_name + ".py")
  776. if maybe_dir.is_dir():
  777. example_path = maybe_dir
  778. elif maybe_file.is_file():
  779. example_path = maybe_file
  780. else:
  781. raise LookupError(
  782. f"{func_name} can't be found as module or package in {example_dir}"
  783. )
  784. else:
  785. example_path = example_dir.joinpath(name)
  786. if example_path.is_dir() and not example_path.joinpath("__init__.py").is_file():
  787. shutil.copytree(example_path, self.path, symlinks=True, dirs_exist_ok=True)
  788. return self.path
  789. elif example_path.is_file():
  790. result = self.path.joinpath(example_path.name)
  791. shutil.copy(example_path, result)
  792. return result
  793. else:
  794. raise LookupError(
  795. f'example "{example_path}" is not found as a file or directory'
  796. )
  797. def getnode(self, config: Config, arg: str | os.PathLike[str]) -> Collector | Item:
  798. """Get the collection node of a file.
  799. :param config:
  800. A pytest config.
  801. See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
  802. :param arg:
  803. Path to the file.
  804. :returns:
  805. The node.
  806. """
  807. session = Session.from_config(config)
  808. assert "::" not in str(arg)
  809. p = Path(os.path.abspath(arg))
  810. config.hook.pytest_sessionstart(session=session)
  811. res = session.perform_collect([str(p)], genitems=False)[0]
  812. config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
  813. return res
  814. def getpathnode(self, path: str | os.PathLike[str]) -> Collector | Item:
  815. """Return the collection node of a file.
  816. This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
  817. create the (configured) pytest Config instance.
  818. :param path:
  819. Path to the file.
  820. :returns:
  821. The node.
  822. """
  823. path = Path(path)
  824. config = self.parseconfigure(path)
  825. session = Session.from_config(config)
  826. x = bestrelpath(session.path, path)
  827. config.hook.pytest_sessionstart(session=session)
  828. res = session.perform_collect([x], genitems=False)[0]
  829. config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
  830. return res
  831. def genitems(self, colitems: Sequence[Item | Collector]) -> list[Item]:
  832. """Generate all test items from a collection node.
  833. This recurses into the collection node and returns a list of all the
  834. test items contained within.
  835. :param colitems:
  836. The collection nodes.
  837. :returns:
  838. The collected items.
  839. """
  840. session = colitems[0].session
  841. result: list[Item] = []
  842. for colitem in colitems:
  843. result.extend(session.genitems(colitem))
  844. return result
  845. def runitem(self, source: str) -> Any:
  846. """Run the "test_func" Item.
  847. The calling test instance (class containing the test method) must
  848. provide a ``.getrunner()`` method which should return a runner which
  849. can run the test protocol for a single item, e.g.
  850. ``_pytest.runner.runtestprotocol``.
  851. """
  852. # used from runner functional tests
  853. item = self.getitem(source)
  854. # the test class where we are called from wants to provide the runner
  855. testclassinstance = self._request.instance
  856. runner = testclassinstance.getrunner()
  857. return runner(item)
  858. def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder:
  859. """Run a test module in process using ``pytest.main()``.
  860. This run writes "source" into a temporary file and runs
  861. ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance
  862. for the result.
  863. :param source: The source code of the test module.
  864. :param cmdlineargs: Any extra command line arguments to use.
  865. """
  866. p = self.makepyfile(source)
  867. values = [*list(cmdlineargs), p]
  868. return self.inline_run(*values)
  869. def inline_genitems(self, *args) -> tuple[list[Item], HookRecorder]:
  870. """Run ``pytest.main(['--collect-only'])`` in-process.
  871. Runs the :py:func:`pytest.main` function to run all of pytest inside
  872. the test process itself like :py:meth:`inline_run`, but returns a
  873. tuple of the collected items and a :py:class:`HookRecorder` instance.
  874. """
  875. rec = self.inline_run("--collect-only", *args)
  876. items = [x.item for x in rec.getcalls("pytest_itemcollected")]
  877. return items, rec
  878. def inline_run(
  879. self,
  880. *args: str | os.PathLike[str],
  881. plugins=(),
  882. no_reraise_ctrlc: bool = False,
  883. ) -> HookRecorder:
  884. """Run ``pytest.main()`` in-process, returning a HookRecorder.
  885. Runs the :py:func:`pytest.main` function to run all of pytest inside
  886. the test process itself. This means it can return a
  887. :py:class:`HookRecorder` instance which gives more detailed results
  888. from that run than can be done by matching stdout/stderr from
  889. :py:meth:`runpytest`.
  890. :param args:
  891. Command line arguments to pass to :py:func:`pytest.main`.
  892. :param plugins:
  893. Extra plugin instances the ``pytest.main()`` instance should use.
  894. :param no_reraise_ctrlc:
  895. Typically we reraise keyboard interrupts from the child run. If
  896. True, the KeyboardInterrupt exception is captured.
  897. """
  898. from _pytest.unraisableexception import gc_collect_iterations_key
  899. # (maybe a cpython bug?) the importlib cache sometimes isn't updated
  900. # properly between file creation and inline_run (especially if imports
  901. # are interspersed with file creation)
  902. importlib.invalidate_caches()
  903. plugins = list(plugins)
  904. finalizers = []
  905. try:
  906. # Any sys.module or sys.path changes done while running pytest
  907. # inline should be reverted after the test run completes to avoid
  908. # clashing with later inline tests run within the same pytest test,
  909. # e.g. just because they use matching test module names.
  910. finalizers.append(self.__take_sys_modules_snapshot().restore)
  911. finalizers.append(SysPathsSnapshot().restore)
  912. # Important note:
  913. # - our tests should not leave any other references/registrations
  914. # laying around other than possibly loaded test modules
  915. # referenced from sys.modules, as nothing will clean those up
  916. # automatically
  917. rec = []
  918. class PytesterHelperPlugin:
  919. @staticmethod
  920. def pytest_configure(config: Config) -> None:
  921. rec.append(self.make_hook_recorder(config.pluginmanager))
  922. # The unraisable plugin GC collect slows down inline
  923. # pytester runs too much.
  924. config.stash[gc_collect_iterations_key] = 0
  925. plugins.append(PytesterHelperPlugin())
  926. ret = main([str(x) for x in args], plugins=plugins)
  927. if len(rec) == 1:
  928. reprec = rec.pop()
  929. else:
  930. class reprec: # type: ignore
  931. pass
  932. reprec.ret = ret
  933. # Typically we reraise keyboard interrupts from the child run
  934. # because it's our user requesting interruption of the testing.
  935. if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc:
  936. calls = reprec.getcalls("pytest_keyboard_interrupt")
  937. if calls and calls[-1].excinfo.type == KeyboardInterrupt:
  938. raise KeyboardInterrupt()
  939. return reprec
  940. finally:
  941. for finalizer in finalizers:
  942. finalizer()
  943. def runpytest_inprocess(
  944. self, *args: str | os.PathLike[str], **kwargs: Any
  945. ) -> RunResult:
  946. """Return result of running pytest in-process, providing a similar
  947. interface to what self.runpytest() provides."""
  948. syspathinsert = kwargs.pop("syspathinsert", False)
  949. if syspathinsert:
  950. self.syspathinsert()
  951. instant = timing.Instant()
  952. capture = _get_multicapture("sys")
  953. capture.start_capturing()
  954. try:
  955. try:
  956. reprec = self.inline_run(*args, **kwargs)
  957. except SystemExit as e:
  958. ret = e.args[0]
  959. try:
  960. ret = ExitCode(e.args[0])
  961. except ValueError:
  962. pass
  963. class reprec: # type: ignore
  964. ret = ret
  965. except Exception:
  966. traceback.print_exc()
  967. class reprec: # type: ignore
  968. ret = ExitCode(3)
  969. finally:
  970. out, err = capture.readouterr()
  971. capture.stop_capturing()
  972. sys.stdout.write(out)
  973. sys.stderr.write(err)
  974. assert reprec.ret is not None
  975. res = RunResult(
  976. reprec.ret, out.splitlines(), err.splitlines(), instant.elapsed().seconds
  977. )
  978. res.reprec = reprec # type: ignore
  979. return res
  980. def runpytest(self, *args: str | os.PathLike[str], **kwargs: Any) -> RunResult:
  981. """Run pytest inline or in a subprocess, depending on the command line
  982. option "--runpytest" and return a :py:class:`~pytest.RunResult`."""
  983. new_args = self._ensure_basetemp(args)
  984. if self._method == "inprocess":
  985. return self.runpytest_inprocess(*new_args, **kwargs)
  986. elif self._method == "subprocess":
  987. return self.runpytest_subprocess(*new_args, **kwargs)
  988. raise RuntimeError(f"Unrecognized runpytest option: {self._method}")
  989. def _ensure_basetemp(
  990. self, args: Sequence[str | os.PathLike[str]]
  991. ) -> list[str | os.PathLike[str]]:
  992. new_args = list(args)
  993. for x in new_args:
  994. if str(x).startswith("--basetemp"):
  995. break
  996. else:
  997. new_args.append(
  998. "--basetemp={}".format(self.path.parent.joinpath("basetemp"))
  999. )
  1000. return new_args
  1001. def parseconfig(self, *args: str | os.PathLike[str]) -> Config:
  1002. """Return a new pytest :class:`pytest.Config` instance from given
  1003. commandline args.
  1004. This invokes the pytest bootstrapping code in _pytest.config to create a
  1005. new :py:class:`pytest.PytestPluginManager` and call the
  1006. :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
  1007. instance.
  1008. If :attr:`plugins` has been populated they should be plugin modules
  1009. to be registered with the plugin manager.
  1010. """
  1011. import _pytest.config
  1012. new_args = self._ensure_basetemp(args)
  1013. new_args = [str(x) for x in new_args]
  1014. config = _pytest.config._prepareconfig(new_args, self.plugins) # type: ignore[arg-type]
  1015. # we don't know what the test will do with this half-setup config
  1016. # object and thus we make sure it gets unconfigured properly in any
  1017. # case (otherwise capturing could still be active, for example)
  1018. self._request.addfinalizer(config._ensure_unconfigure)
  1019. return config
  1020. def parseconfigure(self, *args: str | os.PathLike[str]) -> Config:
  1021. """Return a new pytest configured Config instance.
  1022. Returns a new :py:class:`pytest.Config` instance like
  1023. :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
  1024. hook.
  1025. """
  1026. config = self.parseconfig(*args)
  1027. config._do_configure()
  1028. return config
  1029. def getitem(
  1030. self, source: str | os.PathLike[str], funcname: str = "test_func"
  1031. ) -> Item:
  1032. """Return the test item for a test function.
  1033. Writes the source to a python file and runs pytest's collection on
  1034. the resulting module, returning the test item for the requested
  1035. function name.
  1036. :param source:
  1037. The module source.
  1038. :param funcname:
  1039. The name of the test function for which to return a test item.
  1040. :returns:
  1041. The test item.
  1042. """
  1043. items = self.getitems(source)
  1044. for item in items:
  1045. if item.name == funcname:
  1046. return item
  1047. assert 0, f"{funcname!r} item not found in module:\n{source}\nitems: {items}"
  1048. def getitems(self, source: str | os.PathLike[str]) -> list[Item]:
  1049. """Return all test items collected from the module.
  1050. Writes the source to a Python file and runs pytest's collection on
  1051. the resulting module, returning all test items contained within.
  1052. """
  1053. modcol = self.getmodulecol(source)
  1054. return self.genitems([modcol])
  1055. def getmodulecol(
  1056. self,
  1057. source: str | os.PathLike[str],
  1058. configargs=(),
  1059. *,
  1060. withinit: bool = False,
  1061. ):
  1062. """Return the module collection node for ``source``.
  1063. Writes ``source`` to a file using :py:meth:`makepyfile` and then
  1064. runs the pytest collection on it, returning the collection node for the
  1065. test module.
  1066. :param source:
  1067. The source code of the module to collect.
  1068. :param configargs:
  1069. Any extra arguments to pass to :py:meth:`parseconfigure`.
  1070. :param withinit:
  1071. Whether to also write an ``__init__.py`` file to the same
  1072. directory to ensure it is a package.
  1073. """
  1074. if isinstance(source, os.PathLike):
  1075. path = self.path.joinpath(source)
  1076. assert not withinit, "not supported for paths"
  1077. else:
  1078. kw = {self._name: str(source)}
  1079. path = self.makepyfile(**kw)
  1080. if withinit:
  1081. self.makepyfile(__init__="#")
  1082. self.config = config = self.parseconfigure(path, *configargs)
  1083. return self.getnode(config, path)
  1084. def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:
  1085. """Return the collection node for name from the module collection.
  1086. Searches a module collection node for a collection node matching the
  1087. given name.
  1088. :param modcol: A module collection node; see :py:meth:`getmodulecol`.
  1089. :param name: The name of the node to return.
  1090. """
  1091. if modcol not in self._mod_collections:
  1092. self._mod_collections[modcol] = list(modcol.collect())
  1093. for colitem in self._mod_collections[modcol]:
  1094. if colitem.name == name:
  1095. return colitem
  1096. return None
  1097. def popen(
  1098. self,
  1099. cmdargs: Sequence[str | os.PathLike[str]],
  1100. stdout: int | TextIO = subprocess.PIPE,
  1101. stderr: int | TextIO = subprocess.PIPE,
  1102. stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
  1103. **kw,
  1104. ):
  1105. """Invoke :py:class:`subprocess.Popen`.
  1106. Calls :py:class:`subprocess.Popen` making sure the current working
  1107. directory is in ``PYTHONPATH``.
  1108. You probably want to use :py:meth:`run` instead.
  1109. """
  1110. env = os.environ.copy()
  1111. env["PYTHONPATH"] = os.pathsep.join(
  1112. filter(None, [os.getcwd(), env.get("PYTHONPATH", "")])
  1113. )
  1114. kw["env"] = env
  1115. if stdin is self.CLOSE_STDIN:
  1116. kw["stdin"] = subprocess.PIPE
  1117. elif isinstance(stdin, bytes):
  1118. kw["stdin"] = subprocess.PIPE
  1119. else:
  1120. kw["stdin"] = stdin
  1121. popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
  1122. if stdin is self.CLOSE_STDIN:
  1123. assert popen.stdin is not None
  1124. popen.stdin.close()
  1125. elif isinstance(stdin, bytes):
  1126. assert popen.stdin is not None
  1127. popen.stdin.write(stdin)
  1128. return popen
  1129. def run(
  1130. self,
  1131. *cmdargs: str | os.PathLike[str],
  1132. timeout: float | None = None,
  1133. stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,
  1134. ) -> RunResult:
  1135. """Run a command with arguments.
  1136. Run a process using :py:class:`subprocess.Popen` saving the stdout and
  1137. stderr.
  1138. :param cmdargs:
  1139. The sequence of arguments to pass to :py:class:`subprocess.Popen`,
  1140. with path-like objects being converted to :py:class:`str`
  1141. automatically.
  1142. :param timeout:
  1143. The period in seconds after which to timeout and raise
  1144. :py:class:`Pytester.TimeoutExpired`.
  1145. :param stdin:
  1146. Optional standard input.
  1147. - If it is ``CLOSE_STDIN`` (Default), then this method calls
  1148. :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and
  1149. the standard input is closed immediately after the new command is
  1150. started.
  1151. - If it is of type :py:class:`bytes`, these bytes are sent to the
  1152. standard input of the command.
  1153. - Otherwise, it is passed through to :py:class:`subprocess.Popen`.
  1154. For further information in this case, consult the document of the
  1155. ``stdin`` parameter in :py:class:`subprocess.Popen`.
  1156. :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int
  1157. :returns:
  1158. The result.
  1159. """
  1160. __tracebackhide__ = True
  1161. cmdargs = tuple(os.fspath(arg) for arg in cmdargs)
  1162. p1 = self.path.joinpath("stdout")
  1163. p2 = self.path.joinpath("stderr")
  1164. print("running:", *cmdargs)
  1165. print(" in:", Path.cwd())
  1166. with p1.open("w", encoding="utf8") as f1, p2.open("w", encoding="utf8") as f2:
  1167. instant = timing.Instant()
  1168. popen = self.popen(
  1169. cmdargs,
  1170. stdin=stdin,
  1171. stdout=f1,
  1172. stderr=f2,
  1173. close_fds=(sys.platform != "win32"),
  1174. )
  1175. if popen.stdin is not None:
  1176. popen.stdin.close()
  1177. def handle_timeout() -> None:
  1178. __tracebackhide__ = True
  1179. timeout_message = f"{timeout} second timeout expired running: {cmdargs}"
  1180. popen.kill()
  1181. popen.wait()
  1182. raise self.TimeoutExpired(timeout_message)
  1183. if timeout is None:
  1184. ret = popen.wait()
  1185. else:
  1186. try:
  1187. ret = popen.wait(timeout)
  1188. except subprocess.TimeoutExpired:
  1189. handle_timeout()
  1190. with p1.open(encoding="utf8") as f1, p2.open(encoding="utf8") as f2:
  1191. out = f1.read().splitlines()
  1192. err = f2.read().splitlines()
  1193. self._dump_lines(out, sys.stdout)
  1194. self._dump_lines(err, sys.stderr)
  1195. with contextlib.suppress(ValueError):
  1196. ret = ExitCode(ret)
  1197. return RunResult(ret, out, err, instant.elapsed().seconds)
  1198. def _dump_lines(self, lines, fp):
  1199. try:
  1200. for line in lines:
  1201. print(line, file=fp)
  1202. except UnicodeEncodeError:
  1203. print(f"couldn't print to {fp} because of encoding")
  1204. def _getpytestargs(self) -> tuple[str, ...]:
  1205. return sys.executable, "-mpytest"
  1206. def runpython(self, script: os.PathLike[str]) -> RunResult:
  1207. """Run a python script using sys.executable as interpreter."""
  1208. return self.run(sys.executable, script)
  1209. def runpython_c(self, command: str) -> RunResult:
  1210. """Run ``python -c "command"``."""
  1211. return self.run(sys.executable, "-c", command)
  1212. def runpytest_subprocess(
  1213. self, *args: str | os.PathLike[str], timeout: float | None = None
  1214. ) -> RunResult:
  1215. """Run pytest as a subprocess with given arguments.
  1216. Any plugins added to the :py:attr:`plugins` list will be added using the
  1217. ``-p`` command line option. Additionally ``--basetemp`` is used to put
  1218. any temporary files and directories in a numbered directory prefixed
  1219. with "runpytest-" to not conflict with the normal numbered pytest
  1220. location for temporary files and directories.
  1221. :param args:
  1222. The sequence of arguments to pass to the pytest subprocess.
  1223. :param timeout:
  1224. The period in seconds after which to timeout and raise
  1225. :py:class:`Pytester.TimeoutExpired`.
  1226. :returns:
  1227. The result.
  1228. """
  1229. __tracebackhide__ = True
  1230. p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
  1231. args = (f"--basetemp={p}", *args)
  1232. plugins = [x for x in self.plugins if isinstance(x, str)]
  1233. if plugins:
  1234. args = ("-p", plugins[0], *args)
  1235. args = self._getpytestargs() + args
  1236. return self.run(*args, timeout=timeout)
  1237. def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:
  1238. """Run pytest using pexpect.
  1239. This makes sure to use the right pytest and sets up the temporary
  1240. directory locations.
  1241. The pexpect child is returned.
  1242. """
  1243. basetemp = self.path / "temp-pexpect"
  1244. basetemp.mkdir(mode=0o700)
  1245. invoke = " ".join(map(str, self._getpytestargs()))
  1246. cmd = f"{invoke} --basetemp={basetemp} {string}"
  1247. return self.spawn(cmd, expect_timeout=expect_timeout)
  1248. def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:
  1249. """Run a command using pexpect.
  1250. The pexpect child is returned.
  1251. """
  1252. pexpect = importorskip("pexpect", "3.0")
  1253. if hasattr(sys, "pypy_version_info") and "64" in platform.machine():
  1254. skip("pypy-64 bit not supported")
  1255. if not hasattr(pexpect, "spawn"):
  1256. skip("pexpect.spawn not available")
  1257. logfile = self.path.joinpath("spawn.out").open("wb")
  1258. child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout)
  1259. self._request.addfinalizer(logfile.close)
  1260. return child
  1261. class LineComp:
  1262. def __init__(self) -> None:
  1263. self.stringio = StringIO()
  1264. """:class:`python:io.StringIO()` instance used for input."""
  1265. def assert_contains_lines(self, lines2: Sequence[str]) -> None:
  1266. """Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.
  1267. Lines are matched using :func:`LineMatcher.fnmatch_lines <pytest.LineMatcher.fnmatch_lines>`.
  1268. """
  1269. __tracebackhide__ = True
  1270. val = self.stringio.getvalue()
  1271. self.stringio.truncate(0)
  1272. self.stringio.seek(0)
  1273. lines1 = val.split("\n")
  1274. LineMatcher(lines1).fnmatch_lines(lines2)
  1275. class LineMatcher:
  1276. """Flexible matching of text.
  1277. This is a convenience class to test large texts like the output of
  1278. commands.
  1279. The constructor takes a list of lines without their trailing newlines, i.e.
  1280. ``text.splitlines()``.
  1281. """
  1282. def __init__(self, lines: list[str]) -> None:
  1283. self.lines = lines
  1284. self._log_output: list[str] = []
  1285. def __str__(self) -> str:
  1286. """Return the entire original text.
  1287. .. versionadded:: 6.2
  1288. You can use :meth:`str` in older versions.
  1289. """
  1290. return "\n".join(self.lines)
  1291. def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]:
  1292. if isinstance(lines2, str):
  1293. lines2 = Source(lines2)
  1294. if isinstance(lines2, Source):
  1295. lines2 = lines2.strip().lines
  1296. return lines2
  1297. def fnmatch_lines_random(self, lines2: Sequence[str]) -> None:
  1298. """Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`)."""
  1299. __tracebackhide__ = True
  1300. self._match_lines_random(lines2, fnmatch)
  1301. def re_match_lines_random(self, lines2: Sequence[str]) -> None:
  1302. """Check lines exist in the output in any order (using :func:`python:re.match`)."""
  1303. __tracebackhide__ = True
  1304. self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name)))
  1305. def _match_lines_random(
  1306. self, lines2: Sequence[str], match_func: Callable[[str, str], bool]
  1307. ) -> None:
  1308. __tracebackhide__ = True
  1309. lines2 = self._getlines(lines2)
  1310. for line in lines2:
  1311. for x in self.lines:
  1312. if line == x or match_func(x, line):
  1313. self._log("matched: ", repr(line))
  1314. break
  1315. else:
  1316. msg = f"line {line!r} not found in output"
  1317. self._log(msg)
  1318. self._fail(msg)
  1319. def get_lines_after(self, fnline: str) -> Sequence[str]:
  1320. """Return all lines following the given line in the text.
  1321. The given line can contain glob wildcards.
  1322. """
  1323. for i, line in enumerate(self.lines):
  1324. if fnline == line or fnmatch(line, fnline):
  1325. return self.lines[i + 1 :]
  1326. raise ValueError(f"line {fnline!r} not found in output")
  1327. def _log(self, *args) -> None:
  1328. self._log_output.append(" ".join(str(x) for x in args))
  1329. @property
  1330. def _log_text(self) -> str:
  1331. return "\n".join(self._log_output)
  1332. def fnmatch_lines(
  1333. self, lines2: Sequence[str], *, consecutive: bool = False
  1334. ) -> None:
  1335. """Check lines exist in the output (using :func:`python:fnmatch.fnmatch`).
  1336. The argument is a list of lines which have to match and can use glob
  1337. wildcards. If they do not match a pytest.fail() is called. The
  1338. matches and non-matches are also shown as part of the error message.
  1339. :param lines2: String patterns to match.
  1340. :param consecutive: Match lines consecutively?
  1341. """
  1342. __tracebackhide__ = True
  1343. self._match_lines(lines2, fnmatch, "fnmatch", consecutive=consecutive)
  1344. def re_match_lines(
  1345. self, lines2: Sequence[str], *, consecutive: bool = False
  1346. ) -> None:
  1347. """Check lines exist in the output (using :func:`python:re.match`).
  1348. The argument is a list of lines which have to match using ``re.match``.
  1349. If they do not match a pytest.fail() is called.
  1350. The matches and non-matches are also shown as part of the error message.
  1351. :param lines2: string patterns to match.
  1352. :param consecutive: match lines consecutively?
  1353. """
  1354. __tracebackhide__ = True
  1355. self._match_lines(
  1356. lines2,
  1357. lambda name, pat: bool(re.match(pat, name)),
  1358. "re.match",
  1359. consecutive=consecutive,
  1360. )
  1361. def _match_lines(
  1362. self,
  1363. lines2: Sequence[str],
  1364. match_func: Callable[[str, str], bool],
  1365. match_nickname: str,
  1366. *,
  1367. consecutive: bool = False,
  1368. ) -> None:
  1369. """Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.
  1370. :param Sequence[str] lines2:
  1371. List of string patterns to match. The actual format depends on
  1372. ``match_func``.
  1373. :param match_func:
  1374. A callable ``match_func(line, pattern)`` where line is the
  1375. captured line from stdout/stderr and pattern is the matching
  1376. pattern.
  1377. :param str match_nickname:
  1378. The nickname for the match function that will be logged to stdout
  1379. when a match occurs.
  1380. :param consecutive:
  1381. Match lines consecutively?
  1382. """
  1383. if not isinstance(lines2, collections.abc.Sequence):
  1384. raise TypeError(f"invalid type for lines2: {type(lines2).__name__}")
  1385. lines2 = self._getlines(lines2)
  1386. lines1 = self.lines[:]
  1387. extralines = []
  1388. __tracebackhide__ = True
  1389. wnick = len(match_nickname) + 1
  1390. started = False
  1391. for line in lines2:
  1392. nomatchprinted = False
  1393. while lines1:
  1394. nextline = lines1.pop(0)
  1395. if line == nextline:
  1396. self._log("exact match:", repr(line))
  1397. started = True
  1398. break
  1399. elif match_func(nextline, line):
  1400. self._log(f"{match_nickname}:", repr(line))
  1401. self._log(
  1402. "{:>{width}}".format("with:", width=wnick), repr(nextline)
  1403. )
  1404. started = True
  1405. break
  1406. else:
  1407. if consecutive and started:
  1408. msg = f"no consecutive match: {line!r}"
  1409. self._log(msg)
  1410. self._log(
  1411. "{:>{width}}".format("with:", width=wnick), repr(nextline)
  1412. )
  1413. self._fail(msg)
  1414. if not nomatchprinted:
  1415. self._log(
  1416. "{:>{width}}".format("nomatch:", width=wnick), repr(line)
  1417. )
  1418. nomatchprinted = True
  1419. self._log("{:>{width}}".format("and:", width=wnick), repr(nextline))
  1420. extralines.append(nextline)
  1421. else:
  1422. msg = f"remains unmatched: {line!r}"
  1423. self._log(msg)
  1424. self._fail(msg)
  1425. self._log_output = []
  1426. def no_fnmatch_line(self, pat: str) -> None:
  1427. """Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``.
  1428. :param str pat: The pattern to match lines.
  1429. """
  1430. __tracebackhide__ = True
  1431. self._no_match_line(pat, fnmatch, "fnmatch")
  1432. def no_re_match_line(self, pat: str) -> None:
  1433. """Ensure captured lines do not match the given pattern, using ``re.match``.
  1434. :param str pat: The regular expression to match lines.
  1435. """
  1436. __tracebackhide__ = True
  1437. self._no_match_line(
  1438. pat, lambda name, pat: bool(re.match(pat, name)), "re.match"
  1439. )
  1440. def _no_match_line(
  1441. self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str
  1442. ) -> None:
  1443. """Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``.
  1444. :param str pat: The pattern to match lines.
  1445. """
  1446. __tracebackhide__ = True
  1447. nomatch_printed = False
  1448. wnick = len(match_nickname) + 1
  1449. for line in self.lines:
  1450. if match_func(line, pat):
  1451. msg = f"{match_nickname}: {pat!r}"
  1452. self._log(msg)
  1453. self._log("{:>{width}}".format("with:", width=wnick), repr(line))
  1454. self._fail(msg)
  1455. else:
  1456. if not nomatch_printed:
  1457. self._log("{:>{width}}".format("nomatch:", width=wnick), repr(pat))
  1458. nomatch_printed = True
  1459. self._log("{:>{width}}".format("and:", width=wnick), repr(line))
  1460. self._log_output = []
  1461. def _fail(self, msg: str) -> None:
  1462. __tracebackhide__ = True
  1463. log_text = self._log_text
  1464. self._log_output = []
  1465. fail(log_text)
  1466. def str(self) -> str:
  1467. """Return the entire original text."""
  1468. return str(self)