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
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ Tushar Sadhwani
Tyler Goodlet
Tyler Smart
Tzu-ping Chung
Vankudothu Adhi Naik
Vasily Kuznetsov
Victor Maryama
Victor Rodriguez
Expand Down
1 change: 1 addition & 0 deletions changelog/15531.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 5 additions & 1 deletion src/_pytest/assertion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
12 changes: 7 additions & 5 deletions src/_pytest/assertion/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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)
Expand Down
26 changes: 19 additions & 7 deletions testing/test_assertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -180,7 +183,7 @@ def test_dummy_failure(pytester): # how meta!
[
"> r.assertoutcome(passed=1)",
"E AssertionError: ([[][]], [[][]], [[]<TestReport *>[]])*",
"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",
Expand Down Expand Up @@ -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 + "'",
"",
Expand All @@ -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 + "'",
"",
Expand All @@ -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'",
"",
Expand All @@ -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'",
Expand All @@ -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:",
Expand All @@ -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:",
Expand Down Expand Up @@ -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(
Expand Down
14 changes: 8 additions & 6 deletions testing/test_assertrewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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:
Expand Down
Loading