plugin.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. """pytest-asyncio implementation."""
  2. import asyncio
  3. import contextlib
  4. import enum
  5. import functools
  6. import inspect
  7. import socket
  8. import sys
  9. import warnings
  10. from textwrap import dedent
  11. from typing import (
  12. Any,
  13. AsyncIterator,
  14. Awaitable,
  15. Callable,
  16. Dict,
  17. Iterable,
  18. Iterator,
  19. List,
  20. Optional,
  21. Set,
  22. TypeVar,
  23. Union,
  24. cast,
  25. overload,
  26. )
  27. import pytest
  28. from pytest import (
  29. Config,
  30. FixtureRequest,
  31. Function,
  32. Item,
  33. Parser,
  34. PytestPluginManager,
  35. Session,
  36. )
  37. if sys.version_info >= (3, 8):
  38. from typing import Literal
  39. else:
  40. from typing_extensions import Literal
  41. _R = TypeVar("_R")
  42. _ScopeName = Literal["session", "package", "module", "class", "function"]
  43. _T = TypeVar("_T")
  44. SimpleFixtureFunction = TypeVar(
  45. "SimpleFixtureFunction", bound=Callable[..., Awaitable[_R]]
  46. )
  47. FactoryFixtureFunction = TypeVar(
  48. "FactoryFixtureFunction", bound=Callable[..., AsyncIterator[_R]]
  49. )
  50. FixtureFunction = Union[SimpleFixtureFunction, FactoryFixtureFunction]
  51. FixtureFunctionMarker = Callable[[FixtureFunction], FixtureFunction]
  52. # https://github.com/pytest-dev/pytest/pull/9510
  53. FixtureDef = Any
  54. SubRequest = Any
  55. class Mode(str, enum.Enum):
  56. AUTO = "auto"
  57. STRICT = "strict"
  58. ASYNCIO_MODE_HELP = """\
  59. 'auto' - for automatically handling all async functions by the plugin
  60. 'strict' - for autoprocessing disabling (useful if different async frameworks \
  61. should be tested together, e.g. \
  62. both pytest-asyncio and pytest-trio are used in the same project)
  63. """
  64. def pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) -> None:
  65. group = parser.getgroup("asyncio")
  66. group.addoption(
  67. "--asyncio-mode",
  68. dest="asyncio_mode",
  69. default=None,
  70. metavar="MODE",
  71. help=ASYNCIO_MODE_HELP,
  72. )
  73. parser.addini(
  74. "asyncio_mode",
  75. help="default value for --asyncio-mode",
  76. default="auto",
  77. )
  78. @overload
  79. def fixture(
  80. fixture_function: FixtureFunction,
  81. *,
  82. scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
  83. params: Optional[Iterable[object]] = ...,
  84. autouse: bool = ...,
  85. ids: Union[
  86. Iterable[Union[str, float, int, bool, None]],
  87. Callable[[Any], Optional[object]],
  88. None,
  89. ] = ...,
  90. name: Optional[str] = ...,
  91. ) -> FixtureFunction:
  92. ...
  93. @overload
  94. def fixture(
  95. fixture_function: None = ...,
  96. *,
  97. scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
  98. params: Optional[Iterable[object]] = ...,
  99. autouse: bool = ...,
  100. ids: Union[
  101. Iterable[Union[str, float, int, bool, None]],
  102. Callable[[Any], Optional[object]],
  103. None,
  104. ] = ...,
  105. name: Optional[str] = None,
  106. ) -> FixtureFunctionMarker:
  107. ...
  108. def fixture(
  109. fixture_function: Optional[FixtureFunction] = None, **kwargs: Any
  110. ) -> Union[FixtureFunction, FixtureFunctionMarker]:
  111. if fixture_function is not None:
  112. _make_asyncio_fixture_function(fixture_function)
  113. return pytest.fixture(fixture_function, **kwargs)
  114. else:
  115. @functools.wraps(fixture)
  116. def inner(fixture_function: FixtureFunction) -> FixtureFunction:
  117. return fixture(fixture_function, **kwargs)
  118. return inner
  119. def _is_asyncio_fixture_function(obj: Any) -> bool:
  120. obj = getattr(obj, "__func__", obj) # instance method maybe?
  121. return getattr(obj, "_force_asyncio_fixture", False)
  122. def _make_asyncio_fixture_function(obj: Any) -> None:
  123. if hasattr(obj, "__func__"):
  124. # instance method, check the function object
  125. obj = obj.__func__
  126. obj._force_asyncio_fixture = True
  127. def _is_coroutine(obj: Any) -> bool:
  128. """Check to see if an object is really an asyncio coroutine."""
  129. return asyncio.iscoroutinefunction(obj)
  130. def _is_coroutine_or_asyncgen(obj: Any) -> bool:
  131. return _is_coroutine(obj) or inspect.isasyncgenfunction(obj)
  132. def _get_asyncio_mode(config: Config) -> Mode:
  133. val = config.getoption("asyncio_mode")
  134. if val is None:
  135. val = config.getini("asyncio_mode")
  136. try:
  137. return Mode(val)
  138. except ValueError:
  139. modes = ", ".join(m.value for m in Mode)
  140. raise pytest.UsageError(
  141. f"{val!r} is not a valid asyncio_mode. Valid modes: {modes}."
  142. )
  143. def pytest_configure(config: Config) -> None:
  144. """Inject documentation."""
  145. config.addinivalue_line(
  146. "markers",
  147. "asyncio: "
  148. "mark the test as a coroutine, it will be "
  149. "run using an asyncio event loop",
  150. )
  151. @pytest.hookimpl(tryfirst=True)
  152. def pytest_report_header(config: Config) -> List[str]:
  153. """Add asyncio config to pytest header."""
  154. mode = _get_asyncio_mode(config)
  155. return [f"asyncio: mode={mode}"]
  156. def _preprocess_async_fixtures(
  157. config: Config,
  158. processed_fixturedefs: Set[FixtureDef],
  159. ) -> None:
  160. asyncio_mode = _get_asyncio_mode(config)
  161. fixturemanager = config.pluginmanager.get_plugin("funcmanage")
  162. for fixtures in fixturemanager._arg2fixturedefs.values():
  163. for fixturedef in fixtures:
  164. func = fixturedef.func
  165. if fixturedef in processed_fixturedefs or not _is_coroutine_or_asyncgen(
  166. func
  167. ):
  168. continue
  169. if not _is_asyncio_fixture_function(func) and asyncio_mode == Mode.STRICT:
  170. # Ignore async fixtures without explicit asyncio mark in strict mode
  171. # This applies to pytest_trio fixtures, for example
  172. continue
  173. _make_asyncio_fixture_function(func)
  174. _inject_fixture_argnames(fixturedef)
  175. _synchronize_async_fixture(fixturedef)
  176. assert _is_asyncio_fixture_function(fixturedef.func)
  177. processed_fixturedefs.add(fixturedef)
  178. def _inject_fixture_argnames(fixturedef: FixtureDef) -> None:
  179. """
  180. Ensures that `request` and `event_loop` are arguments of the specified fixture.
  181. """
  182. to_add = []
  183. for name in ("request", "event_loop"):
  184. if name not in fixturedef.argnames:
  185. to_add.append(name)
  186. if to_add:
  187. fixturedef.argnames += tuple(to_add)
  188. def _synchronize_async_fixture(fixturedef: FixtureDef) -> None:
  189. """
  190. Wraps the fixture function of an async fixture in a synchronous function.
  191. """
  192. if inspect.isasyncgenfunction(fixturedef.func):
  193. _wrap_asyncgen_fixture(fixturedef)
  194. elif inspect.iscoroutinefunction(fixturedef.func):
  195. _wrap_async_fixture(fixturedef)
  196. def _add_kwargs(
  197. func: Callable[..., Any],
  198. kwargs: Dict[str, Any],
  199. event_loop: asyncio.AbstractEventLoop,
  200. request: SubRequest,
  201. ) -> Dict[str, Any]:
  202. sig = inspect.signature(func)
  203. ret = kwargs.copy()
  204. if "request" in sig.parameters:
  205. ret["request"] = request
  206. if "event_loop" in sig.parameters:
  207. ret["event_loop"] = event_loop
  208. return ret
  209. def _perhaps_rebind_fixture_func(
  210. func: _T, instance: Optional[Any], unittest: bool
  211. ) -> _T:
  212. if instance is not None:
  213. # The fixture needs to be bound to the actual request.instance
  214. # so it is bound to the same object as the test method.
  215. unbound, cls = func, None
  216. try:
  217. unbound, cls = func.__func__, type(func.__self__) # type: ignore
  218. except AttributeError:
  219. pass
  220. # If unittest is true, the fixture is bound unconditionally.
  221. # otherwise, only if the fixture was bound before to an instance of
  222. # the same type.
  223. if unittest or (cls is not None and isinstance(instance, cls)):
  224. func = unbound.__get__(instance) # type: ignore
  225. return func
  226. def _wrap_asyncgen_fixture(fixturedef: FixtureDef) -> None:
  227. fixture = fixturedef.func
  228. @functools.wraps(fixture)
  229. def _asyncgen_fixture_wrapper(
  230. event_loop: asyncio.AbstractEventLoop, request: SubRequest, **kwargs: Any
  231. ):
  232. func = _perhaps_rebind_fixture_func(
  233. fixture, request.instance, fixturedef.unittest
  234. )
  235. gen_obj = func(**_add_kwargs(func, kwargs, event_loop, request))
  236. async def setup():
  237. res = await gen_obj.__anext__()
  238. return res
  239. def finalizer() -> None:
  240. """Yield again, to finalize."""
  241. async def async_finalizer() -> None:
  242. try:
  243. await gen_obj.__anext__()
  244. except StopAsyncIteration:
  245. pass
  246. else:
  247. msg = "Async generator fixture didn't stop."
  248. msg += "Yield only once."
  249. raise ValueError(msg)
  250. event_loop.run_until_complete(async_finalizer())
  251. result = event_loop.run_until_complete(setup())
  252. request.addfinalizer(finalizer)
  253. return result
  254. fixturedef.func = _asyncgen_fixture_wrapper
  255. def _wrap_async_fixture(fixturedef: FixtureDef) -> None:
  256. fixture = fixturedef.func
  257. @functools.wraps(fixture)
  258. def _async_fixture_wrapper(
  259. event_loop: asyncio.AbstractEventLoop, request: SubRequest, **kwargs: Any
  260. ):
  261. func = _perhaps_rebind_fixture_func(
  262. fixture, request.instance, fixturedef.unittest
  263. )
  264. async def setup():
  265. res = await func(**_add_kwargs(func, kwargs, event_loop, request))
  266. return res
  267. return event_loop.run_until_complete(setup())
  268. fixturedef.func = _async_fixture_wrapper
  269. _HOLDER: Set[FixtureDef] = set()
  270. @pytest.hookimpl(tryfirst=True)
  271. def pytest_pycollect_makeitem(
  272. collector: Union[pytest.Module, pytest.Class], name: str, obj: object
  273. ) -> Union[
  274. pytest.Item, pytest.Collector, List[Union[pytest.Item, pytest.Collector]], None
  275. ]:
  276. """A pytest hook to collect asyncio coroutines."""
  277. if not collector.funcnamefilter(name):
  278. return None
  279. _preprocess_async_fixtures(collector.config, _HOLDER)
  280. return None
  281. def pytest_collection_modifyitems(
  282. session: Session, config: Config, items: List[Item]
  283. ) -> None:
  284. """
  285. Marks collected async test items as `asyncio` tests.
  286. The mark is only applied in `AUTO` mode. It is applied to:
  287. - coroutines
  288. - staticmethods wrapping coroutines
  289. - Hypothesis tests wrapping coroutines
  290. """
  291. if _get_asyncio_mode(config) != Mode.AUTO:
  292. return
  293. function_items = (item for item in items if isinstance(item, Function))
  294. for function_item in function_items:
  295. function = function_item.obj
  296. if isinstance(function, staticmethod):
  297. # staticmethods need to be unwrapped.
  298. function = function.__func__
  299. if (
  300. _is_coroutine(function)
  301. or _is_hypothesis_test(function)
  302. and _hypothesis_test_wraps_coroutine(function)
  303. ):
  304. function_item.add_marker("asyncio")
  305. def _hypothesis_test_wraps_coroutine(function: Any) -> bool:
  306. return _is_coroutine(function.hypothesis.inner_test)
  307. @pytest.hookimpl(hookwrapper=True)
  308. def pytest_fixture_setup(
  309. fixturedef: FixtureDef, request: SubRequest
  310. ) -> Optional[object]:
  311. """Adjust the event loop policy when an event loop is produced."""
  312. if fixturedef.argname == "event_loop":
  313. # The use of a fixture finalizer is preferred over the
  314. # pytest_fixture_post_finalizer hook. The fixture finalizer is invoked once
  315. # for each fixture, whereas the hook may be invoked multiple times for
  316. # any specific fixture.
  317. # see https://github.com/pytest-dev/pytest/issues/5848
  318. _add_finalizers(
  319. fixturedef,
  320. _close_event_loop,
  321. _provide_clean_event_loop,
  322. )
  323. outcome = yield
  324. loop = outcome.get_result()
  325. policy = asyncio.get_event_loop_policy()
  326. try:
  327. with warnings.catch_warnings():
  328. warnings.simplefilter("ignore", DeprecationWarning)
  329. old_loop = policy.get_event_loop()
  330. if old_loop is not loop:
  331. old_loop.close()
  332. except RuntimeError:
  333. # Either the current event loop has been set to None
  334. # or the loop policy doesn't specify to create new loops
  335. # or we're not in the main thread
  336. pass
  337. policy.set_event_loop(loop)
  338. return
  339. yield
  340. def _add_finalizers(fixturedef: FixtureDef, *finalizers: Callable[[], object]) -> None:
  341. """
  342. Regsiters the specified fixture finalizers in the fixture.
  343. Finalizers need to specified in the exact order in which they should be invoked.
  344. :param fixturedef: Fixture definition which finalizers should be added to
  345. :param finalizers: Finalizers to be added
  346. """
  347. for finalizer in reversed(finalizers):
  348. fixturedef.addfinalizer(finalizer)
  349. _UNCLOSED_EVENT_LOOP_WARNING = dedent(
  350. """\
  351. pytest-asyncio detected an unclosed event loop when tearing down the event_loop
  352. fixture: %r
  353. pytest-asyncio will close the event loop for you, but future versions of the
  354. library will no longer do so. In order to ensure compatibility with future
  355. versions, please make sure that:
  356. 1. Any custom "event_loop" fixture properly closes the loop after yielding it
  357. 2. The scopes of your custom "event_loop" fixtures do not overlap
  358. 3. Your code does not modify the event loop in async fixtures or tests
  359. """
  360. )
  361. def _close_event_loop() -> None:
  362. policy = asyncio.get_event_loop_policy()
  363. try:
  364. loop = policy.get_event_loop()
  365. except RuntimeError:
  366. loop = None
  367. if loop is not None:
  368. if not loop.is_closed():
  369. warnings.warn(
  370. _UNCLOSED_EVENT_LOOP_WARNING % loop,
  371. DeprecationWarning,
  372. )
  373. loop.close()
  374. def _provide_clean_event_loop() -> None:
  375. # At this point, the event loop for the current thread is closed.
  376. # When a user calls asyncio.get_event_loop(), they will get a closed loop.
  377. # In order to avoid this side effect from pytest-asyncio, we need to replace
  378. # the current loop with a fresh one.
  379. # Note that we cannot set the loop to None, because get_event_loop only creates
  380. # a new loop, when set_event_loop has not been called.
  381. policy = asyncio.get_event_loop_policy()
  382. new_loop = policy.new_event_loop()
  383. policy.set_event_loop(new_loop)
  384. @pytest.hookimpl(tryfirst=True, hookwrapper=True)
  385. def pytest_pyfunc_call(pyfuncitem: pytest.Function) -> Optional[object]:
  386. """
  387. Pytest hook called before a test case is run.
  388. Wraps marked tests in a synchronous function
  389. where the wrapped test coroutine is executed in an event loop.
  390. """
  391. marker = pyfuncitem.get_closest_marker("asyncio")
  392. if marker is not None:
  393. funcargs: Dict[str, object] = pyfuncitem.funcargs # type: ignore[name-defined]
  394. loop = cast(asyncio.AbstractEventLoop, funcargs["event_loop"])
  395. if _is_hypothesis_test(pyfuncitem.obj):
  396. pyfuncitem.obj.hypothesis.inner_test = wrap_in_sync(
  397. pyfuncitem,
  398. pyfuncitem.obj.hypothesis.inner_test,
  399. _loop=loop,
  400. )
  401. else:
  402. pyfuncitem.obj = wrap_in_sync(
  403. pyfuncitem,
  404. pyfuncitem.obj,
  405. _loop=loop,
  406. )
  407. yield
  408. def _is_hypothesis_test(function: Any) -> bool:
  409. return getattr(function, "is_hypothesis_test", False)
  410. def wrap_in_sync(
  411. pyfuncitem: pytest.Function,
  412. func: Callable[..., Awaitable[Any]],
  413. _loop: asyncio.AbstractEventLoop,
  414. ):
  415. """Return a sync wrapper around an async function executing it in the
  416. current event loop."""
  417. # if the function is already wrapped, we rewrap using the original one
  418. # not using __wrapped__ because the original function may already be
  419. # a wrapped one
  420. raw_func = getattr(func, "_raw_test_func", None)
  421. if raw_func is not None:
  422. func = raw_func
  423. @functools.wraps(func)
  424. def inner(*args, **kwargs):
  425. coro = func(*args, **kwargs)
  426. if not inspect.isawaitable(coro):
  427. pyfuncitem.warn(
  428. pytest.PytestWarning(
  429. f"The test {pyfuncitem} is marked with '@pytest.mark.asyncio' "
  430. "but it is not an async function. "
  431. "Please remove asyncio marker. "
  432. "If the test is not marked explicitly, "
  433. "check for global markers applied via 'pytestmark'."
  434. )
  435. )
  436. return
  437. task = asyncio.ensure_future(coro, loop=_loop)
  438. try:
  439. return _loop.run_until_complete(task)
  440. except BaseException:
  441. # run_until_complete doesn't get the result from exceptions
  442. # that are not subclasses of `Exception`. Consume all
  443. # exceptions to prevent asyncio's warning from logging.
  444. if task.done() and not task.cancelled():
  445. task.exception()
  446. raise
  447. inner._raw_test_func = func # type: ignore[attr-defined]
  448. return inner
  449. def pytest_runtest_setup(item: pytest.Item) -> None:
  450. marker = item.get_closest_marker("asyncio")
  451. if marker is None:
  452. return
  453. fixturenames = item.fixturenames # type: ignore[attr-defined]
  454. # inject an event loop fixture for all async tests
  455. if "event_loop" in fixturenames:
  456. fixturenames.remove("event_loop")
  457. fixturenames.insert(0, "event_loop")
  458. obj = getattr(item, "obj", None)
  459. if not getattr(obj, "hypothesis", False) and getattr(
  460. obj, "is_hypothesis_test", False
  461. ):
  462. pytest.fail(
  463. "test function `%r` is using Hypothesis, but pytest-asyncio "
  464. "only works with Hypothesis 3.64.0 or later." % item
  465. )
  466. @pytest.fixture
  467. def event_loop(request: FixtureRequest) -> Iterator[asyncio.AbstractEventLoop]:
  468. """Create an instance of the default event loop for each test case."""
  469. loop = asyncio.get_event_loop_policy().new_event_loop()
  470. yield loop
  471. loop.close()
  472. def _unused_port(socket_type: int) -> int:
  473. """Find an unused localhost port from 1024-65535 and return it."""
  474. with contextlib.closing(socket.socket(type=socket_type)) as sock:
  475. sock.bind(("127.0.0.1", 0))
  476. return sock.getsockname()[1]
  477. @pytest.fixture
  478. def unused_tcp_port() -> int:
  479. return _unused_port(socket.SOCK_STREAM)
  480. @pytest.fixture
  481. def unused_udp_port() -> int:
  482. return _unused_port(socket.SOCK_DGRAM)
  483. @pytest.fixture(scope="session")
  484. def unused_tcp_port_factory() -> Callable[[], int]:
  485. """A factory function, producing different unused TCP ports."""
  486. produced = set()
  487. def factory():
  488. """Return an unused port."""
  489. port = _unused_port(socket.SOCK_STREAM)
  490. while port in produced:
  491. port = _unused_port(socket.SOCK_STREAM)
  492. produced.add(port)
  493. return port
  494. return factory
  495. @pytest.fixture(scope="session")
  496. def unused_udp_port_factory() -> Callable[[], int]:
  497. """A factory function, producing different unused UDP ports."""
  498. produced = set()
  499. def factory():
  500. """Return an unused port."""
  501. port = _unused_port(socket.SOCK_DGRAM)
  502. while port in produced:
  503. port = _unused_port(socket.SOCK_DGRAM)
  504. produced.add(port)
  505. return port
  506. return factory