You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1923 lines
66KB

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