Debian Codegraph @

_pytest/assertion/util.py

raw symbols SCIP
1 """Utilities for assertion debugging"""
2 import pprint
3
4 import _pytest._code
5 import py
6 try:
7 from collections import Sequence
8 except ImportError:
9 Sequence = list
10
11 BuiltinAssertionError = py.builtin.builtins.AssertionError
12 u = py.builtin._totext
13
14 # The _reprcompare attribute on the util module is used by the new assertion
15 # interpretation code and assertion rewriter to detect this plugin was
16 # loaded and in turn call the hooks defined here as part of the
17 # DebugInterpreter.
18 _reprcompare = None
19
20
21 # the re-encoding is needed for python2 repr
22 # with non-ascii characters (see issue 877 and 1379)
23 def ecu(s):
24 try:
25 return u(s, 'utf-8', 'replace')
26 except TypeError:
27 return s
28
29
30 def format_explanation(explanation):
31 """This formats an explanation
32
33 Normally all embedded newlines are escaped, however there are
34 three exceptions: \n{, \n} and \n~. The first two are intended
35 cover nested explanations, see function and attribute explanations
36 for examples (.visit_Call(), visit_Attribute()). The last one is
37 for when one explanation needs to span multiple lines, e.g. when
38 displaying diffs.
39 """
40 explanation = ecu(explanation)
41 explanation = _collapse_false(explanation)
42 lines = _split_explanation(explanation)
43 result = _format_lines(lines)
44 return u('\n').join(result)
45
46
47 def _collapse_false(explanation):
48 """Collapse expansions of False
49
50 So this strips out any "assert False\n{where False = ...\n}"
51 blocks.
52 """
53 where = 0
54 while True:
55 start = where = explanation.find("False\n{False = ", where)
56 if where == -1:
57 break
58 level = 0
59 prev_c = explanation[start]
60 for i, c in enumerate(explanation[start:]):
61 if prev_c + c == "\n{":
62 level += 1
63 elif prev_c + c == "\n}":
64 level -= 1
65 if not level:
66 break
67 prev_c = c
68 else:
69 raise AssertionError("unbalanced braces: %r" % (explanation,))
70 end = start + i
71 where = end
72 if explanation[end - 1] == '\n':
73 explanation = (explanation[:start] + explanation[start+15:end-1] +
74 explanation[end+1:])
75 where -= 17
76 return explanation
77
78
79 def _split_explanation(explanation):
80 """Return a list of individual lines in the explanation
81
82 This will return a list of lines split on '\n{', '\n}' and '\n~'.
83 Any other newlines will be escaped and appear in the line as the
84 literal '\n' characters.
85 """
86 raw_lines = (explanation or u('')).split('\n')
87 lines = [raw_lines[0]]
88 for l in raw_lines[1:]:
89 if l and l[0] in ['{', '}', '~', '>']:
90 lines.append(l)
91 else:
92 lines[-1] += '\\n' + l
93 return lines
94
95
96 def _format_lines(lines):
97 """Format the individual lines
98
99 This will replace the '{', '}' and '~' characters of our mini
100 formatting language with the proper 'where ...', 'and ...' and ' +
101 ...' text, taking care of indentation along the way.
102
103 Return a list of formatted lines.
104 """
105 result = lines[:1]
106 stack = [0]
107 stackcnt = [0]
108 for line in lines[1:]:
109 if line.startswith('{'):
110 if stackcnt[-1]:
111 s = u('and ')
112 else:
113 s = u('where ')
114 stack.append(len(result))
115 stackcnt[-1] += 1
116 stackcnt.append(0)
117 result.append(u(' +') + u(' ')*(len(stack)-1) + s + line[1:])
118 elif line.startswith('}'):
119 stack.pop()
120 stackcnt.pop()
121 result[stack[-1]] += line[1:]
122 else:
123 assert line[0] in ['~', '>']
124 stack[-1] += 1
125 indent = len(stack) if line.startswith('~') else len(stack) - 1
126 result.append(u(' ')*indent + line[1:])
127 assert len(stack) == 1
128 return result
129
130
131 # Provide basestring in python3
132 try:
133 basestring = basestring
134 except NameError:
135 basestring = str
136
137
138 def assertrepr_compare(config, op, left, right):
139 """Return specialised explanations for some operators/operands"""
140 width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
141 left_repr = py.io.saferepr(left, maxsize=int(width/2))
142 right_repr = py.io.saferepr(right, maxsize=width-len(left_repr))
143
144 summary = u('%s %s %s') % (ecu(left_repr), op, ecu(right_repr))
145
146 issequence = lambda x: (isinstance(x, (list, tuple, Sequence)) and
147 not isinstance(x, basestring))
148 istext = lambda x: isinstance(x, basestring)
149 isdict = lambda x: isinstance(x, dict)
150 isset = lambda x: isinstance(x, (set, frozenset))
151
152 def isiterable(obj):
153 try:
154 iter(obj)
155 return not istext(obj)
156 except TypeError:
157 return False
158
159 verbose = config.getoption('verbose')
160 explanation = None
161 try:
162 if op == '==':
163 if istext(left) and istext(right):
164 explanation = _diff_text(left, right, verbose)
165 else:
166 if issequence(left) and issequence(right):
167 explanation = _compare_eq_sequence(left, right, verbose)
168 elif isset(left) and isset(right):
169 explanation = _compare_eq_set(left, right, verbose)
170 elif isdict(left) and isdict(right):
171 explanation = _compare_eq_dict(left, right, verbose)
172 if isiterable(left) and isiterable(right):
173 expl = _compare_eq_iterable(left, right, verbose)
174 if explanation is not None:
175 explanation.extend(expl)
176 else:
177 explanation = expl
178 elif op == 'not in':
179 if istext(left) and istext(right):
180 explanation = _notin_text(left, right, verbose)
181 except Exception:
182 explanation = [
183 u('(pytest_assertion plugin: representation of details failed. '
184 'Probably an object has a faulty __repr__.)'),
185 u(_pytest._code.ExceptionInfo())]
186
187 if not explanation:
188 return None
189
190 return [summary] + explanation
191
192
193 def _diff_text(left, right, verbose=False):
194 """Return the explanation for the diff between text or bytes
195
196 Unless --verbose is used this will skip leading and trailing
197 characters which are identical to keep the diff minimal.
198
199 If the input are bytes they will be safely converted to text.
200 """
201 from difflib import ndiff
202 explanation = []
203 if isinstance(left, py.builtin.bytes):
204 left = u(repr(left)[1:-1]).replace(r'\n', '\n')
205 if isinstance(right, py.builtin.bytes):
206 right = u(repr(right)[1:-1]).replace(r'\n', '\n')
207 if not verbose:
208 i = 0 # just in case left or right has zero length
209 for i in range(min(len(left), len(right))):
210 if left[i] != right[i]:
211 break
212 if i > 42:
213 i -= 10 # Provide some context
214 explanation = [u('Skipping %s identical leading '
215 'characters in diff, use -v to show') % i]
216 left = left[i:]
217 right = right[i:]
218 if len(left) == len(right):
219 for i in range(len(left)):
220 if left[-i] != right[-i]:
221 break
222 if i > 42:
223 i -= 10 # Provide some context
224 explanation += [u('Skipping %s identical trailing '
225 'characters in diff, use -v to show') % i]
226 left = left[:-i]
227 right = right[:-i]
228 explanation += [line.strip('\n')
229 for line in ndiff(left.splitlines(),
230 right.splitlines())]
231 return explanation
232
233
234 def _compare_eq_iterable(left, right, verbose=False):
235 if not verbose:
236 return [u('Use -v to get the full diff')]
237 # dynamic import to speedup pytest
238 import difflib
239
240 try:
241 left_formatting = pprint.pformat(left).splitlines()
242 right_formatting = pprint.pformat(right).splitlines()
243 explanation = [u('Full diff:')]
244 except Exception:
245 # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
246 # sorted() on a list would raise. See issue #718.
247 # As a workaround, the full diff is generated by using the repr() string of each item of each container.
248 left_formatting = sorted(repr(x) for x in left)
249 right_formatting = sorted(repr(x) for x in right)
250 explanation = [u('Full diff (fallback to calling repr on each item):')]
251 explanation.extend(line.strip() for line in difflib.ndiff(left_formatting, right_formatting))
252 return explanation
253
254
255 def _compare_eq_sequence(left, right, verbose=False):
256 explanation = []
257 for i in range(min(len(left), len(right))):
258 if left[i] != right[i]:
259 explanation += [u('At index %s diff: %r != %r')
260 % (i, left[i], right[i])]
261 break
262 if len(left) > len(right):
263 explanation += [u('Left contains more items, first extra item: %s')
264 % py.io.saferepr(left[len(right)],)]
265 elif len(left) < len(right):
266 explanation += [
267 u('Right contains more items, first extra item: %s') %
268 py.io.saferepr(right[len(left)],)]
269 return explanation
270
271
272 def _compare_eq_set(left, right, verbose=False):
273 explanation = []
274 diff_left = left - right
275 diff_right = right - left
276 if diff_left:
277 explanation.append(u('Extra items in the left set:'))
278 for item in diff_left:
279 explanation.append(py.io.saferepr(item))
280 if diff_right:
281 explanation.append(u('Extra items in the right set:'))
282 for item in diff_right:
283 explanation.append(py.io.saferepr(item))
284 return explanation
285
286
287 def _compare_eq_dict(left, right, verbose=False):
288 explanation = []
289 common = set(left).intersection(set(right))
290 same = dict((k, left[k]) for k in common if left[k] == right[k])
291 if same and not verbose:
292 explanation += [u('Omitting %s identical items, use -v to show') %
293 len(same)]
294 elif same:
295 explanation += [u('Common items:')]
296 explanation += pprint.pformat(same).splitlines()
297 diff = set(k for k in common if left[k] != right[k])
298 if diff:
299 explanation += [u('Differing items:')]
300 for k in diff:
301 explanation += [py.io.saferepr({k: left[k]}) + ' != ' +
302 py.io.saferepr({k: right[k]})]
303 extra_left = set(left) - set(right)
304 if extra_left:
305 explanation.append(u('Left contains more items:'))
306 explanation.extend(pprint.pformat(
307 dict((k, left[k]) for k in extra_left)).splitlines())
308 extra_right = set(right) - set(left)
309 if extra_right:
310 explanation.append(u('Right contains more items:'))
311 explanation.extend(pprint.pformat(
312 dict((k, right[k]) for k in extra_right)).splitlines())
313 return explanation
314
315
316 def _notin_text(term, text, verbose=False):
317 index = text.find(term)
318 head = text[:index]
319 tail = text[index+len(term):]
320 correct_text = head + tail
321 diff = _diff_text(correct_text, text, verbose)
322 newdiff = [u('%s is contained here:') % py.io.saferepr(term, maxsize=42)]
323 for line in diff:
324 if line.startswith(u('Skipping')):
325 continue
326 if line.startswith(u('- ')):
327 continue
328 if line.startswith(u('+ ')):
329 newdiff.append(u(' ') + line[2:])
330 else:
331 newdiff.append(line)
332 return newdiff