Debian Codegraph @

_pytest/assertion/reinterpret.py

raw symbols SCIP
1 """
2 Find intermediate evalutation results in assert statements through builtin AST.
3 """
4 import ast
5 import sys
6
7 import _pytest._code
8 import py
9 from _pytest.assertion import util
10 u = py.builtin._totext
11
12
13 class AssertionError(util.BuiltinAssertionError):
14 def __init__(self, *args):
15 util.BuiltinAssertionError.__init__(self, *args)
16 if args:
17 # on Python2.6 we get len(args)==2 for: assert 0, (x,y)
18 # on Python2.7 and above we always get len(args) == 1
19 # with args[0] being the (x,y) tuple.
20 if len(args) > 1:
21 toprint = args
22 else:
23 toprint = args[0]
24 try:
25 self.msg = u(toprint)
26 except Exception:
27 self.msg = u(
28 "<[broken __repr__] %s at %0xd>"
29 % (toprint.__class__, id(toprint)))
30 else:
31 f = _pytest._code.Frame(sys._getframe(1))
32 try:
33 source = f.code.fullsource
34 if source is not None:
35 try:
36 source = source.getstatement(f.lineno, assertion=True)
37 except IndexError:
38 source = None
39 else:
40 source = str(source.deindent()).strip()
41 except py.error.ENOENT:
42 source = None
43 # this can also occur during reinterpretation, when the
44 # co_filename is set to "<run>".
45 if source:
46 self.msg = reinterpret(source, f, should_fail=True)
47 else:
48 self.msg = "<could not determine information>"
49 if not self.args:
50 self.args = (self.msg,)
51
52 if sys.version_info > (3, 0):
53 AssertionError.__module__ = "builtins"
54
55 if sys.platform.startswith("java"):
56 # See http://bugs.jython.org/issue1497
57 _exprs = ("BoolOp", "BinOp", "UnaryOp", "Lambda", "IfExp", "Dict",
58 "ListComp", "GeneratorExp", "Yield", "Compare", "Call",
59 "Repr", "Num", "Str", "Attribute", "Subscript", "Name",
60 "List", "Tuple")
61 _stmts = ("FunctionDef", "ClassDef", "Return", "Delete", "Assign",
62 "AugAssign", "Print", "For", "While", "If", "With", "Raise",
63 "TryExcept", "TryFinally", "Assert", "Import", "ImportFrom",
64 "Exec", "Global", "Expr", "Pass", "Break", "Continue")
65 _expr_nodes = set(getattr(ast, name) for name in _exprs)
66 _stmt_nodes = set(getattr(ast, name) for name in _stmts)
67 def _is_ast_expr(node):
68 return node.__class__ in _expr_nodes
69 def _is_ast_stmt(node):
70 return node.__class__ in _stmt_nodes
71 else:
72 def _is_ast_expr(node):
73 return isinstance(node, ast.expr)
74 def _is_ast_stmt(node):
75 return isinstance(node, ast.stmt)
76
77 try:
78 _Starred = ast.Starred
79 except AttributeError:
80 # Python 2. Define a dummy class so isinstance() will always be False.
81 class _Starred(object): pass
82
83
84 class Failure(Exception):
85 """Error found while interpreting AST."""
86
87 def __init__(self, explanation=""):
88 self.cause = sys.exc_info()
89 self.explanation = explanation
90
91
92 def reinterpret(source, frame, should_fail=False):
93 mod = ast.parse(source)
94 visitor = DebugInterpreter(frame)
95 try:
96 visitor.visit(mod)
97 except Failure:
98 failure = sys.exc_info()[1]
99 return getfailure(failure)
100 if should_fail:
101 return ("(assertion failed, but when it was re-run for "
102 "printing intermediate values, it did not fail. Suggestions: "
103 "compute assert expression before the assert or use --assert=plain)")
104
105 def run(offending_line, frame=None):
106 if frame is None:
107 frame = _pytest._code.Frame(sys._getframe(1))
108 return reinterpret(offending_line, frame)
109
110 def getfailure(e):
111 explanation = util.format_explanation(e.explanation)
112 value = e.cause[1]
113 if str(value):
114 lines = explanation.split('\n')
115 lines[0] += " << %s" % (value,)
116 explanation = '\n'.join(lines)
117 text = "%s: %s" % (e.cause[0].__name__, explanation)
118 if text.startswith('AssertionError: assert '):
119 text = text[16:]
120 return text
121
122 operator_map = {
123 ast.BitOr : "|",
124 ast.BitXor : "^",
125 ast.BitAnd : "&",
126 ast.LShift : "<<",
127 ast.RShift : ">>",
128 ast.Add : "+",
129 ast.Sub : "-",
130 ast.Mult : "*",
131 ast.Div : "/",
132 ast.FloorDiv : "//",
133 ast.Mod : "%",
134 ast.Eq : "==",
135 ast.NotEq : "!=",
136 ast.Lt : "<",
137 ast.LtE : "<=",
138 ast.Gt : ">",
139 ast.GtE : ">=",
140 ast.Pow : "**",
141 ast.Is : "is",
142 ast.IsNot : "is not",
143 ast.In : "in",
144 ast.NotIn : "not in"
145 }
146
147 unary_map = {
148 ast.Not : "not %s",
149 ast.Invert : "~%s",
150 ast.USub : "-%s",
151 ast.UAdd : "+%s"
152 }
153
154
155 class DebugInterpreter(ast.NodeVisitor):
156 """Interpret AST nodes to gleam useful debugging information. """
157
158 def __init__(self, frame):
159 self.frame = frame
160
161 def generic_visit(self, node):
162 # Fallback when we don't have a special implementation.
163 if _is_ast_expr(node):
164 mod = ast.Expression(node)
165 co = self._compile(mod)
166 try:
167 result = self.frame.eval(co)
168 except Exception:
169 raise Failure()
170 explanation = self.frame.repr(result)
171 return explanation, result
172 elif _is_ast_stmt(node):
173 mod = ast.Module([node])
174 co = self._compile(mod, "exec")
175 try:
176 self.frame.exec_(co)
177 except Exception:
178 raise Failure()
179 return None, None
180 else:
181 raise AssertionError("can't handle %s" %(node,))
182
183 def _compile(self, source, mode="eval"):
184 return compile(source, "<assertion interpretation>", mode)
185
186 def visit_Expr(self, expr):
187 return self.visit(expr.value)
188
189 def visit_Module(self, mod):
190 for stmt in mod.body:
191 self.visit(stmt)
192
193 def visit_Name(self, name):
194 explanation, result = self.generic_visit(name)
195 # See if the name is local.
196 source = "%r in locals() is not globals()" % (name.id,)
197 co = self._compile(source)
198 try:
199 local = self.frame.eval(co)
200 except Exception:
201 # have to assume it isn't
202 local = None
203 if local is None or not self.frame.is_true(local):
204 return name.id, result
205 return explanation, result
206
207 def visit_Compare(self, comp):
208 left = comp.left
209 left_explanation, left_result = self.visit(left)
210 for op, next_op in zip(comp.ops, comp.comparators):
211 next_explanation, next_result = self.visit(next_op)
212 op_symbol = operator_map[op.__class__]
213 explanation = "%s %s %s" % (left_explanation, op_symbol,
214 next_explanation)
215 source = "__exprinfo_left %s __exprinfo_right" % (op_symbol,)
216 co = self._compile(source)
217 try:
218 result = self.frame.eval(co, __exprinfo_left=left_result,
219 __exprinfo_right=next_result)
220 except Exception:
221 raise Failure(explanation)
222 try:
223 if not self.frame.is_true(result):
224 break
225 except KeyboardInterrupt:
226 raise
227 except:
228 break
229 left_explanation, left_result = next_explanation, next_result
230
231 if util._reprcompare is not None:
232 res = util._reprcompare(op_symbol, left_result, next_result)
233 if res:
234 explanation = res
235 return explanation, result
236
237 def visit_BoolOp(self, boolop):
238 is_or = isinstance(boolop.op, ast.Or)
239 explanations = []
240 for operand in boolop.values:
241 explanation, result = self.visit(operand)
242 explanations.append(explanation)
243 if result == is_or:
244 break
245 name = is_or and " or " or " and "
246 explanation = "(" + name.join(explanations) + ")"
247 return explanation, result
248
249 def visit_UnaryOp(self, unary):
250 pattern = unary_map[unary.op.__class__]
251 operand_explanation, operand_result = self.visit(unary.operand)
252 explanation = pattern % (operand_explanation,)
253 co = self._compile(pattern % ("__exprinfo_expr",))
254 try:
255 result = self.frame.eval(co, __exprinfo_expr=operand_result)
256 except Exception:
257 raise Failure(explanation)
258 return explanation, result
259
260 def visit_BinOp(self, binop):
261 left_explanation, left_result = self.visit(binop.left)
262 right_explanation, right_result = self.visit(binop.right)
263 symbol = operator_map[binop.op.__class__]
264 explanation = "(%s %s %s)" % (left_explanation, symbol,
265 right_explanation)
266 source = "__exprinfo_left %s __exprinfo_right" % (symbol,)
267 co = self._compile(source)
268 try:
269 result = self.frame.eval(co, __exprinfo_left=left_result,
270 __exprinfo_right=right_result)
271 except Exception:
272 raise Failure(explanation)
273 return explanation, result
274
275 def visit_Call(self, call):
276 func_explanation, func = self.visit(call.func)
277 arg_explanations = []
278 ns = {"__exprinfo_func" : func}
279 arguments = []
280 for arg in call.args:
281 arg_explanation, arg_result = self.visit(arg)
282 if isinstance(arg, _Starred):
283 arg_name = "__exprinfo_star"
284 ns[arg_name] = arg_result
285 arguments.append("*%s" % (arg_name,))
286 arg_explanations.append("*%s" % (arg_explanation,))
287 else:
288 arg_name = "__exprinfo_%s" % (len(ns),)
289 ns[arg_name] = arg_result
290 arguments.append(arg_name)
291 arg_explanations.append(arg_explanation)
292 for keyword in call.keywords:
293 arg_explanation, arg_result = self.visit(keyword.value)
294 if keyword.arg:
295 arg_name = "__exprinfo_%s" % (len(ns),)
296 keyword_source = "%s=%%s" % (keyword.arg)
297 arguments.append(keyword_source % (arg_name,))
298 arg_explanations.append(keyword_source % (arg_explanation,))
299 else:
300 arg_name = "__exprinfo_kwds"
301 arguments.append("**%s" % (arg_name,))
302 arg_explanations.append("**%s" % (arg_explanation,))
303
304 ns[arg_name] = arg_result
305
306 if getattr(call, 'starargs', None):
307 arg_explanation, arg_result = self.visit(call.starargs)
308 arg_name = "__exprinfo_star"
309 ns[arg_name] = arg_result
310 arguments.append("*%s" % (arg_name,))
311 arg_explanations.append("*%s" % (arg_explanation,))
312
313 if getattr(call, 'kwargs', None):
314 arg_explanation, arg_result = self.visit(call.kwargs)
315 arg_name = "__exprinfo_kwds"
316 ns[arg_name] = arg_result
317 arguments.append("**%s" % (arg_name,))
318 arg_explanations.append("**%s" % (arg_explanation,))
319 args_explained = ", ".join(arg_explanations)
320 explanation = "%s(%s)" % (func_explanation, args_explained)
321 args = ", ".join(arguments)
322 source = "__exprinfo_func(%s)" % (args,)
323 co = self._compile(source)
324 try:
325 result = self.frame.eval(co, **ns)
326 except Exception:
327 raise Failure(explanation)
328 pattern = "%s\n{%s = %s\n}"
329 rep = self.frame.repr(result)
330 explanation = pattern % (rep, rep, explanation)
331 return explanation, result
332
333 def _is_builtin_name(self, name):
334 pattern = "%r not in globals() and %r not in locals()"
335 source = pattern % (name.id, name.id)
336 co = self._compile(source)
337 try:
338 return self.frame.eval(co)
339 except Exception:
340 return False
341
342 def visit_Attribute(self, attr):
343 if not isinstance(attr.ctx, ast.Load):
344 return self.generic_visit(attr)
345 source_explanation, source_result = self.visit(attr.value)
346 explanation = "%s.%s" % (source_explanation, attr.attr)
347 source = "__exprinfo_expr.%s" % (attr.attr,)
348 co = self._compile(source)
349 try:
350 try:
351 result = self.frame.eval(co, __exprinfo_expr=source_result)
352 except AttributeError:
353 # Maybe the attribute name needs to be mangled?
354 if not attr.attr.startswith("__") or attr.attr.endswith("__"):
355 raise
356 source = "getattr(__exprinfo_expr.__class__, '__name__', '')"
357 co = self._compile(source)
358 class_name = self.frame.eval(co, __exprinfo_expr=source_result)
359 mangled_attr = "_" + class_name + attr.attr
360 source = "__exprinfo_expr.%s" % (mangled_attr,)
361 co = self._compile(source)
362 result = self.frame.eval(co, __exprinfo_expr=source_result)
363 except Exception:
364 raise Failure(explanation)
365 explanation = "%s\n{%s = %s.%s\n}" % (self.frame.repr(result),
366 self.frame.repr(result),
367 source_explanation, attr.attr)
368 # Check if the attr is from an instance.
369 source = "%r in getattr(__exprinfo_expr, '__dict__', {})"
370 source = source % (attr.attr,)
371 co = self._compile(source)
372 try:
373 from_instance = self.frame.eval(co, __exprinfo_expr=source_result)
374 except Exception:
375 from_instance = None
376 if from_instance is None or self.frame.is_true(from_instance):
377 rep = self.frame.repr(result)
378 pattern = "%s\n{%s = %s\n}"
379 explanation = pattern % (rep, rep, explanation)
380 return explanation, result
381
382 def visit_Assert(self, assrt):
383 test_explanation, test_result = self.visit(assrt.test)
384 explanation = "assert %s" % (test_explanation,)
385 if not self.frame.is_true(test_result):
386 try:
387 raise util.BuiltinAssertionError
388 except Exception:
389 raise Failure(explanation)
390 return explanation, test_result
391
392 def visit_Assign(self, assign):
393 value_explanation, value_result = self.visit(assign.value)
394 explanation = "... = %s" % (value_explanation,)
395 name = ast.Name("__exprinfo_expr", ast.Load(),
396 lineno=assign.value.lineno,
397 col_offset=assign.value.col_offset)
398 new_assign = ast.Assign(assign.targets, name, lineno=assign.lineno,
399 col_offset=assign.col_offset)
400 mod = ast.Module([new_assign])
401 co = self._compile(mod, "exec")
402 try:
403 self.frame.exec_(co, __exprinfo_expr=value_result)
404 except Exception:
405 raise Failure(explanation)
406 return explanation, value_result
407