diff --git a/changelog/2574.bugfix.rst b/changelog/2574.bugfix.rst new file mode 100644 index 00000000000..8c1923a634e --- /dev/null +++ b/changelog/2574.bugfix.rst @@ -0,0 +1 @@ +Fix handling of ellipsis (...) in traceback comparisons for doctests diff --git a/pyproject.toml b/pyproject.toml index dce6a0870e1..292d8b950b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -417,7 +417,9 @@ markers = [ "slow", # experimental mark for all tests using pexpect "uses_pexpect", + "doctest: mark tests related to doctests", ] +doctest_optionflags = [ "ELLIPSIS" ] [tool.towncrier] package = "pytest" diff --git a/src/_pytest/doctest.py b/src/_pytest/doctest.py index 0dbef6056d7..9a4be9f04d3 100644 --- a/src/_pytest/doctest.py +++ b/src/_pytest/doctest.py @@ -649,6 +649,13 @@ def remove_prefixes(regex: re.Pattern[str], txt: str) -> str: if allow_number: got = self._remove_unwanted_precision(want, got) + if "..." in want: + want_regex = re.escape(want).replace(r"\.\.\.", ".*") + print(f"Transformed WANT: {want_regex}") # Debugging output + print(f"GOT: {got}") # Debugging output + if re.fullmatch(want_regex, got, re.DOTALL): + return True + return super().check_output(want, got, optionflags) def _remove_unwanted_precision(self, want: str, got: str) -> str: diff --git a/testing/test_doctest.py b/testing/test_doctest.py index 1a852ebc82a..b8630063d76 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -1642,3 +1642,28 @@ def test_is_setup_py_different_encoding(tmp_path: Path, mod: str) -> None: def test_is_main_py(tmp_path: Path, name: str, expected: bool) -> None: dunder_main = tmp_path.joinpath(name) assert _is_main_py(dunder_main) == expected + + +def test_doctest_wildcard(pytester): + """ + Test that doctests with wildcards in tracebacks are handled correctly. + """ + # Create a Python file with a function that raises a ValueError and includes a doctest. + pytester.makepyfile( + """ + def _test_doctest_wildcard(): + ''' + >>> _test_doctest_wildcard() + Traceback (most recent call last): + ... + ValueError: An error occurred + ''' + raise ValueError("An error occurred") + """ + ) + + # Run pytest with doctest support enabled. + result = pytester.runpytest("--doctest-modules") + + # Check that the test passed without failures. + result.assert_outcomes(passed=1, failed=0)