Debian Codegraph @

src/_pytest/assertion/_compare_sequence.py

raw
1 from __future__ import annotations
2
3 from collections.abc import Iterable
4 from collections.abc import Iterator
5 from collections.abc import Sequence
6
7 from _pytest._io.pprint import PrettyPrinter
8 from _pytest._io.saferepr import saferepr
9 from _pytest.assertion._typing import _HighlightFunc
10 from _pytest.compat import running_on_ci
11
12
13 def _compare_eq_iterable(
14 left: Iterable[object],
15 right: Iterable[object],
16 highlighter: _HighlightFunc,
17 verbose: int = 0,
18 ) -> Iterator[str]:
19 if verbose <= 0 and not running_on_ci():
20 yield "Use -v to get more diff"
21 return
22 # dynamic import to speedup pytest
23 import difflib
24
25 left_formatting = PrettyPrinter().pformat(left).splitlines()
26 right_formatting = PrettyPrinter().pformat(right).splitlines()
27
28 yield ""
29 yield "Full diff:"
30 # "right" is the expected base against which we compare "left",
31 # see https://github.com/pytest-dev/pytest/issues/3333
32 yield from highlighter(
33 "\n".join(
34 line.rstrip() for line in difflib.ndiff(right_formatting, left_formatting)
35 ),
36 lexer="diff",
37 ).splitlines()
38
39
40 def _compare_eq_sequence(
41 left: Sequence[object],
42 right: Sequence[object],
43 highlighter: _HighlightFunc,
44 verbose: int = 0,
45 ) -> Iterator[str]:
46 comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)
47 len_left = len(left)
48 len_right = len(right)
49 for i in range(min(len_left, len_right)):
50 if left[i] != right[i]:
51 if comparing_bytes:
52 # when comparing bytes, we want to see their ascii representation
53 # instead of their numeric values (#5260)
54 # using a slice gives us the ascii representation:
55 # >>> s = b'foo'
56 # >>> s[0]
57 # 102
58 # >>> s[0:1]
59 # b'f'
60 left_value: object = left[i : i + 1]
61 right_value: object = right[i : i + 1]
62 else:
63 left_value = left[i]
64 right_value = right[i]
65
66 yield (
67 f"At index {i} diff:"
68 f" {highlighter(repr(left_value))} != {highlighter(repr(right_value))}"
69 )
70 break
71
72 if comparing_bytes:
73 # when comparing bytes, it doesn't help to show the "sides contain one or more
74 # items" longer explanation, so skip it
75 return
76
77 len_diff = len_left - len_right
78 if len_diff:
79 if len_diff > 0:
80 dir_with_more = "Left"
81 extra = saferepr(left[len_right])
82 else:
83 len_diff = 0 - len_diff
84 dir_with_more = "Right"
85 extra = saferepr(right[len_left])
86
87 if len_diff == 1:
88 yield f"{dir_with_more} contains one more item: {highlighter(extra)}"
89 else:
90 yield f"{dir_with_more} contains {len_diff} more items, first extra item: {highlighter(extra)}"