Coverage for tests/tools.py: 93%
23 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import asyncio
2import inspect
3from collections.abc import Awaitable, Callable
4from functools import wraps
5from typing import Any, Protocol, TypeVar, cast
6from unittest.mock import AsyncMock
8import pytest
9from typing_extensions import ParamSpec
11P = ParamSpec("P")
12T = TypeVar("T")
13T_co = TypeVar("T_co", covariant=True)
16class SmartMock(Protocol[P, T_co]):
17 mock: AsyncMock
19 def __call__(self, *args: P.args, **kwds: P.kwargs) -> T_co: ...
22def spy_decorator(
23 method: Callable[P, T],
24 event: asyncio.Event | None = None,
25) -> SmartMock[P, T]:
26 mock = AsyncMock()
28 @wraps(method)
29 async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Any:
30 await mock(*args, **kwargs)
31 if event is not None:
32 event.set()
33 return await cast("Callable[P, Awaitable[Any]]", method)(*args, **kwargs)
35 @wraps(method)
36 def sync_wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
37 with pytest.warns(
38 RuntimeWarning,
39 match="coroutine 'AsyncMockMixin._execute_mock_call' was never awaited",
40 ):
41 mock(*args, **kwargs)
42 if event is not None: 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true
43 event.set()
44 return method(*args, **kwargs)
46 wrapper = cast(
47 "SmartMock[P, T]",
48 async_wrapper if inspect.iscoroutinefunction(method) else sync_wrapper,
49 )
50 wrapper.mock = mock
51 return wrapper