Debian Codegraph @

py/_code/_assertionnew.py

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