pytester.py 61 KB

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