Skip to content

Commit

Permalink
Rework the PrettyPrinter implementation for full diffs
Browse files Browse the repository at this point in the history
The normal default pretty printer is not great when objects are nested
and it can get hard to read the diff.

Instead, provide a pretty printer that behaves more like when json get
indented, which allows for smaller, more meaningful differences, at
the expense of a slightly longer diff.

This does not touch the other places where the pretty printer is used,
and only updated the full diff one.
  • Loading branch information
BenjaminSchubert committed Nov 20, 2023
1 parent fdb8bbf commit 86545ed
Show file tree
Hide file tree
Showing 6 changed files with 363 additions and 307 deletions.
7 changes: 7 additions & 0 deletions changelog/1531.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Improved the very verbose diff for every standard library container types. Previously,
this would use the default python pretty printer, which puts opening and closing
markers on the same line as the first/last entry, in addition to not having
consistent indentation.

The indentation is now consistent and the markers on their own separate lines
which should reduce the diffs shown to users.
197 changes: 66 additions & 131 deletions src/_pytest/_io/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def _safe_tuple(t):
class PrettyPrinter:
def __init__(
self,
indent=1,
indent=4,
width=80,
depth=None,
stream=None,
Expand Down Expand Up @@ -146,7 +146,6 @@ def _format(self, object, stream, indent, allowance, context, level):

def _pprint_dataclass(self, object, stream, indent, allowance, context, level):
cls_name = object.__class__.__name__
indent += len(cls_name) + 1
items = [
(f.name, getattr(object, f.name))
for f in _dataclasses.fields(object)
Expand All @@ -164,17 +163,11 @@ def _pprint_dataclass(self, object, stream, indent, allowance, context, level):
def _pprint_dict(self, object, stream, indent, allowance, context, level):
write = stream.write
write("{")
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * " ")
length = len(object)
if length:
if self._sort_dicts:
items = sorted(object.items(), key=_safe_tuple)
else:
items = object.items()
self._format_dict_items(
items, stream, indent, allowance + 1, context, level
)
if self._sort_dicts:
items = sorted(object.items(), key=_safe_tuple)

Check warning on line 167 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L167

Added line #L167 was not covered by tests
else:
items = object.items()
self._format_dict_items(items, stream, indent, allowance, context, level)

Check warning on line 170 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L169-L170

Added lines #L169 - L170 were not covered by tests
write("}")

_dispatch[dict.__repr__] = _pprint_dict
Expand All @@ -185,32 +178,22 @@ def _pprint_ordered_dict(self, object, stream, indent, allowance, context, level
return
cls = object.__class__
stream.write(cls.__name__ + "(")
self._format(
list(object.items()),
stream,
indent + len(cls.__name__) + 1,
allowance + 1,
context,
level,
)
self._pprint_dict(object, stream, indent, allowance, context, level)

Check warning on line 181 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L181

Added line #L181 was not covered by tests
stream.write(")")

_dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict

def _pprint_list(self, object, stream, indent, allowance, context, level):
stream.write("[")
self._format_items(object, stream, indent, allowance + 1, context, level)
self._format_items(object, stream, indent, allowance, context, level)

Check warning on line 188 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L188

Added line #L188 was not covered by tests
stream.write("]")

_dispatch[list.__repr__] = _pprint_list

def _pprint_tuple(self, object, stream, indent, allowance, context, level):
stream.write("(")
endchar = ",)" if len(object) == 1 else ")"
self._format_items(
object, stream, indent, allowance + len(endchar), context, level
)
stream.write(endchar)
self._format_items(object, stream, indent, allowance, context, level)
stream.write(")")

Check warning on line 196 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L195-L196

Added lines #L195 - L196 were not covered by tests

_dispatch[tuple.__repr__] = _pprint_tuple

Expand All @@ -225,11 +208,8 @@ def _pprint_set(self, object, stream, indent, allowance, context, level):
else:
stream.write(typ.__name__ + "({")
endchar = "})"
indent += len(typ.__name__) + 1
object = sorted(object, key=_safe_key)
self._format_items(
object, stream, indent, allowance + len(endchar), context, level
)
self._format_items(object, stream, indent, allowance, context, level)

Check warning on line 212 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L212

Added line #L212 was not covered by tests
stream.write(endchar)

_dispatch[set.__repr__] = _pprint_set
Expand Down Expand Up @@ -319,7 +299,7 @@ def _pprint_bytearray(self, object, stream, indent, allowance, context, level):

def _pprint_mappingproxy(self, object, stream, indent, allowance, context, level):
stream.write("mappingproxy(")
self._format(object.copy(), stream, indent + 13, allowance + 1, context, level)
self._format(object.copy(), stream, indent, allowance, context, level)

Check warning on line 302 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L302

Added line #L302 was not covered by tests
stream.write(")")

_dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
Expand All @@ -333,7 +313,6 @@ def _pprint_simplenamespace(
cls_name = "namespace"
else:
cls_name = object.__class__.__name__
indent += len(cls_name) + 1
items = object.__dict__.items()
stream.write(cls_name + "(")
self._format_namespace_items(items, stream, indent, allowance, context, level)
Expand All @@ -342,32 +321,30 @@ def _pprint_simplenamespace(
_dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace

def _format_dict_items(self, items, stream, indent, allowance, context, level):
if not items:
return

Check warning on line 325 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L325

Added line #L325 was not covered by tests

write = stream.write
indent += self._indent_per_level
delimnl = ",\n" + " " * indent
last_index = len(items) - 1
for i, (key, ent) in enumerate(items):
last = i == last_index
rep = self._repr(key, context, level)
write(rep)
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent

Check warning on line 329 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L328-L329

Added lines #L328 - L329 were not covered by tests
for key, ent in items:
write(delimnl)
write(self._repr(key, context, level))

Check warning on line 332 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L331-L332

Added lines #L331 - L332 were not covered by tests
write(": ")
self._format(
ent,
stream,
indent + len(rep) + 2,
allowance if last else 1,
context,
level,
)
if not last:
write(delimnl)
self._format(ent, stream, item_indent, 1, context, level)
write(",")

Check warning on line 335 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L334-L335

Added lines #L334 - L335 were not covered by tests

write("\n" + " " * indent)

Check warning on line 337 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L337

Added line #L337 was not covered by tests

def _format_namespace_items(self, items, stream, indent, allowance, context, level):
if not items:
return

Check warning on line 341 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L341

Added line #L341 was not covered by tests

write = stream.write
delimnl = ",\n" + " " * indent
last_index = len(items) - 1
for i, (key, ent) in enumerate(items):
last = i == last_index
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent

Check warning on line 345 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L344-L345

Added lines #L344 - L345 were not covered by tests
for key, ent in items:
write(delimnl)

Check warning on line 347 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L347

Added line #L347 was not covered by tests
write(key)
write("=")
if id(ent) in context:
Expand All @@ -378,52 +355,36 @@ def _format_namespace_items(self, items, stream, indent, allowance, context, lev
self._format(
ent,
stream,
indent + len(key) + 1,
allowance if last else 1,
item_indent + len(key) + 1,
1,
context,
level,
)
if not last:
write(delimnl)

write(",")

Check warning on line 364 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L364

Added line #L364 was not covered by tests

write("\n" + " " * indent)

Check warning on line 366 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L366

Added line #L366 was not covered by tests

def _format_items(self, items, stream, indent, allowance, context, level):
if not items:
return

Check warning on line 370 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L370

Added line #L370 was not covered by tests

write = stream.write
indent += self._indent_per_level
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * " ")
delimnl = ",\n" + " " * indent
delim = ""
width = max_width = self._width - indent + 1
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent

Check warning on line 374 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L373-L374

Added lines #L373 - L374 were not covered by tests

it = iter(items)
try:
next_ent = next(it)
except StopIteration:
return
last = False
while not last:
ent = next_ent
while True:
try:
next_ent = next(it)
except StopIteration:
last = True
max_width -= allowance
width -= allowance
if self._compact:
rep = self._repr(ent, context, level)
w = len(rep) + 2
if width < w:
width = max_width
if delim:
delim = delimnl
if width >= w:
width -= w
write(delim)
delim = ", "
write(rep)
continue
write(delim)
delim = delimnl
self._format(ent, stream, indent, allowance if last else 1, context, level)
break

Check warning on line 381 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L381

Added line #L381 was not covered by tests

write(delimnl)
self._format(next_ent, stream, item_indent, 1, context, level)
write(",")

Check warning on line 385 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L383-L385

Added lines #L383 - L385 were not covered by tests

write("\n" + " " * indent)

Check warning on line 387 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L387

Added line #L387 was not covered by tests

def _repr(self, object, context, level):
repr, readable, recursive = self.format(
Expand All @@ -443,66 +404,40 @@ def format(self, object, context, maxlevels, level):
return self._safe_repr(object, context, maxlevels, level)

def _pprint_default_dict(self, object, stream, indent, allowance, context, level):
if not len(object):
stream.write(repr(object))
return
rdf = self._repr(object.default_factory, context, level)
cls = object.__class__
indent += len(cls.__name__) + 1
stream.write(f"{cls.__name__}({rdf},\n{' ' * indent}")
self._pprint_dict(object, stream, indent, allowance + 1, context, level)
stream.write(f"{object.__class__.__name__}({rdf}, ")
self._pprint_dict(object, stream, indent, allowance, context, level)

Check warning on line 409 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L408-L409

Added lines #L408 - L409 were not covered by tests
stream.write(")")

_dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict

def _pprint_counter(self, object, stream, indent, allowance, context, level):
if not len(object):
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "({")
if self._indent_per_level > 1:
stream.write((self._indent_per_level - 1) * " ")
stream.write(object.__class__.__name__ + "({")

Check warning on line 415 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L415

Added line #L415 was not covered by tests
items = object.most_common()
self._format_dict_items(
items, stream, indent + len(cls.__name__) + 1, allowance + 2, context, level
)
self._format_dict_items(items, stream, indent, allowance, context, level)

Check warning on line 417 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L417

Added line #L417 was not covered by tests
stream.write("})")

_dispatch[_collections.Counter.__repr__] = _pprint_counter

def _pprint_chain_map(self, object, stream, indent, allowance, context, level):
if not len(object.maps):
if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "(")
indent += len(cls.__name__) + 1
for i, m in enumerate(object.maps):
if i == len(object.maps) - 1:
self._format(m, stream, indent, allowance + 1, context, level)
stream.write(")")
else:
self._format(m, stream, indent, 1, context, level)
stream.write(",\n" + " " * indent)

stream.write(object.__class__.__name__ + "(")
self._format_items(object.maps, stream, indent, allowance, context, level)
stream.write(")")

Check warning on line 429 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L427-L429

Added lines #L427 - L429 were not covered by tests

_dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map

def _pprint_deque(self, object, stream, indent, allowance, context, level):
if not len(object):
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "(")
indent += len(cls.__name__) + 1
stream.write(object.__class__.__name__ + "(")

Check warning on line 434 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L434

Added line #L434 was not covered by tests
if object.maxlen is not None:
stream.write("maxlen=%d, " % object.maxlen)

Check warning on line 436 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L436

Added line #L436 was not covered by tests
stream.write("[")
if object.maxlen is None:
self._format_items(object, stream, indent, allowance + 2, context, level)
stream.write("])")
else:
self._format_items(object, stream, indent, 2, context, level)
rml = self._repr(object.maxlen, context, level)
stream.write(f"],\n{' ' * indent}maxlen={rml})")

self._format_items(object, stream, indent, allowance + 1, context, level)
stream.write("])")

Check warning on line 440 in src/_pytest/_io/pprint.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/_io/pprint.py#L439-L440

Added lines #L439 - L440 were not covered by tests

_dispatch[_collections.deque.__repr__] = _pprint_deque

Expand Down
28 changes: 2 additions & 26 deletions src/_pytest/assertion/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,18 +318,6 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]:
return explanation


def _surrounding_parens_on_own_lines(lines: List[str]) -> None:
"""Move opening/closing parenthesis/bracket to own lines."""
opening = lines[0][:1]
if opening in ["(", "[", "{"]:
lines[0] = " " + lines[0][1:]
lines[:] = [opening] + lines
closing = lines[-1][-1:]
if closing in [")", "]", "}"]:
lines[-1] = lines[-1][:-1] + ","
lines[:] = lines + [closing]


def _compare_eq_iterable(
left: Iterable[Any],
right: Iterable[Any],
Expand All @@ -341,20 +329,8 @@ def _compare_eq_iterable(
# dynamic import to speedup pytest
import difflib

left_formatting = pprint.pformat(left).splitlines()
right_formatting = pprint.pformat(right).splitlines()

# Re-format for different output lengths.
lines_left = len(left_formatting)
lines_right = len(right_formatting)
if lines_left != lines_right:
printer = PrettyPrinter()
left_formatting = printer.pformat(left).splitlines()
right_formatting = printer.pformat(right).splitlines()

if lines_left > 1 or lines_right > 1:
_surrounding_parens_on_own_lines(left_formatting)
_surrounding_parens_on_own_lines(right_formatting)
left_formatting = PrettyPrinter().pformat(left).splitlines()
right_formatting = PrettyPrinter().pformat(right).splitlines()

Check warning on line 333 in src/_pytest/assertion/util.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/assertion/util.py#L332-L333

Added lines #L332 - L333 were not covered by tests

explanation = ["Full diff:"]
# "right" is the expected base against which we compare "left",
Expand Down
Loading

0 comments on commit 86545ed

Please sign in to comment.