Skip to content

Commit 3378a16

Browse files
committed
Also highlight comparisons between strings
Fixes #13175
1 parent 52a5ff3 commit 3378a16

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

changelog/13175.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The diff is now also highlighted correctly when comparing two strings.

src/_pytest/assertion/util.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def _compare_eq_any(
242242
) -> list[str]:
243243
explanation = []
244244
if istext(left) and istext(right):
245-
explanation = _diff_text(left, right, verbose)
245+
explanation = _diff_text(left, right, highlighter, verbose)
246246
else:
247247
from _pytest.python_api import ApproxBase
248248

@@ -274,7 +274,9 @@ def _compare_eq_any(
274274
return explanation
275275

276276

277-
def _diff_text(left: str, right: str, verbose: int = 0) -> list[str]:
277+
def _diff_text(
278+
left: str, right: str, highlighter: _HighlightFunc, verbose: int = 0
279+
) -> list[str]:
278280
"""Return the explanation for the diff between text.
279281
280282
Unless --verbose is used this will skip leading and trailing
@@ -315,10 +317,15 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> list[str]:
315317
explanation += ["Strings contain only whitespace, escaping them using repr()"]
316318
# "right" is the expected base against which we compare "left",
317319
# see https://github.com/pytest-dev/pytest/issues/3333
318-
explanation += [
319-
line.strip("\n")
320-
for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))
321-
]
320+
explanation.extend(
321+
highlighter(
322+
"\n".join(
323+
line.strip("\n")
324+
for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))
325+
),
326+
lexer="diff",
327+
).splitlines()
328+
)
322329
return explanation
323330

324331

testing/test_assertion.py

+10
Original file line numberDiff line numberDiff line change
@@ -2019,6 +2019,16 @@ def test():
20192019
"{bold}{red}E {light-green}+ 'number-is-5': 5,{hl-reset}{endline}{reset}",
20202020
],
20212021
),
2022+
(
2023+
"""
2024+
def test():
2025+
assert "abcd" == "abce"
2026+
""",
2027+
[
2028+
"{bold}{red}E {reset}{light-red}- abce{hl-reset}{endline}{reset}",
2029+
"{bold}{red}E {light-green}+ abcd{hl-reset}{endline}{reset}",
2030+
],
2031+
),
20222032
),
20232033
)
20242034
def test_comparisons_handle_colors(

0 commit comments

Comments
 (0)