Debian Codegraph @

pypy/tool/pytest/astrewriter/ast_rewrite.py

raw symbols SCIP
1 """Rewrite assertion AST to produce nice error messages"""
2 from pypy.interpreter.astcompiler import ast
3 import itertools
4
5
6 def rewrite_asserts(space, source, filename):
7 """Parse the source code and rewrite asserts statements
8
9 Returns a module object.
10 """
11 c = space.createcompiler()
12 tree = c.compile_to_ast(source, filename, "exec", 0)
13 AssertionRewriter(space).run(tree)
14 co = c.compile_ast(tree, filename, 'exec', 0)
15 return co
16
17 def rewrite_asserts_ast(space, tree):
18 AssertionRewriter(space).run(tree)
19 return tree
20
21
22 unary_map = {
23 ast.Not: "not %s",
24 ast.Invert: "~%s",
25 ast.USub: "-%s",
26 ast.UAdd: "+%s"
27 }
28
29 binop_map = {
30 ast.BitOr: "|",
31 ast.BitXor: "^",
32 ast.BitAnd: "&",
33 ast.LShift: "<<",
34 ast.RShift: ">>",
35 ast.Add: "+",
36 ast.Sub: "-",
37 ast.Mult: "*",
38 ast.Div: "/",
39 ast.FloorDiv: "//",
40 ast.Mod: "%%", # escaped for string formatting
41 ast.Eq: "==",
42 ast.NotEq: "!=",
43 ast.Lt: "<",
44 ast.LtE: "<=",
45 ast.Gt: ">",
46 ast.GtE: ">=",
47 ast.Pow: "**",
48 ast.Is: "is",
49 ast.IsNot: "is not",
50 ast.In: "in",
51 ast.NotIn: "not in",
52 ast.MatMult: "@",
53 }
54
55
56 def set_location(node, lineno, col_offset):
57 """Set node location information recursively."""
58 def _fix(node, lineno, col_offset):
59 if hasattr(node, "lineno"):
60 node.lineno = lineno
61 if hasattr(node, "col_offset"):
62 node.col_offset = col_offset
63 for field, value in iter_fields(node):
64 if isinstance(value, list):
65 for child in value:
66 _fix(child, lineno, col_offset)
67 _fix(node, lineno, col_offset)
68 return node
69
70 FIELDS = {name: (fields1 or []) + (fields2 or [])
71 for (name, base, fields1, fields2, _, _) in ast.State.AST_TYPES}
72
73 def iter_fields(node):
74 fields = FIELDS[type(node).__name__]
75 for name in fields:
76 yield name, getattr(node, name)
77
78 def b(cls, *args):
79 return cls(*args + (-1, -1, -1, -1))
80
81 class AssertionRewriter(ast.ASTVisitor):
82 """Assertion rewriting implementation.
83
84 The main entrypoint is to call .run() with an ast.Module instance,
85 this will then find all the assert statements and rewrite them to
86 provide intermediate values and a detailed assertion error. See
87 http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html
88 for an overview of how this works.
89
90 The entry point here is .run() which will iterate over all the
91 statements in an ast.Module and for each ast.Assert statement it
92 finds call .visit() with it. Then .visit_Assert() takes over and
93 is responsible for creating new ast statements to replace the
94 original assert statement: it rewrites the test of an assertion
95 to provide intermediate values and replace it with an if statement
96 which raises an assertion error with a detailed explanation in
97 case the expression is false.
98
99 For this .visit_Assert() uses the visitor pattern to visit all the
100 AST nodes of the ast.Assert.test field, each visit call returning
101 an AST node and the corresponding explanation string. During this
102 state is kept in several instance attributes:
103
104 :statements: All the AST statements which will replace the assert
105 statement.
106
107 :variables: This is populated by .variable() with each variable
108 used by the statements so that they can all be set to None at
109 the end of the statements.
110
111 :variable_counter: Counter to create new unique variables needed
112 by statements. Variables are created using .variable() and
113 have the form of "@py_assert0".
114
115 :on_failure: The AST statements which will be executed if the
116 assertion test fails. This is the code which will construct
117 the failure message and raises the AssertionError.
118
119 :explanation_specifiers: A dict filled by .explanation_param()
120 with %-formatting placeholders and their corresponding
121 expressions to use in the building of an assertion message.
122 This is used by .pop_format_context() to build a message.
123
124 :stack: A stack of the explanation_specifiers dicts maintained by
125 .push_format_context() and .pop_format_context() which allows
126 to build another %-formatted string while already building one.
127
128 This state is reset on every new assert statement visited and used
129 by the other visitors.
130
131 """
132
133 def __init__(self, space):
134 self.space = space
135
136 def visit(self, node):
137 return getattr(self, "visit_" + type(node).__name__, self.default_visitor)(node)
138
139 def Str(self, s):
140 return b(ast.Constant, self.space.newtext(s), None)
141
142 def Num(self, i):
143 return b(ast.Constant, self.space.newint(i), None)
144
145 def run(self, mod):
146 """Find all assert statements in *mod* and rewrite them."""
147 if not mod.body:
148 # Nothing to do.
149 return
150 # Insert some special imports at the top of the module but after any
151 # docstrings and __future__ imports.
152 builtin_name = 'builtins'
153 aliases = [ast.alias(builtin_name, "@py_builtins", 0, 0, 0, 0),
154 ast.alias("pytest", "@pytest", 0, 0, 0, 0)]
155 doc = getattr(mod, "docstring", None)
156 expect_docstring = doc is None
157 if doc is not None and self.is_rewrite_disabled(doc):
158 return
159 pos = 0
160 lineno = 1
161 for item in mod.body:
162 if (expect_docstring and isinstance(item, ast.Expr) and
163 isinstance(item.value, ast.Constant) and
164 self.space.isinstance_w(item.value.value, self.space.w_unicode)):
165 doc = item.value.value
166 if self.is_rewrite_disabled(doc):
167 return
168 expect_docstring = False
169 elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
170 item.module != "__future__"):
171 lineno = item.lineno
172 break
173 pos += 1
174 else:
175 lineno = item.lineno
176 imports = [ast.Import([alias], lineno=lineno, col_offset=0, end_lineno=lineno, end_col_offset=0)
177 for alias in aliases]
178 mod.body[pos:pos] = imports
179 # Collect asserts.
180 nodes = [mod]
181 while nodes:
182 node = nodes.pop()
183 for name, field in iter_fields(node):
184 if isinstance(field, list):
185 new = []
186 for i, child in enumerate(field):
187 if isinstance(child, ast.Assert):
188 # Transform assert.
189 new.extend(self.visit(child))
190 else:
191 new.append(child)
192 if isinstance(child, ast.AST):
193 nodes.append(child)
194 setattr(node, name, new)
195 elif (isinstance(field, ast.AST) and
196 # Don't recurse into expressions as they can't contain
197 # asserts.
198 not isinstance(field, ast.expr)):
199 nodes.append(field)
200
201 def is_rewrite_disabled(self, docstring):
202 return "PYTEST_DONT_REWRITE" in self.space.text_w(docstring)
203
204 def variable(self):
205 """Get a new variable."""
206 # Use a character invalid in python identifiers to avoid clashing.
207 name = "@py_assert" + str(next(self.variable_counter))
208 self.variables.append(name)
209 return name
210
211 def assign(self, expr):
212 """Give *expr* a name."""
213 name = self.variable()
214 self.statements.append(b(ast.Assign, [b(ast.Name, name, ast.Store)], expr, None))
215 return b(ast.Name, name, ast.Load)
216
217 def display(self, expr):
218 """Call py.io.saferepr on the expression."""
219 return self.helper("saferepr", expr)
220
221 def helper(self, name, *args):
222 """Call a helper in this module."""
223 py_name = b(ast.Name, "@pytest", ast.Load)
224 attr = b(ast.Attribute, py_name, "ar_" + name, ast.Load)
225 return b(ast.Call, attr, list(args), [])
226
227 def builtin(self, name):
228 """Return the builtin called *name*."""
229 builtin_name = b(ast.Name, "@py_builtins", ast.Load)
230 return b(ast.Attribute, builtin_name, name, ast.Load)
231
232 def explanation_param(self, expr):
233 """Return a new named %-formatting placeholder for expr.
234
235 This creates a %-formatting placeholder for expr in the
236 current formatting context, e.g. ``%(py0)s``. The placeholder
237 and expr are placed in the current format context so that it
238 can be used on the next call to .pop_format_context().
239
240 """
241 specifier = "py" + str(next(self.variable_counter))
242 self.explanation_specifiers[specifier] = expr
243 return "%(" + specifier + ")s"
244
245 def push_format_context(self):
246 """Create a new formatting context.
247
248 The format context is used for when an explanation wants to
249 have a variable value formatted in the assertion message. In
250 this case the value required can be added using
251 .explanation_param(). Finally .pop_format_context() is used
252 to format a string of %-formatted values as added by
253 .explanation_param().
254
255 """
256 self.explanation_specifiers = {}
257 self.stack.append(self.explanation_specifiers)
258
259 def pop_format_context(self, expl_expr):
260 """Format the %-formatted string with current format context.
261
262 The expl_expr should be an ast.Str instance constructed from
263 the %-placeholders created by .explanation_param(). This will
264 add the required code to format said string to .on_failure and
265 return the ast.Name instance of the formatted string.
266
267 """
268 current = self.stack.pop()
269 if self.stack:
270 self.explanation_specifiers = self.stack[-1]
271 keys = [self.Str(key) for key in current.keys()]
272 format_dict = b(ast.Dict, keys, list(current.values()))
273 form = b(ast.BinOp, expl_expr, ast.Mod, format_dict)
274 name = "@py_format" + str(next(self.variable_counter))
275 self.on_failure.append(b(ast.Assign, [b(ast.Name, name, ast.Store)], form, None))
276 return b(ast.Name, name, ast.Load)
277
278 def default_visitor(self, node):
279 """Handle expressions we don't have custom code for."""
280 assert isinstance(node, ast.expr)
281 res = self.assign(node)
282 return res, self.explanation_param(self.display(res))
283
284 def visit_Assert(self, assert_):
285 """Return the AST statements to replace the ast.Assert instance.
286
287 This rewrites the test of an assertion to provide
288 intermediate values and replace it with an if statement which
289 raises an assertion error with a detailed explanation in case
290 the expression is false.
291
292 """
293 self.statements = []
294 self.variables = []
295 self.variable_counter = itertools.count()
296 self.stack = []
297 self.on_failure = []
298 self.push_format_context()
299 # Rewrite assert into a bunch of statements.
300 top_condition, explanation = self.visit(assert_.test)
301 # Create failure message.
302 body = self.on_failure
303 negation = b(ast.UnaryOp, ast.Not, top_condition)
304 self.statements.append(b(ast.If, negation, body, []))
305 if assert_.msg:
306 assertmsg = self.helper('format_assertmsg', assert_.msg)
307 explanation = "\n>assert " + explanation
308 else:
309 assertmsg = self.Str("")
310 explanation = "assert " + explanation
311 template = b(ast.BinOp, assertmsg, ast.Add, self.Str(explanation))
312 msg = self.pop_format_context(template)
313 fmt = self.helper("format_explanation", msg)
314 err_name = b(ast.Name, "AssertionError", ast.Load)
315 exc = b(ast.Call, err_name, [fmt], [])
316 raise_ = b(ast.Raise, exc, None)
317 body.append(raise_)
318 # Clear temporary variables by setting them to None.
319 if self.variables:
320 variables = [b(ast.Name, name, ast.Store)
321 for name in self.variables]
322 clear = b(ast.Assign, variables, b(ast.Constant, self.space.w_None, None), None)
323 self.statements.append(clear)
324 # Fix line numbers.
325 for stmt in self.statements:
326 set_location(stmt, assert_.lineno, assert_.col_offset)
327 return self.statements
328
329 def visit_Name(self, name):
330 # Display the repr of the name if it's a local variable or
331 # _should_repr_global_name() thinks it's acceptable.
332 locs = b(ast.Call, self.builtin("locals"), [], [])
333 inlocs = b(ast.Compare, self.Str(name.id), [ast.In], [locs])
334 dorepr = self.helper("should_repr_global_name", name)
335 test = b(ast.BoolOp, ast.Or, [inlocs, dorepr])
336 expr = b(ast.IfExp, test, self.display(name), self.Str(name.id))
337 return name, self.explanation_param(expr)
338
339 def visit_BoolOp(self, boolop):
340 res_var = self.variable()
341 expl_list = self.assign(b(ast.List, [], ast.Load))
342 app = b(ast.Attribute, expl_list, "append", ast.Load)
343 is_or = boolop.op == ast.Or
344 body = save = self.statements
345 fail_save = self.on_failure
346 levels = len(boolop.values) - 1
347 self.push_format_context()
348 # Process each operand, short-circuting if needed.
349 for i, v in enumerate(boolop.values):
350 if i:
351 fail_inner = []
352 # cond is set in a prior loop iteration below
353 self.on_failure.append(b(ast.If, cond, fail_inner, [])) # noqa
354 self.on_failure = fail_inner
355 self.push_format_context()
356 res, expl = self.visit(v)
357 body.append(b(ast.Assign, [b(ast.Name, res_var, ast.Store)], res, None))
358 expl_format = self.pop_format_context(self.Str(expl))
359 call = b(ast.Call, app, [expl_format], [])
360 self.on_failure.append(b(ast.Expr, call))
361 if i < levels:
362 cond = res
363 if is_or:
364 cond = b(ast.UnaryOp, ast.Not, cond)
365 inner = []
366 self.statements.append(b(ast.If, cond, inner, []))
367 self.statements = body = inner
368 self.statements = save
369 self.on_failure = fail_save
370 expl_template = self.helper("format_boolop", expl_list, self.Num(is_or))
371 expl = self.pop_format_context(expl_template)
372 return b(ast.Name, res_var, ast.Load), self.explanation_param(expl)
373
374 def visit_UnaryOp(self, unary):
375 pattern = unary_map[unary.op]
376 operand_res, operand_expl = self.visit(unary.operand)
377 res = self.assign(b(ast.UnaryOp, unary.op, operand_res))
378 return res, pattern % (operand_expl,)
379
380 def visit_BinOp(self, binop):
381 symbol = binop_map[binop.op]
382 left_expr, left_expl = self.visit(binop.left)
383 right_expr, right_expl = self.visit(binop.right)
384 explanation = "(%s %s %s)" % (left_expl, symbol, right_expl)
385 res = self.assign(b(ast.BinOp, left_expr, binop.op, right_expr))
386 return res, explanation
387
388 def visit_Call(self, call):
389 """
390 visit `ast.Call` nodes on Python3.5 and after
391 """
392 new_func, func_expl = self.visit(call.func)
393 arg_expls = []
394 new_args = []
395 new_kwargs = []
396 for arg in call.args or []:
397 res, expl = self.visit(arg)
398 arg_expls.append(expl)
399 new_args.append(res)
400 for keyword in call.keywords or []:
401 res, expl = self.visit(keyword.value)
402 new_kwargs.append(b(ast.keyword, keyword.arg, res))
403 if keyword.arg:
404 arg_expls.append(keyword.arg + "=" + expl)
405 else: # **args have `arg` keywords with an .arg of None
406 arg_expls.append("**" + expl)
407
408 expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
409 new_call = b(ast.Call, new_func, new_args, new_kwargs)
410 res = self.assign(new_call)
411 res_expl = self.explanation_param(self.display(res))
412 outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
413 return res, outer_expl
414
415 def visit_Starred(self, starred):
416 # From Python 3.5, a Starred node can appear in a function call
417 res, expl = self.visit(starred.value)
418 return starred, '*' + expl
419
420 def visit_Attribute(self, attr):
421 if attr.ctx != ast.Load:
422 return self.default_visitor(attr)
423 value, value_expl = self.visit(attr.value)
424 res = self.assign(b(ast.Attribute, value, attr.attr, ast.Load))
425 res_expl = self.explanation_param(self.display(res))
426 pat = "%s\n{%s = %s.%s\n}"
427 expl = pat % (res_expl, res_expl, value_expl, attr.attr)
428 return res, expl
429
430 def visit_Compare(self, comp):
431 self.push_format_context()
432 left_res, left_expl = self.visit(comp.left)
433 if isinstance(comp.left, (ast.Compare, ast.BoolOp)):
434 left_expl = "({0})".format(left_expl)
435 res_variables = [self.variable() for i in range(len(comp.ops))]
436 load_names = [b(ast.Name, v, ast.Load) for v in res_variables]
437 store_names = [b(ast.Name, v, ast.Store) for v in res_variables]
438 it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
439 expls = []
440 syms = []
441 results = [left_res]
442 for i, op, next_operand in it:
443 next_res, next_expl = self.visit(next_operand)
444 if isinstance(next_operand, (ast.Compare, ast.BoolOp)):
445 next_expl = "({0})".format(next_expl)
446 results.append(next_res)
447 sym = binop_map[op]
448 syms.append(self.Str(sym))
449 expl = "%s %s %s" % (left_expl, sym, next_expl)
450 expls.append(self.Str(expl))
451 res_expr = b(ast.Compare, left_res, [op], [next_res])
452 self.statements.append(b(ast.Assign, [store_names[i]], res_expr, None))
453 left_res, left_expl = next_res, next_expl
454 # Use pytest.assertion.util._reprcompare if that's available.
455 expl_call = self.helper("call_reprcompare",
456 b(ast.Tuple, syms, ast.Load),
457 b(ast.Tuple, load_names, ast.Load),
458 b(ast.Tuple, expls, ast.Load),
459 b(ast.Tuple, results, ast.Load))
460 if len(comp.ops) > 1:
461 res = b(ast.BoolOp, ast.And, load_names)
462 else:
463 res = load_names[0]
464 return res, self.explanation_param(self.pop_format_context(expl_call))