| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import gc |
| 4 |
import sys |
| 5 |
from unittest import mock |
| 6 |
|
| 7 |
from _pytest.pytester import Pytester |
| 8 |
import pytest |
| 9 |
|
| 10 |
|
| 11 |
PYPY = hasattr(sys, "pypy_version_info") |
| 12 |
|
| 13 |
UNRAISABLE_LINE = ( |
| 14 |
( |
| 15 |
" * PytestUnraisableExceptionWarning: Exception ignored while calling " |
| 16 |
"deallocator <function BrokenDel.__del__ at *>: None" |
| 17 |
) |
| 18 |
if sys.version_info >= (3, 14) |
| 19 |
else " * PytestUnraisableExceptionWarning: Exception ignored in: <function BrokenDel.__del__ at *>" |
| 20 |
) |
| 21 |
|
| 22 |
TRACEMALLOC_LINES = ( |
| 23 |
() |
| 24 |
if sys.version_info >= (3, 14) |
| 25 |
else ( |
| 26 |
" Enable tracemalloc to get traceback where the object was allocated.", |
| 27 |
" See https* for more info.", |
| 28 |
) |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky") |
| 33 |
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning") |
| 34 |
def test_unraisable(pytester: Pytester) -> None: |
| 35 |
pytester.makepyfile( |
| 36 |
test_it=""" |
| 37 |
class BrokenDel: |
| 38 |
def __del__(self): |
| 39 |
raise ValueError("del is broken") |
| 40 |
|
| 41 |
def test_it(): |
| 42 |
obj = BrokenDel() |
| 43 |
del obj |
| 44 |
|
| 45 |
def test_2(): pass |
| 46 |
""" |
| 47 |
) |
| 48 |
result = pytester.runpytest() |
| 49 |
assert result.ret == 0 |
| 50 |
result.assert_outcomes(passed=2, warnings=1) |
| 51 |
result.stdout.fnmatch_lines( |
| 52 |
[ |
| 53 |
"*= warnings summary =*", |
| 54 |
"test_it.py::test_it", |
| 55 |
UNRAISABLE_LINE, |
| 56 |
" ", |
| 57 |
" Traceback (most recent call last):", |
| 58 |
" ValueError: del is broken", |
| 59 |
" ", |
| 60 |
*TRACEMALLOC_LINES, |
| 61 |
" warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))", |
| 62 |
] |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky") |
| 67 |
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning") |
| 68 |
def test_unraisable_in_setup(pytester: Pytester) -> None: |
| 69 |
pytester.makepyfile( |
| 70 |
test_it=""" |
| 71 |
import pytest |
| 72 |
|
| 73 |
class BrokenDel: |
| 74 |
def __del__(self): |
| 75 |
raise ValueError("del is broken") |
| 76 |
|
| 77 |
@pytest.fixture |
| 78 |
def broken_del(): |
| 79 |
obj = BrokenDel() |
| 80 |
del obj |
| 81 |
|
| 82 |
def test_it(broken_del): pass |
| 83 |
def test_2(): pass |
| 84 |
""" |
| 85 |
) |
| 86 |
result = pytester.runpytest() |
| 87 |
assert result.ret == 0 |
| 88 |
result.assert_outcomes(passed=2, warnings=1) |
| 89 |
result.stdout.fnmatch_lines( |
| 90 |
[ |
| 91 |
"*= warnings summary =*", |
| 92 |
"test_it.py::test_it", |
| 93 |
UNRAISABLE_LINE, |
| 94 |
" ", |
| 95 |
" Traceback (most recent call last):", |
| 96 |
" ValueError: del is broken", |
| 97 |
" ", |
| 98 |
*TRACEMALLOC_LINES, |
| 99 |
" warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))", |
| 100 |
] |
| 101 |
) |
| 102 |
|
| 103 |
|
| 104 |
@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky") |
| 105 |
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning") |
| 106 |
def test_unraisable_in_teardown(pytester: Pytester) -> None: |
| 107 |
pytester.makepyfile( |
| 108 |
test_it=""" |
| 109 |
import pytest |
| 110 |
|
| 111 |
class BrokenDel: |
| 112 |
def __del__(self): |
| 113 |
raise ValueError("del is broken") |
| 114 |
|
| 115 |
@pytest.fixture |
| 116 |
def broken_del(): |
| 117 |
yield |
| 118 |
obj = BrokenDel() |
| 119 |
del obj |
| 120 |
|
| 121 |
def test_it(broken_del): pass |
| 122 |
def test_2(): pass |
| 123 |
""" |
| 124 |
) |
| 125 |
result = pytester.runpytest() |
| 126 |
assert result.ret == 0 |
| 127 |
result.assert_outcomes(passed=2, warnings=1) |
| 128 |
result.stdout.fnmatch_lines( |
| 129 |
[ |
| 130 |
"*= warnings summary =*", |
| 131 |
"test_it.py::test_it", |
| 132 |
UNRAISABLE_LINE, |
| 133 |
" ", |
| 134 |
" Traceback (most recent call last):", |
| 135 |
" ValueError: del is broken", |
| 136 |
" ", |
| 137 |
*TRACEMALLOC_LINES, |
| 138 |
" warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))", |
| 139 |
] |
| 140 |
) |
| 141 |
|
| 142 |
|
| 143 |
@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning") |
| 144 |
def test_unraisable_warning_error(pytester: Pytester) -> None: |
| 145 |
pytester.makepyfile( |
| 146 |
test_it=f""" |
| 147 |
class BrokenDel: |
| 148 |
def __del__(self) -> None: |
| 149 |
raise ValueError("del is broken") |
| 150 |
|
| 151 |
def test_it() -> None: |
| 152 |
obj = BrokenDel() |
| 153 |
del obj |
| 154 |
{"import gc; gc.collect()" * PYPY} |
| 155 |
|
| 156 |
def test_2(): pass |
| 157 |
""" |
| 158 |
) |
| 159 |
result = pytester.runpytest() |
| 160 |
assert result.ret == pytest.ExitCode.TESTS_FAILED |
| 161 |
result.assert_outcomes(passed=1, failed=1) |
| 162 |
|
| 163 |
|
| 164 |
@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning") |
| 165 |
def test_unraisable_warning_multiple_errors(pytester: Pytester) -> None: |
| 166 |
pytester.makepyfile( |
| 167 |
test_it=f""" |
| 168 |
class BrokenDel: |
| 169 |
def __init__(self, msg: str): |
| 170 |
self.msg = msg |
| 171 |
|
| 172 |
def __del__(self) -> None: |
| 173 |
raise ValueError(self.msg) |
| 174 |
|
| 175 |
def test_it() -> None: |
| 176 |
BrokenDel("del is broken 1") |
| 177 |
BrokenDel("del is broken 2") |
| 178 |
{"import gc; gc.collect()" * PYPY} |
| 179 |
|
| 180 |
def test_2(): pass |
| 181 |
""" |
| 182 |
) |
| 183 |
result = pytester.runpytest() |
| 184 |
assert result.ret == pytest.ExitCode.TESTS_FAILED |
| 185 |
result.assert_outcomes(passed=1, failed=1) |
| 186 |
result.stdout.fnmatch_lines( |
| 187 |
[ |
| 188 |
" | *ExceptionGroup: multiple unraisable exception warnings (2 sub-exceptions)" |
| 189 |
] |
| 190 |
) |
| 191 |
|
| 192 |
|
| 193 |
def test_unraisable_collection_failure(pytester: Pytester) -> None: |
| 194 |
pytester.makepyfile( |
| 195 |
test_it=f""" |
| 196 |
class BrokenDel: |
| 197 |
def __del__(self): |
| 198 |
raise ValueError("del is broken") |
| 199 |
|
| 200 |
def test_it(): |
| 201 |
obj = BrokenDel() |
| 202 |
del obj |
| 203 |
{"import gc; gc.collect()" * PYPY} |
| 204 |
|
| 205 |
def test_2(): pass |
| 206 |
""" |
| 207 |
) |
| 208 |
|
| 209 |
class MyError(BaseException): |
| 210 |
pass |
| 211 |
|
| 212 |
with mock.patch("traceback.format_exception", side_effect=MyError): |
| 213 |
result = pytester.runpytest() |
| 214 |
assert result.ret == 1 |
| 215 |
result.assert_outcomes(passed=1, failed=1) |
| 216 |
result.stdout.fnmatch_lines( |
| 217 |
["E RuntimeError: Failed to process unraisable exception"] |
| 218 |
) |
| 219 |
|
| 220 |
|
| 221 |
def _set_gc_state(enabled: bool) -> bool: |
| 222 |
was_enabled = gc.isenabled() |
| 223 |
if enabled: |
| 224 |
gc.enable() |
| 225 |
else: |
| 226 |
gc.disable() |
| 227 |
return was_enabled |
| 228 |
|
| 229 |
|
| 230 |
def test_refcycle_unraisable(pytester: Pytester) -> None: |
| 231 |
# see: https://github.com/pytest-dev/pytest/issues/10404 |
| 232 |
pytester.makepyfile( |
| 233 |
test_it=""" |
| 234 |
# Should catch the unraisable exception even if gc is disabled. |
| 235 |
import gc; gc.disable() |
| 236 |
|
| 237 |
import pytest |
| 238 |
|
| 239 |
class BrokenDel: |
| 240 |
def __init__(self): |
| 241 |
self.self = self # make a reference cycle |
| 242 |
|
| 243 |
def __del__(self): |
| 244 |
raise ValueError("del is broken") |
| 245 |
|
| 246 |
def test_it(): |
| 247 |
BrokenDel() |
| 248 |
""" |
| 249 |
) |
| 250 |
|
| 251 |
result = pytester.runpytest_subprocess( |
| 252 |
"-Wdefault::pytest.PytestUnraisableExceptionWarning" |
| 253 |
) |
| 254 |
|
| 255 |
assert result.ret == 0 |
| 256 |
|
| 257 |
result.assert_outcomes(passed=1) |
| 258 |
result.stderr.fnmatch_lines("ValueError: del is broken") |
| 259 |
|
| 260 |
|
| 261 |
def test_refcycle_unraisable_warning_filter(pytester: Pytester) -> None: |
| 262 |
pytester.makepyfile( |
| 263 |
test_it=""" |
| 264 |
# Should catch the unraisable exception even if gc is disabled. |
| 265 |
import gc; gc.disable() |
| 266 |
|
| 267 |
import pytest |
| 268 |
|
| 269 |
class BrokenDel: |
| 270 |
def __init__(self): |
| 271 |
self.self = self # make a reference cycle |
| 272 |
|
| 273 |
def __del__(self): |
| 274 |
raise ValueError("del is broken") |
| 275 |
|
| 276 |
def test_it(): |
| 277 |
BrokenDel() |
| 278 |
""" |
| 279 |
) |
| 280 |
|
| 281 |
result = pytester.runpytest_subprocess( |
| 282 |
"-Werror::pytest.PytestUnraisableExceptionWarning" |
| 283 |
) |
| 284 |
|
| 285 |
# TODO: Should be a test failure or error. Currently the exception |
| 286 |
# propagates all the way to the top resulting in exit code 1. |
| 287 |
assert result.ret == 1 |
| 288 |
|
| 289 |
result.assert_outcomes(passed=1) |
| 290 |
result.stderr.fnmatch_lines("ValueError: del is broken") |
| 291 |
|
| 292 |
|
| 293 |
def test_create_task_raises_unraisable_warning_filter(pytester: Pytester) -> None: |
| 294 |
# note that the host pytest warning filter is disabled and the pytester |
| 295 |
# warning filter applies during config teardown of unraisablehook. |
| 296 |
# see: https://github.com/pytest-dev/pytest/issues/10404 |
| 297 |
# This is a dupe of the above test, but using the exact reproducer from |
| 298 |
# the issue |
| 299 |
pytester.makepyfile( |
| 300 |
test_it=""" |
| 301 |
# Should catch the unraisable exception even if gc is disabled. |
| 302 |
import gc; gc.disable() |
| 303 |
|
| 304 |
import asyncio |
| 305 |
import pytest |
| 306 |
|
| 307 |
async def my_task(): |
| 308 |
pass |
| 309 |
|
| 310 |
def test_scheduler_must_be_created_within_running_loop() -> None: |
| 311 |
with pytest.raises(RuntimeError) as _: |
| 312 |
asyncio.create_task(my_task()) |
| 313 |
""" |
| 314 |
) |
| 315 |
|
| 316 |
result = pytester.runpytest_subprocess("-Werror") |
| 317 |
|
| 318 |
# TODO: Should be a test failure or error. Currently the exception |
| 319 |
# propagates all the way to the top resulting in exit code 1. |
| 320 |
# -Werror matches the wrapping PytestUnraisableExceptionWarning, so the |
| 321 |
# wrapper propagates; its message embeds the original RuntimeWarning. |
| 322 |
assert result.ret == 1 |
| 323 |
|
| 324 |
result.assert_outcomes(passed=1) |
| 325 |
result.stderr.fnmatch_lines("RuntimeWarning: coroutine 'my_task' was never awaited") |
| 326 |
|
| 327 |
|
| 328 |
def test_refcycle_unraisable_warning_filter_default(pytester: Pytester) -> None: |
| 329 |
# note this time we use a default warning filter for pytester |
| 330 |
# and run it in a subprocess, because the warning can only go to the |
| 331 |
# sys.stdout rather than the terminal reporter, which has already |
| 332 |
# finished. |
| 333 |
# see: https://github.com/pytest-dev/pytest/pull/13057#discussion_r1888396126 |
| 334 |
pytester.makepyfile( |
| 335 |
test_it=""" |
| 336 |
import gc |
| 337 |
gc.disable() |
| 338 |
|
| 339 |
import pytest |
| 340 |
|
| 341 |
class BrokenDel: |
| 342 |
def __init__(self): |
| 343 |
self.self = self # make a reference cycle |
| 344 |
|
| 345 |
def __del__(self): |
| 346 |
raise ValueError("del is broken") |
| 347 |
|
| 348 |
def test_it(): |
| 349 |
BrokenDel() |
| 350 |
""" |
| 351 |
) |
| 352 |
|
| 353 |
# since we use subprocess we need to disable gc inside test_it |
| 354 |
result = pytester.runpytest_subprocess("-Wdefault") |
| 355 |
|
| 356 |
assert result.ret == pytest.ExitCode.OK |
| 357 |
|
| 358 |
# TODO: should be warnings=1, but the outcome has already come out |
| 359 |
# by the time the warning triggers |
| 360 |
result.assert_outcomes(passed=1) |
| 361 |
result.stderr.fnmatch_lines("ValueError: del is broken") |
| 362 |
|
| 363 |
|
| 364 |
def test_unraisable_warning_without_filter_still_wraps(pytester: Pytester) -> None: |
| 365 |
# A Warning raised from ``__del__`` gets wrapped in |
| 366 |
# PytestUnraisableExceptionWarning like any other unraisable exception. |
| 367 |
# pytest does not unwrap it to honor a filter on the inner class, so with |
| 368 |
# no filter matching the wrapper, pytest logs the warning and the run |
| 369 |
# passes. This guards against re-introducing the dropped unwrap path. |
| 370 |
pytester.makepyfile( |
| 371 |
test_it=""" |
| 372 |
class RaisingDel: |
| 373 |
def __del__(self): |
| 374 |
raise UserWarning("oops") |
| 375 |
|
| 376 |
def test_it(): |
| 377 |
obj = RaisingDel() |
| 378 |
del obj |
| 379 |
""" |
| 380 |
) |
| 381 |
|
| 382 |
# Subprocess so we don't inherit the outer pytest's ``error`` filter from |
| 383 |
# pyproject.toml, which would promote the wrapper and fail the run. |
| 384 |
# ``-Wdefault::pytest.PytestUnraisableExceptionWarning`` makes the wrapping |
| 385 |
# warning visible on stderr whether ``__del__`` fires inside the test or |
| 386 |
# during later GC (PyPy). |
| 387 |
result = pytester.runpytest_subprocess( |
| 388 |
"-Wdefault::pytest.PytestUnraisableExceptionWarning" |
| 389 |
) |
| 390 |
|
| 391 |
assert result.ret == 0 |
| 392 |
result.assert_outcomes(passed=1) |
| 393 |
# The unraisable hook emitted PytestUnraisableExceptionWarning. |
| 394 |
# The warning lands in the warnings-summary section of stdout on |
| 395 |
# CPython (where ``__del__`` fires inside the test) and on stderr on |
| 396 |
# PyPy (where it fires during later GC). Check both rather than the |
| 397 |
# outcomes counter, which is timing-dependent. |
| 398 |
combined = "\n".join(result.outlines + result.errlines) |
| 399 |
assert "PytestUnraisableExceptionWarning" in combined |
| 400 |
|
| 401 |
|
| 402 |
@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky") |
| 403 |
def test_unraisable_decouples_from_cleanup_stack_order(pytester: Pytester) -> None: |
| 404 |
# Regression test for the structural fix. The garbage-collection step |
| 405 |
# that surfaces queued unraisables must run before _cleanup_stack.close() |
| 406 |
# so warning filters installed via cleanup-stack-managed contexts are |
| 407 |
# still in effect when finalizers fire. Otherwise correctness depends |
| 408 |
# on the order in which plugins register their cleanups under LIFO. |
| 409 |
# |
| 410 |
# The conftest uses ``@hookimpl(trylast=True)`` so its pytest_configure |
| 411 |
# runs after all built-in pytest_configures. Its |
| 412 |
# ``warnings.resetwarnings`` cleanup then lands on the cleanup stack |
| 413 |
# last and pops first under LIFO. Under the pre-fix layout, where |
| 414 |
# garbage collection runs inside unraisableexception's own cleanup |
| 415 |
# callback, that pop clears the user's |
| 416 |
# ``error::pytest.PytestUnraisableExceptionWarning`` filter before the |
| 417 |
# finalizer raises; pytest logs the wrapped warning instead of |
| 418 |
# promoting it, and the suite exits 0. Under the post-fix layout, |
| 419 |
# ``pytest_unconfigure`` runs the garbage collection and queue processing |
| 420 |
# before the cleanup stack starts closing, so the conftest's reset has no |
| 421 |
# effect. |
| 422 |
pytester.makeini( |
| 423 |
""" |
| 424 |
[pytest] |
| 425 |
filterwarnings = |
| 426 |
error::pytest.PytestUnraisableExceptionWarning |
| 427 |
""" |
| 428 |
) |
| 429 |
pytester.makeconftest( |
| 430 |
""" |
| 431 |
import warnings |
| 432 |
import pytest |
| 433 |
|
| 434 |
@pytest.hookimpl(trylast=True) |
| 435 |
def pytest_configure(config): |
| 436 |
config.add_cleanup(warnings.resetwarnings) |
| 437 |
""" |
| 438 |
) |
| 439 |
pytester.makepyfile( |
| 440 |
test_it=""" |
| 441 |
import gc; gc.disable() |
| 442 |
|
| 443 |
class BrokenDel: |
| 444 |
def __init__(self): |
| 445 |
self.self = self # cycle survives until session-end gc |
| 446 |
|
| 447 |
def __del__(self): |
| 448 |
raise ValueError("del is broken") |
| 449 |
|
| 450 |
def test_it(): |
| 451 |
BrokenDel() |
| 452 |
""" |
| 453 |
) |
| 454 |
|
| 455 |
result = pytester.runpytest_subprocess() |
| 456 |
|
| 457 |
assert result.ret == 1, ( |
| 458 |
"wrapper filter is still installed at GC time, so the unraisable " |
| 459 |
"exits non-zero regardless of cleanup-stack pop order" |
| 460 |
) |
| 461 |
result.assert_outcomes(passed=1) |
| 462 |
result.stderr.fnmatch_lines("*ValueError: del is broken*") |
| 463 |
|
| 464 |
|
| 465 |
def test_pytest_unconfigure_survives_failed_pytest_configure( |
| 466 |
pytester: Pytester, |
| 467 |
) -> None: |
| 468 |
# Regression test for the guard against an unset stash key. When |
| 469 |
# another plugin's pytest_configure raises pytest.UsageError, pluggy |
| 470 |
# stops calling the remaining configure hooks; the unraisable plugin's |
| 471 |
# pytest_configure never runs and config.stash[unraisable_exceptions] |
| 472 |
# stays unset. pytest_unconfigure still fires for partially-configured |
| 473 |
# runs, so without a presence check the unraisable plugin's |
| 474 |
# pytest_unconfigure raises KeyError and pytest reports INTERNALERROR |
| 475 |
# instead of USAGE_ERROR. |
| 476 |
pytester.makeconftest( |
| 477 |
""" |
| 478 |
import pytest |
| 479 |
|
| 480 |
def pytest_configure(config): |
| 481 |
raise pytest.UsageError("simulated bad config") |
| 482 |
""" |
| 483 |
) |
| 484 |
pytester.makepyfile(test_it="def test_it(): pass") |
| 485 |
|
| 486 |
result = pytester.runpytest_subprocess() |
| 487 |
|
| 488 |
assert result.ret == pytest.ExitCode.USAGE_ERROR, ( |
| 489 |
"the UsageError must surface as USAGE_ERROR, not a KeyError INTERNALERROR" |
| 490 |
) |
| 491 |
result.stderr.fnmatch_lines("*ERROR: simulated bad config*") |
| 492 |
result.stderr.no_fnmatch_line("*INTERNALERROR*") |
| 493 |
result.stderr.no_fnmatch_line("*KeyError*") |
| 494 |
|
| 495 |
|
| 496 |
@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning") |
| 497 |
def test_possibly_none_excinfo(pytester: Pytester) -> None: |
| 498 |
pytester.makepyfile( |
| 499 |
test_it=""" |
| 500 |
import sys |
| 501 |
import types |
| 502 |
|
| 503 |
def test_it(): |
| 504 |
sys.unraisablehook( |
| 505 |
types.SimpleNamespace( |
| 506 |
exc_type=RuntimeError, |
| 507 |
exc_value=None, |
| 508 |
exc_traceback=None, |
| 509 |
err_msg=None, |
| 510 |
object=None, |
| 511 |
) |
| 512 |
) |
| 513 |
""" |
| 514 |
) |
| 515 |
|
| 516 |
result = pytester.runpytest() |
| 517 |
|
| 518 |
# TODO: should be a test failure or error |
| 519 |
assert result.ret == pytest.ExitCode.TESTS_FAILED |
| 520 |
|
| 521 |
result.assert_outcomes(failed=1) |
| 522 |
result.stdout.fnmatch_lines( |
| 523 |
[ |
| 524 |
"E pytest.PytestUnraisableExceptionWarning:" |
| 525 |
" Exception ignored in: None", |
| 526 |
"E ", |
| 527 |
"E NoneType: None", |
| 528 |
] |
| 529 |
) |