Debian Codegraph @

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