| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import io |
| 5 |
import re |
| 6 |
import sys |
| 7 |
|
| 8 |
from _pytest.outcomes import Failed |
| 9 |
from _pytest.pytester import Pytester |
| 10 |
from _pytest.warning_types import PytestWarning |
| 11 |
import pytest |
| 12 |
|
| 13 |
|
| 14 |
def wrap_escape(s: str) -> str: |
| 15 |
return "^" + re.escape(s) + "$" |
| 16 |
|
| 17 |
|
| 18 |
class TestRaises: |
| 19 |
def test_check_callable(self) -> None: |
| 20 |
with pytest.raises(TypeError, match=r".* must be callable"): |
| 21 |
pytest.raises(RuntimeError, "int('qwe')") # type: ignore[call-overload] |
| 22 |
|
| 23 |
def test_raises(self): |
| 24 |
with pytest.raises(ValueError) as excinfo: |
| 25 |
int("qwe") |
| 26 |
assert "invalid literal" in str(excinfo.value) |
| 27 |
|
| 28 |
def test_raises_function(self): |
| 29 |
with pytest.raises(ValueError) as excinfo: |
| 30 |
int("hello") |
| 31 |
assert "invalid literal" in str(excinfo.value) |
| 32 |
|
| 33 |
def test_raises_does_not_allow_none(self): |
| 34 |
with pytest.raises( |
| 35 |
ValueError, |
| 36 |
match=wrap_escape("You must specify at least one parameter to match on."), |
| 37 |
): |
| 38 |
# We're testing that this invalid usage gives a helpful error, |
| 39 |
# so we can ignore Mypy telling us that None is invalid. |
| 40 |
pytest.raises(expected_exception=None) # type: ignore |
| 41 |
|
| 42 |
# it's unclear if this message is helpful, and if it is, should it trigger more |
| 43 |
# liberally? Usually you'd get a TypeError here |
| 44 |
def test_raises_false_and_arg(self): |
| 45 |
with pytest.raises( |
| 46 |
ValueError, |
| 47 |
match=wrap_escape( |
| 48 |
"Expected an exception type or a tuple of exception types, but got `False`. " |
| 49 |
"Raising exceptions is already understood as failing the test, so you don't need " |
| 50 |
"any special code to say 'this should never raise an exception'." |
| 51 |
), |
| 52 |
): |
| 53 |
pytest.raises(False, int) # type: ignore[call-overload] |
| 54 |
|
| 55 |
def test_raises_does_not_allow_empty_tuple(self): |
| 56 |
with pytest.raises( |
| 57 |
ValueError, |
| 58 |
match=wrap_escape("You must specify at least one parameter to match on."), |
| 59 |
): |
| 60 |
pytest.raises(expected_exception=()) |
| 61 |
|
| 62 |
def test_raises_callable_no_exception(self) -> None: |
| 63 |
class A: |
| 64 |
def __call__(self): |
| 65 |
pass |
| 66 |
|
| 67 |
try: |
| 68 |
pytest.raises(ValueError, A()) |
| 69 |
except pytest.fail.Exception: |
| 70 |
pass |
| 71 |
|
| 72 |
def test_raises_falsey_type_error(self) -> None: |
| 73 |
with pytest.raises(TypeError): |
| 74 |
with pytest.raises(AssertionError, match=0): # type: ignore[call-overload] |
| 75 |
raise AssertionError("ohai") |
| 76 |
|
| 77 |
def test_raises_repr_inflight(self): |
| 78 |
"""Ensure repr() on an exception info inside a pytest.raises with block works (#4386)""" |
| 79 |
|
| 80 |
class E(Exception): |
| 81 |
pass |
| 82 |
|
| 83 |
with pytest.raises(E) as excinfo: |
| 84 |
# this test prints the inflight uninitialized object |
| 85 |
# using repr and str as well as pprint to demonstrate |
| 86 |
# it works |
| 87 |
print(str(excinfo)) |
| 88 |
print(repr(excinfo)) |
| 89 |
import pprint |
| 90 |
|
| 91 |
pprint.pprint(excinfo) |
| 92 |
raise E() |
| 93 |
|
| 94 |
def test_raises_as_contextmanager(self, pytester: Pytester) -> None: |
| 95 |
pytester.makepyfile( |
| 96 |
""" |
| 97 |
import pytest |
| 98 |
import _pytest._code |
| 99 |
|
| 100 |
def test_simple(): |
| 101 |
with pytest.raises(ZeroDivisionError) as excinfo: |
| 102 |
assert isinstance(excinfo, _pytest._code.ExceptionInfo) |
| 103 |
1/0 |
| 104 |
print(excinfo) |
| 105 |
assert excinfo.type == ZeroDivisionError |
| 106 |
assert isinstance(excinfo.value, ZeroDivisionError) |
| 107 |
|
| 108 |
def test_noraise(): |
| 109 |
with pytest.raises(pytest.raises.Exception): |
| 110 |
with pytest.raises(ValueError): |
| 111 |
int() |
| 112 |
|
| 113 |
def test_raise_wrong_exception_passes_by(): |
| 114 |
with pytest.raises(ZeroDivisionError): |
| 115 |
with pytest.raises(ValueError): |
| 116 |
1/0 |
| 117 |
""" |
| 118 |
) |
| 119 |
result = pytester.runpytest() |
| 120 |
result.stdout.fnmatch_lines(["*3 passed*"]) |
| 121 |
|
| 122 |
def test_does_not_raise(self, pytester: Pytester) -> None: |
| 123 |
pytester.makepyfile( |
| 124 |
""" |
| 125 |
from contextlib import nullcontext as does_not_raise |
| 126 |
import pytest |
| 127 |
|
| 128 |
@pytest.mark.parametrize('example_input,expectation', [ |
| 129 |
(3, does_not_raise()), |
| 130 |
(2, does_not_raise()), |
| 131 |
(1, does_not_raise()), |
| 132 |
(0, pytest.raises(ZeroDivisionError)), |
| 133 |
]) |
| 134 |
def test_division(example_input, expectation): |
| 135 |
'''Test how much I know division.''' |
| 136 |
with expectation: |
| 137 |
assert (6 / example_input) is not None |
| 138 |
""" |
| 139 |
) |
| 140 |
result = pytester.runpytest() |
| 141 |
result.stdout.fnmatch_lines(["*4 passed*"]) |
| 142 |
|
| 143 |
def test_does_not_raise_does_raise(self, pytester: Pytester) -> None: |
| 144 |
pytester.makepyfile( |
| 145 |
""" |
| 146 |
from contextlib import nullcontext as does_not_raise |
| 147 |
import pytest |
| 148 |
|
| 149 |
@pytest.mark.parametrize('example_input,expectation', [ |
| 150 |
(0, does_not_raise()), |
| 151 |
(1, pytest.raises(ZeroDivisionError)), |
| 152 |
]) |
| 153 |
def test_division(example_input, expectation): |
| 154 |
'''Test how much I know division.''' |
| 155 |
with expectation: |
| 156 |
assert (6 / example_input) is not None |
| 157 |
""" |
| 158 |
) |
| 159 |
result = pytester.runpytest() |
| 160 |
result.stdout.fnmatch_lines(["*2 failed*"]) |
| 161 |
|
| 162 |
def test_raises_with_invalid_regex(self, pytester: Pytester) -> None: |
| 163 |
pytester.makepyfile( |
| 164 |
""" |
| 165 |
import pytest |
| 166 |
|
| 167 |
def test_invalid_regex(): |
| 168 |
with pytest.raises(ValueError, match="invalid regex character ["): |
| 169 |
raise ValueError() |
| 170 |
""" |
| 171 |
) |
| 172 |
result = pytester.runpytest() |
| 173 |
result.stdout.fnmatch_lines( |
| 174 |
[ |
| 175 |
"*Invalid regex pattern provided to 'match': unterminated character set at position 24*", |
| 176 |
] |
| 177 |
) |
| 178 |
result.stdout.no_fnmatch_line("*Traceback*") |
| 179 |
result.stdout.no_fnmatch_line("*File*") |
| 180 |
result.stdout.no_fnmatch_line("*line*") |
| 181 |
|
| 182 |
def test_raises_match_failure_suppresses_exception_context( |
| 183 |
self, pytester: Pytester |
| 184 |
) -> None: |
| 185 |
pytester.makepyfile( |
| 186 |
""" |
| 187 |
import pytest |
| 188 |
|
| 189 |
def test_raises_match_failure(): |
| 190 |
with pytest.raises(ValueError, match="expected"): |
| 191 |
raise ValueError("actual") |
| 192 |
""" |
| 193 |
) |
| 194 |
result = pytester.runpytest("--tb=short") |
| 195 |
assert result.ret == 1 |
| 196 |
result.stdout.fnmatch_lines( |
| 197 |
[ |
| 198 |
"*E*AssertionError: Regex pattern did not match.*", |
| 199 |
] |
| 200 |
) |
| 201 |
result.stdout.no_fnmatch_line("*ValueError: actual") |
| 202 |
result.stdout.no_fnmatch_line( |
| 203 |
"*The above exception was the direct cause of the following exception:*" |
| 204 |
) |
| 205 |
result.stdout.no_fnmatch_line( |
| 206 |
"*During handling of the above exception, another exception occurred:*" |
| 207 |
) |
| 208 |
|
| 209 |
def test_noclass(self) -> None: |
| 210 |
with pytest.raises(TypeError): |
| 211 |
with pytest.raises("wrong"): # type: ignore[call-overload] |
| 212 |
... # pragma: no cover |
| 213 |
|
| 214 |
def test_invalid_arguments_to_raises(self) -> None: |
| 215 |
with pytest.raises(TypeError, match="unknown"): |
| 216 |
with pytest.raises(TypeError, unknown="bogus"): # type: ignore[call-overload] |
| 217 |
raise ValueError() |
| 218 |
|
| 219 |
def test_tuple(self): |
| 220 |
with pytest.raises((KeyError, ValueError)): |
| 221 |
raise KeyError("oops") |
| 222 |
|
| 223 |
def test_no_raise_message(self) -> None: |
| 224 |
try: |
| 225 |
with pytest.raises(ValueError): |
| 226 |
int("0") |
| 227 |
except pytest.fail.Exception as e: |
| 228 |
assert e.msg == "DID NOT RAISE ValueError" |
| 229 |
else: |
| 230 |
assert False, "Expected pytest.raises.Exception" |
| 231 |
|
| 232 |
try: |
| 233 |
with pytest.raises(ValueError): |
| 234 |
pass |
| 235 |
except pytest.fail.Exception as e: |
| 236 |
assert e.msg == "DID NOT RAISE ValueError" |
| 237 |
else: |
| 238 |
assert False, "Expected pytest.raises.Exception" |
| 239 |
|
| 240 |
@pytest.mark.parametrize( |
| 241 |
"method", ["function", "function_match", "with", "with_raisesexc", "with_group"] |
| 242 |
) |
| 243 |
def test_raises_cyclic_reference(self, method): |
| 244 |
"""Ensure pytest.raises does not leave a reference cycle (#1965).""" |
| 245 |
import gc |
| 246 |
|
| 247 |
class T: |
| 248 |
def __call__(self): |
| 249 |
raise ValueError |
| 250 |
|
| 251 |
t = T() |
| 252 |
refcount = len(gc.get_referrers(t)) |
| 253 |
|
| 254 |
if method == "function": |
| 255 |
pytest.raises(ValueError, t) |
| 256 |
elif method == "function_match": |
| 257 |
pytest.raises(ValueError, t).match("^$") |
| 258 |
elif method == "with": |
| 259 |
with pytest.raises(ValueError): |
| 260 |
t() |
| 261 |
elif method == "with_raisesexc": |
| 262 |
with pytest.RaisesExc(ValueError): |
| 263 |
t() |
| 264 |
elif method == "with_group": |
| 265 |
with pytest.RaisesGroup(ValueError, allow_unwrapped=True): |
| 266 |
t() |
| 267 |
else: # pragma: no cover |
| 268 |
raise AssertionError("bad parametrization") |
| 269 |
|
| 270 |
# ensure both forms of pytest.raises don't leave exceptions in sys.exc_info() |
| 271 |
assert sys.exc_info() == (None, None, None) |
| 272 |
|
| 273 |
assert refcount == len(gc.get_referrers(t)) |
| 274 |
|
| 275 |
def test_raises_match(self) -> None: |
| 276 |
msg = r"with base \d+" |
| 277 |
with pytest.raises(ValueError, match=msg): |
| 278 |
int("asdf") |
| 279 |
|
| 280 |
msg = "with base 10" |
| 281 |
with pytest.raises(ValueError, match=msg): |
| 282 |
int("asdf") |
| 283 |
|
| 284 |
msg = "with base 16" |
| 285 |
expr = ( |
| 286 |
"Regex pattern did not match.\n" |
| 287 |
f" Expected regex: {msg!r}\n" |
| 288 |
f" Actual message: \"invalid literal for int() with base 10: 'asdf'\"" |
| 289 |
) |
| 290 |
with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"): |
| 291 |
with pytest.raises(ValueError, match=msg): |
| 292 |
int("asdf", base=10) |
| 293 |
|
| 294 |
# "match" without context manager. |
| 295 |
pytest.raises(ValueError, int, "asdf").match("invalid literal") |
| 296 |
with pytest.raises(AssertionError) as excinfo: |
| 297 |
pytest.raises(ValueError, int, "asdf").match(msg) |
| 298 |
assert str(excinfo.value) == expr |
| 299 |
|
| 300 |
pytest.raises(TypeError, int, match="invalid") # type: ignore[call-overload] |
| 301 |
|
| 302 |
def tfunc(match): |
| 303 |
raise ValueError(f"match={match}") |
| 304 |
|
| 305 |
pytest.raises(ValueError, tfunc, match="asdf").match("match=asdf") |
| 306 |
pytest.raises(ValueError, tfunc, match="").match("match=") |
| 307 |
|
| 308 |
# empty string matches everything, which is probably not what the user wants |
| 309 |
with pytest.warns( |
| 310 |
PytestWarning, |
| 311 |
match=wrap_escape( |
| 312 |
"matching against an empty string will *always* pass. If you want to check for an empty message you " |
| 313 |
"need to pass '^$'. If you don't want to match you should pass `None` or leave out the parameter." |
| 314 |
), |
| 315 |
): |
| 316 |
pytest.raises(match="") |
| 317 |
|
| 318 |
def test_match_failure_string_quoting(self): |
| 319 |
with pytest.raises(AssertionError) as excinfo: |
| 320 |
with pytest.raises(AssertionError, match="'foo"): |
| 321 |
raise AssertionError("'bar") |
| 322 |
(msg,) = excinfo.value.args |
| 323 |
assert ( |
| 324 |
msg |
| 325 |
== '''Regex pattern did not match.\n Expected regex: "'foo"\n Actual message: "'bar"''' |
| 326 |
) |
| 327 |
|
| 328 |
def test_match_failure_exact_string_message(self): |
| 329 |
message = "Oh here is a message with (42) numbers in parameters" |
| 330 |
with pytest.raises(AssertionError) as excinfo: |
| 331 |
with pytest.raises(AssertionError, match=message): |
| 332 |
raise AssertionError(message) |
| 333 |
(msg,) = excinfo.value.args |
| 334 |
assert msg == ( |
| 335 |
"Regex pattern did not match.\n" |
| 336 |
" Expected regex: 'Oh here is a message with (42) numbers in parameters'\n" |
| 337 |
" Actual message: 'Oh here is a message with (42) numbers in parameters'\n" |
| 338 |
" Did you mean to `re.escape()` the regex?" |
| 339 |
) |
| 340 |
|
| 341 |
def test_raises_match_wrong_type(self): |
| 342 |
"""Raising an exception with the wrong type and match= given. |
| 343 |
|
| 344 |
pytest should throw the unexpected exception - the pattern match is not |
| 345 |
really relevant if we got a different exception. |
| 346 |
""" |
| 347 |
with pytest.raises( |
| 348 |
ValueError, |
| 349 |
match=wrap_escape("invalid literal for int() with base 10: 'asdf'"), |
| 350 |
): |
| 351 |
with pytest.raises(IndexError, match="nomatch"): |
| 352 |
int("asdf") |
| 353 |
|
| 354 |
def test_raises_exception_looks_iterable(self): |
| 355 |
class Meta(type): |
| 356 |
def __getitem__(self, item): |
| 357 |
return 1 / 0 # pragma: no cover |
| 358 |
|
| 359 |
def __len__(self): |
| 360 |
return 1 # pragma: no cover |
| 361 |
|
| 362 |
class ClassLooksIterableException(Exception, metaclass=Meta): |
| 363 |
pass |
| 364 |
|
| 365 |
with pytest.raises( |
| 366 |
Failed, |
| 367 |
match=r"DID NOT RAISE ClassLooksIterableException", |
| 368 |
): |
| 369 |
with pytest.raises(ClassLooksIterableException): |
| 370 |
... # pragma: no cover |
| 371 |
|
| 372 |
def test_raises_with_raising_dunder_class(self) -> None: |
| 373 |
"""Test current behavior with regard to exceptions via __class__ (#4284).""" |
| 374 |
|
| 375 |
class CrappyClass(Exception): |
| 376 |
# Type ignored because it's bypassed intentionally. |
| 377 |
@property # type: ignore |
| 378 |
def __class__(self): |
| 379 |
assert False, "via __class__" |
| 380 |
|
| 381 |
with pytest.raises(AssertionError) as excinfo: |
| 382 |
with pytest.raises(CrappyClass()): # type: ignore[call-overload] |
| 383 |
pass |
| 384 |
assert "via __class__" in excinfo.value.args[0] |
| 385 |
|
| 386 |
def test_raises_context_manager_with_kwargs(self): |
| 387 |
with pytest.raises(expected_exception=ValueError): |
| 388 |
raise ValueError |
| 389 |
with pytest.raises( |
| 390 |
TypeError, |
| 391 |
match=wrap_escape( |
| 392 |
"Unexpected keyword arguments passed to pytest.raises: foo\n" |
| 393 |
"Use context-manager form instead?" |
| 394 |
), |
| 395 |
): |
| 396 |
with pytest.raises(OSError, foo="bar"): # type: ignore[call-overload] |
| 397 |
pass |
| 398 |
|
| 399 |
def test_expected_exception_is_not_a_baseexception(self) -> None: |
| 400 |
with pytest.raises( |
| 401 |
TypeError, |
| 402 |
match=wrap_escape("Expected a BaseException type, but got 'str'"), |
| 403 |
): |
| 404 |
with pytest.raises("hello"): # type: ignore[call-overload] |
| 405 |
pass # pragma: no cover |
| 406 |
|
| 407 |
class NotAnException: |
| 408 |
pass |
| 409 |
|
| 410 |
with pytest.raises( |
| 411 |
ValueError, |
| 412 |
match=wrap_escape( |
| 413 |
"Expected a BaseException type, but got 'NotAnException'" |
| 414 |
), |
| 415 |
): |
| 416 |
with pytest.raises(NotAnException): # type: ignore[type-var] |
| 417 |
pass # pragma: no cover |
| 418 |
|
| 419 |
with pytest.raises( |
| 420 |
TypeError, |
| 421 |
match=wrap_escape("Expected a BaseException type, but got 'str'"), |
| 422 |
): |
| 423 |
with pytest.raises(("hello", NotAnException)): # type: ignore[arg-type] |
| 424 |
pass # pragma: no cover |
| 425 |
|
| 426 |
def test_issue_11872(self) -> None: |
| 427 |
"""Regression test for #11872. |
| 428 |
|
| 429 |
urllib.error.HTTPError on some Python 3.10/11 minor releases raises |
| 430 |
KeyError instead of AttributeError on invalid attribute access. |
| 431 |
|
| 432 |
https://github.com/python/cpython/issues/98778 |
| 433 |
""" |
| 434 |
from email.message import Message |
| 435 |
from urllib.error import HTTPError |
| 436 |
|
| 437 |
with pytest.raises(HTTPError, match="Not Found") as exc_info: |
| 438 |
raise HTTPError( |
| 439 |
code=404, msg="Not Found", fp=io.BytesIO(), hdrs=Message(), url="" |
| 440 |
) |
| 441 |
exc_info.value.close() # avoid a resource warning |
| 442 |
|
| 443 |
def test_raises_match_compiled_regex(self) -> None: |
| 444 |
"""Test that compiled regex patterns work with pytest.raises.""" |
| 445 |
# Test with a compiled pattern that matches |
| 446 |
pattern = re.compile(r"with base \d+") |
| 447 |
with pytest.raises(ValueError, match=pattern): |
| 448 |
int("asdf") |
| 449 |
|
| 450 |
# Test with a compiled pattern that doesn't match |
| 451 |
pattern_nomatch = re.compile(r"with base 16") |
| 452 |
expr = ( |
| 453 |
"Regex pattern did not match.\n" |
| 454 |
f" Expected regex: {pattern_nomatch.pattern!r}\n" |
| 455 |
f" Actual message: \"invalid literal for int() with base 10: 'asdf'\"" |
| 456 |
) |
| 457 |
with pytest.raises(AssertionError, match="^" + re.escape(expr) + "$"): |
| 458 |
with pytest.raises(ValueError, match=pattern_nomatch): |
| 459 |
int("asdf", base=10) |
| 460 |
|
| 461 |
# Test compiled pattern with flags |
| 462 |
pattern_with_flags = re.compile(r"INVALID LITERAL", re.IGNORECASE) |
| 463 |
with pytest.raises(ValueError, match=pattern_with_flags): |
| 464 |
int("asdf") |
| 465 |
|
| 466 |
def test_pipe_is_treated_as_regex_metacharacter(self) -> None: |
| 467 |
"""| (pipe) must be recognized as a regex metacharacter.""" |
| 468 |
from _pytest.raises import is_fully_escaped |
| 469 |
from _pytest.raises import unescape |
| 470 |
|
| 471 |
assert not is_fully_escaped("foo|bar") |
| 472 |
assert is_fully_escaped(r"foo\|bar") |
| 473 |
assert unescape(r"foo\|bar") == "foo|bar" |
| 474 |
|
| 475 |
def test_consecutive_backslashes_in_escape_check(self) -> None: |
| 476 |
"""Consecutive backslashes escape each other, leaving the metachar unescaped.""" |
| 477 |
from _pytest.raises import is_fully_escaped |
| 478 |
|
| 479 |
# r"\." -> one backslash escapes the dot -> fully escaped |
| 480 |
assert is_fully_escaped(r"\.") |
| 481 |
# r"\\." -> two backslashes: the first escapes the second, dot is unescaped |
| 482 |
assert not is_fully_escaped(r"\\.") |
| 483 |
# r"\\\." -> three backslashes: pair escapes pair, last escapes dot -> fully escaped |
| 484 |
assert is_fully_escaped(r"\\\.") |
| 485 |
# Same idea with pipe metachar |
| 486 |
# "\\\\|" is the string \\| (2 backslashes + pipe): even count, pipe is unescaped |
| 487 |
assert not is_fully_escaped("\\\\|") |
| 488 |
# r"\\\\|" is the string \\\\| (4 backslashes + pipe): even count, pipe is unescaped |
| 489 |
assert not is_fully_escaped(r"\\\\|") |
| 490 |
|
| 491 |
def test_raises_match_verbose_diff(self, pytester: Pytester) -> None: |
| 492 |
"""Test that -v flag shows full diff in raises match failure (#14214).""" |
| 493 |
pytester.makepyfile( |
| 494 |
""" |
| 495 |
import re |
| 496 |
import pytest |
| 497 |
|
| 498 |
def test_raises_v_hint(): |
| 499 |
prefix = "A" * 60 |
| 500 |
expected = prefix + " expected_ending" |
| 501 |
actual = prefix + " actual_ending" |
| 502 |
|
| 503 |
with pytest.raises( |
| 504 |
ValueError, match=f"^{re.escape(expected)}$" |
| 505 |
): |
| 506 |
raise ValueError(actual) |
| 507 |
""" |
| 508 |
) |
| 509 |
# Without -v: should show "Skipping ... identical leading characters" |
| 510 |
result = pytester.runpytest() |
| 511 |
result.stdout.fnmatch_lines(["*Skipping*identical leading*"]) |
| 512 |
|
| 513 |
# With -v: should NOT show "Skipping" — full diff shown |
| 514 |
result_v = pytester.runpytest("-v") |
| 515 |
assert "Skipping" not in result_v.stdout.str() |