pytest_plugin.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from __future__ import annotations
  2. import dataclasses
  3. import socket
  4. import sys
  5. from collections.abc import Callable, Generator, Iterator
  6. from contextlib import ExitStack, contextmanager
  7. from inspect import isasyncgenfunction, iscoroutinefunction, ismethod
  8. from typing import Any, cast
  9. import pytest
  10. from _pytest.fixtures import FuncFixtureInfo, SubRequest
  11. from _pytest.outcomes import Exit
  12. from _pytest.python import CallSpec2
  13. from _pytest.scope import Scope
  14. from . import get_available_backends
  15. from ._core._eventloop import (
  16. current_async_library,
  17. get_async_backend,
  18. reset_current_async_library,
  19. set_current_async_library,
  20. )
  21. from ._core._exceptions import iterate_exceptions
  22. from .abc import TestRunner
  23. if sys.version_info < (3, 11):
  24. from exceptiongroup import ExceptionGroup
  25. _current_runner: TestRunner | None = None
  26. _runner_stack: ExitStack | None = None
  27. _runner_leases = 0
  28. def extract_backend_and_options(backend: object) -> tuple[str, dict[str, Any]]:
  29. if isinstance(backend, str):
  30. return backend, {}
  31. elif isinstance(backend, tuple) and len(backend) == 2:
  32. if isinstance(backend[0], str) and isinstance(backend[1], dict):
  33. return cast(tuple[str, dict[str, Any]], backend)
  34. raise TypeError("anyio_backend must be either a string or tuple of (string, dict)")
  35. @contextmanager
  36. def get_runner(
  37. backend_name: str, backend_options: dict[str, Any]
  38. ) -> Iterator[TestRunner]:
  39. global _current_runner, _runner_leases, _runner_stack
  40. if _current_runner is None:
  41. asynclib = get_async_backend(backend_name)
  42. _runner_stack = ExitStack()
  43. if current_async_library() is None:
  44. # Since we're in control of the event loop, we can cache the name of the
  45. # async library
  46. token = set_current_async_library(backend_name)
  47. _runner_stack.callback(reset_current_async_library, token)
  48. backend_options = backend_options or {}
  49. _current_runner = _runner_stack.enter_context(
  50. asynclib.create_test_runner(backend_options)
  51. )
  52. _runner_leases += 1
  53. try:
  54. yield _current_runner
  55. finally:
  56. _runner_leases -= 1
  57. if not _runner_leases:
  58. assert _runner_stack is not None
  59. _runner_stack.close()
  60. _runner_stack = _current_runner = None
  61. def pytest_addoption(parser: pytest.Parser) -> None:
  62. parser.addini(
  63. "anyio_mode",
  64. default="strict",
  65. help='AnyIO plugin mode (either "strict" or "auto")',
  66. )
  67. def pytest_configure(config: pytest.Config) -> None:
  68. config.addinivalue_line(
  69. "markers",
  70. "anyio: mark the (coroutine function) test to be run asynchronously via anyio.",
  71. )
  72. if (
  73. config.getini("anyio_mode") == "auto"
  74. and config.pluginmanager.has_plugin("asyncio")
  75. and config.getini("asyncio_mode") == "auto"
  76. ):
  77. config.issue_config_time_warning(
  78. pytest.PytestConfigWarning(
  79. "AnyIO auto mode has been enabled together with pytest-asyncio auto "
  80. "mode. This may cause unexpected behavior."
  81. ),
  82. 1,
  83. )
  84. @pytest.hookimpl(hookwrapper=True)
  85. def pytest_fixture_setup(fixturedef: Any, request: Any) -> Generator[Any]:
  86. def wrapper(anyio_backend: Any, request: SubRequest, **kwargs: Any) -> Any:
  87. # Rebind any fixture methods to the request instance
  88. if (
  89. request.instance
  90. and ismethod(func)
  91. and type(func.__self__) is type(request.instance)
  92. ):
  93. local_func = func.__func__.__get__(request.instance)
  94. else:
  95. local_func = func
  96. backend_name, backend_options = extract_backend_and_options(anyio_backend)
  97. if has_backend_arg:
  98. kwargs["anyio_backend"] = anyio_backend
  99. if has_request_arg:
  100. kwargs["request"] = request
  101. with get_runner(backend_name, backend_options) as runner:
  102. # re-entrant call into the test runner detected. this happens when an async fixture
  103. # is dynamically requested via request.getfixturevalue() from inside a running async
  104. # test or fixture. on asyncio this raises RuntimeError: This event loop is already
  105. # running, on trio the runner deadlocks - the host loop blocks waiting for the
  106. # coroutine to return, but the coroutine is waiting for the host loop. raising here
  107. # prevents the hang and gives a consistent error across backends.
  108. if runner.is_running():
  109. raise RuntimeError(
  110. "Cannot schedule a coroutine in the test runner while another is already running; "
  111. "likely caused by request.getfixturevalue() on an async fixture."
  112. )
  113. if isasyncgenfunction(local_func):
  114. yield from runner.run_asyncgen_fixture(local_func, kwargs)
  115. else:
  116. yield runner.run_fixture(local_func, kwargs)
  117. # Only apply this to coroutine functions and async generator functions in requests
  118. # that involve the anyio_backend fixture
  119. func = fixturedef.func
  120. if isasyncgenfunction(func) or iscoroutinefunction(func):
  121. if "anyio_backend" in request.fixturenames:
  122. fixturedef.func = wrapper
  123. original_argname = fixturedef.argnames
  124. if not (has_backend_arg := "anyio_backend" in fixturedef.argnames):
  125. fixturedef.argnames += ("anyio_backend",)
  126. if not (has_request_arg := "request" in fixturedef.argnames):
  127. fixturedef.argnames += ("request",)
  128. try:
  129. return (yield)
  130. finally:
  131. fixturedef.func = func
  132. fixturedef.argnames = original_argname
  133. return (yield)
  134. @pytest.hookimpl(tryfirst=True)
  135. def pytest_pycollect_makeitem(
  136. collector: pytest.Module | pytest.Class, name: str, obj: object
  137. ) -> None:
  138. if collector.istestfunction(obj, name):
  139. inner_func = obj.hypothesis.inner_test if hasattr(obj, "hypothesis") else obj
  140. if iscoroutinefunction(inner_func):
  141. anyio_auto_mode = collector.config.getini("anyio_mode") == "auto"
  142. marker = collector.get_closest_marker("anyio")
  143. own_markers = getattr(obj, "pytestmark", ())
  144. if (
  145. anyio_auto_mode
  146. or marker
  147. or any(marker.name == "anyio" for marker in own_markers)
  148. ):
  149. pytest.mark.usefixtures("anyio_backend")(obj)
  150. def pytest_collection_finish(session: pytest.Session) -> None:
  151. for i, item in reversed(list(enumerate(session.items))):
  152. if (
  153. isinstance(item, pytest.Function)
  154. and iscoroutinefunction(item.function)
  155. and item.get_closest_marker("anyio") is not None
  156. and "anyio_backend" not in item.fixturenames
  157. ):
  158. new_items = []
  159. try:
  160. cs_fields = {f.name for f in dataclasses.fields(CallSpec2)}
  161. except TypeError:
  162. cs_fields = set()
  163. for param_index, backend in enumerate(get_available_backends()):
  164. if "_arg2scope" in cs_fields: # pytest >= 8
  165. callspec = CallSpec2(
  166. params={"anyio_backend": backend},
  167. indices={"anyio_backend": param_index},
  168. _arg2scope={"anyio_backend": Scope.Module},
  169. _idlist=[backend],
  170. marks=[],
  171. )
  172. else: # pytest 7.x
  173. callspec = CallSpec2( # type: ignore[call-arg]
  174. funcargs={},
  175. params={"anyio_backend": backend},
  176. indices={"anyio_backend": param_index},
  177. arg2scope={"anyio_backend": Scope.Module},
  178. idlist=[backend],
  179. marks=[],
  180. )
  181. fi = item._fixtureinfo
  182. new_names_closure = list(fi.names_closure)
  183. if "anyio_backend" not in new_names_closure:
  184. new_names_closure.append("anyio_backend")
  185. new_fixtureinfo = FuncFixtureInfo(
  186. argnames=fi.argnames,
  187. initialnames=fi.initialnames,
  188. names_closure=new_names_closure,
  189. name2fixturedefs=fi.name2fixturedefs,
  190. )
  191. new_item = pytest.Function.from_parent(
  192. item.parent,
  193. name=f"{item.originalname}[{backend}]",
  194. callspec=callspec,
  195. callobj=item.obj,
  196. fixtureinfo=new_fixtureinfo,
  197. keywords=item.keywords,
  198. originalname=item.originalname,
  199. )
  200. new_items.append(new_item)
  201. session.items[i : i + 1] = new_items
  202. @pytest.hookimpl(tryfirst=True)
  203. def pytest_pyfunc_call(pyfuncitem: Any) -> bool | None:
  204. def run_with_hypothesis(**kwargs: Any) -> None:
  205. with get_runner(backend_name, backend_options) as runner:
  206. runner.run_test(original_func, kwargs)
  207. backend = pyfuncitem.funcargs.get("anyio_backend")
  208. if backend:
  209. backend_name, backend_options = extract_backend_and_options(backend)
  210. if hasattr(pyfuncitem.obj, "hypothesis"):
  211. # Wrap the inner test function unless it's already wrapped
  212. original_func = pyfuncitem.obj.hypothesis.inner_test
  213. if original_func.__qualname__ != run_with_hypothesis.__qualname__:
  214. if iscoroutinefunction(original_func):
  215. pyfuncitem.obj.hypothesis.inner_test = run_with_hypothesis
  216. return None
  217. if iscoroutinefunction(pyfuncitem.obj):
  218. funcargs = pyfuncitem.funcargs
  219. testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}
  220. with get_runner(backend_name, backend_options) as runner:
  221. try:
  222. runner.run_test(pyfuncitem.obj, testargs)
  223. except ExceptionGroup as excgrp:
  224. for exc in iterate_exceptions(excgrp):
  225. if isinstance(exc, (Exit, KeyboardInterrupt, SystemExit)):
  226. raise exc from excgrp
  227. raise
  228. return True
  229. return None
  230. @pytest.fixture(scope="module", params=get_available_backends())
  231. def anyio_backend(request: Any) -> Any:
  232. return request.param
  233. @pytest.fixture
  234. def anyio_backend_name(anyio_backend: Any) -> str:
  235. if isinstance(anyio_backend, str):
  236. return anyio_backend
  237. else:
  238. return anyio_backend[0]
  239. @pytest.fixture
  240. def anyio_backend_options(anyio_backend: Any) -> dict[str, Any]:
  241. if isinstance(anyio_backend, str):
  242. return {}
  243. else:
  244. return anyio_backend[1]
  245. class FreePortFactory:
  246. """
  247. Manages port generation based on specified socket kind, ensuring no duplicate
  248. ports are generated.
  249. This class provides functionality for generating available free ports on the
  250. system. It is initialized with a specific socket kind and can generate ports
  251. for given address families while avoiding reuse of previously generated ports.
  252. Users should not instantiate this class directly, but use the
  253. ``free_tcp_port_factory`` and ``free_udp_port_factory`` fixtures instead. For simple
  254. uses cases, ``free_tcp_port`` and ``free_udp_port`` can be used instead.
  255. """
  256. def __init__(self, kind: socket.SocketKind) -> None:
  257. self._kind = kind
  258. self._generated = set[int]()
  259. @property
  260. def kind(self) -> socket.SocketKind:
  261. """
  262. The type of socket connection (e.g., :data:`~socket.SOCK_STREAM` or
  263. :data:`~socket.SOCK_DGRAM`) used to bind for checking port availability
  264. """
  265. return self._kind
  266. def __call__(self, family: socket.AddressFamily | None = None) -> int:
  267. """
  268. Return an unbound port for the given address family.
  269. :param family: if omitted, both IPv4 and IPv6 addresses will be tried
  270. :return: a port number
  271. """
  272. if family is not None:
  273. families = [family]
  274. else:
  275. families = [socket.AF_INET]
  276. if socket.has_ipv6:
  277. families.append(socket.AF_INET6)
  278. while True:
  279. port = 0
  280. with ExitStack() as stack:
  281. for family in families:
  282. sock = stack.enter_context(socket.socket(family, self._kind))
  283. addr = "::1" if family == socket.AF_INET6 else "127.0.0.1"
  284. try:
  285. sock.bind((addr, port))
  286. except OSError:
  287. break
  288. if not port:
  289. port = sock.getsockname()[1]
  290. else:
  291. if port not in self._generated:
  292. self._generated.add(port)
  293. return port
  294. @pytest.fixture(scope="session")
  295. def free_tcp_port_factory() -> FreePortFactory:
  296. return FreePortFactory(socket.SOCK_STREAM)
  297. @pytest.fixture(scope="session")
  298. def free_udp_port_factory() -> FreePortFactory:
  299. return FreePortFactory(socket.SOCK_DGRAM)
  300. @pytest.fixture
  301. def free_tcp_port(free_tcp_port_factory: Callable[[], int]) -> int:
  302. return free_tcp_port_factory()
  303. @pytest.fixture
  304. def free_udp_port(free_udp_port_factory: Callable[[], int]) -> int:
  305. return free_udp_port_factory()