Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/ptpython/printer.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,19 @@ def _format_result_output(
formatted_result_repr = to_formatted_text(
getattr(result, "__pt_repr__")()
)
yield from formatted_result_repr
return
# Only trust the result if every fragment is a well-formed
# ``(style, text)`` tuple. A `unittest.mock.MagicMock` (and
# similar auto-attribute objects) fabricates a `__pt_repr__`
# that resolves to more mocks, so `to_formatted_text` can yield
# malformed fragments such as an empty tuple, which would later
# crash `split_lines` with a "not enough values to unpack"
# `ValueError`. Fall back to the normal `repr()` path instead.
if all(
isinstance(fragment, tuple) and len(fragment) >= 2
for fragment in formatted_result_repr
):
yield from formatted_result_repr
return
except (GeneratorExit, KeyboardInterrupt):
raise # Don't catch here.
except:
Expand Down
42 changes: 42 additions & 0 deletions tests/test_printer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from __future__ import annotations

from unittest.mock import MagicMock

from prompt_toolkit.formatted_text.utils import split_lines

from ptpython.printer import OutputPrinter


def test_format_result_output_handles_mock_with_fabricated_pt_repr() -> None:
"""A ``unittest.mock.MagicMock`` fabricates any attribute, including
``__pt_repr__``, which resolves to more mocks. ``to_formatted_text`` then
yields malformed fragments (e.g. an empty tuple) that used to crash
``split_lines`` with ``ValueError: not enough values to unpack``. The
printer must fall back to the normal ``repr()`` path instead. See #610.
"""
mock = MagicMock()
mock.get()
call = mock.method_calls[0]

printer = OutputPrinter.__new__(OutputPrinter)
fragments = list(
printer._format_result_output(
call,
reformat=False,
highlight=True,
line_length=80,
paginate=False,
)
)

# Every fragment must be a well-formed (style, text) tuple, so splitting
# into lines does not raise.
for fragment in fragments:
assert isinstance(fragment, tuple)
assert len(fragment) >= 2
list(split_lines(fragments))

# The fallback renders the object's ``repr`` rather than the mock's
# fabricated formatted text.
rendered = "".join(text for _, text, *_ in fragments)
assert "call" in rendered