import pytest from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from app.db.base import Base from app.db.models import Round from app.rounds.service import get_active_round, open_new_round_if_needed @pytest.fixture async def session_factory(): engine = create_async_engine("sqlite+aiosqlite:///:memory:") async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield async_sessionmaker(engine, expire_on_commit=False) await engine.dispose() async def test_opens_a_round_when_none_exists(session_factory): async with session_factory() as session: round_ = await open_new_round_if_needed(session) await session.commit() assert round_.status == "open" async def test_reuses_existing_open_round(session_factory): async with session_factory() as session: first = await open_new_round_if_needed(session) await session.commit() first_id = first.id async with session_factory() as session: second = await open_new_round_if_needed(session) assert second.id == first_id @pytest.mark.parametrize("status", ["closing", "drawing", "paying_out"]) async def test_does_not_open_new_round_while_previous_is_in_progress(session_factory, status): async with session_factory() as session: session.add(Round(status=status)) await session.commit() async with session_factory() as session: active = await get_active_round(session) assert active is not None assert active.status == status # open_new_round_if_needed must return the in-progress round, not open a new one returned = await open_new_round_if_needed(session) assert returned.status == status async def test_opens_new_round_after_previous_is_closed(session_factory): async with session_factory() as session: session.add(Round(status="closed")) await session.commit() async with session_factory() as session: round_ = await open_new_round_if_needed(session) assert round_.status == "open"