import pytest from httpx import AsyncClient, ASGITransport from app.main import app from app.database import engine, init_db from app.models import SQLModel from datetime import datetime, timezone @pytest.fixture async def setup_db(): async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.drop_all) await conn.run_sync(SQLModel.metadata.create_all) @pytest.mark.asyncio async def test_create_session(setup_db): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: start_time = datetime.now(timezone.utc).isoformat() payload = {"start_time": start_time} response = await ac.post("/api/sessions", json=payload) assert response.status_code == 201 data = response.json() assert datetime.fromisoformat(data["start_time"]).replace( tzinfo=None ) == datetime.fromisoformat(start_time).replace(tzinfo=None) @pytest.mark.asyncio async def test_create_session_already_open(setup_db): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: start_time = datetime.now(timezone.utc).isoformat() await ac.post("/api/sessions", json={"start_time": start_time}) response = await ac.post("/api/sessions", json={"start_time": start_time}) assert response.status_code == 409 @pytest.mark.asyncio async def test_end_session(setup_db): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: start_time = datetime.now(timezone.utc).isoformat() await ac.post("/api/sessions", json={"start_time": start_time}) end_time = datetime.now(timezone.utc).isoformat() response = await ac.patch("/api/sessions/1/end", json={"end_time": end_time}) assert response.status_code == 200 assert datetime.fromisoformat(response.json()["end_time"]).replace( tzinfo=None ) == datetime.fromisoformat(end_time).replace(tzinfo=None) @pytest.mark.asyncio async def test_list_sessions(setup_db): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as ac: start_time = datetime.now(timezone.utc).isoformat() await ac.post("/api/sessions", json={"start_time": start_time}) response = await ac.get("/api/sessions") assert response.status_code == 200 assert len(response.json()["sessions"]) >= 1