| 1 |
# mypy: allow-untyped-defs |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import sys |
| 5 |
import warnings |
| 6 |
|
| 7 |
import pytest |
| 8 |
from pytest import ExitCode |
| 9 |
from pytest import Pytester |
| 10 |
from pytest import WarningsRecorder |
| 11 |
|
| 12 |
|
| 13 |
def test_recwarn_stacklevel(recwarn: WarningsRecorder) -> None: |
| 14 |
warnings.warn("hello") |
| 15 |
warn = recwarn.pop() |
| 16 |
assert warn.filename == __file__ |
| 17 |
|
| 18 |
|
| 19 |
def test_recwarn_functional(pytester: Pytester) -> None: |
| 20 |
pytester.makepyfile( |
| 21 |
""" |
| 22 |
import warnings |
| 23 |
def test_method(recwarn): |
| 24 |
warnings.warn("hello") |
| 25 |
warn = recwarn.pop() |
| 26 |
assert isinstance(warn.message, UserWarning) |
| 27 |
""" |
| 28 |
) |
| 29 |
reprec = pytester.inline_run() |
| 30 |
reprec.assertoutcome(passed=1) |
| 31 |
|
| 32 |
|
| 33 |
@pytest.mark.filterwarnings("") |
| 34 |
def test_recwarn_captures_deprecation_warning(recwarn: WarningsRecorder) -> None: |
| 35 |
""" |
| 36 |
Check that recwarn can capture DeprecationWarning by default |
| 37 |
without custom filterwarnings (see #8666). |
| 38 |
""" |
| 39 |
warnings.warn(DeprecationWarning("some deprecation")) |
| 40 |
assert len(recwarn) == 1 |
| 41 |
assert recwarn.pop(DeprecationWarning) |
| 42 |
|
| 43 |
|
| 44 |
class TestSubclassWarningPop: |
| 45 |
class ParentWarning(Warning): |
| 46 |
pass |
| 47 |
|
| 48 |
class ChildWarning(ParentWarning): |
| 49 |
pass |
| 50 |
|
| 51 |
class ChildOfChildWarning(ChildWarning): |
| 52 |
pass |
| 53 |
|
| 54 |
@staticmethod |
| 55 |
def raise_warnings_from_list(_warnings: list[type[Warning]]): |
| 56 |
for warn in _warnings: |
| 57 |
warnings.warn(f"Warning {warn().__repr__()}", warn) |
| 58 |
|
| 59 |
def test_pop_finds_exact_match(self): |
| 60 |
with pytest.warns((self.ParentWarning, self.ChildWarning)) as record: |
| 61 |
self.raise_warnings_from_list( |
| 62 |
[self.ChildWarning, self.ParentWarning, self.ChildOfChildWarning] |
| 63 |
) |
| 64 |
|
| 65 |
assert len(record) == 3 |
| 66 |
_warn = record.pop(self.ParentWarning) |
| 67 |
assert _warn.category is self.ParentWarning |
| 68 |
|
| 69 |
def test_pop_raises_if_no_match(self): |
| 70 |
with pytest.raises(AssertionError): |
| 71 |
with pytest.warns(self.ParentWarning) as record: |
| 72 |
self.raise_warnings_from_list([self.ParentWarning]) |
| 73 |
record.pop(self.ChildOfChildWarning) |
| 74 |
|
| 75 |
def test_pop_finds_best_inexact_match(self): |
| 76 |
with pytest.warns(self.ParentWarning) as record: |
| 77 |
self.raise_warnings_from_list( |
| 78 |
[self.ChildOfChildWarning, self.ChildWarning, self.ChildOfChildWarning] |
| 79 |
) |
| 80 |
|
| 81 |
_warn = record.pop(self.ParentWarning) |
| 82 |
assert _warn.category is self.ChildWarning |
| 83 |
|
| 84 |
|
| 85 |
class TestWarningsRecorderChecker: |
| 86 |
def test_recording(self) -> None: |
| 87 |
rec = WarningsRecorder(_ispytest=True) |
| 88 |
with rec: |
| 89 |
assert not rec.list |
| 90 |
warnings.warn_explicit("hello", UserWarning, "xyz", 13) |
| 91 |
assert len(rec.list) == 1 |
| 92 |
warnings.warn(DeprecationWarning("hello")) |
| 93 |
assert len(rec.list) == 2 |
| 94 |
warn = rec.pop() |
| 95 |
assert str(warn.message) == "hello" |
| 96 |
values = rec.list |
| 97 |
rec.clear() |
| 98 |
assert len(rec.list) == 0 |
| 99 |
assert values is rec.list |
| 100 |
with pytest.raises(AssertionError): |
| 101 |
rec.pop() |
| 102 |
|
| 103 |
def test_warn_stacklevel(self) -> None: |
| 104 |
"""#4243""" |
| 105 |
rec = WarningsRecorder(_ispytest=True) |
| 106 |
with rec: |
| 107 |
warnings.warn("test", DeprecationWarning, 2) |
| 108 |
|
| 109 |
def test_typechecking(self) -> None: |
| 110 |
from _pytest.recwarn import WarningsChecker |
| 111 |
|
| 112 |
with pytest.raises(TypeError): |
| 113 |
WarningsChecker(5, _ispytest=True) # type: ignore[arg-type] |
| 114 |
with pytest.raises(TypeError): |
| 115 |
WarningsChecker(("hi", RuntimeWarning), _ispytest=True) # type: ignore[arg-type] |
| 116 |
with pytest.raises(TypeError): |
| 117 |
WarningsChecker([DeprecationWarning, RuntimeWarning], _ispytest=True) # type: ignore[arg-type] |
| 118 |
|
| 119 |
def test_invalid_enter_exit(self) -> None: |
| 120 |
# wrap this test in WarningsRecorder to ensure warning state gets reset |
| 121 |
with WarningsRecorder(_ispytest=True): |
| 122 |
with pytest.raises(RuntimeError): |
| 123 |
rec = WarningsRecorder(_ispytest=True) |
| 124 |
rec.__exit__(None, None, None) # can't exit before entering |
| 125 |
|
| 126 |
with pytest.raises(RuntimeError): |
| 127 |
rec = WarningsRecorder(_ispytest=True) |
| 128 |
with rec: |
| 129 |
with rec: |
| 130 |
pass # can't enter twice |
| 131 |
|
| 132 |
|
| 133 |
class TestDeprecatedCall: |
| 134 |
"""test pytest.deprecated_call()""" |
| 135 |
|
| 136 |
def dep(self, i: int, j: int | None = None) -> int: |
| 137 |
if i == 0: |
| 138 |
warnings.warn("is deprecated", DeprecationWarning, stacklevel=1) |
| 139 |
return 42 |
| 140 |
|
| 141 |
def dep_explicit(self, i: int) -> None: |
| 142 |
if i == 0: |
| 143 |
warnings.warn_explicit( |
| 144 |
"dep_explicit", category=DeprecationWarning, filename="hello", lineno=3 |
| 145 |
) |
| 146 |
|
| 147 |
def test_deprecated_call_raises(self) -> None: |
| 148 |
with pytest.raises(pytest.fail.Exception, match="No warnings of type"): |
| 149 |
with pytest.deprecated_call(): |
| 150 |
self.dep(3, 5) |
| 151 |
|
| 152 |
def test_deprecated_call(self) -> None: |
| 153 |
with pytest.deprecated_call(): |
| 154 |
self.dep(0, 5) |
| 155 |
|
| 156 |
def test_deprecated_call_ret(self) -> None: |
| 157 |
ret = pytest.deprecated_call(self.dep, 0) |
| 158 |
assert ret == 42 |
| 159 |
|
| 160 |
def test_deprecated_call_preserves(self) -> None: |
| 161 |
# Type ignored because `onceregistry` and `filters` are not |
| 162 |
# documented API. |
| 163 |
onceregistry = warnings.onceregistry.copy() # type: ignore |
| 164 |
filters = warnings.filters[:] |
| 165 |
warn = warnings.warn |
| 166 |
warn_explicit = warnings.warn_explicit |
| 167 |
self.test_deprecated_call_raises() |
| 168 |
self.test_deprecated_call() |
| 169 |
assert onceregistry == warnings.onceregistry # type: ignore |
| 170 |
assert filters == warnings.filters |
| 171 |
assert warn is warnings.warn |
| 172 |
assert warn_explicit is warnings.warn_explicit |
| 173 |
|
| 174 |
def test_deprecated_explicit_call_raises(self) -> None: |
| 175 |
with pytest.raises(pytest.fail.Exception): |
| 176 |
with pytest.deprecated_call(): |
| 177 |
self.dep_explicit(3) |
| 178 |
|
| 179 |
def test_deprecated_explicit_call(self) -> None: |
| 180 |
with pytest.deprecated_call(): |
| 181 |
self.dep_explicit(0) |
| 182 |
with pytest.deprecated_call(): |
| 183 |
self.dep_explicit(0) |
| 184 |
|
| 185 |
@pytest.mark.parametrize("mode", ["context_manager", "call"]) |
| 186 |
def test_deprecated_call_no_warning(self, mode) -> None: |
| 187 |
"""Ensure deprecated_call() raises the expected failure when its block/function does |
| 188 |
not raise a deprecation warning. |
| 189 |
""" |
| 190 |
|
| 191 |
def f(): |
| 192 |
pass |
| 193 |
|
| 194 |
msg = "No warnings of type (.*DeprecationWarning.*, .*PendingDeprecationWarning.*)" |
| 195 |
with pytest.raises(pytest.fail.Exception, match=msg): |
| 196 |
if mode == "call": |
| 197 |
pytest.deprecated_call(f) |
| 198 |
else: |
| 199 |
with pytest.deprecated_call(): |
| 200 |
f() |
| 201 |
|
| 202 |
@pytest.mark.parametrize( |
| 203 |
"warning_type", [PendingDeprecationWarning, DeprecationWarning, FutureWarning] |
| 204 |
) |
| 205 |
@pytest.mark.parametrize("mode", ["context_manager", "call"]) |
| 206 |
@pytest.mark.parametrize("call_f_first", [True, False]) |
| 207 |
@pytest.mark.filterwarnings("ignore:hi") |
| 208 |
def test_deprecated_call_modes(self, warning_type, mode, call_f_first) -> None: |
| 209 |
"""Ensure deprecated_call() captures a deprecation warning as expected inside its |
| 210 |
block/function. |
| 211 |
""" |
| 212 |
|
| 213 |
def f(): |
| 214 |
warnings.warn(warning_type("hi")) |
| 215 |
return 10 |
| 216 |
|
| 217 |
# ensure deprecated_call() can capture the warning even if it has already been triggered |
| 218 |
if call_f_first: |
| 219 |
assert f() == 10 |
| 220 |
if mode == "call": |
| 221 |
assert pytest.deprecated_call(f) == 10 |
| 222 |
else: |
| 223 |
with pytest.deprecated_call(): |
| 224 |
assert f() == 10 |
| 225 |
|
| 226 |
def test_deprecated_call_specificity(self) -> None: |
| 227 |
other_warnings = [ |
| 228 |
Warning, |
| 229 |
UserWarning, |
| 230 |
SyntaxWarning, |
| 231 |
RuntimeWarning, |
| 232 |
ImportWarning, |
| 233 |
UnicodeWarning, |
| 234 |
] |
| 235 |
for warning in other_warnings: |
| 236 |
|
| 237 |
def f(): |
| 238 |
warnings.warn(warning("hi")) # noqa: B023 |
| 239 |
|
| 240 |
with pytest.warns(warning): |
| 241 |
with pytest.raises(pytest.fail.Exception): |
| 242 |
pytest.deprecated_call(f) |
| 243 |
with pytest.raises(pytest.fail.Exception): |
| 244 |
with pytest.deprecated_call(): |
| 245 |
f() |
| 246 |
|
| 247 |
def test_deprecated_call_supports_match(self) -> None: |
| 248 |
with pytest.deprecated_call(match=r"must be \d+$"): |
| 249 |
warnings.warn("value must be 42", DeprecationWarning) |
| 250 |
|
| 251 |
with pytest.deprecated_call(): |
| 252 |
with pytest.raises( |
| 253 |
pytest.fail.Exception, match="Regex pattern did not match" |
| 254 |
): |
| 255 |
with pytest.deprecated_call(match=r"must be \d+$"): |
| 256 |
warnings.warn("this is not here", DeprecationWarning) |
| 257 |
|
| 258 |
|
| 259 |
class TestWarns: |
| 260 |
def test_check_callable(self) -> None: |
| 261 |
source = "warnings.warn('w1', RuntimeWarning)" |
| 262 |
with pytest.raises(TypeError, match=r".* must be callable"): |
| 263 |
pytest.warns(RuntimeWarning, source) # type: ignore |
| 264 |
|
| 265 |
def test_several_messages(self) -> None: |
| 266 |
# different messages, b/c Python suppresses multiple identical warnings |
| 267 |
with pytest.warns(RuntimeWarning): |
| 268 |
warnings.warn("w1", RuntimeWarning) |
| 269 |
with pytest.warns(RuntimeWarning): |
| 270 |
with pytest.raises(pytest.fail.Exception): |
| 271 |
with pytest.warns(UserWarning): |
| 272 |
warnings.warn("w2", RuntimeWarning) |
| 273 |
with pytest.warns(RuntimeWarning): |
| 274 |
warnings.warn("w3", RuntimeWarning) |
| 275 |
|
| 276 |
def test_function(self) -> None: |
| 277 |
pytest.warns( |
| 278 |
SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), "syntax" |
| 279 |
) |
| 280 |
|
| 281 |
def test_warning_tuple(self) -> None: |
| 282 |
with pytest.warns((RuntimeWarning, SyntaxWarning)): |
| 283 |
warnings.warn("w1", RuntimeWarning) |
| 284 |
with pytest.warns((RuntimeWarning, SyntaxWarning)): |
| 285 |
warnings.warn("w2", SyntaxWarning) |
| 286 |
with pytest.warns(UserWarning, match="^w3$"): |
| 287 |
with pytest.raises(pytest.fail.Exception): |
| 288 |
with pytest.warns((RuntimeWarning, SyntaxWarning)): |
| 289 |
warnings.warn("w3", UserWarning) |
| 290 |
|
| 291 |
def test_as_contextmanager(self) -> None: |
| 292 |
with pytest.warns(RuntimeWarning): |
| 293 |
warnings.warn("runtime", RuntimeWarning) |
| 294 |
|
| 295 |
with pytest.warns(UserWarning): |
| 296 |
warnings.warn("user", UserWarning) |
| 297 |
|
| 298 |
with pytest.warns(): |
| 299 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 300 |
with pytest.warns(RuntimeWarning): |
| 301 |
warnings.warn("user", UserWarning) |
| 302 |
excinfo.match( |
| 303 |
r"DID NOT WARN. No warnings of type \(.+RuntimeWarning.+,\) were emitted.\n" |
| 304 |
r" Emitted warnings: \[UserWarning\('user',?\)\]." |
| 305 |
) |
| 306 |
|
| 307 |
with pytest.warns(): |
| 308 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 309 |
with pytest.warns(UserWarning): |
| 310 |
warnings.warn("runtime", RuntimeWarning) |
| 311 |
excinfo.match( |
| 312 |
r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) were emitted.\n" |
| 313 |
r" Emitted warnings: \[RuntimeWarning\('runtime',?\)]." |
| 314 |
) |
| 315 |
|
| 316 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 317 |
with pytest.warns(UserWarning): |
| 318 |
pass |
| 319 |
excinfo.match( |
| 320 |
r"DID NOT WARN. No warnings of type \(.+UserWarning.+,\) were emitted.\n" |
| 321 |
r" Emitted warnings: \[\]." |
| 322 |
) |
| 323 |
|
| 324 |
warning_classes = (UserWarning, FutureWarning) |
| 325 |
with pytest.warns(): |
| 326 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 327 |
with pytest.warns(warning_classes) as warninfo: |
| 328 |
warnings.warn("runtime", RuntimeWarning) |
| 329 |
warnings.warn("import", ImportWarning) |
| 330 |
|
| 331 |
messages = [each.message for each in warninfo] |
| 332 |
expected_str = ( |
| 333 |
f"DID NOT WARN. No warnings of type {warning_classes} were emitted.\n" |
| 334 |
f" Emitted warnings: {messages}." |
| 335 |
) |
| 336 |
|
| 337 |
assert str(excinfo.value) == expected_str |
| 338 |
|
| 339 |
def test_record(self) -> None: |
| 340 |
with pytest.warns(UserWarning) as record: |
| 341 |
warnings.warn("user", UserWarning) |
| 342 |
|
| 343 |
assert len(record) == 1 |
| 344 |
assert str(record[0].message) == "user" |
| 345 |
|
| 346 |
def test_record_only(self) -> None: |
| 347 |
with pytest.warns() as record: |
| 348 |
warnings.warn("user", UserWarning) |
| 349 |
warnings.warn("runtime", RuntimeWarning) |
| 350 |
|
| 351 |
assert len(record) == 2 |
| 352 |
assert str(record[0].message) == "user" |
| 353 |
assert str(record[1].message) == "runtime" |
| 354 |
|
| 355 |
def test_record_only_none_type_error(self) -> None: |
| 356 |
with pytest.raises(TypeError): |
| 357 |
pytest.warns(None) # type: ignore[call-overload] |
| 358 |
|
| 359 |
def test_record_by_subclass(self) -> None: |
| 360 |
with pytest.warns(Warning) as record: |
| 361 |
warnings.warn("user", UserWarning) |
| 362 |
warnings.warn("runtime", RuntimeWarning) |
| 363 |
|
| 364 |
assert len(record) == 2 |
| 365 |
assert str(record[0].message) == "user" |
| 366 |
assert str(record[1].message) == "runtime" |
| 367 |
|
| 368 |
class MyUserWarning(UserWarning): |
| 369 |
pass |
| 370 |
|
| 371 |
class MyRuntimeWarning(RuntimeWarning): |
| 372 |
pass |
| 373 |
|
| 374 |
with pytest.warns((UserWarning, RuntimeWarning)) as record: |
| 375 |
warnings.warn("user", MyUserWarning) |
| 376 |
warnings.warn("runtime", MyRuntimeWarning) |
| 377 |
|
| 378 |
assert len(record) == 2 |
| 379 |
assert str(record[0].message) == "user" |
| 380 |
assert str(record[1].message) == "runtime" |
| 381 |
|
| 382 |
def test_double_test(self, pytester: Pytester) -> None: |
| 383 |
"""If a test is run again, the warning should still be raised""" |
| 384 |
pytester.makepyfile( |
| 385 |
""" |
| 386 |
import pytest |
| 387 |
import warnings |
| 388 |
|
| 389 |
@pytest.mark.parametrize('run', [1, 2]) |
| 390 |
def test(run): |
| 391 |
with pytest.warns(RuntimeWarning): |
| 392 |
warnings.warn("runtime", RuntimeWarning) |
| 393 |
""" |
| 394 |
) |
| 395 |
result = pytester.runpytest() |
| 396 |
result.stdout.fnmatch_lines(["*2 passed in*"]) |
| 397 |
|
| 398 |
def test_match_regex(self) -> None: |
| 399 |
with pytest.warns(UserWarning, match=r"must be \d+$"): |
| 400 |
warnings.warn("value must be 42", UserWarning) |
| 401 |
|
| 402 |
with pytest.warns(): |
| 403 |
with pytest.raises(pytest.fail.Exception): |
| 404 |
with pytest.warns(UserWarning, match=r"must be \d+$"): |
| 405 |
warnings.warn("this is not here", UserWarning) |
| 406 |
|
| 407 |
with pytest.warns(): |
| 408 |
with pytest.raises(pytest.fail.Exception): |
| 409 |
with pytest.warns(FutureWarning, match=r"must be \d+$"): |
| 410 |
warnings.warn("value must be 42", UserWarning) |
| 411 |
|
| 412 |
def test_one_from_multiple_warns(self) -> None: |
| 413 |
with pytest.warns(): |
| 414 |
with pytest.raises( |
| 415 |
pytest.fail.Exception, match="Regex pattern did not match" |
| 416 |
): |
| 417 |
with pytest.warns(UserWarning, match=r"aaa"): |
| 418 |
with pytest.warns(UserWarning, match=r"aaa"): |
| 419 |
warnings.warn("cccccccccc", UserWarning) |
| 420 |
warnings.warn("bbbbbbbbbb", UserWarning) |
| 421 |
warnings.warn("aaaaaaaaaa", UserWarning) |
| 422 |
|
| 423 |
def test_none_of_multiple_warns(self) -> None: |
| 424 |
with pytest.warns(): |
| 425 |
with pytest.raises( |
| 426 |
pytest.fail.Exception, match="Regex pattern did not match" |
| 427 |
): |
| 428 |
with pytest.warns(UserWarning, match=r"aaa"): |
| 429 |
warnings.warn("bbbbbbbbbb", UserWarning) |
| 430 |
warnings.warn("cccccccccc", UserWarning) |
| 431 |
|
| 432 |
def test_warns_match_failure_message_detail(self) -> None: |
| 433 |
with pytest.warns(): |
| 434 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 435 |
with pytest.warns(UserWarning, match=r"must be \d+$"): |
| 436 |
warnings.warn("this is not here", UserWarning) |
| 437 |
msg = str(excinfo.value) |
| 438 |
assert "Regex pattern did not match" in msg |
| 439 |
assert "this is not here" in msg |
| 440 |
assert "DID NOT WARN" not in msg |
| 441 |
|
| 442 |
def test_warns_match_re_escape_hint(self) -> None: |
| 443 |
with pytest.warns(): |
| 444 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 445 |
with pytest.warns(UserWarning, match="foo (bar)"): |
| 446 |
warnings.warn("foo (bar)", UserWarning) |
| 447 |
assert "re.escape()" in str(excinfo.value) |
| 448 |
|
| 449 |
def test_warns_match_re_escape_hint_no_false_positive(self) -> None: |
| 450 |
with pytest.warns(): |
| 451 |
with pytest.raises(pytest.fail.Exception) as excinfo: |
| 452 |
with pytest.warns(DeprecationWarning, match="foo (bar)"): |
| 453 |
warnings.warn("some deprecation msg", DeprecationWarning) |
| 454 |
warnings.warn("foo (bar)", UserWarning) |
| 455 |
assert "re.escape()" not in str(excinfo.value) |
| 456 |
|
| 457 |
@pytest.mark.filterwarnings("ignore") |
| 458 |
def test_can_capture_previously_warned(self) -> None: |
| 459 |
def f() -> int: |
| 460 |
warnings.warn(UserWarning("ohai")) |
| 461 |
return 10 |
| 462 |
|
| 463 |
assert f() == 10 |
| 464 |
assert pytest.warns(UserWarning, f) == 10 |
| 465 |
assert pytest.warns(UserWarning, f) == 10 |
| 466 |
assert pytest.warns(UserWarning, f) != "10" # type: ignore[comparison-overlap] |
| 467 |
|
| 468 |
def test_warns_context_manager_with_kwargs(self) -> None: |
| 469 |
with pytest.raises(TypeError) as excinfo: |
| 470 |
with pytest.warns(UserWarning, foo="bar"): # type: ignore |
| 471 |
pass |
| 472 |
assert "Unexpected keyword arguments" in str(excinfo.value) |
| 473 |
|
| 474 |
def test_re_emit_single(self) -> None: |
| 475 |
with pytest.warns(DeprecationWarning): |
| 476 |
with pytest.warns(UserWarning): |
| 477 |
warnings.warn("user warning", UserWarning) |
| 478 |
warnings.warn("some deprecation warning", DeprecationWarning) |
| 479 |
|
| 480 |
def test_re_emit_multiple(self) -> None: |
| 481 |
with pytest.warns(UserWarning): |
| 482 |
warnings.warn("first warning", UserWarning) |
| 483 |
warnings.warn("second warning", UserWarning) |
| 484 |
|
| 485 |
def test_re_emit_match_single(self) -> None: |
| 486 |
with pytest.warns(DeprecationWarning): |
| 487 |
with pytest.warns(UserWarning, match="user warning"): |
| 488 |
warnings.warn("user warning", UserWarning) |
| 489 |
warnings.warn("some deprecation warning", DeprecationWarning) |
| 490 |
|
| 491 |
def test_re_emit_match_multiple(self) -> None: |
| 492 |
with warnings.catch_warnings(): |
| 493 |
warnings.simplefilter("error") # if anything is re-emitted |
| 494 |
with pytest.warns(UserWarning, match="user warning"): |
| 495 |
warnings.warn("first user warning", UserWarning) |
| 496 |
warnings.warn("second user warning", UserWarning) |
| 497 |
|
| 498 |
def test_re_emit_non_match_single(self) -> None: |
| 499 |
with pytest.warns(UserWarning, match="v2 warning"): |
| 500 |
with pytest.warns(UserWarning, match="v1 warning"): |
| 501 |
warnings.warn("v1 warning", UserWarning) |
| 502 |
warnings.warn("non-matching v2 warning", UserWarning) |
| 503 |
|
| 504 |
def test_catch_warning_within_raise(self) -> None: |
| 505 |
# warns-in-raises works since https://github.com/pytest-dev/pytest/pull/11129 |
| 506 |
with pytest.raises(ValueError, match="some exception"): |
| 507 |
with pytest.warns(FutureWarning, match="some warning"): |
| 508 |
warnings.warn("some warning", category=FutureWarning) |
| 509 |
raise ValueError("some exception") |
| 510 |
# and raises-in-warns has always worked but we'll check for symmetry. |
| 511 |
with pytest.warns(FutureWarning, match="some warning"): |
| 512 |
with pytest.raises(ValueError, match="some exception"): |
| 513 |
warnings.warn("some warning", category=FutureWarning) |
| 514 |
raise ValueError("some exception") |
| 515 |
|
| 516 |
def test_skip_within_warns(self, pytester: Pytester) -> None: |
| 517 |
"""Regression test for #11907.""" |
| 518 |
pytester.makepyfile( |
| 519 |
""" |
| 520 |
import pytest |
| 521 |
|
| 522 |
def test_it(): |
| 523 |
with pytest.warns(Warning): |
| 524 |
pytest.skip("this is OK") |
| 525 |
""", |
| 526 |
) |
| 527 |
|
| 528 |
result = pytester.runpytest() |
| 529 |
assert result.ret == ExitCode.OK |
| 530 |
result.assert_outcomes(skipped=1) |
| 531 |
|
| 532 |
def test_fail_within_warns(self, pytester: Pytester) -> None: |
| 533 |
"""Regression test for #11907.""" |
| 534 |
pytester.makepyfile( |
| 535 |
""" |
| 536 |
import pytest |
| 537 |
|
| 538 |
def test_it(): |
| 539 |
with pytest.warns(Warning): |
| 540 |
pytest.fail("BOOM") |
| 541 |
""", |
| 542 |
) |
| 543 |
|
| 544 |
result = pytester.runpytest() |
| 545 |
assert result.ret == ExitCode.TESTS_FAILED |
| 546 |
result.assert_outcomes(failed=1) |
| 547 |
assert "DID NOT WARN" not in str(result.stdout) |
| 548 |
|
| 549 |
def test_exit_within_warns(self, pytester: Pytester) -> None: |
| 550 |
"""Regression test for #11907.""" |
| 551 |
pytester.makepyfile( |
| 552 |
""" |
| 553 |
import pytest |
| 554 |
|
| 555 |
def test_it(): |
| 556 |
with pytest.warns(Warning): |
| 557 |
pytest.exit() |
| 558 |
""", |
| 559 |
) |
| 560 |
|
| 561 |
result = pytester.runpytest() |
| 562 |
assert result.ret == ExitCode.INTERRUPTED |
| 563 |
result.assert_outcomes() |
| 564 |
|
| 565 |
def test_keyboard_interrupt_within_warns(self, pytester: Pytester) -> None: |
| 566 |
"""Regression test for #11907.""" |
| 567 |
pytester.makepyfile( |
| 568 |
""" |
| 569 |
import pytest |
| 570 |
|
| 571 |
def test_it(): |
| 572 |
with pytest.warns(Warning): |
| 573 |
raise KeyboardInterrupt() |
| 574 |
""", |
| 575 |
) |
| 576 |
|
| 577 |
result = pytester.runpytest_subprocess() |
| 578 |
assert result.ret == ExitCode.INTERRUPTED |
| 579 |
result.assert_outcomes() |
| 580 |
|
| 581 |
|
| 582 |
def test_raise_type_error_on_invalid_warning() -> None: |
| 583 |
"""Check pytest.warns validates warning messages are strings (#10865) or |
| 584 |
Warning instances (#11959).""" |
| 585 |
with pytest.raises(TypeError, match="Warning must be str or Warning"): |
| 586 |
with pytest.warns(UserWarning): |
| 587 |
warnings.warn(1) # type: ignore |
| 588 |
|
| 589 |
|
| 590 |
@pytest.mark.parametrize( |
| 591 |
"message", |
| 592 |
[ |
| 593 |
pytest.param("Warning", id="str"), |
| 594 |
pytest.param(UserWarning(), id="UserWarning"), |
| 595 |
pytest.param(Warning(), id="Warning"), |
| 596 |
], |
| 597 |
) |
| 598 |
def test_no_raise_type_error_on_valid_warning(message: str | Warning) -> None: |
| 599 |
"""Check pytest.warns validates warning messages are strings (#10865) or |
| 600 |
Warning instances (#11959).""" |
| 601 |
with pytest.warns(Warning): |
| 602 |
warnings.warn(message) |
| 603 |
|
| 604 |
|
| 605 |
@pytest.mark.skipif( |
| 606 |
hasattr(sys, "pypy_version_info"), |
| 607 |
reason="Not for pypy", |
| 608 |
) |
| 609 |
def test_raise_type_error_on_invalid_warning_message_cpython() -> None: |
| 610 |
# Check that we get the same behavior with the stdlib, at least if filtering |
| 611 |
# (see https://github.com/python/cpython/issues/103577 for details) |
| 612 |
with pytest.raises(TypeError): |
| 613 |
with warnings.catch_warnings(): |
| 614 |
warnings.filterwarnings("ignore", "test") |
| 615 |
warnings.warn(1) # type: ignore |
| 616 |
|
| 617 |
|
| 618 |
def test_multiple_arg_custom_warning() -> None: |
| 619 |
"""Test for issue #11906.""" |
| 620 |
|
| 621 |
class CustomWarning(UserWarning): |
| 622 |
def __init__(self, a, b): |
| 623 |
pass |
| 624 |
|
| 625 |
with pytest.warns(CustomWarning): |
| 626 |
with pytest.raises(pytest.fail.Exception, match="Regex pattern did not match"): |
| 627 |
with pytest.warns(CustomWarning, match="not gonna match"): |
| 628 |
a, b = 1, 2 |
| 629 |
warnings.warn(CustomWarning(a, b)) |