import json 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) -> None: self.login_name = login_name self.password = password 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 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() -> None: import euniv.api as api_module import euniv.service as service_module 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 ) api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient) 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", "monthly_target", } home = client.get("/api/home") assert home.status_code == 200 body = home.json() assert body["name"] == "测试用户" assert body["exams"] == [{"name": "安全考试", "status": "已完成", "start": "2026-05-20 00:01:00"}] 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) def test_manual_jigsaw_keeps_image_pixels_and_retries() -> 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) -> 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", } 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 ) 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() -> 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) 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 again = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}) assert again.status_code == 200 assert calls["login"] == 1 assert client.post("/api/revoke").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 == "" assert decrypt_secret(account.password_cipher) == "secret-pass" 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() -> None: import euniv.api as api_module import euniv.service as service_module 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 ) api_module.fetch_home_summary = lambda db, employee_id: {"name": "分段"} api_module.fetch_home_exams = lambda db, employee_id: {"exams": [{"name": "一门考试"}]} 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_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()