| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import fnmatch |
| 5 |
import importlib |
| 6 |
import io |
| 7 |
import operator |
| 8 |
from pathlib import Path |
| 9 |
import queue |
| 10 |
import re |
| 11 |
import sys |
| 12 |
import textwrap |
| 13 |
from typing import Any |
| 14 |
from typing import cast |
| 15 |
from typing import TYPE_CHECKING |
| 16 |
|
| 17 |
import _pytest._code |
| 18 |
from _pytest._code.code import ExceptionChainRepr |
| 19 |
from _pytest._code.code import ExceptionInfo |
| 20 |
from _pytest._code.code import ExceptionInfoFormatter |
| 21 |
from _pytest._io import TerminalWriter |
| 22 |
from _pytest.monkeypatch import MonkeyPatch |
| 23 |
from _pytest.pathlib import bestrelpath |
| 24 |
from _pytest.pathlib import import_path |
| 25 |
from _pytest.pytester import LineMatcher |
| 26 |
from _pytest.pytester import Pytester |
| 27 |
import pytest |
| 28 |
|
| 29 |
|
| 30 |
if TYPE_CHECKING: |
| 31 |
from _pytest._code.code import TracebackStyle |
| 32 |
|
| 33 |
if sys.version_info < (3, 11): |
| 34 |
from exceptiongroup import BaseExceptionGroup |
| 35 |
from exceptiongroup import ExceptionGroup |
| 36 |
|
| 37 |
|
| 38 |
@pytest.fixture |
| 39 |
def limited_recursion_depth(): |
| 40 |
before = sys.getrecursionlimit() |
| 41 |
sys.setrecursionlimit(150) |
| 42 |
yield |
| 43 |
sys.setrecursionlimit(before) |
| 44 |
|
| 45 |
|
| 46 |
def test_excinfo_simple() -> None: |
| 47 |
try: |
| 48 |
raise ValueError |
| 49 |
except ValueError: |
| 50 |
info = _pytest._code.ExceptionInfo.from_current() |
| 51 |
assert info.type == ValueError |
| 52 |
|
| 53 |
|
| 54 |
def test_excinfo_from_exc_info_simple() -> None: |
| 55 |
try: |
| 56 |
raise ValueError |
| 57 |
except ValueError as e: |
| 58 |
assert e.__traceback__ is not None |
| 59 |
info = _pytest._code.ExceptionInfo.from_exc_info((type(e), e, e.__traceback__)) |
| 60 |
assert info.type == ValueError |
| 61 |
|
| 62 |
|
| 63 |
def test_excinfo_from_exception_simple() -> None: |
| 64 |
try: |
| 65 |
raise ValueError |
| 66 |
except ValueError as e: |
| 67 |
assert e.__traceback__ is not None |
| 68 |
info = _pytest._code.ExceptionInfo.from_exception(e) |
| 69 |
assert info.type == ValueError |
| 70 |
|
| 71 |
|
| 72 |
def test_excinfo_from_exception_missing_traceback_assertion() -> None: |
| 73 |
with pytest.raises(AssertionError, match=r"must have.*__traceback__"): |
| 74 |
_pytest._code.ExceptionInfo.from_exception(ValueError()) |
| 75 |
|
| 76 |
|
| 77 |
def test_excinfo_getstatement(): |
| 78 |
def g(): |
| 79 |
raise ValueError |
| 80 |
|
| 81 |
def f(): |
| 82 |
g() |
| 83 |
|
| 84 |
try: |
| 85 |
f() |
| 86 |
except ValueError: |
| 87 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 88 |
linenumbers = [ |
| 89 |
f.__code__.co_firstlineno - 1 + 4, |
| 90 |
f.__code__.co_firstlineno - 1 + 1, |
| 91 |
g.__code__.co_firstlineno - 1 + 1, |
| 92 |
] |
| 93 |
values = list(excinfo.traceback) |
| 94 |
foundlinenumbers = [x.lineno for x in values] |
| 95 |
assert foundlinenumbers == linenumbers |
| 96 |
# for x in info: |
| 97 |
# print "%s:%d %s" %(x.path.relto(root), x.lineno, x.statement) |
| 98 |
# xxx |
| 99 |
|
| 100 |
|
| 101 |
# testchain for getentries test below |
| 102 |
|
| 103 |
|
| 104 |
def f(): |
| 105 |
# |
| 106 |
raise ValueError |
| 107 |
# |
| 108 |
|
| 109 |
|
| 110 |
def g(): |
| 111 |
# |
| 112 |
__tracebackhide__ = True |
| 113 |
f() |
| 114 |
# |
| 115 |
|
| 116 |
|
| 117 |
def h(): |
| 118 |
# |
| 119 |
g() |
| 120 |
# |
| 121 |
|
| 122 |
|
| 123 |
class TestTraceback_f_g_h: |
| 124 |
def setup_method(self, method): |
| 125 |
try: |
| 126 |
h() |
| 127 |
except ValueError: |
| 128 |
self.excinfo = _pytest._code.ExceptionInfo.from_current() |
| 129 |
|
| 130 |
def test_traceback_entries(self): |
| 131 |
tb = self.excinfo.traceback |
| 132 |
entries = list(tb) |
| 133 |
assert len(tb) == 4 # maybe fragile test |
| 134 |
assert len(entries) == 4 # maybe fragile test |
| 135 |
names = ["f", "g", "h"] |
| 136 |
for entry in entries: |
| 137 |
try: |
| 138 |
names.remove(entry.frame.code.name) |
| 139 |
except ValueError: |
| 140 |
pass |
| 141 |
assert not names |
| 142 |
|
| 143 |
def test_traceback_entry_getsource(self): |
| 144 |
tb = self.excinfo.traceback |
| 145 |
s = str(tb[-1].getsource()) |
| 146 |
assert s.startswith("def f():") |
| 147 |
assert s.endswith("raise ValueError") |
| 148 |
|
| 149 |
def test_traceback_entry_getsource_in_construct(self): |
| 150 |
def xyz(): |
| 151 |
try: |
| 152 |
raise ValueError |
| 153 |
except somenoname: # type: ignore[name-defined] # noqa: F821 |
| 154 |
pass # pragma: no cover |
| 155 |
|
| 156 |
try: |
| 157 |
xyz() |
| 158 |
except NameError: |
| 159 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 160 |
else: |
| 161 |
assert False, "did not raise NameError" |
| 162 |
|
| 163 |
tb = excinfo.traceback |
| 164 |
source = tb[-1].getsource() |
| 165 |
assert source is not None |
| 166 |
assert source.deindent().lines == [ |
| 167 |
"def xyz():", |
| 168 |
" try:", |
| 169 |
" raise ValueError", |
| 170 |
" except somenoname: # type: ignore[name-defined] # noqa: F821", |
| 171 |
] |
| 172 |
|
| 173 |
def test_traceback_cut(self) -> None: |
| 174 |
co = _pytest._code.Code.from_function(f) |
| 175 |
path, firstlineno = co.path, co.firstlineno |
| 176 |
assert isinstance(path, Path) |
| 177 |
traceback = self.excinfo.traceback |
| 178 |
newtraceback = traceback.cut(path=path, firstlineno=firstlineno) |
| 179 |
assert len(newtraceback) == 1 |
| 180 |
newtraceback = traceback.cut(path=path, lineno=firstlineno + 2) |
| 181 |
assert len(newtraceback) == 1 |
| 182 |
|
| 183 |
def test_traceback_cut_excludepath(self, pytester: Pytester) -> None: |
| 184 |
p = pytester.makepyfile("def f(): raise ValueError") |
| 185 |
with pytest.raises(ValueError) as excinfo: |
| 186 |
import_path(p, root=pytester.path, consider_namespace_packages=False).f() |
| 187 |
basedir = Path(pytest.__file__).parent |
| 188 |
newtraceback = excinfo.traceback.cut(excludepath=basedir) |
| 189 |
for x in newtraceback: |
| 190 |
assert isinstance(x.path, Path) |
| 191 |
assert basedir not in x.path.parents |
| 192 |
assert newtraceback[-1].frame.code.path == p |
| 193 |
|
| 194 |
def test_traceback_filter(self): |
| 195 |
traceback = self.excinfo.traceback |
| 196 |
ntraceback = traceback.filter(self.excinfo) |
| 197 |
assert len(ntraceback) == len(traceback) - 1 |
| 198 |
|
| 199 |
@pytest.mark.parametrize( |
| 200 |
"tracebackhide, matching", |
| 201 |
[ |
| 202 |
(lambda info: True, True), |
| 203 |
(lambda info: False, False), |
| 204 |
(operator.methodcaller("errisinstance", ValueError), True), |
| 205 |
(operator.methodcaller("errisinstance", IndexError), False), |
| 206 |
], |
| 207 |
) |
| 208 |
def test_traceback_filter_selective(self, tracebackhide, matching): |
| 209 |
def f(): |
| 210 |
# |
| 211 |
raise ValueError |
| 212 |
# |
| 213 |
|
| 214 |
def g(): |
| 215 |
# |
| 216 |
__tracebackhide__ = tracebackhide |
| 217 |
f() |
| 218 |
# |
| 219 |
|
| 220 |
def h(): |
| 221 |
# |
| 222 |
g() |
| 223 |
# |
| 224 |
|
| 225 |
with pytest.raises(ValueError) as excinfo: |
| 226 |
h() |
| 227 |
traceback = excinfo.traceback |
| 228 |
ntraceback = traceback.filter(excinfo) |
| 229 |
print(f"old: {traceback!r}") |
| 230 |
print(f"new: {ntraceback!r}") |
| 231 |
|
| 232 |
if matching: |
| 233 |
# -1 because of the __tracebackhide__ in pytest.raises |
| 234 |
assert len(ntraceback) == len(traceback) - 1 |
| 235 |
else: |
| 236 |
assert len(ntraceback) == len(traceback) |
| 237 |
|
| 238 |
def test_traceback_recursion_index(self): |
| 239 |
def f(n): |
| 240 |
if n < 10: |
| 241 |
n += 1 |
| 242 |
f(n) |
| 243 |
|
| 244 |
with pytest.raises(RecursionError) as excinfo: |
| 245 |
f(8) |
| 246 |
traceback = excinfo.traceback |
| 247 |
recindex = traceback.recursionindex() |
| 248 |
assert recindex == 3 |
| 249 |
|
| 250 |
def test_traceback_only_specific_recursion_errors(self, monkeypatch): |
| 251 |
def f(n): |
| 252 |
if n == 0: |
| 253 |
raise RuntimeError("hello") |
| 254 |
f(n - 1) |
| 255 |
|
| 256 |
with pytest.raises(RuntimeError) as excinfo: |
| 257 |
f(25) |
| 258 |
monkeypatch.delattr(excinfo.traceback.__class__, "recursionindex") |
| 259 |
repr = excinfo.getrepr() |
| 260 |
assert "RuntimeError: hello" in str(repr.reprcrash) |
| 261 |
|
| 262 |
def test_traceback_no_recursion_index(self) -> None: |
| 263 |
def do_stuff() -> None: |
| 264 |
raise RuntimeError |
| 265 |
|
| 266 |
def reraise_me() -> None: |
| 267 |
import sys |
| 268 |
|
| 269 |
_exc, val, tb = sys.exc_info() |
| 270 |
assert val is not None |
| 271 |
raise val.with_traceback(tb) |
| 272 |
|
| 273 |
def f(n: int) -> None: |
| 274 |
try: |
| 275 |
do_stuff() |
| 276 |
except BaseException: |
| 277 |
reraise_me() |
| 278 |
|
| 279 |
with pytest.raises(RuntimeError) as excinfo: |
| 280 |
f(8) |
| 281 |
traceback = excinfo.traceback |
| 282 |
recindex = traceback.recursionindex() |
| 283 |
assert recindex is None |
| 284 |
|
| 285 |
def test_traceback_messy_recursion(self): |
| 286 |
# XXX: simplified locally testable version |
| 287 |
decorator = pytest.importorskip("decorator").decorator |
| 288 |
|
| 289 |
def log(f, *k, **kw): |
| 290 |
print(f"{k} {kw}") |
| 291 |
f(*k, **kw) |
| 292 |
|
| 293 |
log = decorator(log) |
| 294 |
|
| 295 |
def fail(): |
| 296 |
raise ValueError("") |
| 297 |
|
| 298 |
fail = log(log(fail)) |
| 299 |
|
| 300 |
with pytest.raises(ValueError) as excinfo: |
| 301 |
fail() |
| 302 |
assert excinfo.traceback.recursionindex() is None |
| 303 |
|
| 304 |
def test_getreprcrash(self): |
| 305 |
def i(): |
| 306 |
__tracebackhide__ = True |
| 307 |
raise ValueError |
| 308 |
|
| 309 |
def h(): |
| 310 |
i() |
| 311 |
|
| 312 |
def g(): |
| 313 |
__tracebackhide__ = True |
| 314 |
h() |
| 315 |
|
| 316 |
def f(): |
| 317 |
g() |
| 318 |
|
| 319 |
with pytest.raises(ValueError) as excinfo: |
| 320 |
f() |
| 321 |
reprcrash = excinfo._getreprcrash() |
| 322 |
assert reprcrash is not None |
| 323 |
co = _pytest._code.Code.from_function(h) |
| 324 |
assert reprcrash.path == str(co.path) |
| 325 |
assert reprcrash.lineno == co.firstlineno + 1 + 1 |
| 326 |
|
| 327 |
def test_getreprcrash_empty(self): |
| 328 |
__tracebackhide__ = True |
| 329 |
|
| 330 |
def g(): |
| 331 |
__tracebackhide__ = True |
| 332 |
raise ValueError |
| 333 |
|
| 334 |
def f(): |
| 335 |
__tracebackhide__ = True |
| 336 |
g() |
| 337 |
|
| 338 |
with pytest.raises(ValueError) as excinfo: |
| 339 |
f() |
| 340 |
assert excinfo._getreprcrash() is None |
| 341 |
|
| 342 |
|
| 343 |
def test_excinfo_exconly(): |
| 344 |
with pytest.raises(ValueError) as excinfo: |
| 345 |
h() |
| 346 |
assert excinfo.exconly().startswith("ValueError") |
| 347 |
with pytest.raises(ValueError) as excinfo: |
| 348 |
raise ValueError("hello\nworld") |
| 349 |
msg = excinfo.exconly(tryshort=True) |
| 350 |
assert msg.startswith("ValueError") |
| 351 |
assert msg.endswith("world") |
| 352 |
|
| 353 |
|
| 354 |
def test_excinfo_repr_str() -> None: |
| 355 |
with pytest.raises(ValueError) as excinfo1: |
| 356 |
h() |
| 357 |
assert repr(excinfo1) == "<ExceptionInfo ValueError() tblen=4>" |
| 358 |
assert str(excinfo1) == "<ExceptionInfo ValueError() tblen=4>" |
| 359 |
|
| 360 |
class CustomException(Exception): |
| 361 |
def __repr__(self): |
| 362 |
return "custom_repr" |
| 363 |
|
| 364 |
def raises() -> None: |
| 365 |
raise CustomException() |
| 366 |
|
| 367 |
with pytest.raises(CustomException) as excinfo2: |
| 368 |
raises() |
| 369 |
assert repr(excinfo2) == "<ExceptionInfo custom_repr tblen=2>" |
| 370 |
assert str(excinfo2) == "<ExceptionInfo custom_repr tblen=2>" |
| 371 |
|
| 372 |
|
| 373 |
def test_excinfo_for_later() -> None: |
| 374 |
e = ExceptionInfo[BaseException].for_later() |
| 375 |
assert "for raises" in repr(e) |
| 376 |
assert "for raises" in str(e) |
| 377 |
|
| 378 |
|
| 379 |
def test_excinfo_errisinstance(): |
| 380 |
with pytest.raises(ValueError) as excinfo: |
| 381 |
h() |
| 382 |
assert excinfo.errisinstance(ValueError) |
| 383 |
|
| 384 |
|
| 385 |
def test_excinfo_no_sourcecode(): |
| 386 |
try: |
| 387 |
exec("raise ValueError()") |
| 388 |
except ValueError: |
| 389 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 390 |
s = str(excinfo.traceback[-1]) |
| 391 |
# TODO: Since Python 3.13b1 under pytest-xdist, the * is `import |
| 392 |
# sys;exec(eval(sys.stdin.readline()))` (execnet bootstrap code) |
| 393 |
# instead of `???` like before. Is this OK? |
| 394 |
fnmatch.fnmatch(s, " File '<string>':1 in <module>\n *\n") |
| 395 |
|
| 396 |
|
| 397 |
def test_excinfo_no_python_sourcecode(tmp_path: Path) -> None: |
| 398 |
# XXX: simplified locally testable version |
| 399 |
tmp_path.joinpath("test.txt").write_text("{{ h()}}:", encoding="utf-8") |
| 400 |
|
| 401 |
jinja2 = pytest.importorskip("jinja2") |
| 402 |
loader = jinja2.FileSystemLoader(str(tmp_path)) |
| 403 |
env = jinja2.Environment(loader=loader) |
| 404 |
template = env.get_template("test.txt") |
| 405 |
with pytest.raises(ValueError) as excinfo: |
| 406 |
template.render(h=h) |
| 407 |
for item in excinfo.traceback: |
| 408 |
print(item) # XXX: for some reason jinja.Template.render is printed in full |
| 409 |
_ = item.source # shouldn't fail |
| 410 |
if isinstance(item.path, Path) and item.path.name == "test.txt": |
| 411 |
assert str(item.source) == "{{ h()}}:" |
| 412 |
|
| 413 |
|
| 414 |
def test_entrysource_Queue_example(): |
| 415 |
try: |
| 416 |
queue.Queue().get(timeout=0.001) |
| 417 |
except queue.Empty: |
| 418 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 419 |
entry = excinfo.traceback[-1] |
| 420 |
source = entry.getsource() |
| 421 |
assert source is not None |
| 422 |
s = str(source).strip() |
| 423 |
assert s.startswith("def get") |
| 424 |
|
| 425 |
|
| 426 |
def test_codepath_Queue_example() -> None: |
| 427 |
try: |
| 428 |
queue.Queue().get(timeout=0.001) |
| 429 |
except queue.Empty: |
| 430 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 431 |
entry = excinfo.traceback[-1] |
| 432 |
path = entry.path |
| 433 |
assert isinstance(path, Path) |
| 434 |
assert path.name.lower() == "queue.py" |
| 435 |
assert path.exists() |
| 436 |
|
| 437 |
|
| 438 |
def test_match_succeeds(): |
| 439 |
with pytest.raises(ZeroDivisionError) as excinfo: |
| 440 |
_ = 0 // 0 |
| 441 |
excinfo.match(r".*zero.*") |
| 442 |
|
| 443 |
|
| 444 |
def test_match_raises_error(pytester: Pytester) -> None: |
| 445 |
pytester.makepyfile( |
| 446 |
""" |
| 447 |
import pytest |
| 448 |
def test_division_zero(): |
| 449 |
with pytest.raises(ZeroDivisionError) as excinfo: |
| 450 |
0 / 0 |
| 451 |
excinfo.match(r'[123]+') |
| 452 |
""" |
| 453 |
) |
| 454 |
result = pytester.runpytest("--tb=short") |
| 455 |
assert result.ret != 0 |
| 456 |
|
| 457 |
match = [ |
| 458 |
r"E\s+AssertionError: Regex pattern did not match.", |
| 459 |
r"E\s+Expected regex: '\[123\]\+'", |
| 460 |
r"E\s+Actual message: 'division by zero'", |
| 461 |
] |
| 462 |
result.stdout.re_match_lines(match) |
| 463 |
result.stdout.no_fnmatch_line("*__tracebackhide__ = True*") |
| 464 |
|
| 465 |
result = pytester.runpytest("--fulltrace") |
| 466 |
assert result.ret != 0 |
| 467 |
result.stdout.re_match_lines([r".*__tracebackhide__ = True.*", *match]) |
| 468 |
|
| 469 |
|
| 470 |
def test_raises_accepts_generic_group() -> None: |
| 471 |
with pytest.raises(ExceptionGroup[Exception]) as exc_info: |
| 472 |
raise ExceptionGroup("", [RuntimeError()]) |
| 473 |
assert exc_info.group_contains(RuntimeError) |
| 474 |
|
| 475 |
|
| 476 |
def test_raises_accepts_generic_base_group() -> None: |
| 477 |
with pytest.raises(BaseExceptionGroup[BaseException]) as exc_info: |
| 478 |
raise ExceptionGroup("", [RuntimeError()]) |
| 479 |
assert exc_info.group_contains(RuntimeError) |
| 480 |
|
| 481 |
|
| 482 |
def test_raises_rejects_specific_generic_group() -> None: |
| 483 |
with pytest.raises(ValueError): |
| 484 |
pytest.raises(ExceptionGroup[RuntimeError]) |
| 485 |
|
| 486 |
|
| 487 |
def test_raises_accepts_generic_group_in_tuple() -> None: |
| 488 |
with pytest.raises((ValueError, ExceptionGroup[Exception])) as exc_info: |
| 489 |
raise ExceptionGroup("", [RuntimeError()]) |
| 490 |
assert exc_info.group_contains(RuntimeError) |
| 491 |
|
| 492 |
|
| 493 |
def test_raises_exception_escapes_generic_group() -> None: |
| 494 |
try: |
| 495 |
with pytest.raises(ExceptionGroup[Exception]): |
| 496 |
raise ValueError("my value error") |
| 497 |
except ValueError as e: |
| 498 |
assert str(e) == "my value error" |
| 499 |
else: |
| 500 |
pytest.fail("Expected ValueError to be raised") |
| 501 |
|
| 502 |
|
| 503 |
class TestGroupContains: |
| 504 |
def test_contains_exception_type(self) -> None: |
| 505 |
exc_group = ExceptionGroup("", [RuntimeError()]) |
| 506 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 507 |
raise exc_group |
| 508 |
assert exc_info.group_contains(RuntimeError) |
| 509 |
|
| 510 |
def test_doesnt_contain_exception_type(self) -> None: |
| 511 |
exc_group = ExceptionGroup("", [ValueError()]) |
| 512 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 513 |
raise exc_group |
| 514 |
assert not exc_info.group_contains(RuntimeError) |
| 515 |
|
| 516 |
def test_contains_exception_match(self) -> None: |
| 517 |
exc_group = ExceptionGroup("", [RuntimeError("exception message")]) |
| 518 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 519 |
raise exc_group |
| 520 |
assert exc_info.group_contains(RuntimeError, match=r"^exception message$") |
| 521 |
|
| 522 |
def test_doesnt_contain_exception_match(self) -> None: |
| 523 |
exc_group = ExceptionGroup("", [RuntimeError("message that will not match")]) |
| 524 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 525 |
raise exc_group |
| 526 |
assert not exc_info.group_contains(RuntimeError, match=r"^exception message$") |
| 527 |
|
| 528 |
def test_contains_exception_type_unlimited_depth(self) -> None: |
| 529 |
exc_group = ExceptionGroup("", [ExceptionGroup("", [RuntimeError()])]) |
| 530 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 531 |
raise exc_group |
| 532 |
assert exc_info.group_contains(RuntimeError) |
| 533 |
|
| 534 |
def test_contains_exception_type_at_depth_1(self) -> None: |
| 535 |
exc_group = ExceptionGroup("", [RuntimeError()]) |
| 536 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 537 |
raise exc_group |
| 538 |
assert exc_info.group_contains(RuntimeError, depth=1) |
| 539 |
|
| 540 |
def test_doesnt_contain_exception_type_past_depth(self) -> None: |
| 541 |
exc_group = ExceptionGroup("", [ExceptionGroup("", [RuntimeError()])]) |
| 542 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 543 |
raise exc_group |
| 544 |
assert not exc_info.group_contains(RuntimeError, depth=1) |
| 545 |
|
| 546 |
def test_contains_exception_type_specific_depth(self) -> None: |
| 547 |
exc_group = ExceptionGroup("", [ExceptionGroup("", [RuntimeError()])]) |
| 548 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 549 |
raise exc_group |
| 550 |
assert exc_info.group_contains(RuntimeError, depth=2) |
| 551 |
|
| 552 |
def test_contains_exception_match_unlimited_depth(self) -> None: |
| 553 |
exc_group = ExceptionGroup( |
| 554 |
"", [ExceptionGroup("", [RuntimeError("exception message")])] |
| 555 |
) |
| 556 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 557 |
raise exc_group |
| 558 |
assert exc_info.group_contains(RuntimeError, match=r"^exception message$") |
| 559 |
|
| 560 |
def test_contains_exception_match_at_depth_1(self) -> None: |
| 561 |
exc_group = ExceptionGroup("", [RuntimeError("exception message")]) |
| 562 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 563 |
raise exc_group |
| 564 |
assert exc_info.group_contains( |
| 565 |
RuntimeError, match=r"^exception message$", depth=1 |
| 566 |
) |
| 567 |
|
| 568 |
def test_doesnt_contain_exception_match_past_depth(self) -> None: |
| 569 |
exc_group = ExceptionGroup( |
| 570 |
"", [ExceptionGroup("", [RuntimeError("exception message")])] |
| 571 |
) |
| 572 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 573 |
raise exc_group |
| 574 |
assert not exc_info.group_contains( |
| 575 |
RuntimeError, match=r"^exception message$", depth=1 |
| 576 |
) |
| 577 |
|
| 578 |
def test_contains_exception_match_specific_depth(self) -> None: |
| 579 |
exc_group = ExceptionGroup( |
| 580 |
"", [ExceptionGroup("", [RuntimeError("exception message")])] |
| 581 |
) |
| 582 |
with pytest.raises(ExceptionGroup) as exc_info: |
| 583 |
raise exc_group |
| 584 |
assert exc_info.group_contains( |
| 585 |
RuntimeError, match=r"^exception message$", depth=2 |
| 586 |
) |
| 587 |
|
| 588 |
|
| 589 |
class TestExceptionInfoFormatter: |
| 590 |
@pytest.fixture |
| 591 |
def importasmod(self, tmp_path: Path, _sys_snapshot): |
| 592 |
def importasmod(source): |
| 593 |
source = textwrap.dedent(source) |
| 594 |
modpath = tmp_path.joinpath("mod.py") |
| 595 |
tmp_path.joinpath("__init__.py").touch() |
| 596 |
modpath.write_text(source, encoding="utf-8") |
| 597 |
importlib.invalidate_caches() |
| 598 |
return import_path( |
| 599 |
modpath, root=tmp_path, consider_namespace_packages=False |
| 600 |
) |
| 601 |
|
| 602 |
return importasmod |
| 603 |
|
| 604 |
def test_repr_source(self): |
| 605 |
pr = ExceptionInfoFormatter() |
| 606 |
source = _pytest._code.Source( |
| 607 |
"""\ |
| 608 |
def f(x): |
| 609 |
pass |
| 610 |
""" |
| 611 |
).strip() |
| 612 |
pr.flow_marker = "|" # type: ignore[misc] |
| 613 |
lines = pr.get_source(source, 0) |
| 614 |
assert len(lines) == 2 |
| 615 |
assert lines[0] == "| def f(x):" |
| 616 |
assert lines[1] == " pass" |
| 617 |
|
| 618 |
def test_repr_source_out_of_bounds(self): |
| 619 |
pr = ExceptionInfoFormatter() |
| 620 |
source = _pytest._code.Source( |
| 621 |
"""\ |
| 622 |
def f(x): |
| 623 |
pass |
| 624 |
""" |
| 625 |
).strip() |
| 626 |
pr.flow_marker = "|" # type: ignore[misc] |
| 627 |
|
| 628 |
lines = pr.get_source(source, 100) |
| 629 |
assert len(lines) == 1 |
| 630 |
assert lines[0] == "| ???" |
| 631 |
|
| 632 |
lines = pr.get_source(source, -100) |
| 633 |
assert len(lines) == 1 |
| 634 |
assert lines[0] == "| ???" |
| 635 |
|
| 636 |
def test_repr_source_excinfo(self) -> None: |
| 637 |
"""Check if indentation is right.""" |
| 638 |
try: |
| 639 |
|
| 640 |
def f(): |
| 641 |
_ = 1 / 0 |
| 642 |
|
| 643 |
f() |
| 644 |
|
| 645 |
except BaseException: |
| 646 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 647 |
else: |
| 648 |
assert False, "did not raise" |
| 649 |
|
| 650 |
pr = ExceptionInfoFormatter() |
| 651 |
source = pr._getentrysource(excinfo.traceback[-1]) |
| 652 |
assert source is not None |
| 653 |
lines = pr.get_source(source, 1, excinfo) |
| 654 |
for line in lines: |
| 655 |
print(line) |
| 656 |
assert lines == [ |
| 657 |
" def f():", |
| 658 |
"> _ = 1 / 0", |
| 659 |
"E ZeroDivisionError: division by zero", |
| 660 |
] |
| 661 |
|
| 662 |
def test_repr_source_not_existing(self): |
| 663 |
pr = ExceptionInfoFormatter() |
| 664 |
co = compile("raise ValueError()", "", "exec") |
| 665 |
try: |
| 666 |
exec(co) |
| 667 |
except ValueError: |
| 668 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 669 |
repr = pr.repr_excinfo(excinfo) |
| 670 |
assert repr.reprtraceback.reprentries[1].lines[0] == "> ???" |
| 671 |
assert repr.chain[0][0].reprentries[1].lines[0] == "> ???" |
| 672 |
|
| 673 |
def test_repr_many_line_source_not_existing(self): |
| 674 |
pr = ExceptionInfoFormatter() |
| 675 |
co = compile( |
| 676 |
""" |
| 677 |
a = 1 |
| 678 |
raise ValueError() |
| 679 |
""", |
| 680 |
"", |
| 681 |
"exec", |
| 682 |
) |
| 683 |
try: |
| 684 |
exec(co) |
| 685 |
except ValueError: |
| 686 |
excinfo = _pytest._code.ExceptionInfo.from_current() |
| 687 |
repr = pr.repr_excinfo(excinfo) |
| 688 |
assert repr.reprtraceback.reprentries[1].lines[0] == "> ???" |
| 689 |
assert repr.chain[0][0].reprentries[1].lines[0] == "> ???" |
| 690 |
|
| 691 |
def test_repr_source_failing_fullsource(self, monkeypatch) -> None: |
| 692 |
pr = ExceptionInfoFormatter() |
| 693 |
|
| 694 |
try: |
| 695 |
_ = 1 / 0 |
| 696 |
except ZeroDivisionError: |
| 697 |
excinfo = ExceptionInfo.from_current() |
| 698 |
|
| 699 |
with monkeypatch.context() as m: |
| 700 |
m.setattr(_pytest._code.Code, "fullsource", property(lambda self: None)) |
| 701 |
repr = pr.repr_excinfo(excinfo) |
| 702 |
|
| 703 |
assert repr.reprtraceback.reprentries[0].lines[0] == "> ???" |
| 704 |
assert repr.chain[0][0].reprentries[0].lines[0] == "> ???" |
| 705 |
|
| 706 |
def test_repr_local(self) -> None: |
| 707 |
p = ExceptionInfoFormatter(showlocals=True) |
| 708 |
loc = {"y": 5, "z": 7, "x": 3, "@x": 2, "__builtins__": {}} |
| 709 |
reprlocals = p.repr_locals(loc) |
| 710 |
assert reprlocals is not None |
| 711 |
assert reprlocals.lines |
| 712 |
assert reprlocals.lines[0] == "__builtins__ = <builtins>" |
| 713 |
assert reprlocals.lines[1] == "x = 3" |
| 714 |
assert reprlocals.lines[2] == "y = 5" |
| 715 |
assert reprlocals.lines[3] == "z = 7" |
| 716 |
|
| 717 |
def test_repr_local_with_error(self) -> None: |
| 718 |
class ObjWithErrorInRepr: |
| 719 |
def __repr__(self): |
| 720 |
raise NotImplementedError |
| 721 |
|
| 722 |
p = ExceptionInfoFormatter(showlocals=True, truncate_locals=False) |
| 723 |
loc = {"x": ObjWithErrorInRepr(), "__builtins__": {}} |
| 724 |
reprlocals = p.repr_locals(loc) |
| 725 |
assert reprlocals is not None |
| 726 |
assert reprlocals.lines |
| 727 |
assert reprlocals.lines[0] == "__builtins__ = <builtins>" |
| 728 |
assert "[NotImplementedError() raised in repr()]" in reprlocals.lines[1] |
| 729 |
|
| 730 |
def test_repr_local_with_exception_in_class_property(self) -> None: |
| 731 |
class ExceptionWithBrokenClass(Exception): |
| 732 |
# Type ignored because it's bypassed intentionally. |
| 733 |
@property # type: ignore |
| 734 |
def __class__(self): |
| 735 |
raise TypeError("boom!") |
| 736 |
|
| 737 |
class ObjWithErrorInRepr: |
| 738 |
def __repr__(self): |
| 739 |
raise ExceptionWithBrokenClass() |
| 740 |
|
| 741 |
p = ExceptionInfoFormatter(showlocals=True, truncate_locals=False) |
| 742 |
loc = {"x": ObjWithErrorInRepr(), "__builtins__": {}} |
| 743 |
reprlocals = p.repr_locals(loc) |
| 744 |
assert reprlocals is not None |
| 745 |
assert reprlocals.lines |
| 746 |
assert reprlocals.lines[0] == "__builtins__ = <builtins>" |
| 747 |
assert "[ExceptionWithBrokenClass() raised in repr()]" in reprlocals.lines[1] |
| 748 |
|
| 749 |
def test_repr_local_truncated(self) -> None: |
| 750 |
loc = {"l": [i for i in range(10)]} |
| 751 |
p = ExceptionInfoFormatter(showlocals=True) |
| 752 |
truncated_reprlocals = p.repr_locals(loc) |
| 753 |
assert truncated_reprlocals is not None |
| 754 |
assert truncated_reprlocals.lines |
| 755 |
assert truncated_reprlocals.lines[0] == "l = [0, 1, 2, 3, 4, 5, ...]" |
| 756 |
|
| 757 |
q = ExceptionInfoFormatter(showlocals=True, truncate_locals=False) |
| 758 |
full_reprlocals = q.repr_locals(loc) |
| 759 |
assert full_reprlocals is not None |
| 760 |
assert full_reprlocals.lines |
| 761 |
assert full_reprlocals.lines[0] == "l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" |
| 762 |
|
| 763 |
def test_repr_args_not_truncated(self, importasmod) -> None: |
| 764 |
mod = importasmod( |
| 765 |
""" |
| 766 |
def func1(m): |
| 767 |
raise ValueError("hello\\nworld") |
| 768 |
""" |
| 769 |
) |
| 770 |
with pytest.raises(ValueError) as excinfo: |
| 771 |
mod.func1("m" * 500) |
| 772 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 773 |
entry = excinfo.traceback[-1] |
| 774 |
p = ExceptionInfoFormatter(funcargs=True, truncate_args=True) |
| 775 |
reprfuncargs = p.repr_args(entry) |
| 776 |
assert reprfuncargs is not None |
| 777 |
arg1 = cast(str, reprfuncargs.args[0][1]) |
| 778 |
assert len(arg1) < 500 |
| 779 |
assert "..." in arg1 |
| 780 |
# again without truncate |
| 781 |
p = ExceptionInfoFormatter(funcargs=True, truncate_args=False) |
| 782 |
reprfuncargs = p.repr_args(entry) |
| 783 |
assert reprfuncargs is not None |
| 784 |
assert reprfuncargs.args[0] == ("m", repr("m" * 500)) |
| 785 |
assert "..." not in reprfuncargs.args[0][1] |
| 786 |
|
| 787 |
def test_repr_tracebackentry_lines(self, importasmod) -> None: |
| 788 |
mod = importasmod( |
| 789 |
""" |
| 790 |
def func1(): |
| 791 |
raise ValueError("hello\\nworld") |
| 792 |
""" |
| 793 |
) |
| 794 |
with pytest.raises(ValueError) as excinfo: |
| 795 |
mod.func1() |
| 796 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 797 |
p = ExceptionInfoFormatter() |
| 798 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-1]) |
| 799 |
|
| 800 |
# test as intermittent entry |
| 801 |
lines = reprtb.lines |
| 802 |
assert lines[0] == " def func1():" |
| 803 |
assert lines[1] == '> raise ValueError("hello\\nworld")' |
| 804 |
|
| 805 |
# test as last entry |
| 806 |
p = ExceptionInfoFormatter(showlocals=True) |
| 807 |
repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) |
| 808 |
lines = repr_entry.lines |
| 809 |
assert lines[0] == " def func1():" |
| 810 |
assert lines[1] == '> raise ValueError("hello\\nworld")' |
| 811 |
assert lines[2] == "E ValueError: hello" |
| 812 |
assert lines[3] == "E world" |
| 813 |
assert not lines[4:] |
| 814 |
|
| 815 |
loc = repr_entry.reprfileloc |
| 816 |
assert loc is not None |
| 817 |
assert loc.path == mod.__file__ |
| 818 |
assert loc.lineno == 3 |
| 819 |
# assert loc.message == "ValueError: hello" |
| 820 |
|
| 821 |
def test_repr_tracebackentry_lines2(self, importasmod, tw_mock) -> None: |
| 822 |
mod = importasmod( |
| 823 |
""" |
| 824 |
def func1(m, x, y, z): |
| 825 |
raise ValueError("hello\\nworld") |
| 826 |
""" |
| 827 |
) |
| 828 |
with pytest.raises(ValueError) as excinfo: |
| 829 |
mod.func1("m" * 90, 5, 13, "z" * 120) |
| 830 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 831 |
entry = excinfo.traceback[-1] |
| 832 |
p = ExceptionInfoFormatter(funcargs=True) |
| 833 |
reprfuncargs = p.repr_args(entry) |
| 834 |
assert reprfuncargs is not None |
| 835 |
assert reprfuncargs.args[0] == ("m", repr("m" * 90)) |
| 836 |
assert reprfuncargs.args[1] == ("x", "5") |
| 837 |
assert reprfuncargs.args[2] == ("y", "13") |
| 838 |
assert reprfuncargs.args[3] == ("z", repr("z" * 120)) |
| 839 |
|
| 840 |
p = ExceptionInfoFormatter(funcargs=True) |
| 841 |
repr_entry = p.repr_traceback_entry(entry) |
| 842 |
assert repr_entry.reprfuncargs is not None |
| 843 |
assert repr_entry.reprfuncargs.args == reprfuncargs.args |
| 844 |
repr_entry.toterminal(tw_mock) |
| 845 |
assert tw_mock.lines[0] == "m = " + repr("m" * 90) |
| 846 |
assert tw_mock.lines[1] == "x = 5, y = 13" |
| 847 |
assert tw_mock.lines[2] == "z = " + repr("z" * 120) |
| 848 |
|
| 849 |
def test_repr_tracebackentry_lines_var_kw_args(self, importasmod, tw_mock) -> None: |
| 850 |
mod = importasmod( |
| 851 |
""" |
| 852 |
def func1(x, *y, **z): |
| 853 |
raise ValueError("hello\\nworld") |
| 854 |
""" |
| 855 |
) |
| 856 |
with pytest.raises(ValueError) as excinfo: |
| 857 |
mod.func1("a", "b", c="d") |
| 858 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 859 |
entry = excinfo.traceback[-1] |
| 860 |
p = ExceptionInfoFormatter(funcargs=True) |
| 861 |
reprfuncargs = p.repr_args(entry) |
| 862 |
assert reprfuncargs is not None |
| 863 |
assert reprfuncargs.args[0] == ("x", repr("a")) |
| 864 |
assert reprfuncargs.args[1] == ("y", repr(("b",))) |
| 865 |
assert reprfuncargs.args[2] == ("z", repr({"c": "d"})) |
| 866 |
|
| 867 |
p = ExceptionInfoFormatter(funcargs=True) |
| 868 |
repr_entry = p.repr_traceback_entry(entry) |
| 869 |
assert repr_entry.reprfuncargs |
| 870 |
assert repr_entry.reprfuncargs.args == reprfuncargs.args |
| 871 |
repr_entry.toterminal(tw_mock) |
| 872 |
assert tw_mock.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}" |
| 873 |
|
| 874 |
def test_repr_tracebackentry_short(self, importasmod) -> None: |
| 875 |
mod = importasmod( |
| 876 |
""" |
| 877 |
def func1(): |
| 878 |
raise ValueError("hello") |
| 879 |
def entry(): |
| 880 |
func1() |
| 881 |
""" |
| 882 |
) |
| 883 |
with pytest.raises(ValueError) as excinfo: |
| 884 |
mod.entry() |
| 885 |
p = ExceptionInfoFormatter(style="short") |
| 886 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-2]) |
| 887 |
lines = reprtb.lines |
| 888 |
basename = Path(mod.__file__).name |
| 889 |
assert lines[0] == " func1()" |
| 890 |
assert reprtb.reprfileloc is not None |
| 891 |
assert basename in str(reprtb.reprfileloc.path) |
| 892 |
assert reprtb.reprfileloc.lineno == 5 |
| 893 |
|
| 894 |
# test last entry |
| 895 |
p = ExceptionInfoFormatter(style="short") |
| 896 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) |
| 897 |
lines = reprtb.lines |
| 898 |
assert lines[0] == ' raise ValueError("hello")' |
| 899 |
assert lines[1] == "E ValueError: hello" |
| 900 |
assert reprtb.reprfileloc is not None |
| 901 |
assert basename in str(reprtb.reprfileloc.path) |
| 902 |
assert reprtb.reprfileloc.lineno == 3 |
| 903 |
|
| 904 |
@pytest.mark.skipif( |
| 905 |
"sys.version_info < (3,11)", |
| 906 |
reason="Column level traceback info added in python 3.11", |
| 907 |
) |
| 908 |
def test_repr_traceback_entry_short_carets(self, importasmod) -> None: |
| 909 |
mod = importasmod( |
| 910 |
""" |
| 911 |
def div_by_zero(): |
| 912 |
return 1 / 0 |
| 913 |
def func1(): |
| 914 |
return 42 + div_by_zero() |
| 915 |
def entry(): |
| 916 |
func1() |
| 917 |
""" |
| 918 |
) |
| 919 |
with pytest.raises(ZeroDivisionError) as excinfo: |
| 920 |
mod.entry() |
| 921 |
p = ExceptionInfoFormatter(style="short") |
| 922 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-3]) |
| 923 |
assert len(reprtb.lines) == 1 |
| 924 |
assert reprtb.lines[0] == " func1()" |
| 925 |
|
| 926 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-2]) |
| 927 |
assert len(reprtb.lines) == 2 |
| 928 |
assert reprtb.lines[0] == " return 42 + div_by_zero()" |
| 929 |
assert reprtb.lines[1] == " ^^^^^^^^^^^^^" |
| 930 |
|
| 931 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-1]) |
| 932 |
assert len(reprtb.lines) == 2 |
| 933 |
assert reprtb.lines[0] == " return 1 / 0" |
| 934 |
assert reprtb.lines[1] == " ^^^^^" |
| 935 |
|
| 936 |
def test_repr_tracebackentry_no(self, importasmod): |
| 937 |
mod = importasmod( |
| 938 |
""" |
| 939 |
def func1(): |
| 940 |
raise ValueError("hello") |
| 941 |
def entry(): |
| 942 |
func1() |
| 943 |
""" |
| 944 |
) |
| 945 |
with pytest.raises(ValueError) as excinfo: |
| 946 |
mod.entry() |
| 947 |
p = ExceptionInfoFormatter(style="no") |
| 948 |
p.repr_traceback_entry(excinfo.traceback[-2]) |
| 949 |
|
| 950 |
p = ExceptionInfoFormatter(style="no") |
| 951 |
reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo) |
| 952 |
lines = reprentry.lines |
| 953 |
assert lines[0] == "E ValueError: hello" |
| 954 |
assert not lines[1:] |
| 955 |
|
| 956 |
def test_repr_traceback_tbfilter(self, importasmod): |
| 957 |
__tracebackhide__ = True |
| 958 |
mod = importasmod( |
| 959 |
""" |
| 960 |
def f(x): |
| 961 |
raise ValueError(x) |
| 962 |
def entry(): |
| 963 |
f(0) |
| 964 |
""" |
| 965 |
) |
| 966 |
with pytest.raises(ValueError) as excinfo: |
| 967 |
mod.entry() |
| 968 |
p = ExceptionInfoFormatter(tbfilter=True) |
| 969 |
reprtb = p.repr_traceback(excinfo) |
| 970 |
assert len(reprtb.reprentries) == 2 |
| 971 |
p = ExceptionInfoFormatter(tbfilter=False) |
| 972 |
reprtb = p.repr_traceback(excinfo) |
| 973 |
assert len(reprtb.reprentries) == 3 |
| 974 |
|
| 975 |
def test_traceback_short_no_source( |
| 976 |
self, |
| 977 |
importasmod, |
| 978 |
monkeypatch: pytest.MonkeyPatch, |
| 979 |
) -> None: |
| 980 |
mod = importasmod( |
| 981 |
""" |
| 982 |
def func1(): |
| 983 |
raise ValueError("hello") |
| 984 |
def entry(): |
| 985 |
func1() |
| 986 |
""" |
| 987 |
) |
| 988 |
with pytest.raises(ValueError) as excinfo: |
| 989 |
mod.entry() |
| 990 |
from _pytest._code.code import Code |
| 991 |
|
| 992 |
with monkeypatch.context() as mp: |
| 993 |
mp.setattr(Code, "path", "bogus") |
| 994 |
p = ExceptionInfoFormatter(style="short") |
| 995 |
reprtb = p.repr_traceback_entry(excinfo.traceback[-2]) |
| 996 |
lines = reprtb.lines |
| 997 |
last_p = ExceptionInfoFormatter(style="short") |
| 998 |
last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo) |
| 999 |
last_lines = last_reprtb.lines |
| 1000 |
assert lines[0] == " func1()" |
| 1001 |
|
| 1002 |
assert last_lines[0] == ' raise ValueError("hello")' |
| 1003 |
assert last_lines[1] == "E ValueError: hello" |
| 1004 |
|
| 1005 |
def test_repr_traceback_and_excinfo(self, importasmod) -> None: |
| 1006 |
__tracebackhide__ = True |
| 1007 |
mod = importasmod( |
| 1008 |
""" |
| 1009 |
def f(x): |
| 1010 |
raise ValueError(x) |
| 1011 |
def entry(): |
| 1012 |
f(0) |
| 1013 |
""" |
| 1014 |
) |
| 1015 |
with pytest.raises(ValueError) as excinfo: |
| 1016 |
mod.entry() |
| 1017 |
|
| 1018 |
styles: tuple[TracebackStyle, ...] = ("long", "short") |
| 1019 |
for style in styles: |
| 1020 |
p = ExceptionInfoFormatter(style=style) |
| 1021 |
reprtb = p.repr_traceback(excinfo) |
| 1022 |
assert len(reprtb.reprentries) == 2 |
| 1023 |
assert reprtb.style == style |
| 1024 |
assert not reprtb.extraline |
| 1025 |
repr = p.repr_excinfo(excinfo) |
| 1026 |
assert repr.reprtraceback |
| 1027 |
assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries) |
| 1028 |
|
| 1029 |
assert repr.chain[0][0] |
| 1030 |
assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries) |
| 1031 |
assert repr.reprcrash is not None |
| 1032 |
assert repr.reprcrash.path.endswith("mod.py") |
| 1033 |
assert repr.reprcrash.message == "ValueError: 0" |
| 1034 |
|
| 1035 |
def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch) -> None: |
| 1036 |
__tracebackhide__ = True |
| 1037 |
mod = importasmod( |
| 1038 |
""" |
| 1039 |
def f(x): |
| 1040 |
raise ValueError(x) |
| 1041 |
def entry(): |
| 1042 |
f(0) |
| 1043 |
""" |
| 1044 |
) |
| 1045 |
with pytest.raises(ValueError) as excinfo: |
| 1046 |
mod.entry() |
| 1047 |
|
| 1048 |
p = ExceptionInfoFormatter(abspath=False) |
| 1049 |
|
| 1050 |
raised = 0 |
| 1051 |
|
| 1052 |
orig_path_cwd = Path.cwd |
| 1053 |
|
| 1054 |
def raiseos(): |
| 1055 |
nonlocal raised |
| 1056 |
upframe = sys._getframe().f_back |
| 1057 |
assert upframe is not None |
| 1058 |
if upframe.f_code.co_name == "_makepath": |
| 1059 |
# Only raise with expected calls, and not accidentally via 'inspect' |
| 1060 |
# See 79ae86cc3f76d69460e1c7beca4ce95e68ab80a6 |
| 1061 |
raised += 1 |
| 1062 |
raise OSError(2, "custom_oserror") |
| 1063 |
return orig_path_cwd() |
| 1064 |
|
| 1065 |
monkeypatch.setattr(Path, "cwd", raiseos) |
| 1066 |
assert p._makepath(Path(__file__)) == __file__ |
| 1067 |
assert raised == 1 |
| 1068 |
repr_tb = p.repr_traceback(excinfo) |
| 1069 |
|
| 1070 |
matcher = LineMatcher(str(repr_tb).splitlines()) |
| 1071 |
matcher.fnmatch_lines( |
| 1072 |
[ |
| 1073 |
"def entry():", |
| 1074 |
"> f(0)", |
| 1075 |
"", |
| 1076 |
f"{mod.__file__}:5: ", |
| 1077 |
"_ _ *", |
| 1078 |
"", |
| 1079 |
" def f(x):", |
| 1080 |
"> raise ValueError(x)", |
| 1081 |
"E ValueError: 0", |
| 1082 |
"", |
| 1083 |
f"{mod.__file__}:3: ValueError", |
| 1084 |
] |
| 1085 |
) |
| 1086 |
assert raised == 3 |
| 1087 |
|
| 1088 |
def test_repr_excinfo_addouterr(self, importasmod, tw_mock): |
| 1089 |
mod = importasmod( |
| 1090 |
""" |
| 1091 |
def entry(): |
| 1092 |
raise ValueError() |
| 1093 |
""" |
| 1094 |
) |
| 1095 |
with pytest.raises(ValueError) as excinfo: |
| 1096 |
mod.entry() |
| 1097 |
repr = excinfo.getrepr() |
| 1098 |
repr.addsection("title", "content") |
| 1099 |
repr.toterminal(tw_mock) |
| 1100 |
assert tw_mock.lines[-1] == "content" |
| 1101 |
assert tw_mock.lines[-2] == ("-", "title") |
| 1102 |
|
| 1103 |
def test_repr_excinfo_reprcrash(self, importasmod) -> None: |
| 1104 |
mod = importasmod( |
| 1105 |
""" |
| 1106 |
def entry(): |
| 1107 |
raise ValueError() |
| 1108 |
""" |
| 1109 |
) |
| 1110 |
with pytest.raises(ValueError) as excinfo: |
| 1111 |
mod.entry() |
| 1112 |
repr = excinfo.getrepr() |
| 1113 |
assert repr.reprcrash is not None |
| 1114 |
assert repr.reprcrash.path.endswith("mod.py") |
| 1115 |
assert repr.reprcrash.lineno == 3 |
| 1116 |
assert repr.reprcrash.message == "ValueError" |
| 1117 |
assert str(repr.reprcrash).endswith("mod.py:3: ValueError") |
| 1118 |
|
| 1119 |
def test_repr_traceback_recursion(self, importasmod): |
| 1120 |
mod = importasmod( |
| 1121 |
""" |
| 1122 |
def rec2(x): |
| 1123 |
return rec1(x+1) |
| 1124 |
def rec1(x): |
| 1125 |
return rec2(x-1) |
| 1126 |
def entry(): |
| 1127 |
rec1(42) |
| 1128 |
""" |
| 1129 |
) |
| 1130 |
with pytest.raises(RuntimeError) as excinfo: |
| 1131 |
mod.entry() |
| 1132 |
|
| 1133 |
for style in ("short", "long", "no"): |
| 1134 |
p = ExceptionInfoFormatter(style=style) |
| 1135 |
reprtb = p.repr_traceback(excinfo) |
| 1136 |
assert reprtb.extraline == "!!! Recursion detected (same locals & position)" |
| 1137 |
assert str(reprtb) |
| 1138 |
|
| 1139 |
def test_reprexcinfo_getrepr(self, importasmod) -> None: |
| 1140 |
mod = importasmod( |
| 1141 |
""" |
| 1142 |
def f(x): |
| 1143 |
raise ValueError(x) |
| 1144 |
def entry(): |
| 1145 |
f(0) |
| 1146 |
""" |
| 1147 |
) |
| 1148 |
with pytest.raises(ValueError) as excinfo: |
| 1149 |
mod.entry() |
| 1150 |
|
| 1151 |
styles: tuple[TracebackStyle, ...] = ("short", "long", "no") |
| 1152 |
for style in styles: |
| 1153 |
for showlocals in (True, False): |
| 1154 |
repr = excinfo.getrepr(style=style, showlocals=showlocals) |
| 1155 |
assert repr.reprtraceback.style == style |
| 1156 |
|
| 1157 |
assert isinstance(repr, ExceptionChainRepr) |
| 1158 |
for r in repr.chain: |
| 1159 |
assert r[0].style == style |
| 1160 |
|
| 1161 |
def test_reprexcinfo_unicode(self): |
| 1162 |
from _pytest._code.code import TerminalRepr |
| 1163 |
|
| 1164 |
class MyRepr(TerminalRepr): |
| 1165 |
def toterminal(self, tw: TerminalWriter) -> None: |
| 1166 |
tw.line("я") |
| 1167 |
|
| 1168 |
x = str(MyRepr()) |
| 1169 |
assert x == "я" |
| 1170 |
|
| 1171 |
def test_toterminal_long(self, importasmod, tw_mock): |
| 1172 |
__tracebackhide__ = True |
| 1173 |
mod = importasmod( |
| 1174 |
""" |
| 1175 |
def g(x): |
| 1176 |
raise ValueError(x) |
| 1177 |
def f(): |
| 1178 |
g(3) |
| 1179 |
""" |
| 1180 |
) |
| 1181 |
with pytest.raises(ValueError) as excinfo: |
| 1182 |
mod.f() |
| 1183 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 1184 |
repr = excinfo.getrepr() |
| 1185 |
repr.toterminal(tw_mock) |
| 1186 |
assert tw_mock.lines[0] == "" |
| 1187 |
tw_mock.lines.pop(0) |
| 1188 |
assert tw_mock.lines[0] == " def f():" |
| 1189 |
assert tw_mock.lines[1] == "> g(3)" |
| 1190 |
assert tw_mock.lines[2] == "" |
| 1191 |
line = tw_mock.get_write_msg(3) |
| 1192 |
assert line.endswith("mod.py") |
| 1193 |
assert tw_mock.lines[4] == (":5: ") |
| 1194 |
assert tw_mock.lines[5] == ("_ ", None) |
| 1195 |
assert tw_mock.lines[6] == "" |
| 1196 |
assert tw_mock.lines[7] == " def g(x):" |
| 1197 |
assert tw_mock.lines[8] == "> raise ValueError(x)" |
| 1198 |
assert tw_mock.lines[9] == "E ValueError: 3" |
| 1199 |
assert tw_mock.lines[10] == "" |
| 1200 |
line = tw_mock.get_write_msg(11) |
| 1201 |
assert line.endswith("mod.py") |
| 1202 |
assert tw_mock.lines[12] == ":3: ValueError" |
| 1203 |
|
| 1204 |
def test_toterminal_long_missing_source( |
| 1205 |
self, importasmod, tmp_path: Path, tw_mock |
| 1206 |
) -> None: |
| 1207 |
__tracebackhide__ = True |
| 1208 |
mod = importasmod( |
| 1209 |
""" |
| 1210 |
def g(x): |
| 1211 |
raise ValueError(x) |
| 1212 |
def f(): |
| 1213 |
g(3) |
| 1214 |
""" |
| 1215 |
) |
| 1216 |
with pytest.raises(ValueError) as excinfo: |
| 1217 |
mod.f() |
| 1218 |
tmp_path.joinpath("mod.py").unlink() |
| 1219 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 1220 |
repr = excinfo.getrepr() |
| 1221 |
repr.toterminal(tw_mock) |
| 1222 |
assert tw_mock.lines[0] == "" |
| 1223 |
tw_mock.lines.pop(0) |
| 1224 |
assert tw_mock.lines[0] == "> ???" |
| 1225 |
assert tw_mock.lines[1] == "" |
| 1226 |
line = tw_mock.get_write_msg(2) |
| 1227 |
assert line.endswith("mod.py") |
| 1228 |
assert tw_mock.lines[3] == ":5: " |
| 1229 |
assert tw_mock.lines[4] == ("_ ", None) |
| 1230 |
assert tw_mock.lines[5] == "" |
| 1231 |
assert tw_mock.lines[6] == "> ???" |
| 1232 |
assert tw_mock.lines[7] == "E ValueError: 3" |
| 1233 |
assert tw_mock.lines[8] == "" |
| 1234 |
line = tw_mock.get_write_msg(9) |
| 1235 |
assert line.endswith("mod.py") |
| 1236 |
assert tw_mock.lines[10] == ":3: ValueError" |
| 1237 |
|
| 1238 |
def test_toterminal_long_incomplete_source( |
| 1239 |
self, importasmod, tmp_path: Path, tw_mock |
| 1240 |
) -> None: |
| 1241 |
__tracebackhide__ = True |
| 1242 |
mod = importasmod( |
| 1243 |
""" |
| 1244 |
def g(x): |
| 1245 |
raise ValueError(x) |
| 1246 |
def f(): |
| 1247 |
g(3) |
| 1248 |
""" |
| 1249 |
) |
| 1250 |
with pytest.raises(ValueError) as excinfo: |
| 1251 |
mod.f() |
| 1252 |
tmp_path.joinpath("mod.py").write_text("asdf", encoding="utf-8") |
| 1253 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 1254 |
repr = excinfo.getrepr() |
| 1255 |
repr.toterminal(tw_mock) |
| 1256 |
assert tw_mock.lines[0] == "" |
| 1257 |
tw_mock.lines.pop(0) |
| 1258 |
assert tw_mock.lines[0] == "> ???" |
| 1259 |
assert tw_mock.lines[1] == "" |
| 1260 |
line = tw_mock.get_write_msg(2) |
| 1261 |
assert line.endswith("mod.py") |
| 1262 |
assert tw_mock.lines[3] == ":5: " |
| 1263 |
assert tw_mock.lines[4] == ("_ ", None) |
| 1264 |
assert tw_mock.lines[5] == "" |
| 1265 |
assert tw_mock.lines[6] == "> ???" |
| 1266 |
assert tw_mock.lines[7] == "E ValueError: 3" |
| 1267 |
assert tw_mock.lines[8] == "" |
| 1268 |
line = tw_mock.get_write_msg(9) |
| 1269 |
assert line.endswith("mod.py") |
| 1270 |
assert tw_mock.lines[10] == ":3: ValueError" |
| 1271 |
|
| 1272 |
def test_toterminal_long_filenames( |
| 1273 |
self, importasmod, tw_mock, monkeypatch: MonkeyPatch |
| 1274 |
) -> None: |
| 1275 |
__tracebackhide__ = True |
| 1276 |
mod = importasmod( |
| 1277 |
""" |
| 1278 |
def f(): |
| 1279 |
raise ValueError() |
| 1280 |
""" |
| 1281 |
) |
| 1282 |
with pytest.raises(ValueError) as excinfo: |
| 1283 |
mod.f() |
| 1284 |
path = Path(mod.__file__) |
| 1285 |
monkeypatch.chdir(path.parent) |
| 1286 |
repr = excinfo.getrepr(abspath=False) |
| 1287 |
repr.toterminal(tw_mock) |
| 1288 |
x = bestrelpath(Path.cwd(), path) |
| 1289 |
if len(x) < len(str(path)): |
| 1290 |
msg = tw_mock.get_write_msg(-2) |
| 1291 |
assert msg == "mod.py" |
| 1292 |
assert tw_mock.lines[-1] == ":3: ValueError" |
| 1293 |
|
| 1294 |
repr = excinfo.getrepr(abspath=True) |
| 1295 |
repr.toterminal(tw_mock) |
| 1296 |
msg = tw_mock.get_write_msg(-2) |
| 1297 |
assert msg == str(path) |
| 1298 |
line = tw_mock.lines[-1] |
| 1299 |
assert line == ":3: ValueError" |
| 1300 |
|
| 1301 |
def test_toterminal_value(self, importasmod, tw_mock): |
| 1302 |
mod = importasmod( |
| 1303 |
""" |
| 1304 |
def g(x): |
| 1305 |
raise ValueError(x) |
| 1306 |
def f(): |
| 1307 |
g('some_value') |
| 1308 |
""" |
| 1309 |
) |
| 1310 |
with pytest.raises(ValueError) as excinfo: |
| 1311 |
mod.f() |
| 1312 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 1313 |
repr = excinfo.getrepr(style="value") |
| 1314 |
repr.toterminal(tw_mock) |
| 1315 |
|
| 1316 |
assert tw_mock.get_write_msg(0) == "some_value" |
| 1317 |
assert tw_mock.get_write_msg(1) == "\n" |
| 1318 |
|
| 1319 |
@pytest.mark.parametrize( |
| 1320 |
"reproptions", |
| 1321 |
[ |
| 1322 |
pytest.param( |
| 1323 |
{ |
| 1324 |
"style": style, |
| 1325 |
"showlocals": showlocals, |
| 1326 |
"funcargs": funcargs, |
| 1327 |
"tbfilter": tbfilter, |
| 1328 |
}, |
| 1329 |
id=f"style={style},showlocals={showlocals},funcargs={funcargs},tbfilter={tbfilter}", |
| 1330 |
) |
| 1331 |
for style in ["long", "short", "line", "no", "native", "value", "auto"] |
| 1332 |
for showlocals in (True, False) |
| 1333 |
for tbfilter in (True, False) |
| 1334 |
for funcargs in (True, False) |
| 1335 |
], |
| 1336 |
) |
| 1337 |
def test_format_excinfo(self, reproptions: dict[str, Any]) -> None: |
| 1338 |
def bar(): |
| 1339 |
assert False, "some error" |
| 1340 |
|
| 1341 |
def foo(): |
| 1342 |
bar() |
| 1343 |
|
| 1344 |
# using inline functions as opposed to importasmod so we get source code lines |
| 1345 |
# in the tracebacks (otherwise getinspect doesn't find the source code). |
| 1346 |
with pytest.raises(AssertionError) as excinfo: |
| 1347 |
foo() |
| 1348 |
file = io.StringIO() |
| 1349 |
tw = TerminalWriter(file=file) |
| 1350 |
repr = excinfo.getrepr(**reproptions) |
| 1351 |
repr.toterminal(tw) |
| 1352 |
assert file.getvalue() |
| 1353 |
|
| 1354 |
def test_traceback_repr_style(self, importasmod, tw_mock): |
| 1355 |
__tracebackhide__ = True |
| 1356 |
mod = importasmod( |
| 1357 |
""" |
| 1358 |
def f(): |
| 1359 |
g() |
| 1360 |
def g(): |
| 1361 |
h() |
| 1362 |
def h(): |
| 1363 |
i() |
| 1364 |
def i(): |
| 1365 |
raise ValueError() |
| 1366 |
""" |
| 1367 |
) |
| 1368 |
with pytest.raises(ValueError) as excinfo: |
| 1369 |
mod.f() |
| 1370 |
excinfo.traceback = excinfo.traceback.filter(excinfo) |
| 1371 |
excinfo.traceback = _pytest._code.Traceback( |
| 1372 |
entry if i not in (1, 2) else entry.with_repr_style("short") |
| 1373 |
for i, entry in enumerate(excinfo.traceback) |
| 1374 |
) |
| 1375 |
r = excinfo.getrepr(style="long") |
| 1376 |
r.toterminal(tw_mock) |
| 1377 |
for line in tw_mock.lines: |
| 1378 |
print(line) |
| 1379 |
assert tw_mock.lines[0] == "" |
| 1380 |
assert tw_mock.lines[1] == " def f():" |
| 1381 |
assert tw_mock.lines[2] == "> g()" |
| 1382 |
assert tw_mock.lines[3] == "" |
| 1383 |
msg = tw_mock.get_write_msg(4) |
| 1384 |
assert msg.endswith("mod.py") |
| 1385 |
assert tw_mock.lines[5] == ":3: " |
| 1386 |
assert tw_mock.lines[6] == ("_ ", None) |
| 1387 |
tw_mock.get_write_msg(7) |
| 1388 |
assert tw_mock.lines[8].endswith("in g") |
| 1389 |
assert tw_mock.lines[9] == " h()" |
| 1390 |
tw_mock.get_write_msg(10) |
| 1391 |
assert tw_mock.lines[11].endswith("in h") |
| 1392 |
assert tw_mock.lines[12] == " i()" |
| 1393 |
assert tw_mock.lines[13] == ("_ ", None) |
| 1394 |
assert tw_mock.lines[14] == "" |
| 1395 |
assert tw_mock.lines[15] == " def i():" |
| 1396 |
assert tw_mock.lines[16] == "> raise ValueError()" |
| 1397 |
assert tw_mock.lines[17] == "E ValueError" |
| 1398 |
assert tw_mock.lines[18] == "" |
| 1399 |
msg = tw_mock.get_write_msg(19) |
| 1400 |
msg.endswith("mod.py") |
| 1401 |
assert tw_mock.lines[20] == ":9: ValueError" |
| 1402 |
|
| 1403 |
def test_exc_chain_repr(self, importasmod, tw_mock): |
| 1404 |
__tracebackhide__ = True |
| 1405 |
mod = importasmod( |
| 1406 |
""" |
| 1407 |
class Err(Exception): |
| 1408 |
pass |
| 1409 |
def f(): |
| 1410 |
try: |
| 1411 |
g() |
| 1412 |
except Exception as e: |
| 1413 |
raise Err() from e |
| 1414 |
finally: |
| 1415 |
h() |
| 1416 |
def g(): |
| 1417 |
raise ValueError() |
| 1418 |
|
| 1419 |
def h(): |
| 1420 |
if True: raise AttributeError() |
| 1421 |
""" |
| 1422 |
) |
| 1423 |
with pytest.raises(AttributeError) as excinfo: |
| 1424 |
mod.f() |
| 1425 |
r = excinfo.getrepr(style="long") |
| 1426 |
r.toterminal(tw_mock) |
| 1427 |
for line in tw_mock.lines: |
| 1428 |
print(line) |
| 1429 |
assert tw_mock.lines[0] == "" |
| 1430 |
assert tw_mock.lines[1] == " def f():" |
| 1431 |
assert tw_mock.lines[2] == " try:" |
| 1432 |
assert tw_mock.lines[3] == "> g()" |
| 1433 |
assert tw_mock.lines[4] == "" |
| 1434 |
line = tw_mock.get_write_msg(5) |
| 1435 |
assert line.endswith("mod.py") |
| 1436 |
assert tw_mock.lines[6] == ":6: " |
| 1437 |
assert tw_mock.lines[7] == ("_ ", None) |
| 1438 |
assert tw_mock.lines[8] == "" |
| 1439 |
assert tw_mock.lines[9] == " def g():" |
| 1440 |
assert tw_mock.lines[10] == "> raise ValueError()" |
| 1441 |
assert tw_mock.lines[11] == "E ValueError" |
| 1442 |
assert tw_mock.lines[12] == "" |
| 1443 |
line = tw_mock.get_write_msg(13) |
| 1444 |
assert line.endswith("mod.py") |
| 1445 |
assert tw_mock.lines[14] == ":12: ValueError" |
| 1446 |
assert tw_mock.lines[15] == "" |
| 1447 |
assert ( |
| 1448 |
tw_mock.lines[16] |
| 1449 |
== "The above exception was the direct cause of the following exception:" |
| 1450 |
) |
| 1451 |
assert tw_mock.lines[17] == "" |
| 1452 |
assert tw_mock.lines[18] == " def f():" |
| 1453 |
assert tw_mock.lines[19] == " try:" |
| 1454 |
assert tw_mock.lines[20] == " g()" |
| 1455 |
assert tw_mock.lines[21] == " except Exception as e:" |
| 1456 |
assert tw_mock.lines[22] == "> raise Err() from e" |
| 1457 |
assert tw_mock.lines[23] == "E test_exc_chain_repr0.mod.Err" |
| 1458 |
assert tw_mock.lines[24] == "" |
| 1459 |
line = tw_mock.get_write_msg(25) |
| 1460 |
assert line.endswith("mod.py") |
| 1461 |
assert tw_mock.lines[26] == ":8: Err" |
| 1462 |
assert tw_mock.lines[27] == "" |
| 1463 |
assert ( |
| 1464 |
tw_mock.lines[28] |
| 1465 |
== "During handling of the above exception, another exception occurred:" |
| 1466 |
) |
| 1467 |
assert tw_mock.lines[29] == "" |
| 1468 |
assert tw_mock.lines[30] == " def f():" |
| 1469 |
assert tw_mock.lines[31] == " try:" |
| 1470 |
assert tw_mock.lines[32] == " g()" |
| 1471 |
assert tw_mock.lines[33] == " except Exception as e:" |
| 1472 |
assert tw_mock.lines[34] == " raise Err() from e" |
| 1473 |
assert tw_mock.lines[35] == " finally:" |
| 1474 |
assert tw_mock.lines[36] == "> h()" |
| 1475 |
assert tw_mock.lines[37] == "" |
| 1476 |
line = tw_mock.get_write_msg(38) |
| 1477 |
assert line.endswith("mod.py") |
| 1478 |
assert tw_mock.lines[39] == ":10: " |
| 1479 |
assert tw_mock.lines[40] == ("_ ", None) |
| 1480 |
assert tw_mock.lines[41] == "" |
| 1481 |
assert tw_mock.lines[42] == " def h():" |
| 1482 |
# On python 3.11 and greater, check for carets in the traceback. |
| 1483 |
if sys.version_info >= (3, 11): |
| 1484 |
assert tw_mock.lines[43] == "> if True: raise AttributeError()" |
| 1485 |
assert tw_mock.lines[44] == " ^^^^^^^^^^^^^^^^^^^^^^" |
| 1486 |
assert tw_mock.lines[45] == "E AttributeError" |
| 1487 |
assert tw_mock.lines[46] == "" |
| 1488 |
line = tw_mock.get_write_msg(47) |
| 1489 |
assert line.endswith("mod.py") |
| 1490 |
assert tw_mock.lines[48] == ":15: AttributeError" |
| 1491 |
else: |
| 1492 |
assert tw_mock.lines[43] == "> if True: raise AttributeError()" |
| 1493 |
assert tw_mock.lines[44] == "E AttributeError" |
| 1494 |
assert tw_mock.lines[45] == "" |
| 1495 |
line = tw_mock.get_write_msg(46) |
| 1496 |
assert line.endswith("mod.py") |
| 1497 |
assert tw_mock.lines[47] == ":15: AttributeError" |
| 1498 |
|
| 1499 |
@pytest.mark.parametrize("mode", ["from_none", "explicit_suppress"]) |
| 1500 |
def test_exc_repr_chain_suppression(self, importasmod, mode, tw_mock): |
| 1501 |
"""Check that exc repr does not show chained exceptions in Python 3. |
| 1502 |
- When the exception is raised with "from None" |
| 1503 |
- Explicitly suppressed with "chain=False" to ExceptionInfo.getrepr(). |
| 1504 |
""" |
| 1505 |
__tracebackhide__ = True |
| 1506 |
raise_suffix = " from None" if mode == "from_none" else "" |
| 1507 |
mod = importasmod( |
| 1508 |
f""" |
| 1509 |
def f(): |
| 1510 |
try: |
| 1511 |
g() |
| 1512 |
except Exception: |
| 1513 |
raise AttributeError(){raise_suffix} |
| 1514 |
def g(): |
| 1515 |
raise ValueError() |
| 1516 |
""" |
| 1517 |
) |
| 1518 |
with pytest.raises(AttributeError) as excinfo: |
| 1519 |
mod.f() |
| 1520 |
r = excinfo.getrepr(style="long", chain=mode != "explicit_suppress") |
| 1521 |
r.toterminal(tw_mock) |
| 1522 |
for line in tw_mock.lines: |
| 1523 |
print(line) |
| 1524 |
assert tw_mock.lines[0] == "" |
| 1525 |
assert tw_mock.lines[1] == " def f():" |
| 1526 |
assert tw_mock.lines[2] == " try:" |
| 1527 |
assert tw_mock.lines[3] == " g()" |
| 1528 |
assert tw_mock.lines[4] == " except Exception:" |
| 1529 |
assert tw_mock.lines[5] == f"> raise AttributeError(){raise_suffix}" |
| 1530 |
assert tw_mock.lines[6] == "E AttributeError" |
| 1531 |
assert tw_mock.lines[7] == "" |
| 1532 |
line = tw_mock.get_write_msg(8) |
| 1533 |
assert line.endswith("mod.py") |
| 1534 |
assert tw_mock.lines[9] == ":6: AttributeError" |
| 1535 |
assert len(tw_mock.lines) == 10 |
| 1536 |
|
| 1537 |
@pytest.mark.parametrize( |
| 1538 |
"reason, description", |
| 1539 |
[ |
| 1540 |
pytest.param( |
| 1541 |
"cause", |
| 1542 |
"The above exception was the direct cause of the following exception:", |
| 1543 |
id="cause", |
| 1544 |
), |
| 1545 |
pytest.param( |
| 1546 |
"context", |
| 1547 |
"During handling of the above exception, another exception occurred:", |
| 1548 |
id="context", |
| 1549 |
), |
| 1550 |
], |
| 1551 |
) |
| 1552 |
def test_exc_chain_repr_without_traceback(self, importasmod, reason, description): |
| 1553 |
""" |
| 1554 |
Handle representation of exception chains where one of the exceptions doesn't have a |
| 1555 |
real traceback, such as those raised in a subprocess submitted by the multiprocessing |
| 1556 |
module (#1984). |
| 1557 |
""" |
| 1558 |
exc_handling_code = " from e" if reason == "cause" else "" |
| 1559 |
mod = importasmod( |
| 1560 |
f""" |
| 1561 |
def f(): |
| 1562 |
try: |
| 1563 |
g() |
| 1564 |
except Exception as e: |
| 1565 |
raise RuntimeError('runtime problem'){exc_handling_code} |
| 1566 |
def g(): |
| 1567 |
raise ValueError('invalid value') |
| 1568 |
""" |
| 1569 |
) |
| 1570 |
|
| 1571 |
with pytest.raises(RuntimeError) as excinfo: |
| 1572 |
mod.f() |
| 1573 |
|
| 1574 |
# emulate the issue described in #1984 |
| 1575 |
attr = f"__{reason}__" |
| 1576 |
getattr(excinfo.value, attr).__traceback__ = None |
| 1577 |
|
| 1578 |
r = excinfo.getrepr() |
| 1579 |
file = io.StringIO() |
| 1580 |
tw = TerminalWriter(file=file) |
| 1581 |
tw.hasmarkup = False |
| 1582 |
r.toterminal(tw) |
| 1583 |
|
| 1584 |
matcher = LineMatcher(file.getvalue().splitlines()) |
| 1585 |
matcher.fnmatch_lines( |
| 1586 |
[ |
| 1587 |
"ValueError: invalid value", |
| 1588 |
description, |
| 1589 |
"* except Exception as e:", |
| 1590 |
"> * raise RuntimeError('runtime problem')" + exc_handling_code, |
| 1591 |
"E *RuntimeError: runtime problem", |
| 1592 |
] |
| 1593 |
) |
| 1594 |
|
| 1595 |
def test_exc_chain_repr_cycle(self, importasmod, tw_mock): |
| 1596 |
__tracebackhide__ = True |
| 1597 |
mod = importasmod( |
| 1598 |
""" |
| 1599 |
class Err(Exception): |
| 1600 |
pass |
| 1601 |
def fail(): |
| 1602 |
return 0 / 0 |
| 1603 |
def reraise(): |
| 1604 |
try: |
| 1605 |
fail() |
| 1606 |
except ZeroDivisionError as e: |
| 1607 |
raise Err() from e |
| 1608 |
def unreraise(): |
| 1609 |
try: |
| 1610 |
reraise() |
| 1611 |
except Err as e: |
| 1612 |
raise e.__cause__ |
| 1613 |
""" |
| 1614 |
) |
| 1615 |
with pytest.raises(ZeroDivisionError) as excinfo: |
| 1616 |
mod.unreraise() |
| 1617 |
r = excinfo.getrepr(style="short") |
| 1618 |
r.toterminal(tw_mock) |
| 1619 |
out = "\n".join(line for line in tw_mock.lines if isinstance(line, str)) |
| 1620 |
# Assert highlighting carets in python3.11+ |
| 1621 |
if sys.version_info >= (3, 11): |
| 1622 |
expected_out = textwrap.dedent( |
| 1623 |
"""\ |
| 1624 |
:13: in unreraise |
| 1625 |
reraise() |
| 1626 |
:10: in reraise |
| 1627 |
raise Err() from e |
| 1628 |
E test_exc_chain_repr_cycle0.mod.Err |
| 1629 |
|
| 1630 |
During handling of the above exception, another exception occurred: |
| 1631 |
:15: in unreraise |
| 1632 |
raise e.__cause__ |
| 1633 |
:8: in reraise |
| 1634 |
fail() |
| 1635 |
:5: in fail |
| 1636 |
return 0 / 0 |
| 1637 |
^^^^^ |
| 1638 |
E ZeroDivisionError: division by zero""" |
| 1639 |
) |
| 1640 |
else: |
| 1641 |
expected_out = textwrap.dedent( |
| 1642 |
"""\ |
| 1643 |
:13: in unreraise |
| 1644 |
reraise() |
| 1645 |
:10: in reraise |
| 1646 |
raise Err() from e |
| 1647 |
E test_exc_chain_repr_cycle0.mod.Err |
| 1648 |
|
| 1649 |
During handling of the above exception, another exception occurred: |
| 1650 |
:15: in unreraise |
| 1651 |
raise e.__cause__ |
| 1652 |
:8: in reraise |
| 1653 |
fail() |
| 1654 |
:5: in fail |
| 1655 |
return 0 / 0 |
| 1656 |
E ZeroDivisionError: division by zero""" |
| 1657 |
) |
| 1658 |
assert out == expected_out |
| 1659 |
|
| 1660 |
def test_exec_type_error_filter(self, importasmod): |
| 1661 |
"""See #7742""" |
| 1662 |
mod = importasmod( |
| 1663 |
"""\ |
| 1664 |
def f(): |
| 1665 |
exec("a = 1", {}, []) |
| 1666 |
""" |
| 1667 |
) |
| 1668 |
with pytest.raises(TypeError) as excinfo: |
| 1669 |
mod.f() |
| 1670 |
# previously crashed with `AttributeError: list has no attribute get` |
| 1671 |
excinfo.traceback.filter(excinfo) |
| 1672 |
|
| 1673 |
|
| 1674 |
@pytest.mark.parametrize("style", ["short", "long"]) |
| 1675 |
@pytest.mark.parametrize("encoding", [None, "utf8", "utf16"]) |
| 1676 |
def test_repr_traceback_with_unicode(style, encoding): |
| 1677 |
if encoding is None: |
| 1678 |
msg: str | bytes = "☹" |
| 1679 |
else: |
| 1680 |
msg = "☹".encode(encoding) |
| 1681 |
try: |
| 1682 |
raise RuntimeError(msg) |
| 1683 |
except RuntimeError: |
| 1684 |
e_info = ExceptionInfo.from_current() |
| 1685 |
formatter = ExceptionInfoFormatter(style=style) |
| 1686 |
repr_traceback = formatter.repr_traceback(e_info) |
| 1687 |
assert repr_traceback is not None |
| 1688 |
|
| 1689 |
|
| 1690 |
def test_cwd_deleted(pytester: Pytester) -> None: |
| 1691 |
pytester.makepyfile( |
| 1692 |
""" |
| 1693 |
import os |
| 1694 |
|
| 1695 |
def test(tmp_path): |
| 1696 |
os.chdir(tmp_path) |
| 1697 |
tmp_path.unlink() |
| 1698 |
assert False |
| 1699 |
""" |
| 1700 |
) |
| 1701 |
result = pytester.runpytest() |
| 1702 |
result.stdout.fnmatch_lines(["* 1 failed in *"]) |
| 1703 |
result.stdout.no_fnmatch_line("*INTERNALERROR*") |
| 1704 |
result.stderr.no_fnmatch_line("*INTERNALERROR*") |
| 1705 |
|
| 1706 |
|
| 1707 |
def test_regression_negative_line_index(pytester: Pytester) -> None: |
| 1708 |
""" |
| 1709 |
With Python 3.10 alphas, there was an INTERNALERROR reported in |
| 1710 |
https://github.com/pytest-dev/pytest/pull/8227 |
| 1711 |
This test ensures it does not regress. |
| 1712 |
""" |
| 1713 |
pytester.makepyfile( |
| 1714 |
""" |
| 1715 |
import ast |
| 1716 |
import pytest |
| 1717 |
|
| 1718 |
|
| 1719 |
def test_literal_eval(): |
| 1720 |
with pytest.raises(ValueError, match="^$"): |
| 1721 |
ast.literal_eval("pytest") |
| 1722 |
""" |
| 1723 |
) |
| 1724 |
result = pytester.runpytest() |
| 1725 |
result.stdout.fnmatch_lines(["* 1 failed in *"]) |
| 1726 |
result.stdout.no_fnmatch_line("*INTERNALERROR*") |
| 1727 |
result.stderr.no_fnmatch_line("*INTERNALERROR*") |
| 1728 |
|
| 1729 |
|
| 1730 |
@pytest.mark.usefixtures("limited_recursion_depth") |
| 1731 |
def test_exception_repr_extraction_error_on_recursion(): |
| 1732 |
""" |
| 1733 |
Ensure we can properly detect a recursion error even |
| 1734 |
if some locals raise error on comparison (#2459). |
| 1735 |
""" |
| 1736 |
|
| 1737 |
class numpy_like: |
| 1738 |
def __eq__(self, other): |
| 1739 |
if type(other) is numpy_like: |
| 1740 |
raise ValueError( |
| 1741 |
"The truth value of an array " |
| 1742 |
"with more than one element is ambiguous." |
| 1743 |
) |
| 1744 |
|
| 1745 |
def a(x): |
| 1746 |
return b(numpy_like()) |
| 1747 |
|
| 1748 |
def b(x): |
| 1749 |
return a(numpy_like()) |
| 1750 |
|
| 1751 |
with pytest.raises(RuntimeError) as excinfo: |
| 1752 |
a(numpy_like()) |
| 1753 |
|
| 1754 |
matcher = LineMatcher(str(excinfo.getrepr()).splitlines()) |
| 1755 |
matcher.fnmatch_lines( |
| 1756 |
[ |
| 1757 |
"!!! Recursion error detected, but an error occurred locating the origin of recursion.", |
| 1758 |
"*The following exception happened*", |
| 1759 |
"*ValueError: The truth value of an array*", |
| 1760 |
] |
| 1761 |
) |
| 1762 |
|
| 1763 |
|
| 1764 |
@pytest.mark.usefixtures("limited_recursion_depth") |
| 1765 |
def test_no_recursion_index_on_recursion_error(): |
| 1766 |
""" |
| 1767 |
Ensure that we don't break in case we can't find the recursion index |
| 1768 |
during a recursion error (#2486). |
| 1769 |
""" |
| 1770 |
|
| 1771 |
class RecursionDepthError: |
| 1772 |
def __getattr__(self, attr): |
| 1773 |
return getattr(self, "_" + attr) |
| 1774 |
|
| 1775 |
with pytest.raises(RuntimeError) as excinfo: |
| 1776 |
_ = RecursionDepthError().trigger |
| 1777 |
assert "maximum recursion" in str(excinfo.getrepr()) |
| 1778 |
|
| 1779 |
|
| 1780 |
def _exceptiongroup_common( |
| 1781 |
pytester: Pytester, |
| 1782 |
outer_chain: str, |
| 1783 |
inner_chain: str, |
| 1784 |
native: bool, |
| 1785 |
) -> None: |
| 1786 |
pre_raise = "exceptiongroup." if not native else "" |
| 1787 |
pre_catch = pre_raise if sys.version_info < (3, 11) else "" |
| 1788 |
filestr = f""" |
| 1789 |
{"import exceptiongroup" if not native else ""} |
| 1790 |
import pytest |
| 1791 |
|
| 1792 |
def f(): raise ValueError("From f()") |
| 1793 |
def g(): raise BaseException("From g()") |
| 1794 |
|
| 1795 |
def inner(inner_chain): |
| 1796 |
excs = [] |
| 1797 |
for callback in [f, g]: |
| 1798 |
try: |
| 1799 |
callback() |
| 1800 |
except BaseException as err: |
| 1801 |
excs.append(err) |
| 1802 |
if excs: |
| 1803 |
if inner_chain == "none": |
| 1804 |
raise {pre_raise}BaseExceptionGroup("Oops", excs) |
| 1805 |
try: |
| 1806 |
raise SyntaxError() |
| 1807 |
except SyntaxError as e: |
| 1808 |
if inner_chain == "from": |
| 1809 |
raise {pre_raise}BaseExceptionGroup("Oops", excs) from e |
| 1810 |
else: |
| 1811 |
raise {pre_raise}BaseExceptionGroup("Oops", excs) |
| 1812 |
|
| 1813 |
def outer(outer_chain, inner_chain): |
| 1814 |
try: |
| 1815 |
inner(inner_chain) |
| 1816 |
except {pre_catch}BaseExceptionGroup as e: |
| 1817 |
if outer_chain == "none": |
| 1818 |
raise |
| 1819 |
if outer_chain == "from": |
| 1820 |
raise IndexError() from e |
| 1821 |
else: |
| 1822 |
raise IndexError() |
| 1823 |
|
| 1824 |
|
| 1825 |
def test(): |
| 1826 |
outer("{outer_chain}", "{inner_chain}") |
| 1827 |
""" |
| 1828 |
pytester.makepyfile(test_excgroup=filestr) |
| 1829 |
result = pytester.runpytest() |
| 1830 |
match_lines = [] |
| 1831 |
if inner_chain in ("another", "from"): |
| 1832 |
match_lines.append(r"SyntaxError: <no detail available>") |
| 1833 |
|
| 1834 |
match_lines += [ |
| 1835 |
r" + Exception Group Traceback (most recent call last):", |
| 1836 |
rf" \| {pre_catch}BaseExceptionGroup: Oops \(2 sub-exceptions\)", |
| 1837 |
r" \| ValueError: From f\(\)", |
| 1838 |
r" \| BaseException: From g\(\)", |
| 1839 |
r"=* short test summary info =*", |
| 1840 |
] |
| 1841 |
if outer_chain in ("another", "from"): |
| 1842 |
match_lines.append(r"FAILED test_excgroup.py::test - IndexError") |
| 1843 |
else: |
| 1844 |
match_lines.append( |
| 1845 |
rf"FAILED test_excgroup.py::test - {pre_catch}BaseExceptionGroup: Oops \(2.*" |
| 1846 |
) |
| 1847 |
result.stdout.re_match_lines(match_lines) |
| 1848 |
# Check for traceback filtering of pytest internals. |
| 1849 |
result.stdout.no_fnmatch_line("*, line *, in pytest_pyfunc_call") |
| 1850 |
result.stdout.no_fnmatch_line("*, line *, in pytest_runtest_call") |
| 1851 |
|
| 1852 |
|
| 1853 |
@pytest.mark.skipif( |
| 1854 |
sys.version_info < (3, 11), reason="Native ExceptionGroup not implemented" |
| 1855 |
) |
| 1856 |
@pytest.mark.parametrize("outer_chain", ["none", "from", "another"]) |
| 1857 |
@pytest.mark.parametrize("inner_chain", ["none", "from", "another"]) |
| 1858 |
def test_native_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None: |
| 1859 |
_exceptiongroup_common(pytester, outer_chain, inner_chain, native=True) |
| 1860 |
|
| 1861 |
|
| 1862 |
@pytest.mark.parametrize("outer_chain", ["none", "from", "another"]) |
| 1863 |
@pytest.mark.parametrize("inner_chain", ["none", "from", "another"]) |
| 1864 |
def test_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None: |
| 1865 |
# with py>=3.11 does not depend on exceptiongroup, though there is a toxenv for it |
| 1866 |
pytest.importorskip("exceptiongroup") |
| 1867 |
_exceptiongroup_common(pytester, outer_chain, inner_chain, native=False) |
| 1868 |
|
| 1869 |
|
| 1870 |
def test_exceptiongroup_short_summary_info(pytester: Pytester): |
| 1871 |
pytester.makepyfile( |
| 1872 |
""" |
| 1873 |
import sys |
| 1874 |
|
| 1875 |
if sys.version_info < (3, 11): |
| 1876 |
from exceptiongroup import BaseExceptionGroup, ExceptionGroup |
| 1877 |
|
| 1878 |
def test_base() -> None: |
| 1879 |
raise BaseExceptionGroup("NOT IN SUMMARY", [SystemExit("a" * 10)]) |
| 1880 |
|
| 1881 |
def test_nonbase() -> None: |
| 1882 |
raise ExceptionGroup("NOT IN SUMMARY", [ValueError("a" * 10)]) |
| 1883 |
|
| 1884 |
def test_nested() -> None: |
| 1885 |
raise ExceptionGroup( |
| 1886 |
"NOT DISPLAYED", [ |
| 1887 |
ExceptionGroup("NOT IN SUMMARY", [ValueError("a" * 10)]) |
| 1888 |
] |
| 1889 |
) |
| 1890 |
|
| 1891 |
def test_multiple() -> None: |
| 1892 |
raise ExceptionGroup( |
| 1893 |
"b" * 10, |
| 1894 |
[ |
| 1895 |
ValueError("NOT IN SUMMARY"), |
| 1896 |
TypeError("NOT IN SUMMARY"), |
| 1897 |
] |
| 1898 |
) |
| 1899 |
|
| 1900 |
def test_nested_multiple() -> None: |
| 1901 |
raise ExceptionGroup( |
| 1902 |
"b" * 10, |
| 1903 |
[ |
| 1904 |
ExceptionGroup( |
| 1905 |
"c" * 10, |
| 1906 |
[ |
| 1907 |
ValueError("NOT IN SUMMARY"), |
| 1908 |
TypeError("NOT IN SUMMARY"), |
| 1909 |
] |
| 1910 |
) |
| 1911 |
] |
| 1912 |
) |
| 1913 |
""" |
| 1914 |
) |
| 1915 |
# run with -vv to not truncate summary info, default width in tests is very low |
| 1916 |
result = pytester.runpytest("-vv") |
| 1917 |
assert result.ret == 1 |
| 1918 |
backport_str = "exceptiongroup." if sys.version_info < (3, 11) else "" |
| 1919 |
result.stdout.fnmatch_lines( |
| 1920 |
[ |
| 1921 |
"*= short test summary info =*", |
| 1922 |
( |
| 1923 |
"FAILED test_exceptiongroup_short_summary_info.py::test_base - " |
| 1924 |
"SystemExit('aaaaaaaaaa') [single exception in BaseExceptionGroup]" |
| 1925 |
), |
| 1926 |
( |
| 1927 |
"FAILED test_exceptiongroup_short_summary_info.py::test_nonbase - " |
| 1928 |
"ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]" |
| 1929 |
), |
| 1930 |
( |
| 1931 |
"FAILED test_exceptiongroup_short_summary_info.py::test_nested - " |
| 1932 |
"ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]" |
| 1933 |
), |
| 1934 |
( |
| 1935 |
"FAILED test_exceptiongroup_short_summary_info.py::test_multiple - " |
| 1936 |
f"{backport_str}ExceptionGroup: bbbbbbbbbb (2 sub-exceptions)" |
| 1937 |
), |
| 1938 |
( |
| 1939 |
"FAILED test_exceptiongroup_short_summary_info.py::test_nested_multiple - " |
| 1940 |
f"{backport_str}ExceptionGroup: bbbbbbbbbb (1 sub-exception)" |
| 1941 |
), |
| 1942 |
"*= 5 failed in *", |
| 1943 |
] |
| 1944 |
) |
| 1945 |
|
| 1946 |
|
| 1947 |
@pytest.mark.parametrize("tbstyle", ("long", "short", "auto", "line", "native")) |
| 1948 |
@pytest.mark.parametrize("group", (True, False), ids=("group", "bare")) |
| 1949 |
def test_all_entries_hidden(pytester: Pytester, tbstyle: str, group: bool) -> None: |
| 1950 |
"""Regression test for #10903.""" |
| 1951 |
pytester.makepyfile( |
| 1952 |
f""" |
| 1953 |
import sys |
| 1954 |
if sys.version_info < (3, 11): |
| 1955 |
from exceptiongroup import ExceptionGroup |
| 1956 |
def test(): |
| 1957 |
__tracebackhide__ = True |
| 1958 |
raise {'ExceptionGroup("", [ValueError("bar")])' if group else 'ValueError("bar")'} |
| 1959 |
""" |
| 1960 |
) |
| 1961 |
result = pytester.runpytest("--tb", tbstyle) |
| 1962 |
assert result.ret == 1 |
| 1963 |
if tbstyle != "line": |
| 1964 |
result.stdout.fnmatch_lines(["*ValueError: bar"]) |
| 1965 |
if tbstyle not in ("line", "native"): |
| 1966 |
result.stdout.fnmatch_lines(["All traceback entries are hidden.*"]) |
| 1967 |
|
| 1968 |
|
| 1969 |
def test_hidden_entries_of_chained_exceptions_are_not_shown(pytester: Pytester) -> None: |
| 1970 |
"""Hidden entries of chained exceptions are not shown (#1904).""" |
| 1971 |
p = pytester.makepyfile( |
| 1972 |
""" |
| 1973 |
def g1(): |
| 1974 |
__tracebackhide__ = True |
| 1975 |
str.does_not_exist |
| 1976 |
|
| 1977 |
def f3(): |
| 1978 |
__tracebackhide__ = True |
| 1979 |
1 / 0 |
| 1980 |
|
| 1981 |
def f2(): |
| 1982 |
try: |
| 1983 |
f3() |
| 1984 |
except Exception: |
| 1985 |
g1() |
| 1986 |
|
| 1987 |
def f1(): |
| 1988 |
__tracebackhide__ = True |
| 1989 |
f2() |
| 1990 |
|
| 1991 |
def test(): |
| 1992 |
f1() |
| 1993 |
""" |
| 1994 |
) |
| 1995 |
result = pytester.runpytest(str(p), "--tb=short") |
| 1996 |
assert result.ret == 1 |
| 1997 |
result.stdout.fnmatch_lines( |
| 1998 |
[ |
| 1999 |
"*.py:11: in f2", |
| 2000 |
" f3()", |
| 2001 |
"E ZeroDivisionError: division by zero", |
| 2002 |
"", |
| 2003 |
"During handling of the above exception, another exception occurred:", |
| 2004 |
"*.py:20: in test", |
| 2005 |
" f1()", |
| 2006 |
"*.py:13: in f2", |
| 2007 |
" g1()", |
| 2008 |
"E AttributeError:*'does_not_exist'", |
| 2009 |
], |
| 2010 |
consecutive=True, |
| 2011 |
) |
| 2012 |
|
| 2013 |
|
| 2014 |
def add_note(err: BaseException, msg: str) -> None: |
| 2015 |
"""Adds a note to an exception inplace.""" |
| 2016 |
if sys.version_info < (3, 11): |
| 2017 |
err.__notes__ = [*getattr(err, "__notes__", []), msg] # type: ignore[attr-defined] |
| 2018 |
else: |
| 2019 |
err.add_note(msg) |
| 2020 |
|
| 2021 |
|
| 2022 |
@pytest.mark.parametrize( |
| 2023 |
"error,notes,match", |
| 2024 |
[ |
| 2025 |
(Exception("test"), [], "test"), |
| 2026 |
(AssertionError("foo"), ["bar"], "bar"), |
| 2027 |
(AssertionError("foo"), ["bar", "baz"], "bar"), |
| 2028 |
(AssertionError("foo"), ["bar", "baz"], "baz"), |
| 2029 |
(ValueError("foo"), ["bar", "baz"], re.compile(r"bar\nbaz", re.MULTILINE)), |
| 2030 |
(ValueError("foo"), ["bar", "baz"], re.compile(r"BAZ", re.IGNORECASE)), |
| 2031 |
], |
| 2032 |
) |
| 2033 |
def test_check_error_notes_success( |
| 2034 |
error: Exception, notes: list[str], match: str |
| 2035 |
) -> None: |
| 2036 |
for note in notes: |
| 2037 |
add_note(error, note) |
| 2038 |
|
| 2039 |
with pytest.raises(Exception, match=match): |
| 2040 |
raise error |
| 2041 |
|
| 2042 |
|
| 2043 |
@pytest.mark.parametrize( |
| 2044 |
"error, notes, match", |
| 2045 |
[ |
| 2046 |
(Exception("test"), [], "foo"), |
| 2047 |
(AssertionError("foo"), ["bar"], "baz"), |
| 2048 |
(AssertionError("foo"), ["bar"], "foo\nbaz"), |
| 2049 |
], |
| 2050 |
) |
| 2051 |
def test_check_error_notes_failure( |
| 2052 |
error: Exception, notes: list[str], match: str |
| 2053 |
) -> None: |
| 2054 |
for note in notes: |
| 2055 |
add_note(error, note) |
| 2056 |
|
| 2057 |
with pytest.raises(AssertionError): |
| 2058 |
with pytest.raises(type(error), match=match): |
| 2059 |
raise error |