| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Support for presenting detailed information in failing assertions.""" |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from collections.abc import Generator |
| 7 |
import sys |
| 8 |
from typing import Any |
| 9 |
from typing import Protocol |
| 10 |
from typing import TYPE_CHECKING |
| 11 |
|
| 12 |
from _pytest.assertion import rewrite |
| 13 |
from _pytest.assertion import truncate |
| 14 |
from _pytest.assertion import util |
| 15 |
from _pytest.assertion.rewrite import assertstate_key |
| 16 |
from _pytest.config import Config |
| 17 |
from _pytest.config import hookimpl |
| 18 |
from _pytest.config.argparsing import Parser |
| 19 |
from _pytest.nodes import Item |
| 20 |
|
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from _pytest.main import Session |
| 24 |
|
| 25 |
|
| 26 |
def pytest_addoption(parser: Parser) -> None: |
| 27 |
group = parser.getgroup("debugconfig") |
| 28 |
group.addoption( |
| 29 |
"--assert", |
| 30 |
action="store", |
| 31 |
dest="assertmode", |
| 32 |
choices=("rewrite", "plain"), |
| 33 |
default="rewrite", |
| 34 |
metavar="MODE", |
| 35 |
help=( |
| 36 |
"Control assertion debugging tools.\n" |
| 37 |
"'plain' performs no assertion debugging.\n" |
| 38 |
"'rewrite' (the default) rewrites assert statements in test modules" |
| 39 |
" on import to provide assert expression information." |
| 40 |
), |
| 41 |
) |
| 42 |
parser.addini( |
| 43 |
"enable_assertion_pass_hook", |
| 44 |
type="bool", |
| 45 |
default=False, |
| 46 |
help="Enables the pytest_assertion_pass hook. " |
| 47 |
"Make sure to delete any previously generated pyc cache files.", |
| 48 |
) |
| 49 |
|
| 50 |
parser.addini( |
| 51 |
"truncation_limit_lines", |
| 52 |
default=None, |
| 53 |
help="Set threshold of LINES after which truncation will take effect", |
| 54 |
) |
| 55 |
parser.addini( |
| 56 |
"truncation_limit_chars", |
| 57 |
default=None, |
| 58 |
help=("Set threshold of CHARS after which truncation will take effect"), |
| 59 |
) |
| 60 |
parser.addini( |
| 61 |
"assertion_text_diff_style", |
| 62 |
default=util.ASSERTION_TEXT_DIFF_STYLE_NDIFF, |
| 63 |
help=( |
| 64 |
"Choose how pytest renders diffs for string equality assertions: " |
| 65 |
f"{util.ASSERTION_TEXT_DIFF_STYLE_NDIFF} or " |
| 66 |
f"{util.ASSERTION_TEXT_DIFF_STYLE_BLOCK}" |
| 67 |
), |
| 68 |
) |
| 69 |
|
| 70 |
Config._add_verbosity_ini( |
| 71 |
parser, |
| 72 |
Config.VERBOSITY_ASSERTIONS, |
| 73 |
help=( |
| 74 |
"Specify a verbosity level for assertions, overriding the main level. " |
| 75 |
"Higher levels will provide more detailed explanation when an assertion fails." |
| 76 |
), |
| 77 |
) |
| 78 |
|
| 79 |
|
| 80 |
def pytest_configure(config: Config) -> None: |
| 81 |
util.validate_assertion_text_diff_style(config) |
| 82 |
|
| 83 |
|
| 84 |
def register_assert_rewrite(*names: str) -> None: |
| 85 |
"""Register one or more module names to be rewritten on import. |
| 86 |
|
| 87 |
This function will make sure that this module or all modules inside |
| 88 |
the package will get their assert statements rewritten. |
| 89 |
Thus you should make sure to call this before the module is |
| 90 |
actually imported, usually in your __init__.py if you are a plugin |
| 91 |
using a package. |
| 92 |
|
| 93 |
:param names: The module names to register. |
| 94 |
""" |
| 95 |
for name in names: |
| 96 |
if not isinstance(name, str): |
| 97 |
msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable] |
| 98 |
raise TypeError(msg.format(repr(names))) |
| 99 |
rewrite_hook: RewriteHook |
| 100 |
for hook in sys.meta_path: |
| 101 |
if isinstance(hook, rewrite.AssertionRewritingHook): |
| 102 |
rewrite_hook = hook |
| 103 |
break |
| 104 |
else: |
| 105 |
rewrite_hook = DummyRewriteHook() |
| 106 |
rewrite_hook.mark_rewrite(*names) |
| 107 |
|
| 108 |
|
| 109 |
class RewriteHook(Protocol): |
| 110 |
def mark_rewrite(self, *names: str) -> None: ... |
| 111 |
|
| 112 |
|
| 113 |
class DummyRewriteHook: |
| 114 |
"""A no-op import hook for when rewriting is disabled.""" |
| 115 |
|
| 116 |
def mark_rewrite(self, *names: str) -> None: |
| 117 |
pass |
| 118 |
|
| 119 |
|
| 120 |
class AssertionState: |
| 121 |
"""State for the assertion plugin.""" |
| 122 |
|
| 123 |
def __init__(self, config: Config, mode) -> None: |
| 124 |
self.mode = mode |
| 125 |
self.trace = config.trace.root.get("assertion") |
| 126 |
self.hook: rewrite.AssertionRewritingHook | None = None |
| 127 |
|
| 128 |
|
| 129 |
def install_importhook(config: Config) -> rewrite.AssertionRewritingHook: |
| 130 |
"""Try to install the rewrite hook, raise SystemError if it fails.""" |
| 131 |
config.stash[assertstate_key] = AssertionState(config, "rewrite") |
| 132 |
config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config) |
| 133 |
sys.meta_path.insert(0, hook) |
| 134 |
config.stash[assertstate_key].trace("installed rewrite import hook") |
| 135 |
|
| 136 |
def undo() -> None: |
| 137 |
hook = config.stash[assertstate_key].hook |
| 138 |
if hook is not None and hook in sys.meta_path: |
| 139 |
sys.meta_path.remove(hook) |
| 140 |
|
| 141 |
config.add_cleanup(undo) |
| 142 |
return hook |
| 143 |
|
| 144 |
|
| 145 |
def pytest_collection(session: Session) -> None: |
| 146 |
# This hook is only called when test modules are collected |
| 147 |
# so for example not in the managing process of pytest-xdist |
| 148 |
# (which does not collect test modules). |
| 149 |
assertstate = session.config.stash.get(assertstate_key, None) |
| 150 |
if assertstate: |
| 151 |
if assertstate.hook is not None: |
| 152 |
assertstate.hook.set_session(session) |
| 153 |
|
| 154 |
|
| 155 |
@hookimpl(wrapper=True, tryfirst=True) |
| 156 |
def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]: |
| 157 |
"""Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks. |
| 158 |
|
| 159 |
The rewrite module will use util._reprcompare if it exists to use custom |
| 160 |
reporting via the pytest_assertrepr_compare hook. This sets up this custom |
| 161 |
comparison for the test. |
| 162 |
""" |
| 163 |
ihook = item.ihook |
| 164 |
|
| 165 |
def callbinrepr(op, left: object, right: object) -> str | None: |
| 166 |
"""Call the pytest_assertrepr_compare hook and prepare the result. |
| 167 |
|
| 168 |
This uses the first result from the hook and then ensures the |
| 169 |
following: |
| 170 |
* Overly verbose explanations are truncated unless configured otherwise |
| 171 |
(eg. if running in verbose mode). |
| 172 |
* Embedded newlines are escaped to help util.format_explanation() |
| 173 |
later. |
| 174 |
* If the rewrite mode is used embedded %-characters are replaced |
| 175 |
to protect later % formatting. |
| 176 |
|
| 177 |
The result can be formatted by util.format_explanation() for |
| 178 |
pretty printing. |
| 179 |
""" |
| 180 |
hook_result = ihook.pytest_assertrepr_compare( |
| 181 |
config=item.config, op=op, left=left, right=right |
| 182 |
) |
| 183 |
for new_expl in hook_result: |
| 184 |
if new_expl: |
| 185 |
new_expl = truncate.truncate_if_required(new_expl, item) |
| 186 |
new_expl = [line.replace("\n", "\\n") for line in new_expl] |
| 187 |
res = "\n~".join(new_expl) |
| 188 |
if item.config.getvalue("assertmode") == "rewrite": |
| 189 |
res = res.replace("%", "%%") |
| 190 |
return res |
| 191 |
return None |
| 192 |
|
| 193 |
saved_assert_hooks = util._reprcompare, util._assertion_pass |
| 194 |
util._reprcompare = callbinrepr |
| 195 |
util._config = item.config |
| 196 |
|
| 197 |
if ihook.pytest_assertion_pass.get_hookimpls(): |
| 198 |
|
| 199 |
def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None: |
| 200 |
ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl) |
| 201 |
|
| 202 |
util._assertion_pass = call_assertion_pass_hook |
| 203 |
|
| 204 |
try: |
| 205 |
return (yield) |
| 206 |
finally: |
| 207 |
util._reprcompare, util._assertion_pass = saved_assert_hooks |
| 208 |
util._config = None |
| 209 |
|
| 210 |
|
| 211 |
def pytest_sessionfinish(session: Session) -> None: |
| 212 |
assertstate = session.config.stash.get(assertstate_key, None) |
| 213 |
if assertstate: |
| 214 |
if assertstate.hook is not None: |
| 215 |
assertstate.hook.set_session(None) |
| 216 |
|
| 217 |
|
| 218 |
def pytest_assertrepr_compare( |
| 219 |
config: Config, op: str, left: Any, right: Any |
| 220 |
) -> list[str] | None: |
| 221 |
if config.pluginmanager.has_plugin("terminalreporter"): |
| 222 |
highlighter = config.get_terminal_writer()._highlight |
| 223 |
else: |
| 224 |
# Keep it plaintext when not using terminalrepoterer (#14377). |
| 225 |
highlighter = util.dummy_highlighter |
| 226 |
explanation = list( |
| 227 |
util.assertrepr_compare( |
| 228 |
op=op, |
| 229 |
left=left, |
| 230 |
right=right, |
| 231 |
verbose=config.get_verbosity(Config.VERBOSITY_ASSERTIONS), |
| 232 |
highlighter=highlighter, |
| 233 |
assertion_text_diff_style=util.get_assertion_text_diff_style(config), |
| 234 |
) |
| 235 |
) |
| 236 |
return explanation or None |