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",
"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_schedule_enabled",
"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)
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
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 account.password_cipher == ""
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:49 | 94 | 通过 |
| 2026-05-22 16:02:13 | 89 | 未通过 |
""")
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 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": True,
"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
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_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_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"
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"] == 2
assert home.json()["total_hours"] == history.json()["total_hours"] == 2
assert home.json()["today_hours"] == history.json()["today_hours"] == 0
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_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()