Debian Codegraph @

src/_pytest/assertion/util.py

raw
1 # mypy: allow-untyped-defs
2 """Utilities for assertion debugging."""
3
4 from __future__ import annotations
5
6 from collections.abc import Callable
7 from collections.abc import Iterator
8 from collections.abc import Sequence
9 from typing import Literal
10 from unicodedata import normalize
11
12 from _pytest import outcomes
13 import _pytest._code
14 from _pytest._io.saferepr import saferepr
15 from _pytest._io.saferepr import saferepr_unlimited
16 from _pytest.assertion._compare_any import _compare_eq_any
17 from _pytest.assertion._compare_set import SET_COMPARISON_FUNCTIONS
18 from _pytest.assertion._guards import isset
19 from _pytest.assertion._guards import istext
20 from _pytest.assertion._typing import _AssertionTextDiffStyle
21 from _pytest.assertion._typing import _HighlightFunc
22 from _pytest.assertion.compare_text import _notin_text
23 from _pytest.assertion.highlight import dummy_highlighter as dummy_highlighter
24 from _pytest.config import Config
25 from _pytest.config import UsageError
26
27
28 # The _reprcompare attribute on the util module is used by the new assertion
29 # interpretation code and assertion rewriter to detect this plugin was
30 # loaded and in turn call the hooks defined here as part of the
31 # DebugInterpreter.
32 _reprcompare: Callable[[str, object, object], str | None] | None = None
33
34 # Works similarly as _reprcompare attribute. Is populated with the hook call
35 # when pytest_runtest_setup is called.
36 _assertion_pass: Callable[[int, str, str], None] | None = None
37
38 # Config object which is assigned during pytest_runtest_protocol.
39 _config: Config | None = None
40
41 ASSERTION_TEXT_DIFF_STYLE_INI = "assertion_text_diff_style"
42 ASSERTION_TEXT_DIFF_STYLE_NDIFF: Literal["ndiff"] = "ndiff"
43 ASSERTION_TEXT_DIFF_STYLE_BLOCK: Literal["block"] = "block"
44 ASSERTION_TEXT_DIFF_STYLE_CHOICES = (
45 ASSERTION_TEXT_DIFF_STYLE_NDIFF,
46 ASSERTION_TEXT_DIFF_STYLE_BLOCK,
47 )
48
49
50 def get_assertion_text_diff_style(config: Config) -> _AssertionTextDiffStyle:
51 style = str(config.getini(ASSERTION_TEXT_DIFF_STYLE_INI))
52 match style:
53 case "ndiff" | "block":
54 return style
55 case _:
56 choices = ", ".join(
57 repr(choice) for choice in ASSERTION_TEXT_DIFF_STYLE_CHOICES
58 )
59 raise UsageError(
60 f"{ASSERTION_TEXT_DIFF_STYLE_INI} must be one of {choices}; got {style!r}"
61 )
62
63
64 def validate_assertion_text_diff_style(config: Config) -> None:
65 get_assertion_text_diff_style(config)
66
67
68 def format_explanation(explanation: str) -> str:
69 r"""Format an explanation.
70
71 Normally all embedded newlines are escaped, however there are
72 three exceptions: \n{, \n} and \n~. The first two are intended
73 cover nested explanations, see function and attribute explanations
74 for examples (.visit_Call(), visit_Attribute()). The last one is
75 for when one explanation needs to span multiple lines, e.g. when
76 displaying diffs.
77 """
78 lines = _split_explanation(explanation)
79 result = _format_lines(lines)
80 return "\n".join(result)
81
82
83 def _split_explanation(explanation: str) -> list[str]:
84 r"""Return a list of individual lines in the explanation.
85
86 This will return a list of lines split on '\n{', '\n}' and '\n~'.
87 Any other newlines will be escaped and appear in the line as the
88 literal '\n' characters.
89 """
90 raw_lines = (explanation or "").split("\n")
91 lines = [raw_lines[0]]
92 for values in raw_lines[1:]:
93 if values and values[0] in ["{", "}", "~", ">"]:
94 lines.append(values)
95 else:
96 lines[-1] += "\\n" + values
97 return lines
98
99
100 def _format_lines(lines: Sequence[str]) -> list[str]:
101 """Format the individual lines.
102
103 This will replace the '{', '}' and '~' characters of our mini formatting
104 language with the proper 'where ...', 'and ...' and ' + ...' text, taking
105 care of indentation along the way.
106
107 Return a list of formatted lines.
108 """
109 result = list(lines[:1])
110 stack = [0]
111 stackcnt = [0]
112 for line in lines[1:]:
113 if line.startswith("{"):
114 if stackcnt[-1]:
115 s = "and "
116 else:
117 s = "where "
118 stack.append(len(result))
119 stackcnt[-1] += 1
120 stackcnt.append(0)
121 result.append(" +" + " " * (len(stack) - 1) + s + line[1:])
122 elif line.startswith("}"):
123 stack.pop()
124 stackcnt.pop()
125 result[stack[-1]] += line[1:]
126 else:
127 assert line[0] in ["~", ">"]
128 stack[-1] += 1
129 indent = len(stack) if line.startswith("~") else len(stack) - 1
130 result.append(" " * indent + line[1:])
131 assert len(stack) == 1
132 return result
133
134
135 def assertrepr_compare(
136 op: str,
137 left: object,
138 right: object,
139 *,
140 verbose: int,
141 highlighter: _HighlightFunc,
142 assertion_text_diff_style: _AssertionTextDiffStyle,
143 ) -> Iterator[str]:
144 """Yield specialised explanations for some operators/operands.
145
146 The first line yielded is always the summary (``left op right``);
147 subsequent lines are the detailed explanation. Yields nothing when no
148 specialised explanation applies, which lets consumers map an empty
149 iterator to "no explanation" without materialising anything.
150
151 The iterator is lazy on purpose: a streaming consumer can stop pulling
152 lines as soon as it has enough to show, so an enormous diff doesn't
153 have to be built in full just to be thrown away.
154 """
155 # Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier.
156 # See issue #3246.
157 use_ascii = (
158 isinstance(left, str)
159 and isinstance(right, str)
160 and normalize("NFD", left) == normalize("NFD", right)
161 )
162
163 if verbose > 1:
164 left_repr = saferepr_unlimited(left, use_ascii=use_ascii)
165 right_repr = saferepr_unlimited(right, use_ascii=use_ascii)
166 else:
167 # XXX: "15 chars indentation" is wrong
168 # ("E AssertionError: assert "); should use term width.
169 maxsize = (
170 80 - 15 - len(op) - 2
171 ) // 2 # 15 chars indentation, 1 space around op
172
173 left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii)
174 right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii)
175
176 summary = f"{left_repr} {op} {right_repr}"
177
178 try:
179 if op == "==":
180 source = _compare_eq_any(
181 left,
182 right,
183 highlighter,
184 verbose,
185 assertion_text_diff_style,
186 )
187 elif op == "not in" and istext(left) and istext(right):
188 source = _notin_text(left, right, verbose)
189 elif op in {"!=", ">=", "<=", ">", "<"} and isset(left) and isset(right):
190 source = SET_COMPARISON_FUNCTIONS[op](left, right, highlighter, verbose)
191 else:
192 source = iter(())
193
194 # Only yield the summary if there is a detailed explanation.
195 # Make sure there's a separating empty line after the summary.
196 summary_yielded = False
197 for line in source:
198 if not summary_yielded:
199 yield summary
200 if line != "":
201 yield ""
202 summary_yielded = True
203 yield line
204 except outcomes.Exit:
205 raise
206 except Exception:
207 repr_crash = _pytest._code.ExceptionInfo.from_current()._getreprcrash()
208 if not summary_yielded:
209 yield summary
210 yield ""
211 summary_yielded = True
212 yield (
213 f"(pytest_assertion plugin: representation of details failed: {repr_crash}."
214 )
215 yield " Probably an object has a faulty __repr__.)"