Debian Codegraph @

pypy/tool/pytest/astrewriter/ast_util.py

raw symbols SCIP
1 """Utilities for assertion debugging"""
2 from __future__ import absolute_import, division, print_function
3
4 u = str
5
6 # The _reprcompare attribute on the util module is used by the new assertion
7 # interpretation code and assertion rewriter to detect this plugin was
8 # loaded and in turn call the hooks defined here as part of the
9 # DebugInterpreter.
10 _reprcompare = None
11
12
13 # Provide basestring in python3
14 try:
15 basestring = basestring
16 except NameError:
17 basestring = str
18
19
20 def saferepr(obj, maxsize=None):
21 s = repr(obj)
22 if maxsize is not None:
23 s = s[:maxsize]
24 return s
25
26 def callbinrepr(op, left, right):
27 new_expl = assertrepr_compare(op, left, right)
28 new_expl = [line.replace("\n", "\\n") for line in new_expl]
29 res = "\n~".join(new_expl)
30 res = res.replace("%", "%%")
31 return res
32
33
34 def assertrepr_compare(op, left, right, verbose=False):
35 """Return specialised explanations for some operators/operands"""
36 width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
37 left_repr = saferepr(left, maxsize=int(width // 2))
38 right_repr = saferepr(right, maxsize=width - len(left_repr))
39
40 summary = u('%s %s %s') % (left_repr, op, right_repr)
41
42 def issequence(x):
43 return hasattr(x, '__iter__') and not isinstance(x, basestring)
44
45 def istext(x):
46 return isinstance(x, basestring)
47
48 def isdict(x):
49 return isinstance(x, dict)
50
51 def isset(x):
52 return isinstance(x, (set, frozenset))
53
54 def isiterable(obj):
55 try:
56 iter(obj)
57 return not istext(obj)
58 except TypeError:
59 return False
60
61 explanation = None
62 try:
63 if op == '==':
64 if istext(left) and istext(right):
65 explanation = _diff_text(left, right, verbose)
66 else:
67 if issequence(left) and issequence(right):
68 explanation = _compare_eq_sequence(left, right, verbose)
69 elif isset(left) and isset(right):
70 explanation = _compare_eq_set(left, right, verbose)
71 elif isdict(left) and isdict(right):
72 explanation = _compare_eq_dict(left, right, verbose)
73 if isiterable(left) and isiterable(right):
74 expl = _compare_eq_iterable(left, right, verbose)
75 if explanation is not None:
76 explanation.extend(expl)
77 else:
78 explanation = expl
79 elif op == 'not in':
80 if istext(left) and istext(right):
81 explanation = _notin_text(left, right, verbose)
82 except Exception as err:
83 explanation = [
84 '(pytest assertion: representation of details failed. '
85 'Probably an object has a faulty __repr__.)', str(err)]
86
87 if not explanation:
88 return None
89
90 return [summary] + explanation
91
92
93 def _diff_text(left, right, verbose=False):
94 """Return the explanation for the diff between text or bytes
95
96 Unless --verbose is used this will skip leading and trailing
97 characters which are identical to keep the diff minimal.
98
99 If the input are bytes they will be safely converted to text.
100 """
101 from difflib import ndiff
102 explanation = []
103 if not verbose:
104 i = 0 # just in case left or right has zero length
105 for i in range(min(len(left), len(right))):
106 if left[i] != right[i]:
107 break
108 if i > 42:
109 i -= 10 # Provide some context
110 explanation = ['Skipping %s identical leading '
111 'characters in diff, use -v to show' % i]
112 left = left[i:]
113 right = right[i:]
114 if len(left) == len(right):
115 for i in range(len(left)):
116 if left[-i] != right[-i]:
117 break
118 if i > 42:
119 i -= 10 # Provide some context
120 explanation += ['Skipping %s identical trailing '
121 'characters in diff, use -v to show' % i]
122 left = left[:-i]
123 right = right[:-i]
124 keepends = True
125 explanation += [line.strip('\n')
126 for line in ndiff(left.splitlines(keepends),
127 right.splitlines(keepends))]
128 return explanation
129
130
131 def _compare_eq_iterable(left, right, verbose=False):
132 if not verbose:
133 return ['Use -v to get the full diff']
134 # dynamic import to speedup pytest
135 import difflib, pprint
136 try:
137 left_formatting = pprint.pformat(left).splitlines()
138 right_formatting = pprint.pformat(right).splitlines()
139 explanation = ['Full diff:']
140 except Exception:
141 # hack: PrettyPrinter.pformat() in python 2 fails when formatting items that can't be sorted(), ie, calling
142 # sorted() on a list would raise. See issue #718.
143 # As a workaround, the full diff is generated by using the repr() string of each item of each container.
144 left_formatting = sorted(repr(x) for x in left)
145 right_formatting = sorted(repr(x) for x in right)
146 explanation = ['Full diff (fallback to calling repr on each item):']
147 explanation.extend(line.strip() for line in difflib.ndiff(left_formatting, right_formatting))
148 return explanation
149
150
151 def _compare_eq_sequence(left, right, verbose=False):
152 explanation = []
153 for i in range(min(len(left), len(right))):
154 if left[i] != right[i]:
155 explanation += [u('At index %s diff: %r != %r')
156 % (i, left[i], right[i])]
157 break
158 if len(left) > len(right):
159 explanation += [u('Left contains more items, first extra item: %s')
160 % saferepr(left[len(right)],)]
161 elif len(left) < len(right):
162 explanation += [
163 u('Right contains more items, first extra item: %s') %
164 saferepr(right[len(left)],)]
165 return explanation
166
167
168 def _compare_eq_set(left, right, verbose=False):
169 explanation = []
170 diff_left = left - right
171 diff_right = right - left
172 if diff_left:
173 explanation.append(u('Extra items in the left set:'))
174 for item in diff_left:
175 explanation.append(saferepr(item))
176 if diff_right:
177 explanation.append(u('Extra items in the right set:'))
178 for item in diff_right:
179 explanation.append(saferepr(item))
180 return explanation
181
182
183 def _compare_eq_dict(left, right, verbose=False):
184 import pprint
185 explanation = []
186 common = set(left).intersection(set(right))
187 same = dict((k, left[k]) for k in common if left[k] == right[k])
188 if same and verbose < 2:
189 explanation += [u('Omitting %s identical items, use -vv to show') %
190 len(same)]
191 elif same:
192 explanation += [u('Common items:')]
193 explanation += pprint.pformat(same).splitlines()
194 diff = set(k for k in common if left[k] != right[k])
195 if diff:
196 explanation += [u('Differing items:')]
197 for k in diff:
198 explanation += [saferepr({k: left[k]}) + ' != ' +
199 saferepr({k: right[k]})]
200 extra_left = set(left) - set(right)
201 if extra_left:
202 explanation.append(u('Left contains more items:'))
203 explanation.extend(pprint.pformat(
204 dict((k, left[k]) for k in extra_left)).splitlines())
205 extra_right = set(right) - set(left)
206 if extra_right:
207 explanation.append(u('Right contains more items:'))
208 explanation.extend(pprint.pformat(
209 dict((k, right[k]) for k in extra_right)).splitlines())
210 return explanation
211
212
213 def _notin_text(term, text, verbose=False):
214 index = text.find(term)
215 head = text[:index]
216 tail = text[index + len(term):]
217 correct_text = head + tail
218 diff = _diff_text(correct_text, text, verbose)
219 newdiff = [u('%s is contained here:') % saferepr(term, maxsize=42)]
220 for line in diff:
221 if line.startswith(u('Skipping')):
222 continue
223 if line.startswith(u('- ')):
224 continue
225 if line.startswith(u('+ ')):
226 newdiff.append(u(' ') + line[2:])
227 else:
228 newdiff.append(line)
229 return newdiff