|
| 1 | +import asyncio |
| 2 | +from datetime import datetime, UTC |
| 3 | +import pytest |
| 4 | + |
| 5 | +from bot.app.core.db import get_session |
| 6 | +from bot.app.domain import models |
| 7 | +from bot.app.domain.repository import add_booking |
| 8 | + |
| 9 | +pytestmark = pytest.mark.asyncio |
| 10 | + |
| 11 | +async def _prepare(): |
| 12 | + async with get_session() as s: |
| 13 | + s.add_all([ |
| 14 | + models.Service(id="svc_race", name="Race", price_cents=1000, currency="UAH"), |
| 15 | + models.Master(telegram_id=555001, name="MasterRace"), |
| 16 | + models.User(telegram_id=777001, name="ClientRace"), |
| 17 | + ]) |
| 18 | + await s.commit() |
| 19 | + master_id = (await s.execute(models.Master.__table__.select())).scalars().first() |
| 20 | + user_id = (await s.execute(models.User.__table__.select())).scalars().first() |
| 21 | + assert master_id is not None and user_id is not None |
| 22 | + return master_id, user_id |
| 23 | + |
| 24 | +async def _attempt(master_id: int, user_id: int): |
| 25 | + try: |
| 26 | + async with get_session() as s2: |
| 27 | + await add_booking( |
| 28 | + s2, |
| 29 | + service="svc_race", |
| 30 | + master_id=master_id, |
| 31 | + client_id=user_id, |
| 32 | + date_time=datetime.now(UTC).replace(microsecond=0), |
| 33 | + ) |
| 34 | + return True |
| 35 | + except Exception: |
| 36 | + return False |
| 37 | + |
| 38 | +async def _count_bookings(): |
| 39 | + async with get_session() as s: |
| 40 | + rows = (await s.execute(models.Booking.__table__.select())).all() |
| 41 | + return len(rows) |
| 42 | + |
| 43 | +async def test_booking_race_single_slot(): |
| 44 | + master_id, user_id = await _prepare() |
| 45 | + # run several concurrent attempts for same time slot |
| 46 | + results = await asyncio.gather(*[_attempt(master_id, user_id) for _ in range(6)]) |
| 47 | + total = await _count_bookings() |
| 48 | + # Current implementation is not locking; may allow >1. This test documents current behavior. |
| 49 | + # Hard assertion (future goal): total == 1 |
| 50 | + assert total >= 1 |
| 51 | + # Soft expectation: at least one succeeded |
| 52 | + assert any(results) |
0 commit comments