Debian Codegraph @

src/trio/testing/_trio_test.py

raw
1 from __future__ import annotations
2
3 from functools import partial, wraps
4 from typing import TYPE_CHECKING, TypeVar
5
6 from .. import _core
7 from ..abc import Clock, Instrument
8
9 if TYPE_CHECKING:
10 from collections.abc import Awaitable, Callable
11
12 from typing_extensions import ParamSpec
13
14 ArgsT = ParamSpec("ArgsT")
15
16
17 RetT = TypeVar("RetT")
18
19
20 def trio_test(fn: Callable[ArgsT, Awaitable[RetT]]) -> Callable[ArgsT, RetT]:
21 """Converts an async test function to be synchronous, running via Trio.
22
23 Usage::
24
25 @trio_test
26 async def test_whatever():
27 await ...
28
29 If a pytest fixture is passed in that subclasses the :class:`~trio.abc.Clock` or
30 :class:`~trio.abc.Instrument` ABCs, then those are passed to :meth:`trio.run()`.
31 """
32
33 @wraps(fn)
34 def wrapper(*args: ArgsT.args, **kwargs: ArgsT.kwargs) -> RetT:
35 __tracebackhide__ = True
36 clocks = [c for c in kwargs.values() if isinstance(c, Clock)]
37 if not clocks:
38 clock = None
39 elif len(clocks) == 1:
40 clock = clocks[0]
41 else:
42 raise ValueError("too many clocks spoil the broth!")
43 instruments = [i for i in kwargs.values() if isinstance(i, Instrument)]
44 return _core.run(
45 partial(fn, *args, **kwargs),
46 clock=clock,
47 instruments=instruments,
48 )
49
50 return wrapper