__init__.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """
  2. support for presenting detailed information in failing assertions.
  3. """
  4. from __future__ import absolute_import, division, print_function
  5. import sys
  6. import six
  7. from _pytest.assertion import util
  8. from _pytest.assertion import rewrite
  9. from _pytest.assertion import truncate
  10. def pytest_addoption(parser):
  11. group = parser.getgroup("debugconfig")
  12. group.addoption(
  13. "--assert",
  14. action="store",
  15. dest="assertmode",
  16. choices=("rewrite", "plain"),
  17. default="rewrite",
  18. metavar="MODE",
  19. help="""Control assertion debugging tools. 'plain'
  20. performs no assertion debugging. 'rewrite'
  21. (the default) rewrites assert statements in
  22. test modules on import to provide assert
  23. expression information.""",
  24. )
  25. def register_assert_rewrite(*names):
  26. """Register one or more module names to be rewritten on import.
  27. This function will make sure that this module or all modules inside
  28. the package will get their assert statements rewritten.
  29. Thus you should make sure to call this before the module is
  30. actually imported, usually in your __init__.py if you are a plugin
  31. using a package.
  32. :raise TypeError: if the given module names are not strings.
  33. """
  34. for name in names:
  35. if not isinstance(name, str):
  36. msg = "expected module names as *args, got {0} instead"
  37. raise TypeError(msg.format(repr(names)))
  38. for hook in sys.meta_path:
  39. if isinstance(hook, rewrite.AssertionRewritingHook):
  40. importhook = hook
  41. break
  42. else:
  43. importhook = DummyRewriteHook()
  44. importhook.mark_rewrite(*names)
  45. class DummyRewriteHook(object):
  46. """A no-op import hook for when rewriting is disabled."""
  47. def mark_rewrite(self, *names):
  48. pass
  49. class AssertionState(object):
  50. """State for the assertion plugin."""
  51. def __init__(self, config, mode):
  52. self.mode = mode
  53. self.trace = config.trace.root.get("assertion")
  54. self.hook = None
  55. def install_importhook(config):
  56. """Try to install the rewrite hook, raise SystemError if it fails."""
  57. # Jython has an AST bug that make the assertion rewriting hook malfunction.
  58. if sys.platform.startswith("java"):
  59. raise SystemError("rewrite not supported")
  60. config._assertstate = AssertionState(config, "rewrite")
  61. config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config)
  62. sys.meta_path.insert(0, hook)
  63. config._assertstate.trace("installed rewrite import hook")
  64. def undo():
  65. hook = config._assertstate.hook
  66. if hook is not None and hook in sys.meta_path:
  67. sys.meta_path.remove(hook)
  68. config.add_cleanup(undo)
  69. return hook
  70. def pytest_collection(session):
  71. # this hook is only called when test modules are collected
  72. # so for example not in the master process of pytest-xdist
  73. # (which does not collect test modules)
  74. assertstate = getattr(session.config, "_assertstate", None)
  75. if assertstate:
  76. if assertstate.hook is not None:
  77. assertstate.hook.set_session(session)
  78. def pytest_runtest_setup(item):
  79. """Setup the pytest_assertrepr_compare hook
  80. The newinterpret and rewrite modules will use util._reprcompare if
  81. it exists to use custom reporting via the
  82. pytest_assertrepr_compare hook. This sets up this custom
  83. comparison for the test.
  84. """
  85. def callbinrepr(op, left, right):
  86. """Call the pytest_assertrepr_compare hook and prepare the result
  87. This uses the first result from the hook and then ensures the
  88. following:
  89. * Overly verbose explanations are truncated unless configured otherwise
  90. (eg. if running in verbose mode).
  91. * Embedded newlines are escaped to help util.format_explanation()
  92. later.
  93. * If the rewrite mode is used embedded %-characters are replaced
  94. to protect later % formatting.
  95. The result can be formatted by util.format_explanation() for
  96. pretty printing.
  97. """
  98. hook_result = item.ihook.pytest_assertrepr_compare(
  99. config=item.config, op=op, left=left, right=right
  100. )
  101. for new_expl in hook_result:
  102. if new_expl:
  103. new_expl = truncate.truncate_if_required(new_expl, item)
  104. new_expl = [line.replace("\n", "\\n") for line in new_expl]
  105. res = six.text_type("\n~").join(new_expl)
  106. if item.config.getvalue("assertmode") == "rewrite":
  107. res = res.replace("%", "%%")
  108. return res
  109. util._reprcompare = callbinrepr
  110. def pytest_runtest_teardown(item):
  111. util._reprcompare = None
  112. def pytest_sessionfinish(session):
  113. assertstate = getattr(session.config, "_assertstate", None)
  114. if assertstate:
  115. if assertstate.hook is not None:
  116. assertstate.hook.set_session(None)
  117. # Expose this plugin's implementation for the pytest_assertrepr_compare hook
  118. pytest_assertrepr_compare = util.assertrepr_compare