pytester.py 60 KB

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