import hashlib from fastapi.testclient import TestClient from sqlalchemy import select from pk_lab_server.db import SessionLocal from pk_lab_server.main import app from pk_lab_server.models import AuthSession def test_health_and_seeded_tests(): with TestClient(app) as client: assert client.get("/health").json() == {"status": "ok"} tests = client.get("/api/v1/tests").json() assert len(tests) == 7 rice = next(item for item in tests if item["slug"] == "rice") assert rice["candidate_count"] == 48 def test_login_complete_and_read_result(): with TestClient(app) as client: login = client.post( "/api/v1/auth/xhs", json={"app_key": "rice", "code": "dev:user-one"} ) assert login.status_code == 200 token = login.json()["token"] headers = {"Authorization": f"Bearer {token}"} with SessionLocal() as db: stored = db.scalar( select(AuthSession).where( AuthSession.token_hash == hashlib.sha256(token.encode()).hexdigest() ) ) assert stored is not None assert stored.token_hash != token assert client.get( "/api/v1/me/results", headers={"Authorization": "Bearer forged-token"} ).status_code == 401 detail = client.get("/api/v1/tests/rice").json() left, right = detail["candidates"][:2] created = client.post( "/api/v1/tests/rice/runs", headers=headers, json={ "app_key": "rice", "champion_id": left["id"], "runner_up_id": right["id"], "ranking_ids": [left["id"], right["id"]], "decisions": [ { "round": 1, "left_id": left["id"], "right_id": right["id"], "winner_id": left["id"], } ], }, ) assert created.status_code == 201, created.text assert created.json()["decisions"][0]["winner_id"] == left["id"] assert created.json()["candidate_names"][left["id"]] == "蛋炒饭" public = client.get("/api/v1/results/discover").json() assert public[0]["champion_name"] == "蛋炒饭" history = client.get("/api/v1/me/results?test_slug=rice", headers=headers).json() assert history[0]["champion_name"] == "蛋炒饭" assert client.post("/api/v1/auth/logout", headers=headers).status_code == 204 assert client.get("/api/v1/me/results", headers=headers).status_code == 401