File: test_set_event_loop.py

package info (click to toggle)
python-pytest-asyncio 1.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 644 kB
  • sloc: python: 3,003; makefile: 24; sh: 1
file content (371 lines) | stat: -rw-r--r-- 11,194 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
from __future__ import annotations

import sys
from textwrap import dedent

import pytest
from pytest import Pytester


@pytest.mark.parametrize(
    "test_loop_scope",
    ("function", "module", "package", "session"),
)
@pytest.mark.parametrize(
    "loop_breaking_action",
    [
        "asyncio.set_event_loop(None)",
        "asyncio.run(asyncio.sleep(0))",
        pytest.param(
            "with asyncio.Runner(): pass",
            marks=pytest.mark.skipif(
                sys.version_info < (3, 11),
                reason="asyncio.Runner requires Python 3.11+",
            ),
        ),
    ],
)
def test_set_event_loop_none(
    pytester: Pytester,
    test_loop_scope: str,
    loop_breaking_action: str,
):
    pytester.makeini(
        dedent(
            f"""\
            [pytest]
            asyncio_default_test_loop_scope = {test_loop_scope}
            asyncio_default_fixture_loop_scope = function
            """
        )
    )
    pytester.makepyfile(
        dedent(
            f"""\
            import asyncio
            import pytest

            pytest_plugins = "pytest_asyncio"

            @pytest.mark.asyncio
            async def test_before():
                pass

            def test_set_event_loop_none():
                {loop_breaking_action}

            @pytest.mark.asyncio
            async def test_after():
                pass
            """
        )
    )
    result = pytester.runpytest_subprocess()
    result.assert_outcomes(passed=3)


@pytest.mark.parametrize(
    "loop_breaking_action",
    [
        "asyncio.set_event_loop(None)",
        "asyncio.run(asyncio.sleep(0))",
        pytest.param(
            "with asyncio.Runner(): pass",
            marks=pytest.mark.skipif(
                sys.version_info < (3, 11),
                reason="asyncio.Runner requires Python 3.11+",
            ),
        ),
    ],
)
def test_set_event_loop_none_class(pytester: Pytester, loop_breaking_action: str):
    pytester.makeini(
        dedent(
            """\
            [pytest]
            asyncio_default_test_loop_scope = class
            asyncio_default_fixture_loop_scope = function
            """
        )
    )
    pytester.makepyfile(
        dedent(
            f"""\
            import asyncio
            import pytest

            pytest_plugins = "pytest_asyncio"


            class TestClass:
                @pytest.mark.asyncio
                async def test_before(self):
                    pass

                def test_set_event_loop_none(self):
                    {loop_breaking_action}

                @pytest.mark.asyncio
                async def test_after(self):
                    pass
            """
        )
    )
    result = pytester.runpytest_subprocess()
    result.assert_outcomes(passed=3)


@pytest.mark.parametrize("test_loop_scope", ("module", "package", "session"))
@pytest.mark.parametrize(
    "loop_breaking_action",
    [
        "asyncio.set_event_loop(None)",
        "asyncio.run(asyncio.sleep(0))",
        pytest.param(
            "with asyncio.Runner(): pass",
            marks=pytest.mark.skipif(
                sys.version_info < (3, 11),
                reason="asyncio.Runner requires Python 3.11+",
            ),
        ),
    ],
)
def test_original_shared_loop_is_reinstated_not_fresh_loop(
    pytester: Pytester,
    test_loop_scope: str,
    loop_breaking_action: str,
):
    pytester.makeini(
        dedent(
            f"""\
            [pytest]
            asyncio_default_test_loop_scope = {test_loop_scope}
            asyncio_default_fixture_loop_scope = function
            """
        )
    )
    pytester.makepyfile(
        dedent(
            f"""\
            import asyncio
            import pytest

            pytest_plugins = "pytest_asyncio"

            original_shared_loop: asyncio.AbstractEventLoop = None

            @pytest.mark.asyncio
            async def test_store_original_shared_loop():
                global original_shared_loop
                original_shared_loop = asyncio.get_running_loop()
                original_shared_loop._custom_marker = "original_loop_marker"

            def test_unset_event_loop():
                {loop_breaking_action}

            @pytest.mark.asyncio
            async def test_verify_original_loop_reinstated():
                global original_shared_loop
                current_loop = asyncio.get_running_loop()
                assert current_loop is original_shared_loop
                assert hasattr(current_loop, '_custom_marker')
                assert current_loop._custom_marker == "original_loop_marker"
            """
        )
    )
    result = pytester.runpytest("--asyncio-mode=strict")
    result.assert_outcomes(passed=3)


@pytest.mark.parametrize("test_loop_scope", ("module", "package", "session"))
@pytest.mark.parametrize(
    "loop_breaking_action",
    [
        "asyncio.set_event_loop(None)",
        "asyncio.run(asyncio.sleep(0))",
        pytest.param(
            "with asyncio.Runner(): pass",
            marks=pytest.mark.skipif(
                sys.version_info < (3, 11),
                reason="asyncio.Runner requires Python 3.11+",
            ),
        ),
    ],
)
def test_shared_loop_with_fixture_preservation(
    pytester: Pytester,
    test_loop_scope: str,
    loop_breaking_action: str,
):
    pytester.makeini(
        dedent(
            f"""\
            [pytest]
            asyncio_default_test_loop_scope = {test_loop_scope}
            asyncio_default_fixture_loop_scope = {test_loop_scope}
            """
        )
    )
    pytester.makepyfile(
        dedent(
            f"""\
            import asyncio
            import pytest
            import pytest_asyncio

            pytest_plugins = "pytest_asyncio"

            fixture_loop: asyncio.AbstractEventLoop = None
            long_running_task = None

            @pytest_asyncio.fixture
            async def webserver():
                global fixture_loop, long_running_task
                fixture_loop = asyncio.get_running_loop()

                async def background_task():
                    while True:
                        await asyncio.sleep(1)

                long_running_task = asyncio.create_task(background_task())
                yield
                long_running_task.cancel()


            @pytest.mark.asyncio
            async def test_before(webserver):
                global fixture_loop, long_running_task
                assert asyncio.get_running_loop() is fixture_loop
                assert not long_running_task.done()


            def test_set_event_loop_none():
                {loop_breaking_action}


            @pytest.mark.asyncio
            async def test_after(webserver):
                global fixture_loop, long_running_task
                current_loop = asyncio.get_running_loop()
                assert current_loop is fixture_loop
                assert not long_running_task.done()
            """
        )
    )
    result = pytester.runpytest("--asyncio-mode=strict")
    result.assert_outcomes(passed=3)


@pytest.mark.parametrize(
    "first_scope,second_scope",
    [
        ("module", "session"),
        ("session", "module"),
        ("package", "session"),
        ("session", "package"),
        ("package", "module"),
        ("module", "package"),
    ],
)
@pytest.mark.parametrize(
    "loop_breaking_action",
    [
        "asyncio.set_event_loop(None)",
        "asyncio.run(asyncio.sleep(0))",
        pytest.param(
            "with asyncio.Runner(): pass",
            marks=pytest.mark.skipif(
                sys.version_info < (3, 11),
                reason="asyncio.Runner requires Python 3.11+",
            ),
        ),
    ],
)
def test_shared_loop_with_multiple_fixtures_preservation(
    pytester: Pytester,
    first_scope: str,
    second_scope: str,
    loop_breaking_action: str,
):
    pytester.makeini(
        dedent(
            """\
            [pytest]
            asyncio_default_test_loop_scope = session
            asyncio_default_fixture_loop_scope = session
            """
        )
    )
    pytester.makepyfile(
        dedent(
            f"""\
            import asyncio
            import pytest
            import pytest_asyncio

            pytest_plugins = "pytest_asyncio"

            first_fixture_loop: asyncio.AbstractEventLoop = None
            second_fixture_loop: asyncio.AbstractEventLoop = None
            first_long_running_task = None
            second_long_running_task = None

            @pytest_asyncio.fixture(scope="{first_scope}", loop_scope="{first_scope}")
            async def first_webserver():
                global first_fixture_loop, first_long_running_task
                first_fixture_loop = asyncio.get_running_loop()

                async def background_task():
                    while True:
                        await asyncio.sleep(0.1)

                first_long_running_task = asyncio.create_task(background_task())
                yield
                first_long_running_task.cancel()

            @pytest_asyncio.fixture(scope="{second_scope}", loop_scope="{second_scope}")
            async def second_webserver():
                global second_fixture_loop, second_long_running_task
                second_fixture_loop = asyncio.get_running_loop()

                async def background_task():
                    while True:
                        await asyncio.sleep(0.1)

                second_long_running_task = asyncio.create_task(background_task())
                yield
                second_long_running_task.cancel()

            @pytest.mark.asyncio(loop_scope="{first_scope}")
            async def test_before_first(first_webserver):
                global first_fixture_loop, first_long_running_task
                assert asyncio.get_running_loop() is first_fixture_loop
                assert not first_long_running_task.done()

            @pytest.mark.asyncio(loop_scope="{second_scope}")
            async def test_before_second(second_webserver):
                global second_fixture_loop, second_long_running_task
                assert asyncio.get_running_loop() is second_fixture_loop
                assert not second_long_running_task.done()

            def test_set_event_loop_none():
                {loop_breaking_action}

            @pytest.mark.asyncio(loop_scope="{first_scope}")
            async def test_after_first(first_webserver):
                global first_fixture_loop, first_long_running_task
                current_loop = asyncio.get_running_loop()
                assert current_loop is first_fixture_loop
                assert not first_long_running_task.done()

            @pytest.mark.asyncio(loop_scope="{second_scope}")
            async def test_after_second(second_webserver):
                global second_fixture_loop, second_long_running_task
                current_loop = asyncio.get_running_loop()
                assert current_loop is second_fixture_loop
                assert not second_long_running_task.done()
            """
        )
    )
    result = pytester.runpytest("--asyncio-mode=strict")
    result.assert_outcomes(passed=5)