957 lines
38 KiB
Python
957 lines
38 KiB
Python
import json
|
|
import os
|
|
import threading
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import event
|
|
|
|
from admin.identity import identity
|
|
from admin.models import SystemConfig
|
|
from admin.settings import ensure_admin_seed, load_admin_identity, refresh_interval_seconds
|
|
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw
|
|
from admin.passwords import verify_password
|
|
from euniv.crypto import decrypt_secret, encrypt_secret
|
|
from euniv.db import SessionLocal, engine
|
|
from euniv.models import Account
|
|
from euniv.session import COOKIE_NAME
|
|
|
|
INITIAL_PASSWORD = os.environ["EUNIV_ADMIN_PASSWORD"]
|
|
CREDENTIAL = {
|
|
"ucs_token": "ucs-1",
|
|
"ucs_account_id": "acct",
|
|
"ucs_user_id": "user",
|
|
"ucs_ssoinfo": "sso",
|
|
"ucs_union_id": "union",
|
|
"yxt_token": "yxt-1",
|
|
}
|
|
|
|
|
|
def _app():
|
|
import euniv.api as api_module
|
|
|
|
return api_module
|
|
|
|
|
|
def _add_account(
|
|
employee_id: str,
|
|
password: str = "secret-pass",
|
|
credential: dict | None = CREDENTIAL,
|
|
paused: bool = False,
|
|
refreshed_at: datetime | None = None,
|
|
valid: bool | None = None,
|
|
) -> None:
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
Account(
|
|
employee_id=employee_id,
|
|
password_cipher=encrypt_secret(password),
|
|
credential_cipher=encrypt_secret(json.dumps(credential)) if credential is not None else "",
|
|
refresh_paused=paused,
|
|
last_refresh_at=refreshed_at,
|
|
credential_valid=valid,
|
|
)
|
|
)
|
|
db.commit()
|
|
|
|
|
|
def _settings_body(**overrides) -> dict:
|
|
body = {
|
|
"refresh_interval_minutes": 30,
|
|
"show_manual_jigsaw": True,
|
|
"manual_preference": False,
|
|
"auto_jigsaw_attempts": 3,
|
|
"admin_username": "admin",
|
|
}
|
|
body.update(overrides)
|
|
return body
|
|
|
|
|
|
def test_admin_login_succeeds_and_wrong_password_skips_euniv(monkeypatch) -> None:
|
|
api = _app()
|
|
calls = []
|
|
|
|
def spy(*_args, **_kwargs):
|
|
calls.append("euniv")
|
|
raise AssertionError("不应走 e 学登录")
|
|
|
|
monkeypatch.setattr(api, "login_and_store", spy)
|
|
statements = []
|
|
|
|
def hear(_connection, _cursor, statement, _parameters, _context, _executemany):
|
|
statements.append(statement)
|
|
|
|
event.listen(engine, "before_cursor_execute", hear)
|
|
try:
|
|
client = TestClient(api.app)
|
|
wrong = client.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"})
|
|
assert wrong.status_code == 400
|
|
assert wrong.json()["detail"] == "登录失败"
|
|
assert calls == []
|
|
assert not any("system_config" in statement.lower() for statement in statements)
|
|
|
|
ok = client.post("/api/login", json={"employee_id": " admin ", "password": INITIAL_PASSWORD})
|
|
assert ok.status_code == 200
|
|
assert ok.json() == {"role": "admin", "username": "admin"}
|
|
assert "euniv_admin_session" in client.cookies
|
|
assert COOKIE_NAME not in client.cookies
|
|
assert client.get("/api/session").json() == {"role": "admin", "username": "admin"}
|
|
assert client.get("/api/home/summary").status_code == 403
|
|
assert client.get("/api/home/exams").status_code == 403
|
|
assert client.get("/api/home/trainings").status_code == 403
|
|
assert client.get("/api/exam", params={"path": "/exam/x"}).status_code == 403
|
|
assert client.get("/api/training", params={"path": "/plan/x"}).status_code == 403
|
|
assert calls == []
|
|
finally:
|
|
event.remove(engine, "before_cursor_execute", hear)
|
|
|
|
|
|
def test_default_password_is_kept_when_hashed_and_failures_are_limited() -> None:
|
|
from admin.settings import ensure_admin_seed
|
|
|
|
with SessionLocal() as db:
|
|
row = db.get(SystemConfig, 1)
|
|
assert row is not None
|
|
row.admin_password_cipher = encrypt_secret("242520")
|
|
db.commit()
|
|
ensure_admin_seed()
|
|
load_admin_identity()
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": "242520"}).status_code == 200
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 400
|
|
short = client.put(
|
|
"/api/admin/settings",
|
|
json=_settings_body(admin_password="short", admin_password_current="242520"),
|
|
)
|
|
assert short.status_code == 400
|
|
accepted = client.put(
|
|
"/api/admin/settings",
|
|
json=_settings_body(admin_password="242520", admin_password_current="242520"),
|
|
)
|
|
assert accepted.status_code == 200
|
|
|
|
from admin.login_limit import reset
|
|
|
|
reset()
|
|
locked = TestClient(api.app)
|
|
for _ in range(4):
|
|
assert locked.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"}).status_code == 400
|
|
blocked = locked.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"})
|
|
assert blocked.status_code == 429
|
|
|
|
|
|
def test_admin_identity_uses_memory_until_reload(monkeypatch) -> None:
|
|
api = _app()
|
|
calls = []
|
|
monkeypatch.setattr(
|
|
api,
|
|
"login_and_store",
|
|
lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or {
|
|
"employee_id": employee_id
|
|
},
|
|
)
|
|
with SessionLocal() as db:
|
|
row = db.get(SystemConfig, 1)
|
|
assert row is not None
|
|
row.admin_username = "6650000146"
|
|
row.admin_password_cipher = encrypt_secret("other-secret")
|
|
db.commit()
|
|
|
|
client = TestClient(api.app)
|
|
user = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
|
assert user.status_code == 200
|
|
assert user.json()["role"] == "user"
|
|
assert calls == ["6650000146"]
|
|
|
|
calls.clear()
|
|
admin = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD})
|
|
assert admin.status_code == 200
|
|
assert admin.json() == {"role": "admin", "username": "admin"}
|
|
assert calls == []
|
|
|
|
load_admin_identity()
|
|
rejected = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD})
|
|
assert rejected.status_code == 200
|
|
assert rejected.json()["role"] == "user"
|
|
accepted = client.post("/api/login", json={"employee_id": "6650000146", "password": "other-secret"})
|
|
assert accepted.json() == {"role": "admin", "username": "6650000146"}
|
|
|
|
|
|
def test_seed_does_not_reset_saved_admin() -> None:
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
saved = client.put(
|
|
"/api/admin/settings",
|
|
json=_settings_body(
|
|
admin_username="ops",
|
|
admin_password="next-secret",
|
|
admin_password_current=INITIAL_PASSWORD,
|
|
refresh_interval_minutes=15,
|
|
),
|
|
)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["admin_username"] == "ops"
|
|
assert "admin_password" not in saved.json()
|
|
ensure_admin_seed()
|
|
load_admin_identity()
|
|
assert client.get("/api/admin/settings").json()["admin_username"] == "ops"
|
|
assert client.get("/api/session").json() == {"role": "admin", "username": "ops"}
|
|
old = client.post("/api/login", json={"employee_id": "ops", "password": INITIAL_PASSWORD})
|
|
assert old.status_code == 400
|
|
assert old.json()["detail"] == "登录失败"
|
|
again = client.post("/api/login", json={"employee_id": "ops", "password": "next-secret"})
|
|
assert again.json() == {"role": "admin", "username": "ops"}
|
|
with SessionLocal() as db:
|
|
row = db.get(SystemConfig, 1)
|
|
assert row is not None
|
|
assert verify_password(row.admin_password_cipher, "next-secret")
|
|
|
|
|
|
def test_login_config_changes_meaning_with_visibility(monkeypatch) -> None:
|
|
api = _app()
|
|
seen = {}
|
|
|
|
def spy(db, employee_id, password, manual=False, auto_attempts=3):
|
|
seen["manual"] = manual
|
|
seen["attempts"] = auto_attempts
|
|
return {"employee_id": employee_id}
|
|
|
|
monkeypatch.setattr(api, "login_and_store", spy)
|
|
client = TestClient(api.app)
|
|
opened = client.get("/api/login-config")
|
|
assert opened.json() == {"show_manual_checkbox": True, "manual_checkbox_checked": False}
|
|
assert set(opened.json()) == {"show_manual_checkbox", "manual_checkbox_checked"}
|
|
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
assert client.put("/api/admin/settings", json=_settings_body(manual_preference=True, auto_jigsaw_attempts=6)).status_code == 200
|
|
checked = client.get("/api/login-config").json()
|
|
assert checked == {"show_manual_checkbox": True, "manual_checkbox_checked": True}
|
|
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False})
|
|
assert seen == {"manual": False, "attempts": 6}
|
|
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True})
|
|
assert seen["manual"] is True
|
|
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
hidden = _settings_body(show_manual_jigsaw=False, manual_preference=True, auto_jigsaw_attempts=4)
|
|
assert client.put("/api/admin/settings", json=hidden).status_code == 200
|
|
assert client.get("/api/login-config").json() == {"show_manual_checkbox": False, "manual_checkbox_checked": False}
|
|
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True})
|
|
assert seen["manual"] is False
|
|
assert seen["attempts"] == 4
|
|
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
direct = _settings_body(show_manual_jigsaw=False, manual_preference=False, auto_jigsaw_attempts=9)
|
|
assert client.put("/api/admin/settings", json=direct).status_code == 200
|
|
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False})
|
|
assert seen["manual"] is True
|
|
assert seen["attempts"] == 9
|
|
|
|
|
|
def test_settings_reject_interval_and_attempts_outside_range() -> None:
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
too_wide = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1441))
|
|
assert too_wide.status_code == 400
|
|
assert too_wide.json()["detail"] == "定时刷新间隔须为 1 到 1440 的整数"
|
|
too_many = client.put("/api/admin/settings", json=_settings_body(auto_jigsaw_attempts=0))
|
|
assert too_many.status_code == 400
|
|
assert too_many.json()["detail"] == "自动滑动次数须为 1 到 10 的整数"
|
|
blank = client.put("/api/admin/settings", json=_settings_body(admin_username=" "))
|
|
assert blank.status_code == 400
|
|
assert blank.json()["detail"] == "请填写管理员用户名"
|
|
assert client.get("/api/admin/settings").json()["refresh_interval_minutes"] == 30
|
|
kept = client.put("/api/admin/settings", json=_settings_body(admin_password=""))
|
|
assert kept.status_code == 200
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
edges = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1, auto_jigsaw_attempts=10))
|
|
assert edges.status_code == 200
|
|
assert edges.json()["refresh_interval_minutes"] == 1
|
|
assert edges.json()["auto_jigsaw_attempts"] == 10
|
|
zero = client.put(
|
|
"/api/admin/settings",
|
|
json=_settings_body(heartbeat_video_seconds=0, heartbeat_document_seconds=0, heartbeat_scorm_seconds=0),
|
|
)
|
|
assert zero.status_code == 200
|
|
assert zero.json()["heartbeat_video_seconds"] == 0
|
|
assert zero.json()["heartbeat_document_seconds"] == 0
|
|
assert zero.json()["heartbeat_scorm_seconds"] == 0
|
|
negative = client.put("/api/admin/settings", json=_settings_body(heartbeat_video_seconds=-1))
|
|
assert negative.status_code == 400
|
|
assert negative.json()["detail"] == "视频心跳间隔须为 0 到 300 的整数"
|
|
|
|
|
|
def test_refresh_interval_comes_only_from_database(monkeypatch) -> None:
|
|
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "9")
|
|
assert refresh_interval_seconds() == 30 * 60
|
|
with SessionLocal() as db:
|
|
row = db.get(SystemConfig, 1)
|
|
assert row is not None
|
|
row.refresh_interval_minutes = 12
|
|
db.commit()
|
|
assert refresh_interval_seconds() == 12 * 60
|
|
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1440")
|
|
assert refresh_interval_seconds() == 12 * 60
|
|
|
|
root = Path(__file__).resolve().parents[2]
|
|
example = (root / ".env.example").read_text(encoding="utf-8")
|
|
assert "EUNIV_WORKER_INTERVAL" not in example
|
|
assert "EUNIV_SECRET_KEY" in example
|
|
assert "EUNIV_DB_PATH" in example
|
|
for folder in ("euniv", "admin", "alembic"):
|
|
for path in (root / "backend" / folder).rglob("*.py"):
|
|
assert "EUNIV_WORKER_INTERVAL" not in path.read_text(encoding="utf-8")
|
|
service_text = (root / "backend" / "euniv" / "service.py").read_text(encoding="utf-8")
|
|
assert "1800" not in service_text
|
|
|
|
import euniv.service as service
|
|
|
|
seen = []
|
|
done = threading.Event()
|
|
refreshes = []
|
|
|
|
def wait(self, seconds):
|
|
seen.append(seconds)
|
|
if len(seen) >= 2:
|
|
done.set()
|
|
return "stop"
|
|
return "wake"
|
|
|
|
monkeypatch.setattr(service._RefreshGate, "wait", wait)
|
|
monkeypatch.setattr(service, "refresh_stored_credentials", lambda *args, **kwargs: refreshes.append(1))
|
|
service.start_credential_refresh()
|
|
assert done.wait(2)
|
|
assert seen == [12 * 60, 12 * 60]
|
|
assert refreshes == []
|
|
|
|
|
|
def test_saving_new_interval_restarts_wait_without_refresh(monkeypatch) -> None:
|
|
import euniv.service as service
|
|
|
|
notices = []
|
|
monkeypatch.setattr(service, "notify_refresh_interval_changed", lambda: notices.append(1))
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
same = client.put("/api/admin/settings", json=_settings_body(admin_username="admin"))
|
|
assert same.status_code == 200
|
|
assert notices == []
|
|
changed = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=45))
|
|
assert changed.status_code == 200
|
|
assert notices == [1]
|
|
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1")
|
|
assert refresh_interval_seconds() == 45 * 60
|
|
|
|
|
|
class _Alive:
|
|
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.login_called = False
|
|
|
|
def close(self) -> None:
|
|
return None
|
|
|
|
def restore(self, _credential: dict) -> None:
|
|
return None
|
|
|
|
def credential_alive(self) -> bool:
|
|
return True
|
|
|
|
def month_hours(self) -> str:
|
|
return "660"
|
|
|
|
def export_credential(self) -> dict:
|
|
return dict(CREDENTIAL)
|
|
|
|
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
|
|
self.login_called = True
|
|
raise AssertionError("不应重新登录")
|
|
|
|
def authorize(self, _profile: dict) -> None:
|
|
return None
|
|
|
|
|
|
class _Dead:
|
|
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
|
self.login_name = login_name
|
|
|
|
def close(self) -> None:
|
|
return None
|
|
|
|
def restore(self, _credential: dict) -> None:
|
|
return None
|
|
|
|
def credential_alive(self) -> bool:
|
|
return False
|
|
|
|
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
|
|
from euniv.client import LoginRejected
|
|
|
|
raise LoginRejected("账号或密码错误")
|
|
|
|
|
|
def test_refresh_records_outcome_and_skips_paused_accounts() -> None:
|
|
import euniv.service as service
|
|
|
|
stamped = datetime(2026, 10, 1, 8, 0, tzinfo=timezone.utc)
|
|
_add_account("alive-user")
|
|
_add_account("failed-user")
|
|
_add_account("paused-user", paused=True, refreshed_at=stamped, valid=True)
|
|
_add_account("empty-user", credential=None, refreshed_at=stamped, valid=False)
|
|
created = []
|
|
|
|
def factory(login_name: str, password: str, proxy: str | None = None):
|
|
created.append(login_name)
|
|
if login_name == "failed-user":
|
|
return _Dead(login_name, password)
|
|
return _Alive(login_name, password)
|
|
|
|
service.refresh_stored_credentials(factory)
|
|
assert created == ["alive-user", "failed-user"]
|
|
with SessionLocal() as db:
|
|
alive = db.get(Account, "alive-user")
|
|
failed = db.get(Account, "failed-user")
|
|
paused = db.get(Account, "paused-user")
|
|
empty = db.get(Account, "empty-user")
|
|
assert alive is not None and failed is not None and paused is not None and empty is not None
|
|
assert alive.credential_valid is True
|
|
assert alive.month_hours == "660"
|
|
assert alive.last_refresh_at is not None
|
|
assert decrypt_secret(alive.password_cipher) == "secret-pass"
|
|
assert json.loads(decrypt_secret(alive.credential_cipher))["yxt_token"] == "yxt-1"
|
|
assert failed.credential_valid is False
|
|
assert failed.last_refresh_at is not None
|
|
assert decrypt_secret(failed.password_cipher) == "secret-pass"
|
|
assert failed.credential_cipher == ""
|
|
assert paused.last_refresh_at == stamped.replace(tzinfo=None) or paused.last_refresh_at == stamped
|
|
assert paused.credential_valid is True
|
|
assert empty.credential_valid is False
|
|
assert decrypt_secret(empty.password_cipher) == "secret-pass"
|
|
|
|
|
|
def test_paused_account_still_updates_when_opening_home() -> None:
|
|
import euniv.service as service
|
|
|
|
_add_account("paused-user", paused=True)
|
|
|
|
class HomeClient(_Alive):
|
|
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
|
super().__init__(login_name, password, proxy)
|
|
self._token = "yxt-1"
|
|
|
|
def home_summary(self) -> dict:
|
|
self._token = "yxt-2"
|
|
return {"name": "测试用户"}
|
|
|
|
def export_credential(self) -> dict:
|
|
exported = dict(CREDENTIAL)
|
|
exported["yxt_token"] = self._token
|
|
return exported
|
|
|
|
with SessionLocal() as db:
|
|
assert service.fetch_home_summary(db, "paused-user", HomeClient)["name"] == "测试用户"
|
|
account = db.get(Account, "paused-user")
|
|
assert account is not None
|
|
assert account.refresh_paused is True
|
|
assert json.loads(decrypt_secret(account.credential_cipher))["yxt_token"] == "yxt-2"
|
|
|
|
|
|
def test_check_skips_empty_credential_and_updates_saved_one(monkeypatch) -> None:
|
|
import admin.users as users
|
|
|
|
stamped = datetime(2026, 10, 2, 9, 30, tzinfo=timezone.utc)
|
|
_add_account("empty-user", credential=None, refreshed_at=stamped, valid=True)
|
|
_add_account("saved-user")
|
|
calls = []
|
|
|
|
def factory(login_name: str, password: str, proxy: str | None = None):
|
|
calls.append(login_name)
|
|
return _Alive(login_name, password)
|
|
|
|
monkeypatch.setattr(users, "build_client", factory)
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
missed = client.post("/api/admin/users/empty-user/check")
|
|
assert missed.status_code == 200
|
|
assert missed.json() == {"employee_id": "empty-user", "result": "未保存"}
|
|
assert calls == []
|
|
with SessionLocal() as db:
|
|
empty = db.get(Account, "empty-user")
|
|
assert empty is not None
|
|
assert empty.credential_valid is True
|
|
assert empty.last_refresh_at == stamped or empty.last_refresh_at == stamped.replace(tzinfo=None)
|
|
|
|
checked = client.post("/api/admin/users/saved-user/check")
|
|
assert checked.status_code == 200
|
|
assert checked.json() == {"employee_id": "saved-user", "result": "有效"}
|
|
assert calls == ["saved-user"]
|
|
listed = client.get("/api/admin/users")
|
|
assert listed.status_code == 200
|
|
body = listed.json()
|
|
assert isinstance(body, list)
|
|
saved = next(item for item in body if item["employee_id"] == "saved-user")
|
|
assert set(saved) == {
|
|
"employee_id",
|
|
"has_credential",
|
|
"refresh_paused",
|
|
"last_refresh_at",
|
|
"credential_valid",
|
|
"month_hours",
|
|
"monthly_target",
|
|
"has_proxy",
|
|
"proxy",
|
|
"study_start",
|
|
"study_start_day",
|
|
"study_start_hour",
|
|
"study_start_minute",
|
|
"study_start_second",
|
|
"study_schedule_enabled",
|
|
"course_workers",
|
|
"study_paused",
|
|
"study_ignore_window",
|
|
"study_started",
|
|
"hours_month",
|
|
"study_active",
|
|
"state",
|
|
}
|
|
assert saved["has_credential"] is True
|
|
assert saved["refresh_paused"] is False
|
|
assert saved["credential_valid"] is True
|
|
assert saved["month_hours"] == ""
|
|
assert isinstance(saved["last_refresh_at"], str)
|
|
calls.clear()
|
|
again = client.get("/api/admin/users")
|
|
assert again.status_code == 200
|
|
assert calls == []
|
|
|
|
|
|
def test_check_all_reports_each_saved_account(monkeypatch) -> None:
|
|
import admin.users as users
|
|
|
|
_add_account("a-user")
|
|
_add_account("b-user")
|
|
_add_account("c-user", credential=None)
|
|
calls = []
|
|
|
|
def factory(login_name: str, password: str, proxy: str | None = None):
|
|
calls.append(login_name)
|
|
if login_name == "b-user":
|
|
raise RuntimeError("网络失败")
|
|
return _Alive(login_name, password)
|
|
|
|
monkeypatch.setattr(users, "build_client", factory)
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
response = client.post("/api/admin/users/check-all")
|
|
assert response.status_code == 200
|
|
assert response.json() == [
|
|
{"employee_id": "a-user", "result": "有效"},
|
|
{"employee_id": "b-user", "result": "检查失败", "detail": "检查失败"},
|
|
]
|
|
assert calls == ["a-user", "b-user"]
|
|
with SessionLocal() as db:
|
|
failed = db.get(Account, "b-user")
|
|
untouched = db.get(Account, "c-user")
|
|
assert failed is not None and failed.credential_valid is None
|
|
assert failed.last_refresh_at is not None
|
|
assert untouched is not None and untouched.last_refresh_at is None
|
|
|
|
|
|
def test_credentials_and_delete_user(monkeypatch) -> None:
|
|
import admin.users as users
|
|
|
|
monkeypatch.setattr(
|
|
users,
|
|
"build_client",
|
|
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学")),
|
|
)
|
|
_add_account("6650000146")
|
|
_add_account("empty-user", credential=None)
|
|
api = _app()
|
|
admin = TestClient(api.app)
|
|
assert admin.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
secret = admin.get("/api/admin/users/6650000146/credentials")
|
|
assert secret.status_code == 200
|
|
assert secret.headers["cache-control"] == "no-store"
|
|
assert secret.json()["password"] == "secret-pass"
|
|
assert secret.json()["ucs_token"] == "ucs-1"
|
|
assert secret.json()["yxt_token"] == "yxt-1"
|
|
assert "detail" not in secret.json()
|
|
missing = admin.get("/api/admin/users/empty-user/credentials")
|
|
assert missing.json()["detail"] == "尚未完成登录或已注销"
|
|
assert missing.json()["password"] == "secret-pass"
|
|
assert missing.json()["yxt_token"] == ""
|
|
|
|
from euniv.session import seal
|
|
|
|
user = TestClient(api.app)
|
|
user.cookies.set(COOKIE_NAME, seal("user", "6650000146"))
|
|
assert user.get("/api/session").json() == {"role": "user", "employee_id": "6650000146"}
|
|
removed = admin.delete("/api/admin/users/6650000146")
|
|
assert removed.status_code == 200
|
|
assert removed.json() == {"ok": True}
|
|
with SessionLocal() as db:
|
|
assert db.get(Account, "6650000146") is None
|
|
assert user.get("/api/session").status_code == 401
|
|
assert admin.get("/api/admin/users/6650000146/credentials").status_code == 404
|
|
|
|
|
|
def test_pause_only_changes_refresh_flag() -> None:
|
|
_add_account("6650000146", paused=False)
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
response = client.post("/api/admin/users/6650000146/refresh", json={"paused": True})
|
|
assert response.status_code == 200
|
|
with SessionLocal() as db:
|
|
account = db.get(Account, "6650000146")
|
|
assert account is not None
|
|
assert account.refresh_paused is True
|
|
assert account.credential_cipher
|
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
|
listed = client.get("/api/admin/users").json()
|
|
row = next(item for item in listed if item["employee_id"] == "6650000146")
|
|
assert row["refresh_paused"] is True
|
|
assert row["has_credential"] is True
|
|
|
|
|
|
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie(monkeypatch) -> None:
|
|
api = _app()
|
|
monkeypatch.setattr(
|
|
api,
|
|
"login_and_store",
|
|
lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id},
|
|
)
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
|
|
_add_account("6650000146")
|
|
assert client.get("/api/admin/users").status_code == 401
|
|
assert client.get("/api/admin/settings").status_code == 401
|
|
assert client.post("/api/admin/logout").status_code == 200
|
|
assert client.get("/api/session").json()["role"] == "user"
|
|
assert client.post("/api/logout").status_code == 200
|
|
assert client.get("/api/session").status_code == 401
|
|
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
assert client.post("/api/logout").status_code == 200
|
|
assert client.get("/api/session").json()["role"] == "admin"
|
|
assert client.post("/api/admin/logout").status_code == 200
|
|
assert client.get("/api/session").status_code == 401
|
|
|
|
|
|
def test_auto_attempts_count_only_rejections(monkeypatch) -> None:
|
|
monkeypatch.setattr("euniv.client.jigsaw_offset", lambda *_args: 12)
|
|
client = EunivClient.__new__(EunivClient)
|
|
loads = {"n": 0}
|
|
submits = {"n": 0}
|
|
|
|
def load():
|
|
loads["n"] += 1
|
|
return b"b", b"s", 1
|
|
|
|
def submit(_offset: int):
|
|
submits["n"] += 1
|
|
if submits["n"] == 1:
|
|
raise JigsawRejected("拼图未通过")
|
|
raise RuntimeError("登录失败:密码错误")
|
|
|
|
client._load_jigsaw = load
|
|
client.submit_jigsaw = submit
|
|
client.current_puzzle = lambda: {"y": 1}
|
|
try:
|
|
client._login_with_jigsaw(False, 5)
|
|
except RuntimeError as exc:
|
|
assert "密码错误" in str(exc)
|
|
else:
|
|
raise AssertionError("密码错误应立即停止")
|
|
assert submits["n"] == 2
|
|
assert loads["n"] == 2
|
|
|
|
submits["n"] = 0
|
|
loads["n"] = 0
|
|
|
|
def reject(_offset: int):
|
|
submits["n"] += 1
|
|
raise JigsawRejected("拼图未通过")
|
|
|
|
client.submit_jigsaw = reject
|
|
try:
|
|
client._login_with_jigsaw(False, 4)
|
|
except ManualJigsaw:
|
|
pass
|
|
else:
|
|
raise AssertionError("用完次数后应交给手动拼图")
|
|
assert submits["n"] == 4
|
|
assert loads["n"] == 5
|
|
loads["n"] = 0
|
|
try:
|
|
client._login_with_jigsaw(True, 4)
|
|
except ManualJigsaw:
|
|
pass
|
|
else:
|
|
raise AssertionError("直接手动时不应自动滑动")
|
|
assert loads["n"] == 1
|
|
|
|
|
|
def test_settings_do_not_expose_process_switches() -> None:
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
body = client.get("/api/admin/settings").json()
|
|
assert set(body) == {
|
|
"refresh_interval_minutes",
|
|
"show_manual_jigsaw",
|
|
"manual_preference",
|
|
"auto_jigsaw_attempts",
|
|
"admin_username",
|
|
"heartbeat_interval_mode",
|
|
"heartbeat_video_seconds",
|
|
"heartbeat_document_seconds",
|
|
"heartbeat_scorm_seconds",
|
|
"hours_source",
|
|
}
|
|
assert body["hours_source"] == "api"
|
|
assert identity.password_ok(INITIAL_PASSWORD)
|
|
|
|
|
|
def test_admin_can_set_and_clear_proxy_for_selected_users() -> None:
|
|
_add_account("p1-user")
|
|
_add_account("p2-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
saved = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={
|
|
"employee_ids": ["p1-user", "p2-user"],
|
|
"scheme": "socks5",
|
|
"host": "8.8.8.8",
|
|
"port": 1080,
|
|
"username": "u",
|
|
"password": "secret",
|
|
},
|
|
)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["count"] == 2
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
|
assert one["has_proxy"] is True
|
|
assert one["proxy"] == "SOCKS5 8.8.8.8:1080"
|
|
detail = client.get("/api/admin/users/p1-user/proxy")
|
|
assert detail.status_code == 200
|
|
assert detail.json()["username"] == "u"
|
|
assert detail.json()["has_password"] is True
|
|
assert "password" not in detail.json()
|
|
cleared = client.post("/api/admin/users/proxy/clear", json={"employee_ids": ["p1-user"]})
|
|
assert cleared.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
|
two = next(item for item in listed if item["employee_id"] == "p2-user")
|
|
assert one["has_proxy"] is False
|
|
assert two["has_proxy"] is True
|
|
no_auth = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={
|
|
"employee_ids": ["p1-user"],
|
|
"scheme": "http",
|
|
"host": "1.1.1.1",
|
|
"port": 8080,
|
|
"username": "",
|
|
"password": "",
|
|
},
|
|
)
|
|
assert no_auth.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "p1-user")
|
|
assert one["proxy"] == "HTTP 1.1.1.1:8080"
|
|
detail = client.get("/api/admin/users/p1-user/proxy")
|
|
assert detail.json()["has_password"] is False
|
|
assert detail.json()["username"] == ""
|
|
|
|
|
|
def test_admin_can_set_study_start_for_selected_users() -> None:
|
|
_add_account("s1-user")
|
|
_add_account("s2-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
saved = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["s1-user", "s2-user"], "day": 5, "hour": 16, "minute": 8, "second": 9},
|
|
)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["count"] == 2
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "s1-user")
|
|
two = next(item for item in listed if item["employee_id"] == "s2-user")
|
|
assert one["study_start"] == "每月5日 16:08:09"
|
|
assert two["study_start"] == "每月5日 16:08:09"
|
|
one_only = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["s1-user"], "day": 20, "hour": 0, "minute": 0, "second": 0},
|
|
)
|
|
assert one_only.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "s1-user")
|
|
two = next(item for item in listed if item["employee_id"] == "s2-user")
|
|
assert one["study_start"] == "每月20日 00:00:00"
|
|
assert two["study_start"] == "每月5日 16:08:09"
|
|
assert one["study_start_day"] == 20
|
|
edges = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["s1-user"], "day": 1, "hour": 0, "minute": 0, "second": 0},
|
|
)
|
|
assert edges.status_code == 200
|
|
late = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["s1-user"], "day": 28, "hour": 23, "minute": 59, "second": 59},
|
|
)
|
|
assert late.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "s1-user")
|
|
assert one["study_start"] == "每月28日 23:59:59"
|
|
rejected = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["s1-user"], "day": 29, "hour": 0, "minute": 0, "second": 0},
|
|
)
|
|
assert rejected.status_code == 400
|
|
|
|
|
|
def test_admin_can_set_course_workers_for_selected_users() -> None:
|
|
_add_account("w1-user")
|
|
_add_account("w2-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
|
assert one["course_workers"] == 1
|
|
saved = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["w1-user", "w2-user"], "workers": 4},
|
|
)
|
|
assert saved.status_code == 200
|
|
assert saved.json()["count"] == 2
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
|
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
|
assert one["course_workers"] == 4
|
|
assert two["course_workers"] == 4
|
|
one_only = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["w1-user"], "workers": 1},
|
|
)
|
|
assert one_only.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "w1-user")
|
|
two = next(item for item in listed if item["employee_id"] == "w2-user")
|
|
assert one["course_workers"] == 1
|
|
assert two["course_workers"] == 4
|
|
bad = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["w1-user"], "workers": 9},
|
|
)
|
|
assert bad.status_code == 400
|
|
|
|
|
|
def test_admin_can_turn_off_proxy_with_scheme() -> None:
|
|
_add_account("off-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["off-user"], "scheme": "http", "host": "1.1.1.1", "port": 8080},
|
|
)
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "off-user")
|
|
assert one["has_proxy"] is True
|
|
closed = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={"employee_ids": ["off-user"], "scheme": "off"},
|
|
)
|
|
assert closed.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "off-user")
|
|
assert one["has_proxy"] is False
|
|
detail = client.get("/api/admin/users/off-user/proxy")
|
|
assert detail.json()["enabled"] is False
|
|
assert detail.json()["scheme"] == "off"
|
|
|
|
|
|
def test_admin_can_start_and_stop_study_for_selected_users() -> None:
|
|
_add_account("run-user")
|
|
_add_account("wait-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
started = client.post("/api/admin/users/study", json={"employee_ids": ["run-user", "wait-user"], "action": "start"})
|
|
assert started.status_code == 200
|
|
assert started.json()["count"] == 2
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "run-user")
|
|
two = next(item for item in listed if item["employee_id"] == "wait-user")
|
|
assert one["study_started"] is True
|
|
assert two["study_paused"] is False
|
|
stopped = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "stop"})
|
|
assert stopped.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "run-user")
|
|
two = next(item for item in listed if item["employee_id"] == "wait-user")
|
|
assert one["study_started"] is False
|
|
assert one["study_paused"] is True
|
|
assert two["study_started"] is True
|
|
bad = client.post("/api/admin/users/study", json={"employee_ids": ["run-user"], "action": "pause"})
|
|
assert bad.status_code == 400
|
|
|
|
|
|
def test_admin_can_save_study_settings_in_one_request() -> None:
|
|
_add_account("set-user")
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
saved = client.put(
|
|
"/api/admin/users/study-settings",
|
|
json={
|
|
"employee_ids": ["set-user"],
|
|
"monthly_target": 120,
|
|
"day": 8,
|
|
"hour": 9,
|
|
"minute": 10,
|
|
"second": 11,
|
|
"workers": 2,
|
|
"scheme": "http",
|
|
"host": "9.9.9.9",
|
|
"port": 8080,
|
|
"username": "",
|
|
"password": "",
|
|
},
|
|
)
|
|
assert saved.status_code == 200
|
|
listed = client.get("/api/admin/users").json()
|
|
one = next(item for item in listed if item["employee_id"] == "set-user")
|
|
assert one["monthly_target"] == 120
|
|
assert one["study_start"] == "每月8日 09:10:11"
|
|
assert one["course_workers"] == 2
|
|
assert one["proxy"] == "HTTP 9.9.9.9:8080"
|
|
|
|
|
|
def test_admin_can_switch_hours_source() -> None:
|
|
api = _app()
|
|
client = TestClient(api.app)
|
|
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
|
|
saved = client.put("/api/admin/settings", json=_settings_body(hours_source="history"))
|
|
assert saved.status_code == 200
|
|
assert saved.json()["hours_source"] == "history"
|
|
assert client.get("/api/admin/settings").json()["hours_source"] == "history"
|
|
bad = client.put("/api/admin/settings", json=_settings_body(hours_source="other"))
|
|
assert bad.status_code == 400
|
|
assert bad.json()["detail"] == "学时达标依据须为 api 或 history"
|