import asyncio from fastapi.testclient import TestClient from euniv.autostudy import AutoStudyWorker, is_wanted from euniv.crypto import encrypt_secret from euniv.db import SessionLocal, engine from euniv.models import Account, Course from euniv.study_window import month_key def test_schema_matches_models() -> None: from alembic.autogenerate import compare_metadata from alembic.migration import MigrationContext import admin.models # noqa: F401 from euniv.models import Base with engine.connect() as connection: context = MigrationContext.configure( connection, opts={"compare_server_default": True, "render_as_batch": True}, ) diff = compare_metadata(context, Base.metadata) assert diff == [] def test_process_starts_and_health_reads_database() -> None: from euniv.api import app with TestClient(app) as client: response = client.get("/api/health") assert response.status_code == 200 body = response.json() assert body == {"ok": True, "database": True, "study": False} def test_tick_does_not_relaunch_and_stops_when_hours_met() -> None: launched: list[str] = [] async def hang(self, job, _course_list, _generation) -> None: launched.append(job[0]) await asyncio.Event().wait() with SessionLocal() as db: db.add( Account( employee_id="u-tick", password_cipher=encrypt_secret("pw"), credential_cipher=encrypt_secret('{"token":"x"}'), credential_valid=True, monthly_target=60, month_hours="0", hours_month=month_key(), study_ignore_window=True, study_schedule_enabled=True, ) ) db.add(Course(path="/kng/view/video/tick.html", title="定时课", kind="视频")) db.commit() async def main() -> None: worker = AutoStudyWorker() worker._loop = asyncio.get_running_loop() worker._run_account = hang.__get__(worker, AutoStudyWorker) worker._tick() await asyncio.sleep(0) first = worker._tasks["u-tick"] assert launched == ["u-tick"] assert is_wanted("u-tick") worker._tick() await asyncio.sleep(0) assert worker._tasks["u-tick"] is first assert launched == ["u-tick"] with SessionLocal() as db: row = db.get(Account, "u-tick") assert row is not None row.month_hours = "60" row.hours_month = month_key() db.commit() worker._tick() assert "u-tick" not in launched[1:] assert launched == ["u-tick"] assert not is_wanted("u-tick") assert worker._tasks["u-tick"] is first first.cancel() await asyncio.gather(first, return_exceptions=True) asyncio.run(main())