Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pytester.py

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