From 0e1e6ccf17ff8c7db5ceebe326934b8380ab6cd3 Mon Sep 17 00:00:00 2001 From: adhinaik13 <22je1052@iitism.ac.in> Date: Sat, 5 Dec 2026 01:30:19 +0530 Subject: [PATCH 1/2] Fix assertion summary width calculation --- AUTHORS | 1 + changelog/15531.bugfix.rst | 1 + src/_pytest/assertion/__init__.py | 6 +++++- src/_pytest/assertion/util.py | 12 +++++++----- testing/test_assertion.py | 26 +++++++++++++++++++------- 5 files changed, 33 insertions(+), 13 deletions(-) create mode 100644 changelog/15531.bugfix.rst diff --git a/AUTHORS b/AUTHORS index f04403e2d5c..6792d43d396 100644 --- a/AUTHORS +++ b/AUTHORS @@ -524,6 +524,7 @@ Tushar Sadhwani Tyler Goodlet Tyler Smart Tzu-ping Chung +Vankudothu Adhi Naik Vasily Kuznetsov Victor Maryama Victor Rodriguez diff --git a/changelog/15531.bugfix.rst b/changelog/15531.bugfix.rst new file mode 100644 index 00000000000..31f3d81ac0a --- /dev/null +++ b/changelog/15531.bugfix.rst @@ -0,0 +1 @@ +Assertion comparison summaries now size their operand representations to the detected terminal width. This avoids overlong summary lines on narrow terminals and makes better use of wide terminals. diff --git a/src/_pytest/assertion/__init__.py b/src/_pytest/assertion/__init__.py index a171633f320..e3e9f33dd6d 100644 --- a/src/_pytest/assertion/__init__.py +++ b/src/_pytest/assertion/__init__.py @@ -226,10 +226,13 @@ def pytest_assertrepr_compare( config: Config, op: str, left: Any, right: Any ) -> list[str] | None: if config.pluginmanager.has_plugin("terminalreporter"): - highlighter = config.get_terminal_writer()._highlight + terminal_writer = config.get_terminal_writer() + highlighter = terminal_writer._highlight + width = terminal_writer.fullwidth else: # Keep it plaintext when not using terminalrepoterer (#14377). highlighter = util.dummy_highlighter + width = 80 # When truncation is going to clip the explanation downstream, cap the # comparison helpers' formatting at what the truncator will actually pull # (the raw limits plus the footer slack) so no effort is spent formatting @@ -254,5 +257,6 @@ def pytest_assertrepr_compare( highlighter=highlighter, assertion_text_diff_style=config.getini("assertion_text_diff_style"), truncation_budget=truncation_budget, + width=width, ) return truncate.materialize_with_truncation(lines, config) or None diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py index dd993d7bcae..81433414533 100644 --- a/src/_pytest/assertion/util.py +++ b/src/_pytest/assertion/util.py @@ -114,6 +114,7 @@ def assertrepr_compare( highlighter: _HighlightFunc, assertion_text_diff_style: _AssertionTextDiffStyle, truncation_budget: TruncationBudget = NO_TRUNCATION_BUDGET, + width: int | None = None, ) -> Iterator[str]: """Yield specialised explanations for some operators/operands. @@ -138,11 +139,12 @@ def assertrepr_compare( left_repr = saferepr_unlimited(left, use_ascii=use_ascii) right_repr = saferepr_unlimited(right, use_ascii=use_ascii) else: - # XXX: "15 chars indentation" is wrong - # ("E AssertionError: assert "); should use term width. - maxsize = ( - 80 - 15 - len(op) - 2 - ) // 2 # 15 chars indentation, 1 space around op + if width is None: + # Preserve the historical budget for direct internal callers. + maxsize = (80 - 15 - len(op) - 2) // 2 + else: + prefix = "E AssertionError: assert " + maxsize = max(0, (width - len(prefix) - len(op) - 2) // 2) left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii) right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 035aad31c54..b4b1d12b41c 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -40,8 +40,11 @@ def mock_config( truncation_limit_lines: str = "0", truncation_limit_chars: str = "0", has_terminalreporter: bool = True, + terminal_width: int = 80, ): class TerminalWriter: + fullwidth = terminal_width + def _highlight(self, source, lexer="python"): return source @@ -180,7 +183,7 @@ def test_dummy_failure(pytester): # how meta! [ "> r.assertoutcome(passed=1)", "E AssertionError: ([[][]], [[][]], [[][]])*", - "E assert {'failed': 1,... 'skipped': 0} == {'failed': 0,... 'skipped': 0}", + "E assert {'failed'* == {'failed'*", "E Omitting 1 identical items, use -vv to show", "E Differing items:", "E Use -v to get more diff", @@ -802,7 +805,7 @@ def test_list_wrap_for_multiple_lines(self) -> None: l2 = ["a", "b", "c", long_d] diff = callequal(l1, l2, verbose=True) assert diff == [ - "['a', 'b', 'c'] == ['a', 'b', 'c...dddddddddddd']", + "['a', 'b', 'c'] == ['a', 'b'...dddddddd']", "", "Right contains one more item: '" + long_d + "'", "", @@ -817,7 +820,7 @@ def test_list_wrap_for_multiple_lines(self) -> None: diff = callequal(l2, l1, verbose=True) assert diff == [ - "['a', 'b', 'c...dddddddddddd'] == ['a', 'b', 'c']", + "['a', 'b'...dddddddd'] == ['a', 'b', 'c']", "", "Left contains one more item: '" + long_d + "'", "", @@ -838,7 +841,7 @@ def test_list_wrap_for_width_rewrap_same_length(self) -> None: l2 = [long_b, long_c, long_a] diff = callequal(l1, l2, verbose=True) assert diff == [ - "['aaaaaaaaaaa...cccccccccccc'] == ['bbbbbbbbbbb...aaaaaaaaaaaa']", + "['aaaaaaa...cccccccc'] == ['bbbbbbb...aaaaaaaa']", "", "At index 0 diff: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' != 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'", "", @@ -857,7 +860,7 @@ def test_list_dont_wrap_strings(self) -> None: l2 = ["should not get wrapped"] diff = callequal(l1, l2, verbose=True) assert diff == [ - "['a', 'aaaaaa...aaaaaaa', ...] == ['should not get wrapped']", + "['a', 'aa...aaa', ...] == ['should ... wrapped']", "", "At index 0 diff: 'a' != 'should not get wrapped'", "Left contains 7 more items, first extra item: 'aaaaaaaaaa'", @@ -882,7 +885,7 @@ def test_dict_wrap(self) -> None: diff = callequal(d1, d2, verbose=True) assert diff == [ - "{'common': 1,...1, 'env2': 2}} == {'common': 1,...: {'env1': 1}}", + "{'common'...env2': 2}} == {'common'...env1': 1}}", "", "Omitting 1 identical items, use -vv to show", "Differing items:", @@ -904,7 +907,7 @@ def test_dict_wrap(self) -> None: d2 = {"env": {"sub": sub}, "new": 1} diff = callequal(d1, d2, verbose=True) assert diff == [ - "{'env': {'sub... wrapped '}}}} == {'env': {'sub...}}}, 'new': 1}", + "{'env': {...pped '}}}} == {'env': {... 'new': 1}", "", "Omitting 1 identical items, use -vv to show", "Right contains 1 more item:", @@ -2220,6 +2223,15 @@ def test_no_terminalreporter_uses_plaintext_highlighter(self) -> None: assert any("Extra items" in line for line in result) assert not any("\x1b[" in line for line in result) + @pytest.mark.parametrize("terminal_width", [80, 200]) + def test_summary_uses_terminal_width(self, terminal_width: int) -> None: + config = mock_config(terminal_width=terminal_width) + result = plugin.pytest_assertrepr_compare(config, "==", "a" * 100, "b" * 100) + assert result is not None + + summary_line = f"E AssertionError: assert {result[0]}" + assert len(summary_line) <= terminal_width + def test_python25_compile_issue257(pytester: Pytester) -> None: pytester.makepyfile( From 65050d4e222454c2e174fa922d553e5e4cf71aae Mon Sep 17 00:00:00 2001 From: adhinaik13 <22je1052@iitism.ac.in> Date: Sat, 5 Dec 2026 01:41:55 +0530 Subject: [PATCH 2/2] Test terminal width in rewritten assertion summaries --- testing/test_assertrewrite.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/testing/test_assertrewrite.py b/testing/test_assertrewrite.py index 3ca422dd755..d2c293e42a9 100644 --- a/testing/test_assertrewrite.py +++ b/testing/test_assertrewrite.py @@ -426,8 +426,8 @@ class X: lines = msg.splitlines() assert lines == ["assert cls == 42"] - def test_assertrepr_compare_same_width(self, request) -> None: - """Should use same width/truncation with same initial width.""" + def test_assertrepr_compare_respects_terminal_width(self, request) -> None: + """The comparison summary should fit within the terminal width.""" def f() -> None: assert "1234567890" * 5 + "A" == "1234567890" * 5 + "B" @@ -441,10 +441,12 @@ def f() -> None: "== '12345678901234567890123456789012345678901234567890B'" ) else: - assert line == ( - "assert '123456789012...901234567890A' " - "== '123456789012...901234567890B'" - ) + assert line.startswith("assert '") + assert " == " in line + assert "..." in line + assert line.endswith("B'") + summary_line = f"E AssertionError: {line}" + assert len(summary_line) <= request.config.get_terminal_writer().fullwidth def test_dont_rewrite_if_hasattr_fails(self, request) -> None: class Y: