async def test_has_capacity(): limiter = AsyncLimiter(1) assert limiter.has_capacity() assert not limiter.has_capacity(42) await limiter.acquire() assert not limiter.has_capacity()
async def test_acquire(event_loop, task): current_time = 0 def mocked_time(): return current_time # capacity released every 2 seconds limiter = AsyncLimiter(5, 10) with mock.patch.object(event_loop, "time", mocked_time): tasks = [asyncio.ensure_future(task(limiter)) for _ in range(10)] pending = await wait_for_n_done(tasks, 5) assert len(pending) == 5 current_time = 3 # releases capacity for one and some buffer assert limiter.has_capacity() pending = await wait_for_n_done(pending, 1) assert len(pending) == 4 current_time = 7 # releases capacity for two more, plus buffer pending = await wait_for_n_done(pending, 2) assert len(pending) == 2 current_time = 11 # releases the remainder pending = await wait_for_n_done(pending, 2) assert len(pending) == 0