Debian Codegraph @

_pytest/assertion/rewrite.py

raw symbols SCIP
1 """Rewrite assertion AST to produce nice error messages"""
2
3 import ast
4 import errno
5 import itertools
6 import imp
7 import marshal
8 import os
9 import re
10 import struct
11 import sys
12 import types
13
14 import py
15 from _pytest.assertion import util
16
17
18 # pytest caches rewritten pycs in __pycache__.
19 if hasattr(imp, "get_tag"):
20 PYTEST_TAG = imp.get_tag() + "-PYTEST"
21 else:
22 if hasattr(sys, "pypy_version_info"):
23 impl = "pypy"
24 elif sys.platform == "java":
25 impl = "jython"
26 else:
27 impl = "cpython"
28 ver = sys.version_info
29 PYTEST_TAG = "%s-%s%s-PYTEST" % (impl, ver[0], ver[1])
30 del ver, impl
31
32 PYC_EXT = ".py" + (__debug__ and "c" or "o")
33 PYC_TAIL = "." + PYTEST_TAG + PYC_EXT
34
35 REWRITE_NEWLINES = sys.version_info[:2] != (2, 7) and sys.version_info < (3, 2)
36 ASCII_IS_DEFAULT_ENCODING = sys.version_info[0] < 3
37
38 if sys.version_info >= (3,5):
39 ast_Call = ast.Call
40 else:
41 ast_Call = lambda a,b,c: ast.Call(a, b, c, None, None)
42
43
44 class AssertionRewritingHook(object):
45 """PEP302 Import hook which rewrites asserts."""
46
47 def __init__(self):
48 self.session = None
49 self.modules = {}
50 self._register_with_pkg_resources()
51
52 def set_session(self, session):
53 self.fnpats = session.config.getini("python_files")
54 self.session = session
55
56 def find_module(self, name, path=None):
57 if self.session is None:
58 return None
59 sess = self.session
60 state = sess.config._assertstate
61 state.trace("find_module called for: %s" % name)
62 names = name.rsplit(".", 1)
63 lastname = names[-1]
64 pth = None
65 if path is not None:
66 # Starting with Python 3.3, path is a _NamespacePath(), which
67 # causes problems if not converted to list.
68 path = list(path)
69 if len(path) == 1:
70 pth = path[0]
71 if pth is None:
72 try:
73 fd, fn, desc = imp.find_module(lastname, path)
74 except ImportError:
75 return None
76 if fd is not None:
77 fd.close()
78 tp = desc[2]
79 if tp == imp.PY_COMPILED:
80 if hasattr(imp, "source_from_cache"):
81 fn = imp.source_from_cache(fn)
82 else:
83 fn = fn[:-1]
84 elif tp != imp.PY_SOURCE:
85 # Don't know what this is.
86 return None
87 else:
88 fn = os.path.join(pth, name.rpartition(".")[2] + ".py")
89 fn_pypath = py.path.local(fn)
90 # Is this a test file?
91 if not sess.isinitpath(fn):
92 # We have to be very careful here because imports in this code can
93 # trigger a cycle.
94 self.session = None
95 try:
96 for pat in self.fnpats:
97 if fn_pypath.fnmatch(pat):
98 state.trace("matched test file %r" % (fn,))
99 break
100 else:
101 return None
102 finally:
103 self.session = sess
104 else:
105 state.trace("matched test file (was specified on cmdline): %r" %
106 (fn,))
107 # The requested module looks like a test file, so rewrite it. This is
108 # the most magical part of the process: load the source, rewrite the
109 # asserts, and load the rewritten source. We also cache the rewritten
110 # module code in a special pyc. We must be aware of the possibility of
111 # concurrent pytest processes rewriting and loading pycs. To avoid
112 # tricky race conditions, we maintain the following invariant: The
113 # cached pyc is always a complete, valid pyc. Operations on it must be
114 # atomic. POSIX's atomic rename comes in handy.
115 write = not sys.dont_write_bytecode
116 cache_dir = os.path.join(fn_pypath.dirname, "__pycache__")
117 if write:
118 try:
119 os.mkdir(cache_dir)
120 except OSError:
121 e = sys.exc_info()[1].errno
122 if e == errno.EEXIST:
123 # Either the __pycache__ directory already exists (the
124 # common case) or it's blocked by a non-dir node. In the
125 # latter case, we'll ignore it in _write_pyc.
126 pass
127 elif e in [errno.ENOENT, errno.ENOTDIR]:
128 # One of the path components was not a directory, likely
129 # because we're in a zip file.
130 write = False
131 elif e in [errno.EACCES, errno.EROFS, errno.EPERM]:
132 state.trace("read only directory: %r" % fn_pypath.dirname)
133 write = False
134 else:
135 raise
136 cache_name = fn_pypath.basename[:-3] + PYC_TAIL
137 pyc = os.path.join(cache_dir, cache_name)
138 # Notice that even if we're in a read-only directory, I'm going
139 # to check for a cached pyc. This may not be optimal...
140 co = _read_pyc(fn_pypath, pyc, state.trace)
141 if co is None:
142 state.trace("rewriting %r" % (fn,))
143 source_stat, co = _rewrite_test(state, fn_pypath)
144 if co is None:
145 # Probably a SyntaxError in the test.
146 return None
147 if write:
148 _make_rewritten_pyc(state, source_stat, pyc, co)
149 else:
150 state.trace("found cached rewritten pyc for %r" % (fn,))
151 self.modules[name] = co, pyc
152 return self
153
154 def load_module(self, name):
155 # If there is an existing module object named 'fullname' in
156 # sys.modules, the loader must use that existing module. (Otherwise,
157 # the reload() builtin will not work correctly.)
158 if name in sys.modules:
159 return sys.modules[name]
160
161 co, pyc = self.modules.pop(name)
162 # I wish I could just call imp.load_compiled here, but __file__ has to
163 # be set properly. In Python 3.2+, this all would be handled correctly
164 # by load_compiled.
165 mod = sys.modules[name] = imp.new_module(name)
166 try:
167 mod.__file__ = co.co_filename
168 # Normally, this attribute is 3.2+.
169 mod.__cached__ = pyc
170 mod.__loader__ = self
171 py.builtin.exec_(co, mod.__dict__)
172 except:
173 del sys.modules[name]
174 raise
175 return sys.modules[name]
176
177
178
179 def is_package(self, name):
180 try:
181 fd, fn, desc = imp.find_module(name)
182 except ImportError:
183 return False
184 if fd is not None:
185 fd.close()
186 tp = desc[2]
187 return tp == imp.PKG_DIRECTORY
188
189 @classmethod
190 def _register_with_pkg_resources(cls):
191 """
192 Ensure package resources can be loaded from this loader. May be called
193 multiple times, as the operation is idempotent.
194 """
195 try:
196 import pkg_resources
197 # access an attribute in case a deferred importer is present
198 pkg_resources.__name__
199 except ImportError:
200 return
201
202 # Since pytest tests are always located in the file system, the
203 # DefaultProvider is appropriate.
204 pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider)
205
206 def get_data(self, pathname):
207 """Optional PEP302 get_data API.
208 """
209 with open(pathname, 'rb') as f:
210 return f.read()
211
212
213 def _write_pyc(state, co, source_stat, pyc):
214 # Technically, we don't have to have the same pyc format as
215 # (C)Python, since these "pycs" should never be seen by builtin
216 # import. However, there's little reason deviate, and I hope
217 # sometime to be able to use imp.load_compiled to load them. (See
218 # the comment in load_module above.)
219 try:
220 fp = open(pyc, "wb")
221 except IOError:
222 err = sys.exc_info()[1].errno
223 state.trace("error writing pyc file at %s: errno=%s" %(pyc, err))
224 # we ignore any failure to write the cache file
225 # there are many reasons, permission-denied, __pycache__ being a
226 # file etc.
227 return False
228 try:
229 fp.write(imp.get_magic())
230 mtime = int(source_stat.mtime)
231 size = source_stat.size & 0xFFFFFFFF
232 fp.write(struct.pack("<ll", mtime, size))
233 marshal.dump(co, fp)
234 finally:
235 fp.close()
236 return True
237
238 RN = "\r\n".encode("utf-8")
239 N = "\n".encode("utf-8")
240
241 cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+")
242 BOM_UTF8 = '\xef\xbb\xbf'
243
244 def _rewrite_test(state, fn):
245 """Try to read and rewrite *fn* and return the code object."""
246 try:
247 stat = fn.stat()
248 source = fn.read("rb")
249 except EnvironmentError:
250 return None, None
251 if ASCII_IS_DEFAULT_ENCODING:
252 # ASCII is the default encoding in Python 2. Without a coding
253 # declaration, Python 2 will complain about any bytes in the file
254 # outside the ASCII range. Sadly, this behavior does not extend to
255 # compile() or ast.parse(), which prefer to interpret the bytes as
256 # latin-1. (At least they properly handle explicit coding cookies.) To
257 # preserve this error behavior, we could force ast.parse() to use ASCII
258 # as the encoding by inserting a coding cookie. Unfortunately, that
259 # messes up line numbers. Thus, we have to check ourselves if anything
260 # is outside the ASCII range in the case no encoding is explicitly
261 # declared. For more context, see issue #269. Yay for Python 3 which
262 # gets this right.
263 end1 = source.find("\n")
264 end2 = source.find("\n", end1 + 1)
265 if (not source.startswith(BOM_UTF8) and
266 cookie_re.match(source[0:end1]) is None and
267 cookie_re.match(source[end1 + 1:end2]) is None):
268 if hasattr(state, "_indecode"):
269 # encodings imported us again, so don't rewrite.
270 return None, None
271 state._indecode = True
272 try:
273 try:
274 source.decode("ascii")
275 except UnicodeDecodeError:
276 # Let it fail in real import.
277 return None, None
278 finally:
279 del state._indecode
280 # On Python versions which are not 2.7 and less than or equal to 3.1, the
281 # parser expects *nix newlines.
282 if REWRITE_NEWLINES:
283 source = source.replace(RN, N) + N
284 try:
285 tree = ast.parse(source)
286 except SyntaxError:
287 # Let this pop up again in the real import.
288 state.trace("failed to parse: %r" % (fn,))
289 return None, None
290 rewrite_asserts(tree)
291 try:
292 co = compile(tree, fn.strpath, "exec")
293 except SyntaxError:
294 # It's possible that this error is from some bug in the
295 # assertion rewriting, but I don't know of a fast way to tell.
296 state.trace("failed to compile: %r" % (fn,))
297 return None, None
298 return stat, co
299
300 def _make_rewritten_pyc(state, source_stat, pyc, co):
301 """Try to dump rewritten code to *pyc*."""
302 if sys.platform.startswith("win"):
303 # Windows grants exclusive access to open files and doesn't have atomic
304 # rename, so just write into the final file.
305 _write_pyc(state, co, source_stat, pyc)
306 else:
307 # When not on windows, assume rename is atomic. Dump the code object
308 # into a file specific to this process and atomically replace it.
309 proc_pyc = pyc + "." + str(os.getpid())
310 if _write_pyc(state, co, source_stat, proc_pyc):
311 os.rename(proc_pyc, pyc)
312
313 def _read_pyc(source, pyc, trace=lambda x: None):
314 """Possibly read a pytest pyc containing rewritten code.
315
316 Return rewritten code if successful or None if not.
317 """
318 try:
319 fp = open(pyc, "rb")
320 except IOError:
321 return None
322 with fp:
323 try:
324 mtime = int(source.mtime())
325 size = source.size()
326 data = fp.read(12)
327 except EnvironmentError as e:
328 trace('_read_pyc(%s): EnvironmentError %s' % (source, e))
329 return None
330 # Check for invalid or out of date pyc file.
331 if (len(data) != 12 or data[:4] != imp.get_magic() or
332 struct.unpack("<ll", data[4:]) != (mtime, size)):
333 trace('_read_pyc(%s): invalid or out of date pyc' % source)
334 return None
335 try:
336 co = marshal.load(fp)
337 except Exception as e:
338 trace('_read_pyc(%s): marshal.load error %s' % (source, e))
339 return None
340 if not isinstance(co, types.CodeType):
341 trace('_read_pyc(%s): not a code object' % source)
342 return None
343 return co
344
345
346 def rewrite_asserts(mod):
347 """Rewrite the assert statements in mod."""
348 AssertionRewriter().run(mod)
349
350
351 def _saferepr(obj):
352 """Get a safe repr of an object for assertion error messages.
353
354 The assertion formatting (util.format_explanation()) requires
355 newlines to be escaped since they are a special character for it.
356 Normally assertion.util.format_explanation() does this but for a
357 custom repr it is possible to contain one of the special escape
358 sequences, especially '\n{' and '\n}' are likely to be present in
359 JSON reprs.
360
361 """
362 repr = py.io.saferepr(obj)
363 if py.builtin._istext(repr):
364 t = py.builtin.text
365 else:
366 t = py.builtin.bytes
367 return repr.replace(t("\n"), t("\\n"))
368
369
370 from _pytest.assertion.util import format_explanation as _format_explanation # noqa
371
372 def _format_assertmsg(obj):
373 """Format the custom assertion message given.
374
375 For strings this simply replaces newlines with '\n~' so that
376 util.format_explanation() will preserve them instead of escaping
377 newlines. For other objects py.io.saferepr() is used first.
378
379 """
380 # reprlib appears to have a bug which means that if a string
381 # contains a newline it gets escaped, however if an object has a
382 # .__repr__() which contains newlines it does not get escaped.
383 # However in either case we want to preserve the newline.
384 if py.builtin._istext(obj) or py.builtin._isbytes(obj):
385 s = obj
386 is_repr = False
387 else:
388 s = py.io.saferepr(obj)
389 is_repr = True
390 if py.builtin._istext(s):
391 t = py.builtin.text
392 else:
393 t = py.builtin.bytes
394 s = s.replace(t("\n"), t("\n~")).replace(t("%"), t("%%"))
395 if is_repr:
396 s = s.replace(t("\\n"), t("\n~"))
397 return s
398
399 def _should_repr_global_name(obj):
400 return not hasattr(obj, "__name__") and not py.builtin.callable(obj)
401
402 def _format_boolop(explanations, is_or):
403 explanation = "(" + (is_or and " or " or " and ").join(explanations) + ")"
404 if py.builtin._istext(explanation):
405 t = py.builtin.text
406 else:
407 t = py.builtin.bytes
408 return explanation.replace(t('%'), t('%%'))
409
410 def _call_reprcompare(ops, results, expls, each_obj):
411 for i, res, expl in zip(range(len(ops)), results, expls):
412 try:
413 done = not res
414 except Exception:
415 done = True
416 if done:
417 break
418 if util._reprcompare is not None:
419 custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])
420 if custom is not None:
421 return custom
422 return expl
423
424
425 unary_map = {
426 ast.Not: "not %s",
427 ast.Invert: "~%s",
428 ast.USub: "-%s",
429 ast.UAdd: "+%s"
430 }
431
432 binop_map = {
433 ast.BitOr: "|",
434 ast.BitXor: "^",
435 ast.BitAnd: "&",
436 ast.LShift: "<<",
437 ast.RShift: ">>",
438 ast.Add: "+",
439 ast.Sub: "-",
440 ast.Mult: "*",
441 ast.Div: "/",
442 ast.FloorDiv: "//",
443 ast.Mod: "%%", # escaped for string formatting
444 ast.Eq: "==",
445 ast.NotEq: "!=",
446 ast.Lt: "<",
447 ast.LtE: "<=",
448 ast.Gt: ">",
449 ast.GtE: ">=",
450 ast.Pow: "**",
451 ast.Is: "is",
452 ast.IsNot: "is not",
453 ast.In: "in",
454 ast.NotIn: "not in"
455 }
456 # Python 3.5+ compatibility
457 try:
458 binop_map[ast.MatMult] = "@"
459 except AttributeError:
460 pass
461
462 # Python 3.4+ compatibility
463 if hasattr(ast, "NameConstant"):
464 _NameConstant = ast.NameConstant
465 else:
466 def _NameConstant(c):
467 return ast.Name(str(c), ast.Load())
468
469
470 def set_location(node, lineno, col_offset):
471 """Set node location information recursively."""
472 def _fix(node, lineno, col_offset):
473 if "lineno" in node._attributes:
474 node.lineno = lineno
475 if "col_offset" in node._attributes:
476 node.col_offset = col_offset
477 for child in ast.iter_child_nodes(node):
478 _fix(child, lineno, col_offset)
479 _fix(node, lineno, col_offset)
480 return node
481
482
483 class AssertionRewriter(ast.NodeVisitor):
484 """Assertion rewriting implementation.
485
486 The main entrypoint is to call .run() with an ast.Module instance,
487 this will then find all the assert statements and re-write them to
488 provide intermediate values and a detailed assertion error. See
489 http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html
490 for an overview of how this works.
491
492 The entry point here is .run() which will iterate over all the
493 statements in an ast.Module and for each ast.Assert statement it
494 finds call .visit() with it. Then .visit_Assert() takes over and
495 is responsible for creating new ast statements to replace the
496 original assert statement: it re-writes the test of an assertion
497 to provide intermediate values and replace it with an if statement
498 which raises an assertion error with a detailed explanation in
499 case the expression is false.
500
501 For this .visit_Assert() uses the visitor pattern to visit all the
502 AST nodes of the ast.Assert.test field, each visit call returning
503 an AST node and the corresponding explanation string. During this
504 state is kept in several instance attributes:
505
506 :statements: All the AST statements which will replace the assert
507 statement.
508
509 :variables: This is populated by .variable() with each variable
510 used by the statements so that they can all be set to None at
511 the end of the statements.
512
513 :variable_counter: Counter to create new unique variables needed
514 by statements. Variables are created using .variable() and
515 have the form of "@py_assert0".
516
517 :on_failure: The AST statements which will be executed if the
518 assertion test fails. This is the code which will construct
519 the failure message and raises the AssertionError.
520
521 :explanation_specifiers: A dict filled by .explanation_param()
522 with %-formatting placeholders and their corresponding
523 expressions to use in the building of an assertion message.
524 This is used by .pop_format_context() to build a message.
525
526 :stack: A stack of the explanation_specifiers dicts maintained by
527 .push_format_context() and .pop_format_context() which allows
528 to build another %-formatted string while already building one.
529
530 This state is reset on every new assert statement visited and used
531 by the other visitors.
532
533 """
534
535 def run(self, mod):
536 """Find all assert statements in *mod* and rewrite them."""
537 if not mod.body:
538 # Nothing to do.
539 return
540 # Insert some special imports at the top of the module but after any
541 # docstrings and __future__ imports.
542 aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
543 ast.alias("_pytest.assertion.rewrite", "@pytest_ar")]
544 expect_docstring = True
545 pos = 0
546 lineno = 0
547 for item in mod.body:
548 if (expect_docstring and isinstance(item, ast.Expr) and
549 isinstance(item.value, ast.Str)):
550 doc = item.value.s
551 if "PYTEST_DONT_REWRITE" in doc:
552 # The module has disabled assertion rewriting.
553 return
554 lineno += len(doc) - 1
555 expect_docstring = False
556 elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
557 item.module != "__future__"):
558 lineno = item.lineno
559 break
560 pos += 1
561 # Now actually insert the special imports.
562 if sys.version_info >= (3, 10):
563 aliases = [
564 ast.alias("builtins", "@py_builtins", lineno=lineno, col_offset=0),
565 ast.alias(
566 "_pytest.assertion.rewrite",
567 "@pytest_ar",
568 lineno=lineno,
569 col_offset=0,
570 ),
571 ]
572 else:
573 aliases = [
574 ast.alias("builtins", "@py_builtins"),
575 ast.alias("_pytest.assertion.rewrite", "@pytest_ar"),
576 ]
577 imports = [
578 ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases
579 ]
580 mod.body[pos:pos] = imports
581 # Collect asserts.
582 nodes = [mod]
583 while nodes:
584 node = nodes.pop()
585 for name, field in ast.iter_fields(node):
586 if isinstance(field, list):
587 new = []
588 for i, child in enumerate(field):
589 if isinstance(child, ast.Assert):
590 # Transform assert.
591 new.extend(self.visit(child))
592 else:
593 new.append(child)
594 if isinstance(child, ast.AST):
595 nodes.append(child)
596 setattr(node, name, new)
597 elif (isinstance(field, ast.AST) and
598 # Don't recurse into expressions as they can't contain
599 # asserts.
600 not isinstance(field, ast.expr)):
601 nodes.append(field)
602
603 def variable(self):
604 """Get a new variable."""
605 # Use a character invalid in python identifiers to avoid clashing.
606 name = "@py_assert" + str(next(self.variable_counter))
607 self.variables.append(name)
608 return name
609
610 def assign(self, expr):
611 """Give *expr* a name."""
612 name = self.variable()
613 self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
614 return ast.Name(name, ast.Load())
615
616 def display(self, expr):
617 """Call py.io.saferepr on the expression."""
618 return self.helper("saferepr", expr)
619
620 def helper(self, name, *args):
621 """Call a helper in this module."""
622 py_name = ast.Name("@pytest_ar", ast.Load())
623 attr = ast.Attribute(py_name, "_" + name, ast.Load())
624 return ast_Call(attr, list(args), [])
625
626 def builtin(self, name):
627 """Return the builtin called *name*."""
628 builtin_name = ast.Name("@py_builtins", ast.Load())
629 return ast.Attribute(builtin_name, name, ast.Load())
630
631 def explanation_param(self, expr):
632 """Return a new named %-formatting placeholder for expr.
633
634 This creates a %-formatting placeholder for expr in the
635 current formatting context, e.g. ``%(py0)s``. The placeholder
636 and expr are placed in the current format context so that it
637 can be used on the next call to .pop_format_context().
638
639 """
640 specifier = "py" + str(next(self.variable_counter))
641 self.explanation_specifiers[specifier] = expr
642 return "%(" + specifier + ")s"
643
644 def push_format_context(self):
645 """Create a new formatting context.
646
647 The format context is used for when an explanation wants to
648 have a variable value formatted in the assertion message. In
649 this case the value required can be added using
650 .explanation_param(). Finally .pop_format_context() is used
651 to format a string of %-formatted values as added by
652 .explanation_param().
653
654 """
655 self.explanation_specifiers = {}
656 self.stack.append(self.explanation_specifiers)
657
658 def pop_format_context(self, expl_expr):
659 """Format the %-formatted string with current format context.
660
661 The expl_expr should be an ast.Str instance constructed from
662 the %-placeholders created by .explanation_param(). This will
663 add the required code to format said string to .on_failure and
664 return the ast.Name instance of the formatted string.
665
666 """
667 current = self.stack.pop()
668 if self.stack:
669 self.explanation_specifiers = self.stack[-1]
670 keys = [ast.Str(key) for key in current.keys()]
671 format_dict = ast.Dict(keys, list(current.values()))
672 form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
673 name = "@py_format" + str(next(self.variable_counter))
674 self.on_failure.append(ast.Assign([ast.Name(name, ast.Store())], form))
675 return ast.Name(name, ast.Load())
676
677 def generic_visit(self, node):
678 """Handle expressions we don't have custom code for."""
679 assert isinstance(node, ast.expr)
680 res = self.assign(node)
681 return res, self.explanation_param(self.display(res))
682
683 def visit_Assert(self, assert_):
684 """Return the AST statements to replace the ast.Assert instance.
685
686 This re-writes the test of an assertion to provide
687 intermediate values and replace it with an if statement which
688 raises an assertion error with a detailed explanation in case
689 the expression is false.
690
691 """
692 self.statements = []
693 self.variables = []
694 self.variable_counter = itertools.count()
695 self.stack = []
696 self.on_failure = []
697 self.push_format_context()
698 # Rewrite assert into a bunch of statements.
699 top_condition, explanation = self.visit(assert_.test)
700 # Create failure message.
701 body = self.on_failure
702 negation = ast.UnaryOp(ast.Not(), top_condition)
703 self.statements.append(ast.If(negation, body, []))
704 if assert_.msg:
705 assertmsg = self.helper('format_assertmsg', assert_.msg)
706 explanation = "\n>assert " + explanation
707 else:
708 assertmsg = ast.Str("")
709 explanation = "assert " + explanation
710 template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
711 msg = self.pop_format_context(template)
712 fmt = self.helper("format_explanation", msg)
713 err_name = ast.Name("AssertionError", ast.Load())
714 exc = ast_Call(err_name, [fmt], [])
715 if sys.version_info[0] >= 3:
716 raise_ = ast.Raise(exc, None)
717 else:
718 raise_ = ast.Raise(exc, None, None)
719 body.append(raise_)
720 # Clear temporary variables by setting them to None.
721 if self.variables:
722 variables = [ast.Name(name, ast.Store())
723 for name in self.variables]
724 clear = ast.Assign(variables, _NameConstant(None))
725 self.statements.append(clear)
726 # Fix line numbers.
727 for stmt in self.statements:
728 set_location(stmt, assert_.lineno, assert_.col_offset)
729 return self.statements
730
731 def visit_Name(self, name):
732 # Display the repr of the name if it's a local variable or
733 # _should_repr_global_name() thinks it's acceptable.
734 locs = ast_Call(self.builtin("locals"), [], [])
735 inlocs = ast.Compare(ast.Str(name.id), [ast.In()], [locs])
736 dorepr = self.helper("should_repr_global_name", name)
737 test = ast.BoolOp(ast.Or(), [inlocs, dorepr])
738 expr = ast.IfExp(test, self.display(name), ast.Str(name.id))
739 return name, self.explanation_param(expr)
740
741 def visit_BoolOp(self, boolop):
742 res_var = self.variable()
743 expl_list = self.assign(ast.List([], ast.Load()))
744 app = ast.Attribute(expl_list, "append", ast.Load())
745 is_or = int(isinstance(boolop.op, ast.Or))
746 body = save = self.statements
747 fail_save = self.on_failure
748 levels = len(boolop.values) - 1
749 self.push_format_context()
750 # Process each operand, short-circuting if needed.
751 for i, v in enumerate(boolop.values):
752 if i:
753 fail_inner = []
754 # cond is set in a prior loop iteration below
755 self.on_failure.append(ast.If(cond, fail_inner, [])) # noqa
756 self.on_failure = fail_inner
757 self.push_format_context()
758 res, expl = self.visit(v)
759 body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))
760 expl_format = self.pop_format_context(ast.Str(expl))
761 call = ast_Call(app, [expl_format], [])
762 self.on_failure.append(ast.Expr(call))
763 if i < levels:
764 cond = res
765 if is_or:
766 cond = ast.UnaryOp(ast.Not(), cond)
767 inner = []
768 self.statements.append(ast.If(cond, inner, []))
769 self.statements = body = inner
770 self.statements = save
771 self.on_failure = fail_save
772 expl_template = self.helper("format_boolop", expl_list, ast.Num(is_or))
773 expl = self.pop_format_context(expl_template)
774 return ast.Name(res_var, ast.Load()), self.explanation_param(expl)
775
776 def visit_UnaryOp(self, unary):
777 pattern = unary_map[unary.op.__class__]
778 operand_res, operand_expl = self.visit(unary.operand)
779 res = self.assign(ast.UnaryOp(unary.op, operand_res))
780 return res, pattern % (operand_expl,)
781
782 def visit_BinOp(self, binop):
783 symbol = binop_map[binop.op.__class__]
784 left_expr, left_expl = self.visit(binop.left)
785 right_expr, right_expl = self.visit(binop.right)
786 explanation = "(%s %s %s)" % (left_expl, symbol, right_expl)
787 res = self.assign(ast.BinOp(left_expr, binop.op, right_expr))
788 return res, explanation
789
790 def visit_Call_35(self, call):
791 """
792 visit `ast.Call` nodes on Python3.5 and after
793 """
794 new_func, func_expl = self.visit(call.func)
795 arg_expls = []
796 new_args = []
797 new_kwargs = []
798 for arg in call.args:
799 res, expl = self.visit(arg)
800 arg_expls.append(expl)
801 new_args.append(res)
802 for keyword in call.keywords:
803 res, expl = self.visit(keyword.value)
804 new_kwargs.append(ast.keyword(keyword.arg, res))
805 if keyword.arg:
806 arg_expls.append(keyword.arg + "=" + expl)
807 else: ## **args have `arg` keywords with an .arg of None
808 arg_expls.append("**" + expl)
809
810 expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
811 new_call = ast.Call(new_func, new_args, new_kwargs)
812 res = self.assign(new_call)
813 res_expl = self.explanation_param(self.display(res))
814 outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
815 return res, outer_expl
816
817 def visit_Starred(self, starred):
818 # From Python 3.5, a Starred node can appear in a function call
819 res, expl = self.visit(starred.value)
820 return starred, '*' + expl
821
822 def visit_Call_legacy(self, call):
823 """
824 visit `ast.Call nodes on 3.4 and below`
825 """
826 new_func, func_expl = self.visit(call.func)
827 arg_expls = []
828 new_args = []
829 new_kwargs = []
830 new_star = new_kwarg = None
831 for arg in call.args:
832 res, expl = self.visit(arg)
833 new_args.append(res)
834 arg_expls.append(expl)
835 for keyword in call.keywords:
836 res, expl = self.visit(keyword.value)
837 new_kwargs.append(ast.keyword(keyword.arg, res))
838 arg_expls.append(keyword.arg + "=" + expl)
839 if call.starargs:
840 new_star, expl = self.visit(call.starargs)
841 arg_expls.append("*" + expl)
842 if call.kwargs:
843 new_kwarg, expl = self.visit(call.kwargs)
844 arg_expls.append("**" + expl)
845 expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
846 new_call = ast.Call(new_func, new_args, new_kwargs,
847 new_star, new_kwarg)
848 res = self.assign(new_call)
849 res_expl = self.explanation_param(self.display(res))
850 outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
851 return res, outer_expl
852
853 # ast.Call signature changed on 3.5,
854 # conditionally change which methods is named
855 # visit_Call depending on Python version
856 if sys.version_info >= (3, 5):
857 visit_Call = visit_Call_35
858 else:
859 visit_Call = visit_Call_legacy
860
861
862 def visit_Attribute(self, attr):
863 if not isinstance(attr.ctx, ast.Load):
864 return self.generic_visit(attr)
865 value, value_expl = self.visit(attr.value)
866 res = self.assign(ast.Attribute(value, attr.attr, ast.Load()))
867 res_expl = self.explanation_param(self.display(res))
868 pat = "%s\n{%s = %s.%s\n}"
869 expl = pat % (res_expl, res_expl, value_expl, attr.attr)
870 return res, expl
871
872 def visit_Compare(self, comp):
873 self.push_format_context()
874 left_res, left_expl = self.visit(comp.left)
875 res_variables = [self.variable() for i in range(len(comp.ops))]
876 load_names = [ast.Name(v, ast.Load()) for v in res_variables]
877 store_names = [ast.Name(v, ast.Store()) for v in res_variables]
878 it = zip(range(len(comp.ops)), comp.ops, comp.comparators)
879 expls = []
880 syms = []
881 results = [left_res]
882 for i, op, next_operand in it:
883 next_res, next_expl = self.visit(next_operand)
884 results.append(next_res)
885 sym = binop_map[op.__class__]
886 syms.append(ast.Str(sym))
887 expl = "%s %s %s" % (left_expl, sym, next_expl)
888 expls.append(ast.Str(expl))
889 res_expr = ast.Compare(left_res, [op], [next_res])
890 self.statements.append(ast.Assign([store_names[i]], res_expr))
891 left_res, left_expl = next_res, next_expl
892 # Use pytest.assertion.util._reprcompare if that's available.
893 expl_call = self.helper("call_reprcompare",
894 ast.Tuple(syms, ast.Load()),
895 ast.Tuple(load_names, ast.Load()),
896 ast.Tuple(expls, ast.Load()),
897 ast.Tuple(results, ast.Load()))
898 if len(comp.ops) > 1:
899 res = ast.BoolOp(ast.And(), load_names)
900 else:
901 res = load_names[0]
902 return res, self.explanation_param(self.pop_format_context(expl_call))