Skip to content

Commit 0cef530

Browse files
authored
Add str() support to LineMatcher (#8050)
1 parent 52fef81 commit 0cef530

File tree

4 files changed

+17
-2
lines changed

4 files changed

+17
-2
lines changed

changelog/1265.improvement.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added an ``__str__`` implementation to the :class:`~pytest.pytester.LineMatcher` class which is returned from ``pytester.run_pytest().stdout`` and similar. It returns the entire output, like the existing ``str()`` method.

doc/en/reference.rst

+1
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,7 @@ To use it, include in your topmost ``conftest.py`` file:
527527

528528
.. autoclass:: LineMatcher()
529529
:members:
530+
:special-members: __str__
530531

531532
.. autoclass:: HookRecorder()
532533
:members:

src/_pytest/pytester.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,7 @@ def __init__(
512512
self.stdout = LineMatcher(outlines)
513513
""":class:`LineMatcher` of stdout.
514514
515-
Use e.g. :func:`stdout.str() <LineMatcher.str()>` to reconstruct stdout, or the commonly used
515+
Use e.g. :func:`str(stdout) <LineMatcher.__str__()>` to reconstruct stdout, or the commonly used
516516
:func:`stdout.fnmatch_lines() <LineMatcher.fnmatch_lines()>` method.
517517
"""
518518
self.stderr = LineMatcher(errlines)
@@ -1707,6 +1707,14 @@ def __init__(self, lines: List[str]) -> None:
17071707
self.lines = lines
17081708
self._log_output: List[str] = []
17091709

1710+
def __str__(self) -> str:
1711+
"""Return the entire original text.
1712+
1713+
.. versionadded:: 6.2
1714+
You can use :meth:`str` in older versions.
1715+
"""
1716+
return "\n".join(self.lines)
1717+
17101718
def _getlines(self, lines2: Union[str, Sequence[str], Source]) -> Sequence[str]:
17111719
if isinstance(lines2, str):
17121720
lines2 = Source(lines2)
@@ -1908,4 +1916,4 @@ def _fail(self, msg: str) -> None:
19081916

19091917
def str(self) -> str:
19101918
"""Return the entire original text."""
1911-
return "\n".join(self.lines)
1919+
return str(self)

testing/test_pytester.py

+5
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,11 @@ def test_linematcher_no_matching_after_match() -> None:
610610
assert str(e.value).splitlines() == ["fnmatch: '*'", " with: '1'"]
611611

612612

613+
def test_linematcher_string_api() -> None:
614+
lm = LineMatcher(["foo", "bar"])
615+
assert str(lm) == "foo\nbar"
616+
617+
613618
def test_pytester_addopts_before_testdir(request, monkeypatch) -> None:
614619
orig = os.environ.get("PYTEST_ADDOPTS", None)
615620
monkeypatch.setenv("PYTEST_ADDOPTS", "--orig-unused")

0 commit comments

Comments
 (0)