|
| 1 | +import asyncio |
| 2 | +import functools |
| 3 | +import inspect |
| 4 | +import warnings |
| 5 | +from typing import Callable, ContextManager, ParamSpec, TypeVar |
| 6 | + |
| 7 | +from looptime import loops |
| 8 | + |
| 9 | +P = ParamSpec('P') |
| 10 | +R = TypeVar('R') |
| 11 | + |
| 12 | + |
| 13 | +class enabled(ContextManager[None]): |
| 14 | + """ |
| 15 | + Enable the looptime time compaction temporarily. |
| 16 | +
|
| 17 | + If used as a context manager, enables the time compaction for the wrapped |
| 18 | + code block only:: |
| 19 | +
|
| 20 | + import asyncio |
| 21 | + import looptime |
| 22 | +
|
| 23 | + async def main() -> None: |
| 24 | + with looptime.enabled(strict=True): |
| 25 | + await asyncio.sleep(10) |
| 26 | +
|
| 27 | + if __name__ == '__main__': |
| 28 | + asuncio.run(main()) |
| 29 | +
|
| 30 | + If used as a function/fixture decorator, enables the time compaction |
| 31 | + for the duration of the function/fixture:: |
| 32 | +
|
| 33 | + import asyncio |
| 34 | + import looptime |
| 35 | +
|
| 36 | + @looptime.enabled(strict=True) |
| 37 | + async def main() -> None: |
| 38 | + await asyncio.sleep(10) |
| 39 | +
|
| 40 | + if __name__ == '__main__': |
| 41 | + asuncio.run(main()) |
| 42 | +
|
| 43 | + In both cases, the event loop must be pre-patched (usually at creation). |
| 44 | + In strict mode, if the event loop is not patched, the call will fail. |
| 45 | + In non-strict mode (the default), it will issue a warning and continue |
| 46 | + with the real time flow (i.e. with no time compaction). |
| 47 | +
|
| 48 | + Use it, for example, for fixtures or finalizers of fixtures where the fast |
| 49 | + time flow is required despite fixtures are normally excluded from the time |
| 50 | + compaction magic (because it is impossible or difficult to infer which |
| 51 | + event loop is being used in the multi-scoped setup of pytest-asyncio), |
| 52 | + and because of the structure of pytest hooks for fixture finalizing |
| 53 | + (no finalizer hook, only the post-finalizer hook, when it is too late). |
| 54 | +
|
| 55 | + Beware of a caveat: if used as a decorator on a yield-based fixture, |
| 56 | + it will enable the looptime magic for the whole duration of the test, |
| 57 | + including all its fixtures (even undecorated ones), until the decorated |
| 58 | + fixture reaches its finalizer. This might have unexpected side effects. |
| 59 | + """ |
| 60 | + strict: bool |
| 61 | + _loop: asyncio.AbstractEventLoop | None |
| 62 | + _mgr: ContextManager[None] | None |
| 63 | + |
| 64 | + def __init__(self, *, strict: bool = False, loop: asyncio.AbstractEventLoop | None = None) -> None: |
| 65 | + super().__init__() |
| 66 | + self.strict = strict |
| 67 | + self._loop = loop |
| 68 | + self._mgr = None |
| 69 | + |
| 70 | + def __enter__(self) -> None: |
| 71 | + msg = "The running loop is not a looptime-patched loop, cannot enable it." |
| 72 | + loop = self._loop if self._loop is not None else asyncio.get_running_loop() |
| 73 | + if isinstance(loop, loops.LoopTimeEventLoop): |
| 74 | + self._mgr = loop.looptime_enabled() |
| 75 | + self._mgr.__enter__() |
| 76 | + elif self.strict: |
| 77 | + raise RuntimeError(msg) |
| 78 | + else: |
| 79 | + warnings.warn(msg, UserWarning) |
| 80 | + |
| 81 | + def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 82 | + if self._mgr is not None: |
| 83 | + self._mgr.__exit__(exc_type, exc_val, exc_tb) |
| 84 | + self._mgr = None |
| 85 | + |
| 86 | + def __call__(self, fn: Callable[P, R]) -> Callable[P, R]: |
| 87 | + if inspect.iscoroutinefunction(fn): |
| 88 | + @functools.wraps(fn) |
| 89 | + async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 90 | + nonlocal self |
| 91 | + with self: |
| 92 | + return await fn(*args, **kwargs) |
| 93 | + else: |
| 94 | + @functools.wraps(fn) |
| 95 | + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: |
| 96 | + nonlocal self |
| 97 | + with self: |
| 98 | + return fn(*args, **kwargs) |
| 99 | + |
| 100 | + return wrapper |
0 commit comments