1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
|
import asyncio
from collections.abc import AsyncIterator, Awaitable, Iterator
from contextlib import asynccontextmanager, contextmanager
from typing import Callable, Optional, TypeVar
import pytest
from advanced_alchemy.utils.sync_tools import (
CapacityLimiter,
async_,
await_,
ensure_async_,
run_,
with_ensure_async_,
)
T = TypeVar("T")
async def test_ensure_async_() -> None:
@ensure_async_
def sync_func(x: int) -> int:
return x * 2
@ensure_async_ # type: ignore[arg-type]
async def async_func(x: int) -> int:
return x * 2
assert await sync_func(21) == 42
assert await async_func(21) == 42
@pytest.mark.asyncio
async def test_with_ensure_async_() -> None:
@contextmanager
def sync_cm() -> Iterator[int]:
yield 42
@asynccontextmanager
async def async_cm() -> AsyncIterator[int]:
yield 42
async with with_ensure_async_(sync_cm()) as value:
assert value == 42
async with with_ensure_async_(async_cm()) as value:
assert value == 42
@pytest.mark.asyncio
async def test_capacity_limiter() -> None:
limiter = CapacityLimiter(1)
async with limiter:
assert limiter.total_tokens == 0
assert limiter.total_tokens == 1
def test_run_() -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = run_(async_func)
assert sync_func(21) == 42
def test_await_() -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = await_(async_func, raise_sync_error=False)
assert sync_func(21) == 42
async def test_async_() -> None:
def sync_func(x: int) -> int:
return x * 2
async_func = async_(sync_func)
assert await async_func(21) == 42
async def test_capacity_limiter_setter() -> None:
limiter = CapacityLimiter(2)
assert limiter.total_tokens == 2
limiter.total_tokens = 5
assert limiter.total_tokens == 5
async def test_capacity_limiter_release_without_acquire() -> None:
limiter = CapacityLimiter(1)
# Release without acquire should not raise, but will increase tokens beyond initial
limiter.release()
assert limiter.total_tokens == 2
async def test_run_with_running_loop(monkeypatch: pytest.MonkeyPatch) -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = run_(async_func)
# Simulate running loop
class DummyLoop:
def is_running(self) -> bool:
return True
monkeypatch.setattr("asyncio.get_running_loop", lambda: DummyLoop())
# The new implementation should handle running loops correctly using ThreadPoolExecutor
result = sync_func(1)
assert result == 2
def test_run_with_uvloop(monkeypatch: pytest.MonkeyPatch) -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = run_(async_func)
monkeypatch.setattr(
"advanced_alchemy.utils.sync_tools.uvloop", type("UVLoop", (), {"install": staticmethod(lambda: None)})()
)
monkeypatch.setattr("sys.platform", "linux")
# Should not raise
assert sync_func(2) == 4
def test_await_no_loop_raises() -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = await_(async_func, raise_sync_error=True)
# Remove running loop
orig = asyncio.get_running_loop
asyncio.get_running_loop = lambda: (_ for _ in ()).throw(RuntimeError())
try:
with pytest.raises(RuntimeError, match="await_ called without a running event loop and raise_sync_error=True"):
sync_func(1)
finally:
asyncio.get_running_loop = orig
def test_await_in_async_task(monkeypatch: pytest.MonkeyPatch) -> None:
from typing import Optional
async def async_func(x: int) -> int:
return x * 2
sync_func = await_(async_func, raise_sync_error=True)
class DummyLoop:
def __init__(self) -> None:
self.running = True
def is_running(self) -> bool:
return self.running
def _run_once(self) -> None:
# Simulate loop iteration
self.running = False
class DummyTask:
pass
class DummyFuture:
def __init__(self) -> None:
self._done = False
self._result = 4
def done(self) -> bool:
return self._done
def result(self) -> int:
self._done = True
return self._result
loop = DummyLoop()
monkeypatch.setattr("asyncio.get_running_loop", lambda: loop)
def dummy_current_task(loop: Optional[object] = None) -> DummyTask:
return DummyTask()
def dummy_ensure_future(coro: object, loop: object = None) -> DummyFuture:
return DummyFuture()
monkeypatch.setattr("asyncio.current_task", dummy_current_task)
monkeypatch.setattr("asyncio.ensure_future", dummy_ensure_future)
# The new implementation uses _run_once() workaround and should succeed
result = sync_func(1)
assert result == 4
def test_await_non_running_loop(monkeypatch: pytest.MonkeyPatch) -> None:
async def async_func(x: int) -> int:
return x * 2
sync_func = await_(async_func, raise_sync_error=True)
class DummyLoop:
def is_running(self) -> bool:
return False
monkeypatch.setattr("asyncio.get_running_loop", lambda: DummyLoop())
with pytest.raises(RuntimeError, match="await_ found a non-running loop via get_running_loop"):
sync_func(1)
def test_ensure_async_identity() -> None:
async def afunc(x: int) -> int:
return x
wrapped: Callable[[int], Awaitable[int]] = ensure_async_(afunc)
assert wrapped is afunc
def test_ensure_async_awaitable() -> None:
def sync_func(x: int) -> Awaitable[int]:
async def coro() -> int:
return x * 2
return coro()
wrapped: Callable[[int], Awaitable[int]] = ensure_async_(sync_func)
async def runner() -> int:
return await wrapped(21)
assert asyncio.run(runner()) == 42
def test_ensure_async_non_awaitable() -> None:
def sync_func(x: int) -> int:
return x * 2
wrapped = ensure_async_(sync_func)
async def runner() -> int:
return await wrapped(21)
assert asyncio.run(runner()) == 42
def test_context_manager_wrapper_exceptions() -> None:
from types import TracebackType
class DummyCM:
def __enter__(self) -> int:
raise ValueError("enter error")
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
raise ValueError("exit error")
wrapper = with_ensure_async_(DummyCM())
with pytest.raises(ValueError, match="enter error"):
asyncio.run(wrapper.__aenter__())
# __aexit__ should propagate exception
with pytest.raises(ValueError, match="exit error"):
asyncio.run(wrapper.__aexit__(None, None, None))
def test_with_ensure_async_identity() -> None:
from types import TracebackType
class DummyAsyncCM:
async def __aenter__(self) -> int:
return 42
async def __aexit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
return None
acm = DummyAsyncCM()
assert with_ensure_async_(acm) is acm
async def test_async_with_custom_limiter() -> None:
def sync_func(x: int) -> int:
return x * 2
limiter = CapacityLimiter(1)
async_func = async_(sync_func, limiter=limiter)
async def runner() -> int:
return await async_func(21)
assert await runner() == 42
|