diff --git a/changelog/1265.improvement.rst b/changelog/1265.improvement.rst new file mode 100644 index 000000000..4e7d98c0a --- /dev/null +++ b/changelog/1265.improvement.rst @@ -0,0 +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. diff --git a/doc/en/reference.rst b/doc/en/reference.rst index 34be2c454..971ab1bef 100644 --- a/doc/en/reference.rst +++ b/doc/en/reference.rst @@ -527,6 +527,7 @@ To use it, include in your topmost ``conftest.py`` file: .. autoclass:: LineMatcher() :members: + :special-members: __str__ .. autoclass:: HookRecorder() :members: diff --git a/src/_pytest/pytester.py b/src/_pytest/pytester.py index e55b3ec1a..ab3ecbf59 100644 --- a/src/_pytest/pytester.py +++ b/src/_pytest/pytester.py @@ -512,7 +512,7 @@ class RunResult: self.stdout = LineMatcher(outlines) """:class:`LineMatcher` of stdout. - Use e.g. :func:`stdout.str() ` to reconstruct stdout, or the commonly used + Use e.g. :func:`str(stdout) ` to reconstruct stdout, or the commonly used :func:`stdout.fnmatch_lines() ` method. """ self.stderr = LineMatcher(errlines) @@ -1707,6 +1707,14 @@ class LineMatcher: self.lines = lines self._log_output: List[str] = [] + def __str__(self) -> str: + """Return the entire original text. + + .. versionadded:: 6.2 + You can use :meth:`str` in older versions. + """ + return "\n".join(self.lines) + def _getlines(self, lines2: Union[str, Sequence[str], Source]) -> Sequence[str]: if isinstance(lines2, str): lines2 = Source(lines2) @@ -1908,4 +1916,4 @@ class LineMatcher: def str(self) -> str: """Return the entire original text.""" - return "\n".join(self.lines) + return str(self) diff --git a/testing/test_pytester.py b/testing/test_pytester.py index 457a62dd3..f2e8dd5a3 100644 --- a/testing/test_pytester.py +++ b/testing/test_pytester.py @@ -610,6 +610,11 @@ def test_linematcher_no_matching_after_match() -> None: assert str(e.value).splitlines() == ["fnmatch: '*'", " with: '1'"] +def test_linematcher_string_api() -> None: + lm = LineMatcher(["foo", "bar"]) + assert str(lm) == "foo\nbar" + + def test_pytester_addopts_before_testdir(request, monkeypatch) -> None: orig = os.environ.get("PYTEST_ADDOPTS", None) monkeypatch.setenv("PYTEST_ADDOPTS", "--orig-unused")