Skip to content

Commit 9a0f4e5

Browse files
tirkarthibluetech
authored andcommitted
Add support to display field names in namedtuple diffs.
1 parent 5913cd2 commit 9a0f4e5

File tree

4 files changed

+58
-3
lines changed

4 files changed

+58
-3
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ Justyna Janczyszyn
155155
Kale Kundert
156156
Kamran Ahmad
157157
Karl O. Pinc
158+
Karthikeyan Singaravelan
158159
Katarzyna Jachim
159160
Katarzyna Król
160161
Katerina Koukiou

changelog/7527.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
When a comparison between `namedtuple` instances of the same type fails, pytest now shows the differing field names (possibly nested) instead of their indexes.

src/_pytest/assertion/util.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ def isset(x: Any) -> bool:
110110
return isinstance(x, (set, frozenset))
111111

112112

113+
def isnamedtuple(obj: Any) -> bool:
114+
return isinstance(obj, tuple) and getattr(obj, "_fields", None) is not None
115+
116+
113117
def isdatacls(obj: Any) -> bool:
114118
return getattr(obj, "__dataclass_fields__", None) is not None
115119

@@ -171,14 +175,20 @@ def _compare_eq_any(left: Any, right: Any, verbose: int = 0) -> List[str]:
171175
if istext(left) and istext(right):
172176
explanation = _diff_text(left, right, verbose)
173177
else:
174-
if issequence(left) and issequence(right):
178+
if type(left) == type(right) and (
179+
isdatacls(left) or isattrs(left) or isnamedtuple(left)
180+
):
181+
# Note: unlike dataclasses/attrs, namedtuples compare only the
182+
# field values, not the type or field names. But this branch
183+
# intentionally only handles the same-type case, which was often
184+
# used in older code bases before dataclasses/attrs were available.
185+
explanation = _compare_eq_cls(left, right, verbose)
186+
elif issequence(left) and issequence(right):
175187
explanation = _compare_eq_sequence(left, right, verbose)
176188
elif isset(left) and isset(right):
177189
explanation = _compare_eq_set(left, right, verbose)
178190
elif isdict(left) and isdict(right):
179191
explanation = _compare_eq_dict(left, right, verbose)
180-
elif type(left) == type(right) and (isdatacls(left) or isattrs(left)):
181-
explanation = _compare_eq_cls(left, right, verbose)
182192
elif verbose > 0:
183193
explanation = _compare_eq_verbose(left, right)
184194
if isiterable(left) and isiterable(right):
@@ -408,6 +418,10 @@ def _compare_eq_cls(left: Any, right: Any, verbose: int) -> List[str]:
408418
elif isattrs(left):
409419
all_fields = left.__attrs_attrs__
410420
fields_to_check = [field.name for field in all_fields if getattr(field, "eq")]
421+
elif isnamedtuple(left):
422+
fields_to_check = left._fields
423+
else:
424+
assert False
411425

412426
indent = " "
413427
same = []

testing/test_assertion.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import collections
12
import sys
23
import textwrap
34
from typing import Any
@@ -987,6 +988,44 @@ class SimpleDataObjectTwo:
987988
assert lines is None
988989

989990

991+
class TestAssert_reprcompare_namedtuple:
992+
def test_namedtuple(self) -> None:
993+
NT = collections.namedtuple("NT", ["a", "b"])
994+
995+
left = NT(1, "b")
996+
right = NT(1, "c")
997+
998+
lines = callequal(left, right)
999+
assert lines == [
1000+
"NT(a=1, b='b') == NT(a=1, b='c')",
1001+
"",
1002+
"Omitting 1 identical items, use -vv to show",
1003+
"Differing attributes:",
1004+
"['b']",
1005+
"",
1006+
"Drill down into differing attribute b:",
1007+
" b: 'b' != 'c'",
1008+
" - c",
1009+
" + b",
1010+
"Use -v to get the full diff",
1011+
]
1012+
1013+
def test_comparing_two_different_namedtuple(self) -> None:
1014+
NT1 = collections.namedtuple("NT1", ["a", "b"])
1015+
NT2 = collections.namedtuple("NT2", ["a", "b"])
1016+
1017+
left = NT1(1, "b")
1018+
right = NT2(2, "b")
1019+
1020+
lines = callequal(left, right)
1021+
# Because the types are different, uses the generic sequence matcher.
1022+
assert lines == [
1023+
"NT1(a=1, b='b') == NT2(a=2, b='b')",
1024+
"At index 0 diff: 1 != 2",
1025+
"Use -v to get the full diff",
1026+
]
1027+
1028+
9901029
class TestFormatExplanation:
9911030
def test_special_chars_full(self, pytester: Pytester) -> None:
9921031
# Issue 453, for the bug this would raise IndexError

0 commit comments

Comments
 (0)