import asyncio
from main import fetch_limited
def counting_fetch():
"""A fake fetch that records how many calls are waiting at the same time."""
state = {"running": 0, "peak": 0}
async def fetch(name):
state["running"] += 1
state["peak"] = max(state["peak"], state["running"])
await asyncio.sleep(0.01)
state["running"] -= 1
return name.upper()
return fetch, state
def test_results_in_order():
"""Every name gives its text, in the order of names"""
fetch, _ = counting_fetch()
got = asyncio.run(fetch_limited(["home", "about", "blog"], fetch, 2))
assert got == ["HOME", "ABOUT", "BLOG"], f"fetch_limited returned {got!r}"
def test_limit_is_kept():
"""With limit 2, never more than 2 fetches run at once"""
fetch, state = counting_fetch()
asyncio.run(fetch_limited(["a", "b", "c", "d", "e"], fetch, 2))
assert state["peak"] == 2, f"{state['peak']} fetches ran at once, expected at most 2: hold one shared Semaphore around each fetch"
def test_limit_is_used():
"""With limit 3, three fetches do run at the same time"""
fetch, state = counting_fetch()
asyncio.run(fetch_limited(["a", "b", "c", "d", "e"], fetch, 3))
assert state["peak"] == 3, f"{state['peak']} fetches ran at once, expected 3: create the Semaphore once, not in every fetch"