import json from datetime import datetime import pytest from fastapi.testclient import TestClient from euniv.client import JigsawRejected, ManualJigsaw from euniv.crypto import decrypt_secret from euniv.db import SessionLocal from euniv.models import Account class FakeClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: self.login_name = login_name self.password = password self.proxy = proxy self._token = "yxt-1" self._profile = { "token": "ucs-1", "accountId": login_name, "userId": "u1", "ssoinfo": "sso", "unionId": "", } def close(self) -> None: return None def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: if manual: raise ManualJigsaw({ "big_img": "data:image/png;base64,YQ==", "small_img": "data:image/png;base64,Yg==", "y": 56, "width": 280, "height": 172, "piece_width": 48, "piece_height": 48, }) return dict(self._profile) def credential_alive(self) -> bool: return True def authorize(self, profile: dict) -> None: self._profile = dict(profile) def export_credential(self) -> dict: return { "ucs_token": self._profile["token"], "ucs_account_id": self._profile["accountId"], "ucs_user_id": self._profile["userId"], "ucs_ssoinfo": self._profile["ssoinfo"], "ucs_union_id": self._profile["unionId"], "yxt_token": self._token, } def restore(self, credential: dict) -> None: self._token = credential["yxt_token"] self._profile = { "token": credential["ucs_token"], "accountId": credential["ucs_account_id"], "userId": credential["ucs_user_id"], "ssoinfo": credential["ucs_ssoinfo"], "unionId": credential["ucs_union_id"], } def study_history(self) -> list[dict]: return [ { "title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)", "minutes": 2, "studied_at": "2026-11-14 23:55", "path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html", } ] def home_summary(self) -> dict: return { "name": "测试用户", "avatar": "https://example.test/a.jpg", "department": "测试部门", "level": "Scientist", "year_hours": "100", "month_hours": "60", "today_hours": 1, "total_hours": "10", "total_score": "3.00", "points": 20, } def home_snapshot(self) -> dict: if self._token == "yxt-1": self._token = "yxt-2" return { "name": "测试用户", "avatar": "https://example.test/a.jpg", "department": "测试部门", "level": "Scientist", "year_hours": "100", "month_hours": "60", "today_hours": 1, "total_hours": "10", "total_score": "3.00", "points": 20, "exams": [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}], "trainings": [], } def test_login_stores_password_and_credential_only(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module class RefreshingClient(FakeClient): def home_summary(self) -> dict: if self._token == "yxt-1": self._token = "yxt-2" return super().home_summary() monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) monkeypatch.setattr( api_module, "fetch_home_summary", lambda db, employee_id: service_module.fetch_home_summary(db, employee_id, RefreshingClient), ) client = TestClient(api_module.app) response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert response.status_code == 200 assert response.json() == {"role": "user", "employee_id": "6650000146"} with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert decrypt_secret(account.password_cipher) == "secret-pass" stored = json.loads(decrypt_secret(account.credential_cipher)) assert stored["yxt_token"] == "yxt-1" assert stored["ucs_token"] == "ucs-1" assert set(account.__table__.columns.keys()) == { "employee_id", "password_cipher", "credential_cipher", "refresh_paused", "last_refresh_at", "credential_valid", "month_hours", "user_name", "company", "hours_month", "monthly_target", "proxy_scheme", "proxy_host", "proxy_port", "proxy_username", "proxy_password_cipher", "study_start_day", "study_start_hour", "study_start_minute", "study_start_second", "course_workers", "use_proxy_pool", "study_paused", "study_stop_month", "study_ignore_window", "study_opened_at", "study_schedule_enabled", "heartbeat_mode", "heartbeat_video_seconds", "heartbeat_document_seconds", "heartbeat_scorm_seconds", "sessions_valid_after", "password_login_at", } summary = client.get("/api/home/summary") assert summary.status_code == 200 assert summary.json()["name"] == "测试用户" with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None updated = json.loads(decrypt_secret(account.credential_cipher)) assert updated["yxt_token"] == "yxt-2" assert "测试用户" not in decrypt_secret(account.credential_cipher) assert "测试用户" not in decrypt_secret(account.password_cipher) assert account.user_name == "测试用户" assert account.company == "测试部门" from euniv.service import _remember_profile _remember_profile(db, "6650000146", {"name": " ", "department": "", "level": "Scientist"}) db.refresh(account) assert account.user_name == "测试用户" assert account.company == "测试部门" _remember_profile(db, "6650000146", {"name": "新名字", "department": "广州瀚信广州处", "level": "Scientist"}) db.refresh(account) assert account.user_name == "新名字" assert account.company == "广州瀚信广州处" def test_qr_mark_cannot_password_login_and_unicode_password_is_safe(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module from euniv.client import QR_PASSWORD_MARK from euniv.crypto import encrypt_secret monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) with SessionLocal() as db: db.add( Account( employee_id="7001", password_cipher=encrypt_secret(QR_PASSWORD_MARK), credential_cipher=encrypt_secret(json.dumps({"yxt_token": "yxt-1"})), ) ) db.commit() stolen = client.post("/api/login", json={"employee_id": "7001", "password": QR_PASSWORD_MARK}) assert stolen.status_code == 400 assert stolen.json()["detail"] == "请使用扫码登录" first = client.post("/api/login", json={"employee_id": "7002", "password": "密码一"}) assert first.status_code == 200 second = client.post("/api/login", json={"employee_id": "7002", "password": "密码一"}) assert second.status_code == 200 def test_manual_jigsaw_keeps_image_pixels_and_retries(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module service_module._pending.clear() class ManualClient: def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None: self.login_name = login_name self.password = password self._profile = { "token": "ucs-1", "accountId": login_name, "userId": "u1", "ssoinfo": "sso", "unionId": "", } def close(self) -> None: return None def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: raise ManualJigsaw({ "big_img": "data:image/png;base64,YQ==", "small_img": "data:image/png;base64,Yg==", "y": 56, "width": 280, "height": 172, "piece_width": 48, "piece_height": 48, }) def next_jigsaw(self) -> dict: return { "big_img": "data:image/png;base64,Yw==", "small_img": "data:image/png;base64,ZA==", "y": 60, "width": 280, "height": 172, "piece_width": 48, "piece_height": 48, } def submit_jigsaw(self, offset: int) -> dict: if offset != 157: raise JigsawRejected("拼图未通过") return dict(self._profile) def authorize(self, profile: dict) -> None: self._profile = dict(profile) def export_credential(self) -> dict: return { "ucs_token": "ucs-1", "ucs_account_id": self.login_name, "ucs_user_id": "u1", "ucs_ssoinfo": "sso", "ucs_union_id": "", "yxt_token": "yxt-manual", } monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, ManualClient, manual=manual, auto_attempts=auto_attempts ), ) monkeypatch.setattr(api_module, "submit_jigsaw", service_module.submit_jigsaw) client = TestClient(api_module.app) started = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert started.status_code == 200 body = started.json() assert body["jigsaw"]["width"] == 280 assert body["jigsaw"]["height"] == 172 assert body["jigsaw"]["y"] == 56 assert "password" not in body["jigsaw"] with SessionLocal() as db: assert db.get(Account, "6650000146") is None missed = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 10}) assert missed.status_code == 200 assert missed.json()["jigsaw"]["y"] == 60 done = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 157}) assert done.status_code == 200 assert done.json() == {"role": "user", "employee_id": "6650000146"} with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert decrypt_secret(account.password_cipher) == "secret-pass" def test_browser_session_logout_and_revoke(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module calls = {"login": 0} class RememberClient(FakeClient): def login(self, manual: bool = False, auto_attempts: int = 3) -> dict: calls["login"] += 1 return super().login(manual=manual, auto_attempts=auto_attempts) monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, RememberClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) first = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert first.status_code == 200 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None before = decrypt_secret(account.credential_cipher) second = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert second.json() == {"role": "user", "employee_id": "6650000146"} assert calls["login"] == 1 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert decrypt_secret(account.credential_cipher) == before assert client.get("/api/session").json() == {"role": "user", "employee_id": "6650000146"} assert client.post("/api/logout").status_code == 200 assert client.get("/api/session").status_code == 401 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert account.credential_cipher account.study_schedule_enabled = True db.commit() with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert account.study_schedule_enabled is True again = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert again.status_code == 200 assert calls["login"] == 1 from euniv.autostudy import _wanted from euniv.models import FinishedCourse _wanted["6650000146"] = object() with SessionLocal() as db: db.add(FinishedCourse(employee_id="6650000146", knowledge_id="course-1")) db.commit() assert client.post("/api/revoke").status_code == 200 assert client.get("/api/session").status_code == 401 assert "6650000146" not in _wanted with SessionLocal() as db: from sqlalchemy import select account = db.get(Account, "6650000146") assert account is None left = db.scalars(select(FinishedCourse).where(FinishedCourse.employee_id == "6650000146")).all() assert left == [] def test_logout_keeps_the_other_browser_until_revoke(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) first = TestClient(api_module.app) assert first.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 saved = first.cookies.get("euniv_session") assert saved other = TestClient(api_module.app) other.cookies.set("euniv_session", saved) assert first.post("/api/logout").status_code == 200 assert first.get("/api/session").status_code == 401 assert other.get("/api/session").status_code == 200 assert other.post("/api/revoke").status_code == 200 stale = TestClient(api_module.app) stale.cookies.set("euniv_session", saved) assert stale.get("/api/session").status_code == 401 def test_parse_training_cards_keeps_status() -> None: from euniv.client import parse_training_cards html = """
  • 租赁人员数据保护合规培训-2026
    Jiang Mingjun 194 天 1
  • """ rows = parse_training_cards(html, "已完成") assert rows == [{ "name": "租赁人员数据保护合规培训-2026", "status": "已完成", "progress": 100, "owner": "Jiang Mingjun", "assigned": "194 天", "credits": "1", "detail": "/plan/1de517c30125424e97840b5cd6f28709.html", "sort_days": 194.0, }] def test_lists_put_the_nearest_time_first() -> None: from euniv.client import _by_closeness, parse_exam_cards html = """
  • 较远的考试 :2020-01-01 00:00:00 
  • 较近的考试 :2026-10-20 00:01:00 
  • """ rows = _by_closeness(parse_exam_cards(html), "sort_at") assert [item["name"] for item in rows] == ["较近的考试", "较远的考试"] assert rows[0]["status"] == "已过期" assert "sort_at" not in rows[0] trainings = _by_closeness( [ {"name": "很久以前", "sort_days": 741.0}, {"name": "刚指派", "sort_days": 5.0}, ], "sort_days", ) assert [item["name"] for item in trainings] == ["刚指派", "很久以前"] assert rows[0]["result"] == "未通过" assert rows[1]["result"] == "未通过" def test_exam_and_training_details() -> None: from euniv.client import parse_exam_cards, parse_exam_detail, parse_training_detail cards = parse_exam_cards("""
  • 规范考试 :2026-05-20 00:01:00 
  • """) assert cards[0]["result"] == "已通过" assert cards[0]["detail"] == "/exam/exampreview.htm?examID=abc&examArrangeID=def" detail = parse_exam_detail(""" 规范考试 100 90 45 2026-05-20 00:01~2026-05-25 23:59 2/3 次 30分钟 莫英达 不允许查看答卷详情 考试安排已结束
    时间成绩结果
    2026-05-22 16:19:4994通过
    2026-05-22 16:02:1389未通过
    """) assert detail["pass_score"] == "90" assert detail["attempts"] == [ {"submitted": "2026-05-22 16:19:49", "score": "94", "result": "通过"}, {"submitted": "2026-05-22 16:02:13", "score": "89", "result": "未通过"}, ] training = parse_training_detail("""
    安全规范
    - 123 123 0 0 0 0
    100%
    :2026-11-25
    1规范学习 :123 :12.3
    1.1分享.mp4 0 / 5.2 :52 / 52 100%
    """) assert training["rank"] == "2846" assert training["deadline"] == "2026-11-25" assert training["phases"][0]["tasks"][0] == { "name": "1.1分享.mp4", "progress": "100%", "score": "0/5.2", "hours": "52/52", } def test_home_sections_are_separate(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) monkeypatch.setattr(api_module, "fetch_home_summary", lambda db, employee_id: {"name": "分段"}) monkeypatch.setattr(api_module, "fetch_home_exams", lambda db, employee_id: {"exams": [{"name": "一门考试"}]}) monkeypatch.setattr(api_module, "fetch_home_trainings", lambda db, employee_id: {"trainings": [{"name": "一门培训"}]}) client = TestClient(api_module.app) response = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert response.status_code == 200 assert client.get("/api/home/summary").json()["name"] == "分段" assert client.get("/api/home/exams").json()["exams"] == [{"name": "一门考试"}] assert client.get("/api/home/trainings").json()["trainings"] == [{"name": "一门培训"}] def test_period_page_is_not_fetched_twice() -> None: from euniv.client import EunivClient client = EunivClient.__new__(EunivClient) client._profile = {"token": "t", "accountId": "a"} client._site_ready = False calls: list[str] = [] class Response: text = '' class HTTP: def get(self, url: str, headers=None): calls.append(url) return Response() client.client = HTTP() assert client._period_minutes() == {"year": "34", "month": "12"} assert len(calls) == 1 def test_user_can_set_proxy_with_or_without_password(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 empty = client.get("/api/settings/proxy") assert empty.status_code == 200 assert empty.json()["enabled"] is False assert empty.json()["scheme"] == "off" assert "password" not in empty.json() saved = client.put( "/api/settings/proxy", json={"scheme": "http", "host": "1.1.1.1", "port": 8080, "username": "", "password": ""}, ) assert saved.status_code == 200 assert saved.json() == { "enabled": True, "scheme": "http", "host": "1.1.1.1", "port": 8080, "username": "", "has_password": False, } with_auth = client.put( "/api/settings/proxy", json={"scheme": "socks5", "host": "8.8.8.8", "port": 1080, "username": "u", "password": "p@ss"}, ) assert with_auth.status_code == 200 assert with_auth.json()["has_password"] is True assert "password" not in with_auth.json() kept = client.put( "/api/settings/proxy", json={"scheme": "socks5", "host": "8.8.8.8", "port": 1080, "username": "u", "password": None}, ) assert kept.status_code == 200 assert kept.json()["has_password"] is True with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert decrypt_secret(account.proxy_password_cipher) == "p@ss" cleared = client.put("/api/settings/proxy", json={"scheme": "off"}) assert cleared.status_code == 200 assert cleared.json()["enabled"] is False assert cleared.json()["scheme"] == "off" def test_user_can_set_course_workers(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 empty = client.get("/api/settings/course-workers") assert empty.status_code == 200 assert empty.json() == {"workers": 1, "max": 8, "recommended": True} saved = client.put("/api/settings/course-workers", json={"workers": 3}) assert saved.status_code == 200 assert saved.json() == {"workers": 3, "max": 8, "recommended": False} bad = client.put("/api/settings/course-workers", json={"workers": 9}) assert bad.status_code == 400 def _study_body(**extra: object) -> dict: body = { "monthly_target": 600, "day": 8, "hour": 0, "minute": 0, "second": 0, "enabled": True, "workers": 1, } body.update(extra) return body def test_heartbeat_interval_belongs_to_the_user(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module from euniv.autostudy import _current_intervals monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 initial = client.get("/api/settings/heartbeat") assert initial.status_code == 200 assert initial.json()["heartbeat_mode"] == "auto" assert initial.json()["heartbeat_video_seconds"] == 30 kept = client.put("/api/settings/study", json=_study_body()) assert kept.status_code == 200 assert kept.json()["heartbeat_mode"] == "auto" manual = client.put("/api/settings/study", json=_study_body( heartbeat_mode="manual", heartbeat_video_seconds=1, heartbeat_document_seconds=2, heartbeat_scorm_seconds=3, )) assert manual.status_code == 200 assert manual.json()["heartbeat_video_seconds"] == 1 assert manual.json()["heartbeat_document_seconds"] == 2 assert manual.json()["heartbeat_scorm_seconds"] == 3 omitted = client.put("/api/settings/study", json=_study_body(workers=2)) assert omitted.status_code == 200 assert omitted.json()["workers"] == 2 assert omitted.json()["heartbeat_mode"] == "manual" assert omitted.json()["heartbeat_video_seconds"] == 1 current = client.get("/api/settings/heartbeat") assert current.json()["heartbeat_mode"] == "manual" from euniv.autostudy import _pace_of assert _pace_of("6650000146") == ({"video": 1, "document": 2, "scorm": 3}, False) intervals, auto = _current_intervals("6650000146") assert auto is False assert intervals == {"video": 1, "document": 2, "scorm": 3} fallback, fallback_auto = _current_intervals("nobody") assert fallback_auto is True assert fallback == {"video": 30, "document": 120, "scorm": 120} rejected = client.put("/api/settings/study", json=_study_body(heartbeat_mode="fast")) assert rejected.status_code == 400 too_fast = client.put("/api/settings/study", json=_study_body(heartbeat_video_seconds=301)) assert too_fast.status_code == 400 assert too_fast.json()["detail"] == "视频心跳间隔须为 0 到 300 的整数" def test_user_can_set_monthly_study_start(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 empty = client.get("/api/settings/study-start") assert empty.status_code == 200 assert empty.json() == { "day": 8, "hour": 0, "minute": 0, "second": 0, "enabled": False, "label": "每月8日 00:00:00", } saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7, "enabled": False}) assert saved.status_code == 200 assert saved.json()["label"] == "每月5日 16:00:07" assert saved.json()["enabled"] is False again = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7, "enabled": True}) assert again.json()["enabled"] is True bad = client.put("/api/settings/study-start", json={"day": 4, "hour": 16, "minute": 0, "second": 0}) assert bad.status_code == 400 too_late = client.put("/api/settings/study-start", json={"day": 26, "hour": 16, "minute": 0, "second": 0}) assert too_late.status_code == 400 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None account.study_start_day = 1 db.commit() kept = client.put("/api/settings/study-start", json={"day": 1, "hour": 7, "minute": 0, "second": 0, "enabled": True}) assert kept.status_code == 200 assert kept.json()["label"] == "每月1日 07:00:00" changed = client.put("/api/settings/study-start", json={"day": 2, "hour": 7, "minute": 0, "second": 0}) assert changed.status_code == 400 def _freeze_beijing(monkeypatch, year: int, month: int, day: int) -> None: from euniv.study_window import CN_TZ, as_cn moment = datetime(year, month, day, 12, 0, tzinfo=CN_TZ) def frozen(now=None): if now is not None: return as_cn(now) return moment monkeypatch.setattr("euniv.study_window.as_cn", frozen) def test_new_account_does_not_study_until_the_user_asks(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module from euniv.autostudy import work_running monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) _freeze_beijing(monkeypatch, 2026, 11, 15) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 first = client.get("/api/settings/study-control").json() assert first["window_open"] is True assert first["schedule_enabled"] is False assert first["started"] is False assert first["active"] is False assert work_running("6650000146") is False client.put("/api/settings/study-start", json={"day": 8, "hour": 0, "minute": 0, "second": 0, "enabled": True}) assert work_running("6650000146") is True assert client.get("/api/settings/study-control").json()["started"] is True def test_user_can_start_and_stop_study_immediately(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) _freeze_beijing(monkeypatch, 2026, 11, 15) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 client.put("/api/settings/study-start", json={"day": 25, "hour": 23, "minute": 59, "second": 59}) idle = client.get("/api/settings/study-control") assert idle.status_code == 200 assert idle.json()["workers"] == [] assert idle.json()["hours_met"] is False started = client.post("/api/settings/study-control", json={"action": "start"}) assert started.status_code == 200 assert started.json()["started"] is True assert started.json()["ignore_window"] is True assert started.json()["paused"] is False assert started.json()["hours_met"] is False assert started.json()["workers"] == [] stopped = client.post("/api/settings/study-control", json={"action": "stop"}) assert stopped.status_code == 200 assert stopped.json()["started"] is False assert stopped.json()["paused"] is True assert stopped.json()["ignore_window"] is False bad = client.post("/api/settings/study-control", json={"action": "pause"}) assert bad.status_code == 400 def test_start_saves_the_settings_sent_with_it(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module from euniv.autostudy import work_running monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) _freeze_beijing(monkeypatch, 2026, 11, 15) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 settings = _study_body( monthly_target=900, day=20, hour=6, minute=30, second=5, enabled=False, workers=3, heartbeat_mode="manual", heartbeat_video_seconds=0, heartbeat_document_seconds=7, heartbeat_scorm_seconds=9, ) started = client.post("/api/settings/study-control", json={"action": "start", "settings": settings}) assert started.status_code == 200 assert started.json()["started"] is True assert started.json()["monthly_target"] == 900 assert work_running("6650000146") is True with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert account.monthly_target == 900 assert (account.study_start_day, account.study_start_hour) == (20, 6) assert (account.study_start_minute, account.study_start_second) == (30, 5) assert account.study_schedule_enabled is False assert account.course_workers == 3 assert account.heartbeat_mode == "manual" assert account.heartbeat_video_seconds == 0 assert account.heartbeat_document_seconds == 7 assert account.heartbeat_scorm_seconds == 9 client.post("/api/settings/study-control", json={"action": "stop"}) rejected = client.post( "/api/settings/study-control", json={"action": "start", "settings": _study_body(monthly_target=0, workers=5)}, ) assert rejected.status_code == 400 assert rejected.json()["detail"] == "每月目标为 0,不会学习" bad = client.post( "/api/settings/study-control", json={"action": "start", "settings": _study_body(workers=9)}, ) assert bad.status_code == 400 assert bad.json()["detail"] == "同时学习课程数须为 1 到 8" with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert account.monthly_target == 900 assert account.course_workers == 3 assert work_running("6650000146") is False def test_study_state_is_served_from_memory_until_the_account_changes(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module import euniv.study_control as control monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 loads: list[str] = [] original = control.load_state def counted(employee_id: str) -> dict: loads.append(employee_id) return original(employee_id) monkeypatch.setattr(control, "load_state", counted) control.forget("6650000146") first = control.state_for("6650000146") assert loads == ["6650000146"] assert first["monthly_target"] == 600 for _ in range(5): assert control.state_for("6650000146") == first assert loads == ["6650000146"] held = control._snaps["6650000146"][1] for secret in ("password_cipher", "credential_cipher", "proxy_password_cipher"): assert not hasattr(held, secret) with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None account.monthly_target = 100 db.flush() db.rollback() assert control.state_for("6650000146")["monthly_target"] == 600 assert loads == ["6650000146"] saved = client.put("/api/settings/study", json=_study_body(monthly_target=900)) assert saved.status_code == 200 changed = control.state_for("6650000146") assert changed["monthly_target"] == 900 assert loads == ["6650000146", "6650000146"] assert client.get("/api/settings/study-control").json()["monthly_target"] == 900 assert loads == ["6650000146", "6650000146"] def test_changing_the_course_count_restarts_a_running_study(monkeypatch) -> None: import euniv.api as api_module import euniv.autostudy as autostudy_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) restarted: list[str] = [] original = autostudy_module.restart_work def record(employee_id: str) -> None: restarted.append(employee_id) original(employee_id) monkeypatch.setattr(autostudy_module, "restart_work", record) client = TestClient(api_module.app) _freeze_beijing(monkeypatch, 2026, 11, 15) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 started = client.post("/api/settings/study-control", json={"action": "start", "settings": _study_body(workers=2)}) assert started.status_code == 200 assert client.put("/api/settings/study", json=_study_body(workers=2, monthly_target=700)).status_code == 200 assert restarted == [] assert client.put("/api/settings/study", json=_study_body(workers=3, monthly_target=700)).status_code == 200 assert restarted == ["6650000146"] assert autostudy_module.work_running("6650000146") is True def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None account.monthly_target = 70 account.month_hours = "78" db.commit() started = client.post("/api/settings/study-control", json={"action": "start"}) assert started.status_code == 200 assert started.json()["hours_met"] is True assert started.json()["started"] is False assert started.json()["paused"] is False def test_study_control_websocket_sends_snapshot(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module from starlette.websockets import WebSocketDisconnect monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) client = TestClient(api_module.app) _freeze_beijing(monkeypatch, 2026, 11, 15) with pytest.raises(WebSocketDisconnect) as closed: with client.websocket_connect("/api/settings/study-control/ws") as ws: ws.receive_json() assert closed.value.code == 4401 assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 client.put("/api/settings/study-start", json={"day": 25, "hour": 23, "minute": 59, "second": 59}) with client.websocket_connect("/api/settings/study-control/ws") as ws: data = ws.receive_json() assert data["started"] is False assert data["hours_met"] is False assert data["window_open"] is False assert data["workers"] == [] assert "month_hours" in data ws.send_text("ping") pong = ws.receive_json() assert pong["paused"] is False assert pong["started"] is False def test_user_can_read_study_history(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) monkeypatch.setattr( api_module, "fetch_study_history", lambda db, employee_id: service_module.fetch_study_history(db, employee_id, FakeClient), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 history = client.get("/api/home/history") assert history.status_code == 200 body = history.json() assert body["total"] == 1 assert body["items"][0]["title"].startswith("ZXCTN") assert body["items"][0]["minutes"] == 2 assert body["hours_source"] == "api" assert body["month_hours"] == "60" with SessionLocal() as db: account = db.get(Account, "6650000146") assert account is not None assert account.month_hours == "60" assert body["year_hours"] == "100" assert body["today_hours"] == 1 assert body["total_hours"] == "10" def _set_hours_source(value: str) -> None: from admin.settings import load_config with SessionLocal() as db: row = load_config(db) row.hours_source = value db.commit() def test_home_and_history_hours_follow_source(monkeypatch) -> None: import euniv.api as api_module import euniv.service as service_module monkeypatch.setattr( api_module, "login_and_store", lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store( db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts ), ) monkeypatch.setattr( api_module, "fetch_home_summary", lambda db, employee_id: service_module.fetch_home_summary(db, employee_id, FakeClient), ) monkeypatch.setattr( api_module, "fetch_study_history", lambda db, employee_id: service_module.fetch_study_history(db, employee_id, FakeClient), ) from euniv.client import history_hour_totals from euniv.study_window import CN_TZ frozen = datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ) monkeypatch.setattr( "euniv.service.history_hour_totals", lambda items, now=None: history_hour_totals(items, frozen), ) client = TestClient(api_module.app) assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200 home = client.get("/api/home/summary") history = client.get("/api/home/history") assert home.status_code == 200 assert history.status_code == 200 assert home.json()["month_hours"] == history.json()["month_hours"] == "60" assert home.json()["year_hours"] == history.json()["year_hours"] == "100" assert home.json()["hours_source"] == history.json()["hours_source"] == "api" _set_hours_source("history") home = client.get("/api/home/summary") history = client.get("/api/home/history") assert home.json()["hours_source"] == history.json()["hours_source"] == "history" assert home.json()["month_hours"] == history.json()["month_hours"] == 2 assert home.json()["year_hours"] == history.json()["year_hours"] == "100" assert home.json()["total_hours"] == history.json()["total_hours"] == "10" assert home.json()["today_hours"] == history.json()["today_hours"] == 1 assert home.json()["total_score"] == "3.00" def test_month_hours_refresh_follows_source() -> None: from euniv.service import _month_hours class ApiClient: def month_hours(self) -> str: return "58" def month_history_minutes(self) -> int: raise AssertionError("api 模式不应读历史") assert _month_hours(ApiClient()) == "58" _set_hours_source("history") class HistoryClient: def month_hours(self) -> str: raise AssertionError("history 模式不应读接口") def month_history_minutes(self) -> int: return 80 assert _month_hours(HistoryClient()) == "80" def test_history_course_path_follows_type_and_keeps_explicit_url() -> None: from euniv.client import _history_api_item video = _history_api_item( { "targetName": "视频课", "studyDate": "2026-11-18 10:00", "studyHour": 3, "knowledgeId": "125c7576-c22e-4ae7-be92-ce005171facb", "knowledgeType": "VideoKnowledge", } ) assert video is not None assert video["path"] == "/kng/view/video/125c7576c22e4ae7be92ce005171facb.html" named = _history_api_item( { "title": "已有地址", "studiedAt": "2026-11-18", "duration": 1, "url": "/kng/view/package/abc.html", "knowledgeType": "VideoKnowledge", } ) assert named is not None assert named["path"] == "/kng/view/package/abc.html" def test_month_span_covers_the_whole_month() -> None: from euniv.client import day_span, month_span, period_search_form assert month_span(2026, 11) == ("2026-11-01", "2026-11-30") assert month_span(2024, 2) == ("2024-02-01", "2024-02-29") form = period_search_form("", "2026-11-01", "2026-11-30") assert form["txtStartDate"] == "2026-11-01" assert form["txtEndDate"] == "2026-11-30" assert form["btnSearch"] == "搜索" assert form["ScriptManager1"] == "upList|btnSearch" assert day_span(datetime(2026, 11, 19, 2, 10)) == ("2026-11-19", "2026-11-19") def test_period_page_minutes_match_the_official_table() -> None: from euniv.client import history_rows_from_page, period_cards html = """ 2452... 1020... 126 ACL协议及VRRP协议原理及配置.mp4 111 2026-11-19 01:51 """ assert period_cards(html) == {"year": "10209", "month": "126", "total": "24522"} rows = history_rows_from_page(html) assert rows[0]["minutes"] == 111 assert rows[0]["title"].startswith("ACL协议") def test_study_history_parses_period_table() -> None: from euniv.client import EunivClient html = """
    来源学时日期
    ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN) [详情] 2 2026-11-14 23:55
    """ client = EunivClient.__new__(EunivClient) client._study_period_page = lambda: html # type: ignore[method-assign] rows = client._study_history_page() assert rows == [ { "title": "ZXCTN-A-CH-EVPN原理及配置介绍(IPRAN)", "minutes": 2, "studied_at": "2026-11-14 23:55", "path": "/kng/view/document/125c7576c22e4ae7be92ce005171facb.html", } ] def test_exam_list_rejects_unrecognized_page() -> None: from euniv.client import EunivClient client = EunivClient.__new__(EunivClient) client._profile = {"token": "t", "accountId": "a"} client._site_ready = True class Response: text = "login" class HTTP: def get(self, url: str, headers=None): return Response() def post(self, url: str, data=None, headers=None): return Response() client.client = HTTP() with pytest.raises(RuntimeError, match="考试列表没有获取到"): client.my_exams() def test_tool_upgrade_page_is_reachable_only_by_its_address() -> None: import euniv.api as api_module response = TestClient(api_module.app).get("/tool-upgrade") assert response.status_code == 200 assert "旧版工具已失效" in response.text assert "复制地址" in response.text assert 'type="module"' not in response.text assert response.headers["cache-control"] == "no-cache"