Debian Codegraph @

pytest_asyncio/plugin.py

raw
1 """pytest-asyncio implementation."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import contextlib
7 import contextvars
8 import enum
9 import functools
10 import inspect
11 import socket
12 import sys
13 import traceback
14 import warnings
15 from asyncio import AbstractEventLoop
16 from collections.abc import (
17 AsyncIterator,
18 Awaitable,
19 Callable,
20 Collection,
21 Generator,
22 Iterable,
23 Iterator,
24 Mapping,
25 Sequence,
26 )
27 from types import AsyncGeneratorType, CoroutineType
28 from typing import (
29 TYPE_CHECKING,
30 Any,
31 Literal,
32 ParamSpec,
33 TypeAlias,
34 TypeVar,
35 overload,
36 )
37
38 import pluggy
39 import pytest
40 from _pytest.fixtures import resolve_fixture_function
41 from _pytest.scope import Scope
42 from pytest import (
43 Config,
44 FixtureDef,
45 FixtureRequest,
46 Function,
47 Item,
48 Mark,
49 MonkeyPatch,
50 Parser,
51 PytestCollectionWarning,
52 PytestDeprecationWarning,
53 PytestPluginManager,
54 )
55
56 if sys.version_info >= (3, 11):
57 from asyncio import Runner
58 else:
59 from backports.asyncio.runner import Runner
60
61 if sys.version_info >= (3, 13):
62 from typing import TypeIs
63 else:
64 from typing_extensions import TypeIs
65
66 if TYPE_CHECKING:
67 # AbstractEventLoopPolicy is deprecated and scheduled for removal in Python 3.16
68 # Import it for type checking only to avoid raising a DeprecationWarning.
69 from asyncio import AbstractEventLoopPolicy
70
71 _ScopeName = Literal["session", "package", "module", "class", "function"]
72 _R = TypeVar("_R", bound=Awaitable[Any] | AsyncIterator[Any])
73 _P = ParamSpec("_P")
74 FixtureFunction = Callable[_P, _R]
75 LoopFactory: TypeAlias = Callable[[], AbstractEventLoop]
76
77
78 class PytestAsyncioError(Exception):
79 """Base class for exceptions raised by pytest-asyncio"""
80
81
82 class Mode(str, enum.Enum):
83 AUTO = "auto"
84 STRICT = "strict"
85
86
87 hookspec = pluggy.HookspecMarker("pytest")
88
89
90 class PytestAsyncioSpecs:
91 @hookspec(firstresult=True)
92 def pytest_asyncio_loop_factories(
93 self,
94 config: Config,
95 item: Item,
96 ) -> Mapping[str, LoopFactory] | None:
97 raise NotImplementedError # pragma: no cover
98
99
100 ASYNCIO_MODE_HELP = """\
101 'auto' - for automatically handling all async functions by the plugin
102 'strict' - for autoprocessing disabling (useful if different async frameworks \
103 should be tested together, e.g. \
104 both pytest-asyncio and pytest-trio are used in the same project)
105 """
106
107
108 def pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) -> None:
109 pluginmanager.add_hookspecs(PytestAsyncioSpecs)
110 group = parser.getgroup("asyncio")
111 group.addoption(
112 "--asyncio-mode",
113 dest="asyncio_mode",
114 default=None,
115 metavar="MODE",
116 help=ASYNCIO_MODE_HELP,
117 )
118 group.addoption(
119 "--asyncio-debug",
120 dest="asyncio_debug",
121 action="store_true",
122 default=None,
123 help="enable asyncio debug mode for the default event loop",
124 )
125 parser.addini(
126 "asyncio_mode",
127 help="default value for --asyncio-mode",
128 default="strict",
129 )
130 parser.addini(
131 "asyncio_debug",
132 help="enable asyncio debug mode for the default event loop",
133 type="bool",
134 default="false",
135 )
136 parser.addini(
137 "asyncio_default_fixture_loop_scope",
138 type="string",
139 help="default scope of the asyncio event loop used to execute async fixtures",
140 default=None,
141 )
142 parser.addini(
143 "asyncio_default_test_loop_scope",
144 type="string",
145 help="default scope of the asyncio event loop used to execute tests",
146 default="function",
147 )
148
149
150 @overload
151 def fixture(
152 fixture_function: FixtureFunction[_P, _R],
153 *,
154 scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,
155 loop_scope: _ScopeName | None = ...,
156 params: Iterable[object] | None = ...,
157 autouse: bool = ...,
158 ids: (
159 Iterable[str | float | int | bool | None]
160 | Callable[[Any], object | None]
161 | None
162 ) = ...,
163 name: str | None = ...,
164 ) -> FixtureFunction[_P, _R]: ...
165
166
167 @overload
168 def fixture(
169 fixture_function: None = ...,
170 *,
171 scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,
172 loop_scope: _ScopeName | None = ...,
173 params: Iterable[object] | None = ...,
174 autouse: bool = ...,
175 ids: (
176 Iterable[str | float | int | bool | None]
177 | Callable[[Any], object | None]
178 | None
179 ) = ...,
180 name: str | None = None,
181 ) -> Callable[[FixtureFunction[_P, _R]], FixtureFunction[_P, _R]]: ...
182
183
184 def fixture(
185 fixture_function: FixtureFunction[_P, _R] | None = None,
186 loop_scope: _ScopeName | None = None,
187 **kwargs: Any,
188 ) -> (
189 FixtureFunction[_P, _R]
190 | Callable[[FixtureFunction[_P, _R]], FixtureFunction[_P, _R]]
191 ):
192 if fixture_function is not None:
193 _make_asyncio_fixture_function(fixture_function, loop_scope)
194 return pytest.fixture(fixture_function, **kwargs)
195
196 else:
197
198 @functools.wraps(fixture)
199 def inner(fixture_function: FixtureFunction[_P, _R]) -> FixtureFunction[_P, _R]:
200 return fixture(fixture_function, loop_scope=loop_scope, **kwargs)
201
202 return inner
203
204
205 def _is_asyncio_fixture_function(obj: Any) -> bool:
206 obj = getattr(obj, "__func__", obj) # instance method maybe?
207 return getattr(obj, "_force_asyncio_fixture", False)
208
209
210 def _make_asyncio_fixture_function(obj: Any, loop_scope: _ScopeName | None) -> None:
211 if hasattr(obj, "__func__"):
212 # instance method, check the function object
213 obj = obj.__func__
214 obj._force_asyncio_fixture = True
215 obj._loop_scope = loop_scope
216
217
218 def _is_coroutine_or_asyncgen(obj: Any) -> bool:
219 return inspect.iscoroutinefunction(obj) or inspect.isasyncgenfunction(obj)
220
221
222 def _get_asyncio_mode(config: Config) -> Mode:
223 val = config.getoption("asyncio_mode")
224 if val is None:
225 val = config.getini("asyncio_mode")
226 try:
227 return Mode(val)
228 except ValueError as e:
229 modes = ", ".join(m.value for m in Mode)
230 raise pytest.UsageError(
231 f"{val!r} is not a valid asyncio_mode. Valid modes: {modes}."
232 ) from e
233
234
235 def _get_asyncio_debug(config: Config) -> bool:
236 val = config.getoption("asyncio_debug")
237 if val is None:
238 val = config.getini("asyncio_debug")
239
240 if isinstance(val, bool):
241 return val
242 else:
243 return val == "true"
244
245
246 _INVALID_LOOP_FACTORIES = """\
247 pytest_asyncio_loop_factories must return a non-empty mapping of \
248 factory names to callables.
249 """
250
251
252 def _collect_hook_loop_factories(
253 config: Config,
254 item: Item,
255 ) -> dict[str, LoopFactory] | None:
256 hook_caller = item.ihook.pytest_asyncio_loop_factories
257 if not hook_caller.get_hookimpls():
258 return None
259
260 result = hook_caller(config=config, item=item)
261 if result is None or not isinstance(result, Mapping):
262 raise pytest.UsageError(_INVALID_LOOP_FACTORIES)
263 # Copy into an isolated snapshot so later mutations of the hook's
264 # original container do not affect parametrization.
265 factories = dict(result)
266 if not factories or any(
267 not isinstance(name, str) or not name or not callable(factory)
268 for name, factory in factories.items()
269 ):
270 raise pytest.UsageError(_INVALID_LOOP_FACTORIES)
271 return factories
272
273
274 _DEFAULT_FIXTURE_LOOP_SCOPE_UNSET = """\
275 The configuration option "asyncio_default_fixture_loop_scope" is unset.
276 The event loop scope for asynchronous fixtures will default to the "fixture" caching \
277 scope. Future versions of pytest-asyncio will default the loop scope for asynchronous \
278 fixtures to "function" scope. Set the default fixture loop scope explicitly in order \
279 to avoid unexpected behavior in the future. Valid fixture loop scopes are: \
280 "function", "class", "module", "package", "session"
281 """
282
283
284 def _validate_scope(scope: str | None, option_name: str) -> None:
285 if scope is None:
286 return
287 valid_scopes = [s.value for s in Scope]
288 if scope not in valid_scopes:
289 raise pytest.UsageError(
290 f"{scope!r} is not a valid {option_name}. "
291 f"Valid scopes are: {', '.join(valid_scopes)}."
292 )
293
294
295 def pytest_configure(config: Config) -> None:
296 default_fixture_loop_scope = config.getini("asyncio_default_fixture_loop_scope")
297 _validate_scope(default_fixture_loop_scope, "asyncio_default_fixture_loop_scope")
298 if not default_fixture_loop_scope:
299 warnings.warn(PytestDeprecationWarning(_DEFAULT_FIXTURE_LOOP_SCOPE_UNSET))
300
301 default_test_loop_scope = config.getini("asyncio_default_test_loop_scope")
302 _validate_scope(default_test_loop_scope, "asyncio_default_test_loop_scope")
303 config.addinivalue_line(
304 "markers",
305 "asyncio: "
306 "mark the test as a coroutine, it will be "
307 "run using an asyncio event loop",
308 )
309
310
311 @pytest.hookimpl(tryfirst=True)
312 def pytest_report_header(config: Config) -> list[str]:
313 """Add asyncio config to pytest header."""
314 mode = _get_asyncio_mode(config)
315 debug = _get_asyncio_debug(config)
316 default_fixture_loop_scope = config.getini("asyncio_default_fixture_loop_scope")
317 default_test_loop_scope = _get_default_test_loop_scope(config)
318 header = [
319 f"mode={mode}",
320 f"debug={debug}",
321 f"asyncio_default_fixture_loop_scope={default_fixture_loop_scope}",
322 f"asyncio_default_test_loop_scope={default_test_loop_scope}",
323 ]
324 return [
325 "asyncio: " + ", ".join(header),
326 ]
327
328
329 def _fixture_synchronizer(
330 fixturedef: FixtureDef, runner: Runner, request: FixtureRequest
331 ) -> Callable:
332 """Returns a synchronous function evaluating the specified fixture."""
333 fixture_function = resolve_fixture_function(fixturedef, request)
334 if inspect.isasyncgenfunction(fixturedef.func):
335 return _wrap_asyncgen_fixture(fixture_function, runner, request) # type: ignore[arg-type]
336 elif inspect.iscoroutinefunction(fixturedef.func):
337 return _wrap_async_fixture(fixture_function, runner, request) # type: ignore[arg-type]
338 elif inspect.isgeneratorfunction(fixturedef.func):
339 return _wrap_syncgen_fixture(fixture_function, runner) # type: ignore[arg-type]
340 else:
341 return _wrap_sync_fixture(fixture_function, runner) # type: ignore[arg-type]
342
343
344 SyncGenFixtureParams = ParamSpec("SyncGenFixtureParams")
345 SyncGenFixtureYieldType = TypeVar("SyncGenFixtureYieldType")
346
347
348 def _wrap_syncgen_fixture(
349 fixture_function: Callable[
350 SyncGenFixtureParams, Generator[SyncGenFixtureYieldType]
351 ],
352 runner: Runner,
353 ) -> Callable[SyncGenFixtureParams, Generator[SyncGenFixtureYieldType]]:
354 @functools.wraps(fixture_function)
355 def _syncgen_fixture_wrapper(
356 *args: SyncGenFixtureParams.args,
357 **kwargs: SyncGenFixtureParams.kwargs,
358 ) -> Generator[SyncGenFixtureYieldType]:
359 with _temporary_event_loop(runner.get_loop()):
360 yield from fixture_function(*args, **kwargs)
361
362 return _syncgen_fixture_wrapper
363
364
365 SyncFixtureParams = ParamSpec("SyncFixtureParams")
366 SyncFixtureReturnType = TypeVar("SyncFixtureReturnType")
367
368
369 def _wrap_sync_fixture(
370 fixture_function: Callable[SyncFixtureParams, SyncFixtureReturnType],
371 runner: Runner,
372 ) -> Callable[SyncFixtureParams, SyncFixtureReturnType]:
373 @functools.wraps(fixture_function)
374 def _sync_fixture_wrapper(
375 *args: SyncFixtureParams.args,
376 **kwargs: SyncFixtureParams.kwargs,
377 ) -> SyncFixtureReturnType:
378 with _temporary_event_loop(runner.get_loop()):
379 return fixture_function(*args, **kwargs)
380
381 return _sync_fixture_wrapper
382
383
384 AsyncGenFixtureParams = ParamSpec("AsyncGenFixtureParams")
385 AsyncGenFixtureYieldType = TypeVar("AsyncGenFixtureYieldType")
386
387
388 def _wrap_asyncgen_fixture(
389 fixture_function: Callable[
390 AsyncGenFixtureParams, AsyncGeneratorType[AsyncGenFixtureYieldType, Any]
391 ],
392 runner: Runner,
393 request: FixtureRequest,
394 ) -> Callable[AsyncGenFixtureParams, AsyncGenFixtureYieldType]:
395 @functools.wraps(fixture_function)
396 def _asyncgen_fixture_wrapper(
397 *args: AsyncGenFixtureParams.args,
398 **kwargs: AsyncGenFixtureParams.kwargs,
399 ):
400 gen_obj = fixture_function(*args, **kwargs)
401
402 async def setup():
403 res = await gen_obj.__anext__()
404 return res
405
406 context = contextvars.copy_context()
407 result = runner.run(setup(), context=context)
408
409 reset_contextvars = _apply_contextvar_changes(context)
410
411 def finalizer() -> None:
412 """Yield again, to finalize."""
413
414 async def async_finalizer() -> None:
415 try:
416 await gen_obj.__anext__()
417 except StopAsyncIteration:
418 pass
419 else:
420 msg = "Async generator fixture didn't stop."
421 msg += "Yield only once."
422 raise ValueError(msg)
423
424 runner.run(async_finalizer(), context=context)
425 if reset_contextvars is not None:
426 reset_contextvars()
427
428 request.addfinalizer(finalizer)
429 return result
430
431 return _asyncgen_fixture_wrapper
432
433
434 AsyncFixtureParams = ParamSpec("AsyncFixtureParams")
435 AsyncFixtureReturnType = TypeVar("AsyncFixtureReturnType")
436
437
438 def _wrap_async_fixture(
439 fixture_function: Callable[
440 AsyncFixtureParams, CoroutineType[Any, Any, AsyncFixtureReturnType]
441 ],
442 runner: Runner,
443 request: FixtureRequest,
444 ) -> Callable[AsyncFixtureParams, AsyncFixtureReturnType]:
445 @functools.wraps(fixture_function)
446 def _async_fixture_wrapper(
447 *args: AsyncFixtureParams.args,
448 **kwargs: AsyncFixtureParams.kwargs,
449 ):
450 async def setup():
451 res = await fixture_function(*args, **kwargs)
452 return res
453
454 context = contextvars.copy_context()
455 result = runner.run(setup(), context=context)
456
457 # Copy the context vars modified by the setup task into the current
458 # context, and (if needed) add a finalizer to reset them.
459 #
460 # Note that this is slightly different from the behavior of a non-async
461 # fixture, which would rely on the fixture author to add a finalizer
462 # to reset the variables. In this case, the author of the fixture can't
463 # write such a finalizer because they have no way to capture the Context
464 # in which the setup function was run, so we need to do it for them.
465 reset_contextvars = _apply_contextvar_changes(context)
466 if reset_contextvars is not None:
467 request.addfinalizer(reset_contextvars)
468
469 return result
470
471 return _async_fixture_wrapper
472
473
474 def _apply_contextvar_changes(
475 context: contextvars.Context,
476 ) -> Callable[[], None] | None:
477 """
478 Copy contextvar changes from the given context to the current context.
479
480 If any contextvars were modified by the fixture, return a finalizer that
481 will restore them.
482 """
483 context_tokens = []
484 for var in context:
485 try:
486 if var.get() is context.get(var):
487 # This variable is not modified, so leave it as-is.
488 continue
489 except LookupError:
490 # This variable isn't yet set in the current context at all.
491 pass
492 token = var.set(context.get(var))
493 context_tokens.append((var, token))
494
495 if not context_tokens:
496 return None
497
498 def restore_contextvars():
499 while context_tokens:
500 var, token = context_tokens.pop()
501 var.reset(token)
502
503 return restore_contextvars
504
505
506 class PytestAsyncioFunction(Function):
507 """Base class for all test functions managed by pytest-asyncio."""
508
509 @classmethod
510 def item_subclass_for(cls, item: Function, /) -> type[PytestAsyncioFunction] | None:
511 """
512 Returns a subclass of PytestAsyncioFunction if there is a specialized subclass
513 for the specified function item.
514
515 Return None if no specialized subclass exists for the specified item.
516 """
517 for subclass in cls.__subclasses__():
518 if subclass._can_substitute(item):
519 return subclass
520 return None
521
522 @classmethod
523 def _from_function(cls, function: Function, /) -> Function:
524 """
525 Instantiates this specific PytestAsyncioFunction type from the specified
526 Function item.
527 """
528 assert function.get_closest_marker("asyncio")
529 assert function.parent is not None
530 subclass_instance = cls.from_parent(
531 function.parent,
532 name=function.name,
533 callspec=getattr(function, "callspec", None),
534 callobj=function.obj,
535 fixtureinfo=function._fixtureinfo,
536 keywords=function.keywords,
537 originalname=function.originalname,
538 )
539 subclass_instance.own_markers = function.own_markers
540 assert subclass_instance.own_markers == function.own_markers
541 return subclass_instance
542
543 @staticmethod
544 def _can_substitute(item: Function) -> bool:
545 """Returns whether the specified function can be replaced by this class"""
546 raise NotImplementedError()
547
548 def setup(self) -> None:
549 runner_fixture_id = f"_{self._loop_scope}_scoped_runner"
550 if runner_fixture_id not in self.fixturenames:
551 self.fixturenames.append(runner_fixture_id)
552 # When loop factories are configured, resolve the loop factory
553 # fixture early so that a factory variant change cascades cache
554 # invalidation before any async fixture checks its cache.
555 hook_caller = self.config.hook.pytest_asyncio_loop_factories
556 if hook_caller.get_hookimpls():
557 _ = self._request.getfixturevalue(_asyncio_loop_factory.__name__)
558 return super().setup()
559
560 def runtest(self) -> None:
561 runner_fixture_id = f"_{self._loop_scope}_scoped_runner"
562 runner = self._request.getfixturevalue(runner_fixture_id)
563 context = contextvars.copy_context()
564 synchronized_obj = _synchronize_coroutine(
565 getattr(*self._synchronization_target_attr), runner, context
566 )
567 with MonkeyPatch.context() as c:
568 c.setattr(*self._synchronization_target_attr, synchronized_obj)
569 super().runtest()
570
571 @functools.cached_property
572 def _loop_scope(self) -> _ScopeName:
573 """
574 Return the scope of the asyncio event loop this item is run in.
575
576 The effective scope is determined lazily. It is identical to to the
577 `loop_scope` value of the closest `asyncio` pytest marker. If no such
578 marker is present, the the loop scope is determined by the configuration
579 value of `asyncio_default_test_loop_scope`, instead.
580 """
581 marker = self.get_closest_marker("asyncio")
582 assert marker is not None
583 default_loop_scope = _get_default_test_loop_scope(self.config)
584 loop_scope = marker.kwargs.get("loop_scope") or marker.kwargs.get("scope")
585 if loop_scope is None:
586 return default_loop_scope
587 else:
588 return loop_scope
589
590 @property
591 def _synchronization_target_attr(self) -> tuple[object, str]:
592 """
593 Return the coroutine that needs to be synchronized during the test run.
594
595 This method is intended to be overwritten by subclasses when they need to apply
596 the coroutine synchronizer to a value that's different from self.obj
597 e.g. the AsyncHypothesisTest subclass.
598 """
599 return self, "obj"
600
601
602 class Coroutine(PytestAsyncioFunction):
603 """Pytest item created by a coroutine"""
604
605 @staticmethod
606 def _can_substitute(item: Function) -> bool:
607 func = item.obj
608 return inspect.iscoroutinefunction(func)
609
610
611 class AsyncGenerator(PytestAsyncioFunction):
612 """Pytest item created by an asynchronous generator"""
613
614 @staticmethod
615 def _can_substitute(item: Function) -> bool:
616 func = item.obj
617 return inspect.isasyncgenfunction(func)
618
619 @classmethod
620 def _from_function(cls, function: Function, /) -> Function:
621 async_gen_item = super()._from_function(function)
622 unsupported_item_type_message = (
623 f"Tests based on asynchronous generators are not supported. "
624 f"{function.name} will be ignored."
625 )
626 async_gen_item.warn(PytestCollectionWarning(unsupported_item_type_message))
627 async_gen_item.add_marker(
628 pytest.mark.xfail(run=False, reason=unsupported_item_type_message)
629 )
630 return async_gen_item
631
632
633 class AsyncStaticMethod(PytestAsyncioFunction):
634 """
635 Pytest item that is a coroutine or an asynchronous generator
636 decorated with staticmethod
637 """
638
639 @staticmethod
640 def _can_substitute(item: Function) -> bool:
641 func = item.obj
642 return isinstance(func, staticmethod) and _is_coroutine_or_asyncgen(
643 func.__func__
644 )
645
646
647 class AsyncHypothesisTest(PytestAsyncioFunction):
648 """
649 Pytest item that is coroutine or an asynchronous generator decorated by
650 @hypothesis.given.
651 """
652
653 def setup(self) -> None:
654 if not getattr(self.obj, "hypothesis", False) and getattr(
655 self.obj, "is_hypothesis_test", False
656 ):
657 pytest.fail(
658 f"test function `{self!r}` is using Hypothesis, but pytest-asyncio "
659 "only works with Hypothesis 3.64.0 or later."
660 )
661 return super().setup()
662
663 @staticmethod
664 def _can_substitute(item: Function) -> bool:
665 func = item.obj
666 return (
667 getattr(func, "is_hypothesis_test", False) # type: ignore[return-value]
668 and getattr(func, "hypothesis", None)
669 and inspect.iscoroutinefunction(func.hypothesis.inner_test)
670 )
671
672 @property
673 def _synchronization_target_attr(self) -> tuple[object, str]:
674 return self.obj.hypothesis, "inner_test"
675
676
677 def _resolve_asyncio_marker(item: Function) -> Mark | None:
678 marker = item.get_closest_marker("asyncio")
679 if marker is not None:
680 return marker
681 if _get_asyncio_mode(item.config) == Mode.AUTO:
682 item.add_marker("asyncio")
683 return item.get_closest_marker("asyncio")
684 return None
685
686
687 # The function name needs to start with "pytest_"
688 # see https://github.com/pytest-dev/pytest/issues/11307
689 @pytest.hookimpl(specname="pytest_pycollect_makeitem", hookwrapper=True)
690 def pytest_pycollect_makeitem_convert_async_functions_to_subclass(
691 collector: pytest.Module | pytest.Class, name: str, obj: object
692 ) -> Generator[None, pluggy.Result, None]:
693 """
694 Converts coroutines and async generators collected as pytest.Functions
695 to AsyncFunction items.
696 """
697 hook_result = yield
698 try:
699 node_or_list_of_nodes: (
700 pytest.Item | pytest.Collector | list[pytest.Item | pytest.Collector] | None
701 ) = hook_result.get_result()
702 except BaseException as e:
703 hook_result.force_exception(e)
704 return
705 if not node_or_list_of_nodes:
706 return
707 if isinstance(node_or_list_of_nodes, Sequence):
708 node_iterator = iter(node_or_list_of_nodes)
709 else:
710 # Treat single node as a single-element iterable
711 node_iterator = iter((node_or_list_of_nodes,))
712 updated_node_collection = []
713 for node in node_iterator:
714 updated_item = node
715 if isinstance(node, Function):
716 specialized_item_class = PytestAsyncioFunction.item_subclass_for(node)
717 if (
718 specialized_item_class is not None
719 and _resolve_asyncio_marker(node) is not None
720 ):
721 updated_item = specialized_item_class._from_function(node)
722 updated_node_collection.append(updated_item)
723 hook_result.force_result(updated_node_collection)
724
725
726 @pytest.hookimpl(tryfirst=True)
727 def pytest_generate_tests(metafunc: pytest.Metafunc) -> None:
728 specialized_item_class = PytestAsyncioFunction.item_subclass_for(
729 metafunc.definition
730 )
731 if specialized_item_class is None:
732 return
733
734 asyncio_marker = _resolve_asyncio_marker(metafunc.definition)
735 if asyncio_marker is None:
736 return
737 marker_loop_scope, marker_selected_factory_names = _parse_asyncio_marker(
738 asyncio_marker
739 )
740
741 hook_factories = _collect_hook_loop_factories(metafunc.config, metafunc.definition)
742 if hook_factories is None:
743 if marker_selected_factory_names is not None:
744 raise pytest.UsageError(
745 "mark.asyncio 'loop_factories' requires at least one "
746 "pytest_asyncio_loop_factories hook implementation."
747 )
748 return
749
750 factory_params: Collection[object]
751 factory_ids: Collection[str]
752 if marker_selected_factory_names is None:
753 factory_params = hook_factories.values()
754 factory_ids = hook_factories.keys()
755 else:
756 # Iterate in marker order to preserve explicit user selection
757 # order.
758 factory_ids = marker_selected_factory_names
759 factory_params = [
760 (
761 hook_factories[name]
762 if name in hook_factories
763 else pytest.param(
764 None,
765 marks=pytest.mark.skip(
766 reason=(
767 f"Loop factory {name!r} is not available."
768 f" Available factories:"
769 f" {', '.join(hook_factories)}."
770 ),
771 ),
772 )
773 )
774 for name in marker_selected_factory_names
775 ]
776 metafunc.fixturenames.append(_asyncio_loop_factory.__name__)
777 default_loop_scope = _get_default_test_loop_scope(metafunc.config)
778 loop_scope = marker_loop_scope or default_loop_scope
779 # pytest.HIDDEN_PARAM was added in pytest 8.4
780 hide_id = len(factory_ids) == 1 and hasattr(pytest, "HIDDEN_PARAM")
781 metafunc.parametrize(
782 _asyncio_loop_factory.__name__,
783 factory_params,
784 ids=(pytest.HIDDEN_PARAM,) if hide_id else factory_ids,
785 indirect=True,
786 scope=loop_scope,
787 )
788
789
790 @contextlib.contextmanager
791 def _temporary_event_loop(loop: AbstractEventLoop) -> Iterator[None]:
792 try:
793 old_loop = _get_event_loop_no_warn()
794 except RuntimeError:
795 old_loop = None
796 if old_loop is loop:
797 yield
798 return
799 _set_event_loop(loop)
800 try:
801 yield
802 finally:
803 _set_event_loop(old_loop)
804
805
806 @contextlib.contextmanager
807 def _temporary_event_loop_policy(
808 policy: AbstractEventLoopPolicy,
809 ) -> Iterator[None]:
810 old_loop_policy = _get_event_loop_policy()
811 _set_event_loop_policy(policy)
812 try:
813 yield
814 finally:
815 _set_event_loop_policy(old_loop_policy)
816
817
818 def _get_event_loop_policy() -> AbstractEventLoopPolicy:
819 with warnings.catch_warnings():
820 warnings.simplefilter("ignore", DeprecationWarning)
821 return asyncio.get_event_loop_policy()
822
823
824 def _set_event_loop_policy(policy: AbstractEventLoopPolicy) -> None:
825 with warnings.catch_warnings():
826 warnings.simplefilter("ignore", DeprecationWarning)
827 asyncio.set_event_loop_policy(policy)
828
829
830 def _get_event_loop_no_warn(
831 policy: AbstractEventLoopPolicy | None = None,
832 ) -> asyncio.AbstractEventLoop:
833 with warnings.catch_warnings():
834 warnings.simplefilter("ignore", DeprecationWarning)
835 if policy is not None:
836 return policy.get_event_loop()
837 else:
838 return asyncio.get_event_loop()
839
840
841 def _set_event_loop(loop: AbstractEventLoop | None) -> None:
842 with warnings.catch_warnings():
843 warnings.simplefilter("ignore", DeprecationWarning)
844 asyncio.set_event_loop(loop)
845
846
847 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
848 def pytest_pyfunc_call(pyfuncitem: Function) -> object | None:
849 """Pytest hook called before a test case is run."""
850 if pyfuncitem.get_closest_marker("asyncio") is not None:
851 if is_async_test(pyfuncitem):
852 asyncio_mode = _get_asyncio_mode(pyfuncitem.config)
853 for fixname, fixtures in pyfuncitem._fixtureinfo.name2fixturedefs.items():
854 # name2fixturedefs is a dict between fixture name and a list of matching
855 # fixturedefs. The last entry in the list is closest and the one used.
856 func = fixtures[-1].func
857 if (
858 asyncio_mode == Mode.STRICT
859 and _is_coroutine_or_asyncgen(func)
860 and not _is_asyncio_fixture_function(func)
861 ):
862 warnings.warn(
863 PytestDeprecationWarning(
864 f"asyncio test {pyfuncitem.name!r} requested async "
865 "@pytest.fixture "
866 f"{fixname!r} in strict mode. "
867 "You might want to use @pytest_asyncio.fixture or switch "
868 "to auto mode. "
869 "This will become an error in future versions of "
870 "pytest-asyncio."
871 ),
872 stacklevel=1,
873 )
874 # no stacklevel points at the users code, so we set stacklevel=1
875 # so it at least indicates that it's the plugin complaining.
876 # Pytest gives the test file & name in the warnings summary at least
877
878 else:
879 pyfuncitem.warn(
880 pytest.PytestWarning(
881 f"The test {pyfuncitem} is marked with '@pytest.mark.asyncio' "
882 "but it is not an async function. "
883 "Please remove the asyncio mark. "
884 "If the test is not marked explicitly, "
885 "check for global marks applied via 'pytestmark'."
886 )
887 )
888 yield
889 return None
890
891
892 def _synchronize_coroutine(
893 func: Callable[..., CoroutineType],
894 runner: asyncio.Runner,
895 context: contextvars.Context,
896 ):
897 """
898 Return a sync wrapper around a coroutine executing it in the
899 specified runner and context.
900 """
901
902 @functools.wraps(func)
903 def inner(*args, **kwargs):
904 coro = func(*args, **kwargs)
905 runner.run(coro, context=context)
906
907 return inner
908
909
910 @pytest.hookimpl(wrapper=True)
911 def pytest_fixture_setup(fixturedef: FixtureDef, request) -> object | None:
912 if (
913 fixturedef.argname == "event_loop_policy"
914 and fixturedef.func.__module__ != __name__
915 ):
916 warnings.warn(
917 PytestDeprecationWarning(_EVENT_LOOP_POLICY_FIXTURE_DEPRECATION_WARNING),
918 )
919 asyncio_mode = _get_asyncio_mode(request.config)
920 if not _is_asyncio_fixture_function(fixturedef.func):
921 if asyncio_mode == Mode.STRICT:
922 # Ignore async fixtures without explicit asyncio mark in strict mode
923 # This applies to pytest_trio fixtures, for example
924 return (yield)
925 if not _is_coroutine_or_asyncgen(fixturedef.func):
926 return (yield)
927 default_loop_scope = request.config.getini("asyncio_default_fixture_loop_scope")
928 loop_scope = (
929 getattr(fixturedef.func, "_loop_scope", None)
930 or default_loop_scope
931 or fixturedef.scope
932 )
933 runner_fixture_id = f"_{loop_scope}_scoped_runner"
934 runner = request.getfixturevalue(runner_fixture_id)
935 # Prevent the runner closing before the fixture's async teardown.
936 runner_fixturedef = request._get_active_fixturedef(runner_fixture_id)
937 runner_fixturedef.addfinalizer(
938 functools.partial(fixturedef.finish, request=request)
939 )
940 synchronizer = _fixture_synchronizer(fixturedef, runner, request)
941 _make_asyncio_fixture_function(synchronizer, loop_scope)
942 with MonkeyPatch.context() as c:
943 c.setattr(fixturedef, "func", synchronizer)
944 hook_result = yield
945 return hook_result
946
947
948 _DUPLICATE_LOOP_SCOPE_DEFINITION_ERROR = """\
949 An asyncio pytest marker defines both "scope" and "loop_scope", \
950 but it should only use "loop_scope".
951 """
952
953 _MARKER_SCOPE_KWARG_DEPRECATION_WARNING = """\
954 The "scope" keyword argument to the asyncio marker has been deprecated. \
955 Please use the "loop_scope" argument instead.
956 """
957
958 _INVALID_LOOP_FACTORIES_KWARG = """\
959 mark.asyncio 'loop_factories' must be a non-empty sequence of strings.
960 """
961
962 _EVENT_LOOP_POLICY_FIXTURE_DEPRECATION_WARNING = """\
963 Overriding the "event_loop_policy" fixture is deprecated \
964 and will be removed in a future version of pytest-asyncio. \
965 Use the "pytest_asyncio_loop_factories" hook to customize event loop creation.\
966 """
967
968
969 def _parse_asyncio_marker(
970 asyncio_marker: Mark,
971 ) -> tuple[_ScopeName | None, Sequence[str] | None]:
972 assert asyncio_marker.name == "asyncio"
973 _validate_asyncio_marker(asyncio_marker)
974 if "scope" in asyncio_marker.kwargs:
975 if "loop_scope" in asyncio_marker.kwargs:
976 raise pytest.UsageError(_DUPLICATE_LOOP_SCOPE_DEFINITION_ERROR)
977 warnings.warn(PytestDeprecationWarning(_MARKER_SCOPE_KWARG_DEPRECATION_WARNING))
978 scope = asyncio_marker.kwargs.get("loop_scope") or asyncio_marker.kwargs.get(
979 "scope"
980 )
981 if scope is not None:
982 assert scope in {"function", "class", "module", "package", "session"}
983 marker_value = asyncio_marker.kwargs.get("loop_factories")
984 if marker_value is None:
985 return scope, None
986 if isinstance(marker_value, str) or not isinstance(marker_value, Sequence):
987 raise ValueError(_INVALID_LOOP_FACTORIES_KWARG)
988 if not marker_value or any(
989 not isinstance(factory_name, str) or not factory_name
990 for factory_name in marker_value
991 ):
992 raise ValueError(_INVALID_LOOP_FACTORIES_KWARG)
993 return scope, marker_value
994
995
996 def _validate_asyncio_marker(asyncio_marker: Mark) -> None:
997 if asyncio_marker.args or (
998 asyncio_marker.kwargs
999 and set(asyncio_marker.kwargs) - {"loop_scope", "scope", "loop_factories"}
1000 ):
1001 msg = (
1002 "mark.asyncio accepts only keyword arguments 'loop_scope' and"
1003 " 'loop_factories'."
1004 )
1005 raise ValueError(msg)
1006
1007
1008 def _get_default_test_loop_scope(config: Config) -> Any:
1009 return config.getini("asyncio_default_test_loop_scope")
1010
1011
1012 _RUNNER_TEARDOWN_WARNING = """\
1013 An exception occurred during teardown of an asyncio.Runner. \
1014 The reason is likely that you closed the underlying event loop in a test, \
1015 which prevents the cleanup of asynchronous generators by the runner.
1016 This warning will become an error in future versions of pytest-asyncio. \
1017 Please ensure that your tests don't close the event loop. \
1018 Here is the traceback of the exception triggered during teardown:
1019 %s
1020 """
1021
1022
1023 def _create_scoped_runner_fixture(scope: _ScopeName) -> Callable:
1024 @pytest.fixture(
1025 scope=scope,
1026 name=f"_{scope}_scoped_runner",
1027 )
1028 def _scoped_runner(
1029 event_loop_policy,
1030 _asyncio_loop_factory,
1031 request: FixtureRequest,
1032 ) -> Iterator[Runner]:
1033 new_loop_policy = event_loop_policy
1034 debug_mode = _get_asyncio_debug(request.config)
1035 with _temporary_event_loop_policy(new_loop_policy):
1036 runner = Runner(
1037 debug=debug_mode,
1038 loop_factory=_asyncio_loop_factory,
1039 ).__enter__()
1040 if _asyncio_loop_factory is not None:
1041 _set_event_loop(runner.get_loop())
1042 try:
1043 yield runner
1044 except Exception as e:
1045 runner.__exit__(type(e), e, e.__traceback__)
1046 else:
1047 with warnings.catch_warnings():
1048 warnings.filterwarnings(
1049 "ignore", ".*BaseEventLoop.shutdown_asyncgens.*", RuntimeWarning
1050 )
1051 try:
1052 runner.__exit__(None, None, None)
1053 except RuntimeError:
1054 warnings.warn(
1055 _RUNNER_TEARDOWN_WARNING % traceback.format_exc(),
1056 RuntimeWarning,
1057 )
1058 finally:
1059 if _asyncio_loop_factory is not None:
1060 _set_event_loop(None)
1061
1062 return _scoped_runner
1063
1064
1065 for scope in Scope:
1066 globals()[f"_{scope.value}_scoped_runner"] = _create_scoped_runner_fixture(
1067 scope.value
1068 )
1069
1070
1071 @pytest.fixture(scope="session")
1072 def _asyncio_loop_factory(request: FixtureRequest) -> LoopFactory | None:
1073 return getattr(request, "param", None)
1074
1075
1076 @pytest.fixture(scope="session", autouse=True)
1077 def event_loop_policy() -> AbstractEventLoopPolicy:
1078 """Return an instance of the policy used to create asyncio event loops."""
1079 return _get_event_loop_policy()
1080
1081
1082 def is_async_test(item: Item) -> TypeIs[PytestAsyncioFunction]:
1083 """Returns whether a test item is a pytest-asyncio test"""
1084 return isinstance(item, PytestAsyncioFunction)
1085
1086
1087 def _unused_port(socket_type: int) -> int:
1088 """Find an unused localhost port from 1024-65535 and return it."""
1089 with contextlib.closing(socket.socket(type=socket_type)) as sock:
1090 sock.bind(("127.0.0.1", 0))
1091 return sock.getsockname()[1]
1092
1093
1094 @pytest.fixture
1095 def unused_tcp_port() -> int:
1096 return _unused_port(socket.SOCK_STREAM)
1097
1098
1099 @pytest.fixture
1100 def unused_udp_port() -> int:
1101 return _unused_port(socket.SOCK_DGRAM)
1102
1103
1104 @pytest.fixture(scope="session")
1105 def unused_tcp_port_factory() -> Callable[[], int]:
1106 """A factory function, producing different unused TCP ports."""
1107 produced = set()
1108
1109 def factory():
1110 """Return an unused port."""
1111 port = _unused_port(socket.SOCK_STREAM)
1112
1113 while port in produced:
1114 port = _unused_port(socket.SOCK_STREAM)
1115
1116 produced.add(port)
1117
1118 return port
1119
1120 return factory
1121
1122
1123 @pytest.fixture(scope="session")
1124 def unused_udp_port_factory() -> Callable[[], int]:
1125 """A factory function, producing different unused UDP ports."""
1126 produced = set()
1127
1128 def factory():
1129 """Return an unused port."""
1130 port = _unused_port(socket.SOCK_DGRAM)
1131
1132 while port in produced:
1133 port = _unused_port(socket.SOCK_DGRAM)
1134
1135 produced.add(port)
1136
1137 return port
1138
1139 return factory