pytest_plugin.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. from __future__ import annotations
  2. import socket
  3. import sys
  4. from collections.abc import Callable, Generator, Iterator
  5. from contextlib import ExitStack, contextmanager
  6. from inspect import isasyncgenfunction, iscoroutinefunction, ismethod
  7. from typing import Any, cast
  8. import pytest
  9. import sniffio
  10. from _pytest.fixtures import SubRequest
  11. from _pytest.outcomes import Exit
  12. from ._core._eventloop import get_all_backends, get_async_backend
  13. from ._core._exceptions import iterate_exceptions
  14. from .abc import TestRunner
  15. if sys.version_info < (3, 11):
  16. from exceptiongroup import ExceptionGroup
  17. _current_runner: TestRunner | None = None
  18. _runner_stack: ExitStack | None = None
  19. _runner_leases = 0
  20. def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]:
  21. if isinstance(backend, str):
  22. return backend, {}
  23. elif isinstance(backend, tuple) and len(backend) == 2:
  24. if isinstance(backend[0], str) and isinstance(backend[1], dict):
  25. return cast(tuple[str, dict[str, Any]], backend)
  26. raise TypeError("anyio_backend must be either a string or tuple of (string, dict)")
  27. @contextmanager
  28. def get_runner(
  29. backend_name: str, backend_options: dict[str, Any]
  30. ) -> Iterator[TestRunner]:
  31. global _current_runner, _runner_leases, _runner_stack
  32. if _current_runner is None:
  33. asynclib = get_async_backend(backend_name)
  34. _runner_stack = ExitStack()
  35. if sniffio.current_async_library_cvar.get(None) is None:
  36. # Since we're in control of the event loop, we can cache the name of the
  37. # async library
  38. token = sniffio.current_async_library_cvar.set(backend_name)
  39. _runner_stack.callback(sniffio.current_async_library_cvar.reset, token)
  40. backend_options = backend_options or {}
  41. _current_runner = _runner_stack.enter_context(
  42. asynclib.create_test_runner(backend_options)
  43. )
  44. _runner_leases += 1
  45. try:
  46. yield _current_runner
  47. finally:
  48. _runner_leases -= 1
  49. if not _runner_leases:
  50. assert _runner_stack is not None
  51. _runner_stack.close()
  52. _runner_stack = _current_runner = None
  53. def pytest_addoption(parser: pytest.Parser) -> None:
  54. parser.addini(
  55. "anyio_mode",
  56. default="strict",
  57. help='AnyIO plugin mode (either "strict" or "auto")',
  58. type="string",
  59. )
  60. def pytest_configure(config: pytest.Config) -> None:
  61. config.addinivalue_line(
  62. "markers",
  63. "anyio: mark the (coroutine function) test to be run asynchronously via anyio.",
  64. )
  65. if (
  66. config.getini("anyio_mode") == "auto"
  67. and config.pluginmanager.has_plugin("asyncio")
  68. and config.getini("asyncio_mode") == "auto"
  69. ):
  70. config.issue_config_time_warning(
  71. pytest.PytestConfigWarning(
  72. "AnyIO auto mode has been enabled together with pytest-asyncio auto "
  73. "mode. This may cause unexpected behavior."
  74. ),
  75. 1,
  76. )
  77. @pytest.hookimpl(hookwrapper=True)
  78. def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]:
  79. def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any:
  80. # Rebind any fixture methods to the request instance
  81. if (
  82. request.instance
  83. and ismethod(func)
  84. and type(func.__self__) is type(request.instance)
  85. ):
  86. local_func = func.__func__.__get__(request.instance)
  87. else:
  88. local_func = func
  89. backend_name, backend_options = extract_backend_and_options(anyio_backend)
  90. if has_backend_arg:
  91. kwargs["anyio_backend"] = anyio_backend
  92. if has_request_arg:
  93. kwargs["request"] = request
  94. with get_runner(backend_name, backend_options) as runner:
  95. if isasyncgenfunction(local_func):
  96. yield from runner.run_asyncgen_fixture(local_func, kwargs)
  97. else:
  98. yield runner.run_fixture(local_func, kwargs)
  99. # Only apply this to coroutine functions and async generator functions in requests
  100. # that involve the anyio_backend fixture
  101. func = fixturedef.func
  102. if isasyncgenfunction(func) or iscoroutinefunction(func):
  103. if "anyio_backend" in request.fixturenames:
  104. fixturedef.func = wrapper
  105. original_argname = fixturedef.argnames
  106. if not (has_backend_arg := "anyio_backend" in fixturedef.argnames):
  107. fixturedef.argnames += ("anyio_backend",)
  108. if not (has_request_arg := "request" in fixturedef.argnames):
  109. fixturedef.argnames += ("request",)
  110. try:
  111. return (yield)
  112. finally:
  113. fixturedef.func = func
  114. fixturedef.argnames = original_argname
  115. return (yield)
  116. @pytest.hookimpl(tryfirst=True)
  117. def pytest_pycollect_makeitem(
  118. collector: pytest.Module | pytest.Class, name: str, obj: object
  119. ) -> None:
  120. if collector.istestfunction(obj, name):
  121. inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj
  122. if iscoroutinefunction(inner_func):
  123. anyio_auto_mode = collector.config.getini("anyio_mode") == "auto"
  124. marker = collector.get_closest_marker("anyio")
  125. own_markers = getattr(obj, "pytestmark", ())
  126. if (
  127. anyio_auto_mode
  128. or marker
  129. or any(marker.name == "anyio" for marker in own_markers)
  130. ):
  131. pytest.mark.usefixtures("anyio_backend")(obj)
  132. @pytest.hookimpl(tryfirst=True)
  133. def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None:
  134. def run_with_hypothesis(**kwargs: Any) -> None:
  135. with get_runner(backend_name, backend_options) as runner:
  136. runner.run_test(original_func, kwargs)
  137. backend = pyfuncitem.funcargs.get("anyio_backend")
  138. if backend:
  139. backend_name, backend_options = extract_backend_and_options(backend)
  140. if hasattr(pyfuncitem.obj, "hypothesis"):
  141. # Wrap the inner test function unless it's already wrapped
  142. original_func = pyfuncitem.obj.hypothesis.inner_test
  143. if original_func.__qualname__ != run_with_hypothesis.__qualname__:
  144. if iscoroutinefunction(original_func):
  145. pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis
  146. return None
  147. if iscoroutinefunction(pyfuncitem.obj):
  148. funcargs = pyfuncitem.funcargs
  149. testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
  150. with get_runner(backend_name, backend_options) as runner:
  151. try:
  152. runner.run_test(pyfuncitem.obj, testargs)
  153. except ExceptionGroup as excgrp:
  154. for exc in iterate_exceptions(excgrp):
  155. if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)):
  156. raise exc from excgrp
  157. raise
  158. return True
  159. return None
  160. @pytest.fixture(scope="module", params=get_all_backends())
  161. def anyio_backend(request: Any) -> Any:
  162. return request.param
  163. @pytest.fixture
  164. def anyio_backend_name(anyio_backend: Any) -> str:
  165. if isinstance(anyio_backend, str):
  166. return anyio_backend
  167. else:
  168. return anyio_backend[0]
  169. @pytest.fixture
  170. def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]:
  171. if isinstance(anyio_backend, str):
  172. return {}
  173. else:
  174. return anyio_backend[1]
  175. class FreePortFactory:
  176. """
  177. Manages port generation based on specified socket kind, ensuring no duplicate
  178. ports are generated.
  179. This class provides functionality for generating available free ports on the
  180. system. It is initialized with a specific socket kind and can generate ports
  181. for given address families while avoiding reuse of previously generated ports.
  182. Users should not instantiate this class directly, but use the
  183. ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple
  184. uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead.
  185. """
  186. def __init__(self, kind: socket.SocketKind) -> None:
  187. self._kind = kind
  188. self._generated = set[int]()
  189. @property
  190. def kind(self) -> socket.SocketKind:
  191. """
  192. The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or
  193. :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability
  194. """
  195. return self._kind
  196. def __call__(self, family: socket.AddressFamily | None = None) -> int:
  197. """
  198. Return an unbound port for the given address family.
  199. :param family: if omitted, both IPv4 and IPv6 addresses will be tried
  200. :return: a port number
  201. """
  202. if family is not None:
  203. families = [family]
  204. else:
  205. families = [socket.AF_INET]
  206. if socket.has_ipv6:
  207. families.append(socket.AF_INET6)
  208. while True:
  209. port = 0
  210. with ExitStack() as stack:
  211. for family in families:
  212. sock = stack.enter_context(socket.socket(family, self._kind))
  213. addr = "::1" if family == socket.AF_INET6 else "127.0.0.1"
  214. try:
  215. sock.bind((addr, port))
  216. except OSError:
  217. break
  218. if not port:
  219. port = sock.getsockname()[1]
  220. else:
  221. if port not in self._generated:
  222. self._generated.add(port)
  223. return port
  224. @pytest.fixture(scope="session")
  225. def free_tcp_port_factory() -> FreePortFactory:
  226. return FreePortFactory(socket.SOCK_STREAM)
  227. @pytest.fixture(scope="session")
  228. def free_udp_port_factory() -> FreePortFactory:
  229. return FreePortFactory(socket.SOCK_DGRAM)
  230. @pytest.fixture
  231. def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int:
  232. return free_tcp_port_factory()
  233. @pytest.fixture
  234. def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int:
  235. return free_udp_port_factory()