import pytest from datetime import datetime, timedelta, timezone from app.models import SleepSession from sqlmodel.ext.asyncio.session import AsyncSession from app.database import engine, get_session from sqlmodel import SQLModel @pytest.mark.asyncio async def test_summary_double_counting_midnight(api_client): # Setup: Fresh database for this test async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.drop_all) await conn.run_sync(SQLModel.metadata.create_all) # Use a fresh session for insertion async for db_session in get_session(): # 1. Setup: Insert a sleep session that spans across midnight start_time = datetime(2024, 1, 1, 23, 0) end_time = datetime(2024, 1, 2, 7, 0) new_session = SleepSession(start_time=start_time, end_time=end_time) db_session.add(new_session) await db_session.commit() break # Exit after one iteration # 2. Call the stats endpoint for a period that includes this session from_date = "2024-01-01T00:00:00" to_date = "2024-01-02T23:59:59" response = await api_client.get(f"/api/stats/summary?from_date={from_date}&to_date={to_date}") assert response.status_code == 200 data = response.json() # 3. Verify that total_sleeps is exactly 1 for the requested period print(f"DEBUG: data={data}") assert data["total_sleeps"] == 1, f"Expected 1 sleep session, got {data['total_sleeps']}" # 4. Verify that all-time stats also count this session exactly once assert data["total_sleeps_all_time"] == 1, f"Expected 1 all-time sleep session, got {data['total_sleeps_all_time']}"