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