Files
EnuivTools/backend/tests/test_api.py
T

393 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
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",
}
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 = """
<li class='el-plan-li-3' id="contentitem1" onclick='learningKnowledge("/plan/1de517c30125424e97840b5cd6f28709.html")'>
<div class="el-plan-circle-progress p5" progress="100" id="demo1"></div>
<div class="font-size-16 text-color6 ellipsis">
租赁人员数据保护合规培训-2026</div>
<span class="mr10">
Jiang Mingjun</span><span data-localizeph="sty_lbl_assignedtime"><span>&nbsp;194 天</span></span>
<span data-localizeph='sty_lbl_getcredits' class='el-plan-time'><span>1</span></span>
</li>
"""
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 = """
<li name="userExam">
<a class="my-exam-title ellipsis">较远的考试</a>
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已完成" />
<span data-localize="sty_lbl_teststarttime"></span>:2020-01-01 00:00:00&nbsp;
</li>
<li name="userExam">
<a class="my-exam-title ellipsis">较近的考试</a>
<input type="button" class="btn btn-smd btn-primary my-exam-btn btn-primary" onclick="" value="已过期" />
<span data-localize="sty_lbl_teststarttime"></span>:2026-10-20 00:01:00&nbsp;
</li>
"""
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("""
<li name="userExam">
<a href="/exam/exampreview.htm?examID=abc&amp;examArrangeID=def" class="my-exam-title ellipsis">规范考试</a>
<span class='my-exam-state pass '></span>
<input class="my-exam-btn" onclick="" value="已完成" />
<span data-localize="sty_lbl_teststarttime"></span>:2026-05-20 00:01:00&nbsp;
</li>
""")
assert cards[0]["result"] == "已通过"
assert cards[0]["detail"] == "/exam/exampreview.htm?examID=abc&examArrangeID=def"
detail = parse_exam_detail("""
<span id="lblExamName">规范考试</span>
<span id="lblMaxScore">100</span>
<span id="lblPassScore">90</span>
<span id="lblTotalQuestionQty">45</span>
<span id="lblControlDateTime">2026-05-20 00:01~2026-05-25 23:59</span>
<span id="lblExamTimes">2/3 次</span>
<span id="lblExamLimit">30分钟</span>
<span id="lblUserName">莫英达</span>
<span id="lblViewRestrict">不允许查看答卷详情</span>
<span id="lblMsg">考试安排已结束</span>
<table class="mt15 exam-history-table">
<tr><th>时间</th><th>成绩</th><th>结果</th></tr>
<tr><td><span class="pl20">2026-05-22 16:19:49</span></td><td>94</td><td class="text-center">通过</td></tr>
<tr><td><span class="pl20">2026-05-22 16:02:13</span></td><td>89</td><td class="text-center">未通过</td></tr>
</table>
""")
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("""
<div class="content-body plandetailhead">
<div class="mb20 span-24 font-size-20"><span title="安全规范">安全规范</span></div>
<span id="lblCertificate">-</span>
<span id="Span1">123<span data-localize="sty_lbl_minute"></span></span>
<span id="lblTotalScore">123<span data-localize="sty_lbl_minute"></span></span>
<span id="lblPassScore">0<span data-localize="sty_lbl_minute"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<span>0<span data-localize="sty_lbl_point"></span></span>
<label data-localizeph="sty_lbl_ranknumber"><label><label>2846</label></label></label>
<div class="schedule1 floatleft">100%</div>
<label data-localize="mgt_lbl_requirecompletedate"></label>:2026-11-25
</div>
<div id="knowledgestudy">
<table class="table1 mt30">
<tr><th width="30"><span class="el-mixtrain-num">1</span></th><th class="text-left"><span>规范学习</span></th>
<th>:123<span data-localize="sty_lbl_minute"></span>
<span data-localize="common_lbl_totalscore"></span>:12.3</th></tr>
<tr class="hand">
<td><span class="st" title='1.1分享.mp4'>1.1分享.mp4</span></td>
<td>
<span class="fontnumber" title="已获学分">0</span>&nbsp;/&nbsp;<span class="fontnumber" title="标准学分">5.2</span>
<span data-localize="core_lbl_knghours"></span>:52&nbsp;/&nbsp;52<span data-localize="sty_lbl_minute"></span>
<span>100%</span>
</td>
</tr>
</table>
</div>
""")
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",
}