File: test_unraisableexception.py

package info (click to toggle)
pytest 9.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,308 kB
  • sloc: python: 65,808; makefile: 45
file content (395 lines) | stat: -rw-r--r-- 11,287 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
from __future__ import annotations

import gc
import sys
from unittest import mock

from _pytest.pytester import Pytester
import pytest


PYPY = hasattr(sys, "pypy_version_info")

UNRAISABLE_LINE = (
    (
        "  * PytestUnraisableExceptionWarning: Exception ignored while calling "
        "deallocator <function BrokenDel.__del__ at *>: None"
    )
    if sys.version_info >= (3, 14)
    else "  * PytestUnraisableExceptionWarning: Exception ignored in: <function BrokenDel.__del__ at *>"
)

TRACEMALLOC_LINES = (
    ()
    if sys.version_info >= (3, 14)
    else (
        "  Enable tracemalloc to get traceback where the object was allocated.",
        "  See https* for more info.",
    )
)


@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky")
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning")
def test_unraisable(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it="""
        class BrokenDel:
            def __del__(self):
                raise ValueError("del is broken")

        def test_it():
            obj = BrokenDel()
            del obj

        def test_2(): pass
        """
    )
    result = pytester.runpytest()
    assert result.ret == 0
    result.assert_outcomes(passed=2, warnings=1)
    result.stdout.fnmatch_lines(
        [
            "*= warnings summary =*",
            "test_it.py::test_it",
            UNRAISABLE_LINE,
            "  ",
            "  Traceback (most recent call last):",
            "  ValueError: del is broken",
            "  ",
            *TRACEMALLOC_LINES,
            "    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))",
        ]
    )


@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky")
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning")
def test_unraisable_in_setup(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it="""
        import pytest

        class BrokenDel:
            def __del__(self):
                raise ValueError("del is broken")

        @pytest.fixture
        def broken_del():
            obj = BrokenDel()
            del obj

        def test_it(broken_del): pass
        def test_2(): pass
        """
    )
    result = pytester.runpytest()
    assert result.ret == 0
    result.assert_outcomes(passed=2, warnings=1)
    result.stdout.fnmatch_lines(
        [
            "*= warnings summary =*",
            "test_it.py::test_it",
            UNRAISABLE_LINE,
            "  ",
            "  Traceback (most recent call last):",
            "  ValueError: del is broken",
            "  ",
            *TRACEMALLOC_LINES,
            "    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))",
        ]
    )


@pytest.mark.skipif(PYPY, reason="garbage-collection differences make this flaky")
@pytest.mark.filterwarnings("default::pytest.PytestUnraisableExceptionWarning")
def test_unraisable_in_teardown(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it="""
        import pytest

        class BrokenDel:
            def __del__(self):
                raise ValueError("del is broken")

        @pytest.fixture
        def broken_del():
            yield
            obj = BrokenDel()
            del obj

        def test_it(broken_del): pass
        def test_2(): pass
        """
    )
    result = pytester.runpytest()
    assert result.ret == 0
    result.assert_outcomes(passed=2, warnings=1)
    result.stdout.fnmatch_lines(
        [
            "*= warnings summary =*",
            "test_it.py::test_it",
            UNRAISABLE_LINE,
            "  ",
            "  Traceback (most recent call last):",
            "  ValueError: del is broken",
            "  ",
            *TRACEMALLOC_LINES,
            "    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))",
        ]
    )


@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning")
def test_unraisable_warning_error(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it=f"""
        class BrokenDel:
            def __del__(self) -> None:
                raise ValueError("del is broken")

        def test_it() -> None:
            obj = BrokenDel()
            del obj
            {"import gc; gc.collect()" * PYPY}

        def test_2(): pass
        """
    )
    result = pytester.runpytest()
    assert result.ret == pytest.ExitCode.TESTS_FAILED
    result.assert_outcomes(passed=1, failed=1)


@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning")
def test_unraisable_warning_multiple_errors(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it=f"""
        class BrokenDel:
            def __init__(self, msg: str):
                self.msg = msg

            def __del__(self) -> None:
                raise ValueError(self.msg)

        def test_it() -> None:
            BrokenDel("del is broken 1")
            BrokenDel("del is broken 2")
            {"import gc; gc.collect()" * PYPY}

        def test_2(): pass
        """
    )
    result = pytester.runpytest()
    assert result.ret == pytest.ExitCode.TESTS_FAILED
    result.assert_outcomes(passed=1, failed=1)
    result.stdout.fnmatch_lines(
        [
            "  | *ExceptionGroup: multiple unraisable exception warnings (2 sub-exceptions)"
        ]
    )


def test_unraisable_collection_failure(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it=f"""
        class BrokenDel:
            def __del__(self):
                raise ValueError("del is broken")

        def test_it():
            obj = BrokenDel()
            del obj
            {"import gc; gc.collect()" * PYPY}

        def test_2(): pass
        """
    )

    class MyError(BaseException):
        pass

    with mock.patch("traceback.format_exception", side_effect=MyError):
        result = pytester.runpytest()
    assert result.ret == 1
    result.assert_outcomes(passed=1, failed=1)
    result.stdout.fnmatch_lines(
        ["E               RuntimeError: Failed to process unraisable exception"]
    )


def _set_gc_state(enabled: bool) -> bool:
    was_enabled = gc.isenabled()
    if enabled:
        gc.enable()
    else:
        gc.disable()
    return was_enabled


def test_refcycle_unraisable(pytester: Pytester) -> None:
    # see: https://github.com/pytest-dev/pytest/issues/10404
    pytester.makepyfile(
        test_it="""
        # Should catch the unraisable exception even if gc is disabled.
        import gc; gc.disable()

        import pytest

        class BrokenDel:
            def __init__(self):
                self.self = self  # make a reference cycle

            def __del__(self):
                raise ValueError("del is broken")

        def test_it():
            BrokenDel()
        """
    )

    result = pytester.runpytest_subprocess(
        "-Wdefault::pytest.PytestUnraisableExceptionWarning"
    )

    assert result.ret == 0

    result.assert_outcomes(passed=1)
    result.stderr.fnmatch_lines("ValueError: del is broken")


def test_refcycle_unraisable_warning_filter(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it="""
        # Should catch the unraisable exception even if gc is disabled.
        import gc; gc.disable()

        import pytest

        class BrokenDel:
            def __init__(self):
                self.self = self  # make a reference cycle

            def __del__(self):
                raise ValueError("del is broken")

        def test_it():
            BrokenDel()
        """
    )

    result = pytester.runpytest_subprocess(
        "-Werror::pytest.PytestUnraisableExceptionWarning"
    )

    # TODO: Should be a test failure or error. Currently the exception
    # propagates all the way to the top resulting in exit code 1.
    assert result.ret == 1

    result.assert_outcomes(passed=1)
    result.stderr.fnmatch_lines("ValueError: del is broken")


def test_create_task_raises_unraisable_warning_filter(pytester: Pytester) -> None:
    # note that the host pytest warning filter is disabled and the pytester
    # warning filter applies during config teardown of unraisablehook.
    # see: https://github.com/pytest-dev/pytest/issues/10404
    # This is a dupe of the above test, but using the exact reproducer from
    # the issue
    pytester.makepyfile(
        test_it="""
        # Should catch the unraisable exception even if gc is disabled.
        import gc; gc.disable()

        import asyncio
        import pytest

        async def my_task():
            pass

        def test_scheduler_must_be_created_within_running_loop() -> None:
            with pytest.raises(RuntimeError) as _:
                asyncio.create_task(my_task())
        """
    )

    result = pytester.runpytest_subprocess("-Werror")

    # TODO: Should be a test failure or error. Currently the exception
    # propagates all the way to the top resulting in exit code 1.
    assert result.ret == 1

    result.assert_outcomes(passed=1)
    result.stderr.fnmatch_lines("RuntimeWarning: coroutine 'my_task' was never awaited")


def test_refcycle_unraisable_warning_filter_default(pytester: Pytester) -> None:
    # note this time we use a default warning filter for pytester
    # and run it in a subprocess, because the warning can only go to the
    # sys.stdout rather than the terminal reporter, which has already
    # finished.
    # see: https://github.com/pytest-dev/pytest/pull/13057#discussion_r1888396126
    pytester.makepyfile(
        test_it="""
        import gc
        gc.disable()

        import pytest

        class BrokenDel:
            def __init__(self):
                self.self = self  # make a reference cycle

            def __del__(self):
                raise ValueError("del is broken")

        def test_it():
            BrokenDel()
        """
    )

    # since we use subprocess we need to disable gc inside test_it
    result = pytester.runpytest_subprocess("-Wdefault")

    assert result.ret == pytest.ExitCode.OK

    # TODO: should be warnings=1, but the outcome has already come out
    # by the time the warning triggers
    result.assert_outcomes(passed=1)
    result.stderr.fnmatch_lines("ValueError: del is broken")


@pytest.mark.filterwarnings("error::pytest.PytestUnraisableExceptionWarning")
def test_possibly_none_excinfo(pytester: Pytester) -> None:
    pytester.makepyfile(
        test_it="""
        import sys
        import types

        def test_it():
            sys.unraisablehook(
                types.SimpleNamespace(
                    exc_type=RuntimeError,
                    exc_value=None,
                    exc_traceback=None,
                    err_msg=None,
                    object=None,
                )
            )
        """
    )

    result = pytester.runpytest()

    # TODO: should be a test failure or error
    assert result.ret == pytest.ExitCode.TESTS_FAILED

    result.assert_outcomes(failed=1)
    result.stdout.fnmatch_lines(
        [
            "E                   pytest.PytestUnraisableExceptionWarning:"
            " Exception ignored in: None",
            "E                   ",
            "E                   NoneType: None",
        ]
    )