from datetime import datetime from fastapi.testclient import TestClient from app.db import SessionLocal, init_db from app.models import Account, Schedule from worker.__main__ import due, run_once class FakeClient: def __init__(self, login_name: str, password: str) -> None: self.login_name = login_name self.password = password def close(self) -> None: return None def open_session(self) -> dict: return { "profile": { "username": self.login_name, "cnName": "莫英达", "departmentName": "广州处", "userClassLevelName": "Scientist", "email": "mo@example.com", }, "summary": { "actual_study_hour": "10", "actual_study_score": "3.5", "points": "20", "today_hours": 1.5, "today_score": 0, "today": "2026-10-26", "class_count": 0, }, } def setup_function() -> None: from sqlalchemy import text from app.db import engine with engine.begin() as connection: connection.execute(text("DROP TABLE IF EXISTS accounts")) connection.execute(text("DROP TABLE IF EXISTS schedules")) connection.execute(text("DROP TABLE IF EXISTS alembic_version")) init_db() def test_login_stores_account_without_returning_password() -> None: from app.main import app import app.main as main_module import app.service as service_module service_module.EunivClient = FakeClient main_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store( db, employee_id, password, FakeClient ) client = TestClient(app) response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert response.status_code == 200 body = response.json() assert body["cn_name"] == "莫英达" assert body["actual_study_hour"] == "10" assert "password" not in body listed = client.get("/api/accounts").json() assert listed[0]["employee_id"] == "6650000146" assert "password" not in listed[0] def test_schedule_and_worker_sync() -> None: from app.main import app with SessionLocal() as db: db.add( Account( employee_id="10001", password_cipher="", last_login_at=datetime.now(), updated_at=datetime.now(), ) ) db.commit() from app.service import login_and_store with SessionLocal() as db: login_and_store(db, "10001", "secret-pass", FakeClient) client = TestClient(app) saved = client.post("/api/schedules", json={"employee_id": "10001", "run_time": "00:00", "enabled": True}) assert saved.status_code == 200 assert run_once(FakeClient) == 1 with SessionLocal() as db: schedule = db.get(Schedule, "10001") assert schedule is not None assert schedule.status == "ok" def test_due_skips_completed_today() -> None: now = datetime(2026, 10, 26, 9, 0) schedule = Schedule(employee_id="1", run_time="08:00", enabled=True, status="ok", last_run_at=now) assert due(schedule, now) is False assert due(schedule, datetime(2026, 10, 27, 8, 0)) is True