fix: 补齐审查清单里还没落地的交互和代理复测
This commit is contained in:
@@ -79,7 +79,7 @@ def list_users(db: Session) -> list[dict]:
|
||||
"last_refresh_at": _iso_time(account.last_refresh_at),
|
||||
"credential_valid": _optional_bool(account.credential_valid),
|
||||
"month_hours": account.month_hours or "",
|
||||
"monthly_target": int(account.monthly_target or 600),
|
||||
"monthly_target": account.monthly_target if account.monthly_target is not None else 600,
|
||||
"has_proxy": enabled(account),
|
||||
"proxy": summary_of(account),
|
||||
"study_start": start_label(account),
|
||||
@@ -109,7 +109,7 @@ def _require(db: Session, employee_id: str) -> Account:
|
||||
|
||||
def check_employee(db: Session, employee_id: str) -> dict:
|
||||
from euniv.proxy import bind_url, is_proxy_failure, url_of, uses_pool
|
||||
from euniv.proxy_pool import MAX_SWITCHES, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
|
||||
|
||||
account = _require(db, employee_id)
|
||||
if not account.credential_cipher:
|
||||
@@ -133,7 +133,7 @@ def check_employee(db: Session, employee_id: str) -> dict:
|
||||
break
|
||||
except Exception as exc:
|
||||
if pooled and proxy and is_proxy_failure(exc):
|
||||
mark_failed(employee_id, proxy, str(exc)[:200])
|
||||
retire_if_dead(employee_id, proxy, str(exc)[:200])
|
||||
client.close()
|
||||
client = None
|
||||
continue
|
||||
|
||||
@@ -34,6 +34,7 @@ from euniv.client import (
|
||||
_load_cookies,
|
||||
as_uuid,
|
||||
compact_id,
|
||||
guard_https,
|
||||
play_page_params,
|
||||
study_progress_fields,
|
||||
)
|
||||
@@ -665,14 +666,12 @@ class HoursWatcher:
|
||||
target: int,
|
||||
user_stop: asyncio.Event,
|
||||
interval: float = _HOURS_REFRESH_SECONDS,
|
||||
source: str = "api",
|
||||
) -> None:
|
||||
self.session = session
|
||||
self.employee_id = employee_id
|
||||
self.target = target
|
||||
self.user_stop = user_stop
|
||||
self.interval = interval
|
||||
self.source = source if source in ("api", "history") else "api"
|
||||
self._lock = asyncio.Lock()
|
||||
self.reached = False
|
||||
from euniv.study_window import month_key
|
||||
@@ -764,6 +763,7 @@ class StudySession:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
_load_cookies(self._client, self._initial_cookies)
|
||||
self._proxy_lock = asyncio.Lock()
|
||||
@@ -780,7 +780,7 @@ class StudySession:
|
||||
if not self._use_pool:
|
||||
return False
|
||||
from euniv.proxy import async_httpx_client, parse_proxy
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
|
||||
|
||||
if self._proxy_lock is None:
|
||||
self._proxy_lock = asyncio.Lock()
|
||||
@@ -790,8 +790,10 @@ class StudySession:
|
||||
return True
|
||||
if self._switches >= MAX_SWITCHES:
|
||||
return False
|
||||
dead = await asyncio.to_thread(retire_if_dead, self._employee_id, failed)
|
||||
if not dead:
|
||||
return True
|
||||
self._switches += 1
|
||||
await asyncio.to_thread(mark_failed, self._employee_id, failed)
|
||||
nxt = await asyncio.to_thread(acquire, self._employee_id)
|
||||
parsed = parse_proxy(nxt)
|
||||
if parsed == failed:
|
||||
@@ -801,6 +803,7 @@ class StudySession:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
cookies = self._initial_cookies
|
||||
if self._client is not None:
|
||||
@@ -1454,7 +1457,7 @@ def _prepare_session(employee_id: str, password: str,
|
||||
use_pool: bool = False
|
||||
) -> tuple[str, str, str, list[tuple[str, str, str, str]], str | None, str]:
|
||||
"""同步:恢复会话并导出 cookies。最后一项是 expired 或 network。"""
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, acquire, retire_if_dead
|
||||
|
||||
current = proxy
|
||||
last_reason = "network"
|
||||
@@ -1477,9 +1480,8 @@ def _prepare_session(employee_id: str, password: str,
|
||||
except Exception as exc:
|
||||
log.warning("用户 %s 准备会话失败: %s", employee_id, exc)
|
||||
if use_pool and current and is_proxy_failure(exc):
|
||||
mark_failed(employee_id, current, str(exc)[:200])
|
||||
current = acquire(employee_id)
|
||||
last_reason = "network"
|
||||
if retire_if_dead(employee_id, current, str(exc)[:200]):
|
||||
current = acquire(employee_id)
|
||||
continue
|
||||
last_reason = "expired" if isinstance(exc, SessionExpired) else "network"
|
||||
return "", "", "", [], current, last_reason
|
||||
@@ -1748,7 +1750,7 @@ class AutoStudyWorker:
|
||||
_set_user_status(employee_id, state="已停止")
|
||||
return
|
||||
_set_user_status(employee_id, state="学习中")
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop, source=hours_source)
|
||||
hours = HoursWatcher(session, employee_id, target, user_stop)
|
||||
if await hours.refresh():
|
||||
return
|
||||
ticker = asyncio.create_task(hours.ticker(self._async_stop))
|
||||
|
||||
+11
-6
@@ -755,9 +755,14 @@ class QrWaiting(Exception):
|
||||
"""二维码尚未扫过或还在等待确认。"""
|
||||
|
||||
|
||||
def _https_only(request: httpx.Request) -> None:
|
||||
def guard_https(request: httpx.Request) -> None:
|
||||
if request.url.scheme != "https":
|
||||
raise RuntimeError("只允许 https 请求")
|
||||
host = (request.url.host or "").rstrip(".").lower()
|
||||
if host in {"zte.com.cn", "yunxuetang.cn"} or host.endswith((".zte.com.cn", ".yunxuetang.cn")):
|
||||
return
|
||||
request.headers.pop("token", None)
|
||||
request.headers.pop("Token", None)
|
||||
|
||||
|
||||
def _login_secret_too_long(value: str) -> bool:
|
||||
@@ -776,7 +781,7 @@ class EunivClient:
|
||||
timeout=30,
|
||||
follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
event_hooks={"request": [_https_only]},
|
||||
event_hooks={"request": [guard_https]},
|
||||
)
|
||||
self._profile: dict = {}
|
||||
self._yxt_token = ""
|
||||
@@ -992,7 +997,7 @@ class EunivClient:
|
||||
if profile.get("unionId"):
|
||||
jar["iuacUnionId"] = str(profile["unionId"])
|
||||
for name, value in jar.items():
|
||||
self.client.cookies.set(name, value, domain=domain, path="/")
|
||||
self.client.cookies.set(name, value, domain=domain, path="/", secure=True)
|
||||
|
||||
self._uac_post(
|
||||
"/authentication/token/verify.serv",
|
||||
@@ -1057,8 +1062,8 @@ class EunivClient:
|
||||
token = str(credential.get("yxt_token") or "")
|
||||
self._yxt_token = token
|
||||
if token:
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain="euniv.zte.com.cn", path="/", secure=True)
|
||||
self.client.cookies.set("ELEARNING_00024", token, domain=".yunxuetang.cn", path="/", secure=True)
|
||||
|
||||
def session_token(self) -> str:
|
||||
for cookie in self.client.cookies.jar:
|
||||
@@ -1081,7 +1086,7 @@ class EunivClient:
|
||||
if refreshed:
|
||||
self._yxt_token = refreshed
|
||||
for domain in ("euniv.zte.com.cn", ".yunxuetang.cn"):
|
||||
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/")
|
||||
self.client.cookies.set("ELEARNING_00024", refreshed, domain=domain, path="/", secure=True)
|
||||
if response.status_code == 401:
|
||||
raise SessionExpired("学习平台登录已失效")
|
||||
if response.status_code == 403:
|
||||
|
||||
@@ -201,7 +201,7 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
password = decrypt_secret(account.password_cipher)
|
||||
credential = json.loads(decrypt_secret(account.credential_cipher))
|
||||
from euniv.proxy import bind_url, is_proxy_failure, uses_pool
|
||||
from euniv.proxy_pool import MAX_SWITCHES, mark_failed
|
||||
from euniv.proxy_pool import MAX_SWITCHES, retire_if_dead
|
||||
|
||||
proxy = bind_url(account)
|
||||
courses = None
|
||||
@@ -219,8 +219,8 @@ def _fetch_and_store(trigger: str) -> bool:
|
||||
except Exception as exc:
|
||||
last_exc = exc
|
||||
if uses_pool(account) and proxy and is_proxy_failure(exc):
|
||||
mark_failed(employee_id, proxy, str(exc)[:200])
|
||||
proxy = bind_url(account)
|
||||
if retire_if_dead(employee_id, proxy, str(exc)[:200]):
|
||||
proxy = bind_url(account)
|
||||
continue
|
||||
_cool_failed_sync(employee_id)
|
||||
return False
|
||||
|
||||
@@ -332,6 +332,9 @@ def is_proxy_failure(exc: BaseException) -> bool:
|
||||
httpx.ProxyError,
|
||||
httpx.ConnectError,
|
||||
httpx.ConnectTimeout,
|
||||
httpx.ReadTimeout,
|
||||
httpx.ReadError,
|
||||
httpx.RemoteProtocolError,
|
||||
SocksProxyError,
|
||||
ProxyConnectionError,
|
||||
ProxyTimeoutError,
|
||||
|
||||
@@ -332,6 +332,19 @@ def release(employee_id: str) -> None:
|
||||
db.commit()
|
||||
|
||||
|
||||
def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool:
|
||||
"""立刻复测当前节点。还通就继续用;不通就标死。"""
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
if parsed is None:
|
||||
mark_failed(employee_id, proxy_url, reason)
|
||||
return True
|
||||
ok, _latency, why = probe(parsed[0], parsed[1], parsed[2])
|
||||
if ok:
|
||||
return False
|
||||
mark_failed(employee_id, proxy_url, why or reason)
|
||||
return True
|
||||
|
||||
|
||||
def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None:
|
||||
key = (employee_id or "").strip()
|
||||
parsed = _parse_proxy_url(proxy_url)
|
||||
|
||||
@@ -181,14 +181,14 @@ def _client(factory, employee_id: str, password: str, account: Account | None =
|
||||
|
||||
def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool:
|
||||
from euniv.proxy import is_proxy_failure, uses_pool
|
||||
from euniv.proxy_pool import mark_failed
|
||||
from euniv.proxy_pool import retire_if_dead
|
||||
|
||||
if account is None or not uses_pool(account):
|
||||
return False
|
||||
proxy = getattr(client, "proxy", None)
|
||||
if not proxy or not is_proxy_failure(exc):
|
||||
return False
|
||||
mark_failed(account.employee_id, proxy, str(exc)[:200])
|
||||
retire_if_dead(account.employee_id, proxy, str(exc)[:200])
|
||||
return True
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,16 @@ _last_flush: dict[str, float] = {}
|
||||
|
||||
def attach_loop(loop: asyncio.AbstractEventLoop) -> None:
|
||||
global _loop
|
||||
if _loop is loop:
|
||||
return
|
||||
for handle in list(_pending.values()):
|
||||
handle.cancel()
|
||||
_pending.clear()
|
||||
_inflight.clear()
|
||||
_dirty.clear()
|
||||
_urgent.clear()
|
||||
_last_flush.clear()
|
||||
_clients.clear()
|
||||
_loop = loop
|
||||
|
||||
|
||||
|
||||
+28
-16
@@ -68,7 +68,7 @@ def _settings_body(**overrides) -> dict:
|
||||
return body
|
||||
|
||||
|
||||
def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
|
||||
def test_admin_login_succeeds_and_wrong_password_skips_euniv(monkeypatch) -> None:
|
||||
api = _app()
|
||||
calls = []
|
||||
|
||||
@@ -76,7 +76,7 @@ def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
|
||||
calls.append("euniv")
|
||||
raise AssertionError("不应走 e 学登录")
|
||||
|
||||
api.login_and_store = spy
|
||||
monkeypatch.setattr(api, "login_and_store", spy)
|
||||
statements = []
|
||||
|
||||
def hear(_connection, _cursor, statement, _parameters, _context, _executemany):
|
||||
@@ -134,12 +134,16 @@ def test_legacy_default_password_is_replaced_and_failures_are_limited() -> None:
|
||||
assert blocked.status_code == 429
|
||||
|
||||
|
||||
def test_admin_identity_uses_memory_until_reload() -> None:
|
||||
def test_admin_identity_uses_memory_until_reload(monkeypatch) -> None:
|
||||
api = _app()
|
||||
calls = []
|
||||
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or {
|
||||
"employee_id": employee_id
|
||||
}
|
||||
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
|
||||
@@ -198,7 +202,7 @@ def test_seed_does_not_reset_saved_admin() -> None:
|
||||
assert verify_password(row.admin_password_cipher, "next-secret")
|
||||
|
||||
|
||||
def test_login_config_changes_meaning_with_visibility() -> None:
|
||||
def test_login_config_changes_meaning_with_visibility(monkeypatch) -> None:
|
||||
api = _app()
|
||||
seen = {}
|
||||
|
||||
@@ -207,7 +211,7 @@ def test_login_config_changes_meaning_with_visibility() -> None:
|
||||
seen["attempts"] = auto_attempts
|
||||
return {"employee_id": employee_id}
|
||||
|
||||
api.login_and_store = spy
|
||||
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}
|
||||
@@ -447,7 +451,7 @@ def test_paused_account_still_updates_when_opening_home() -> None:
|
||||
assert json.loads(decrypt_secret(account.credential_cipher))["yxt_token"] == "yxt-2"
|
||||
|
||||
|
||||
def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
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)
|
||||
@@ -459,7 +463,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
calls.append(login_name)
|
||||
return _Alive(login_name, password)
|
||||
|
||||
users.build_client = factory
|
||||
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
|
||||
@@ -517,7 +521,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_check_all_reports_each_saved_account() -> None:
|
||||
def test_check_all_reports_each_saved_account(monkeypatch) -> None:
|
||||
import admin.users as users
|
||||
|
||||
_add_account("a-user")
|
||||
@@ -531,7 +535,7 @@ def test_check_all_reports_each_saved_account() -> None:
|
||||
raise RuntimeError("网络失败")
|
||||
return _Alive(login_name, password)
|
||||
|
||||
users.build_client = factory
|
||||
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
|
||||
@@ -550,10 +554,14 @@ def test_check_all_reports_each_saved_account() -> None:
|
||||
assert untouched is not None and untouched.last_refresh_at is None
|
||||
|
||||
|
||||
def test_credentials_and_delete_user() -> None:
|
||||
def test_credentials_and_delete_user(monkeypatch) -> None:
|
||||
import admin.users as users
|
||||
|
||||
users.build_client = lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学"))
|
||||
monkeypatch.setattr(
|
||||
users,
|
||||
"build_client",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学")),
|
||||
)
|
||||
_add_account("6650000146")
|
||||
_add_account("empty-user", credential=None)
|
||||
api = _app()
|
||||
@@ -604,9 +612,13 @@ def test_pause_only_changes_refresh_flag() -> None:
|
||||
assert row["has_credential"] is True
|
||||
|
||||
|
||||
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie() -> None:
|
||||
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie(monkeypatch) -> None:
|
||||
api = _app()
|
||||
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id}
|
||||
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")
|
||||
|
||||
+115
-51
@@ -109,7 +109,7 @@ class FakeClient:
|
||||
}
|
||||
|
||||
|
||||
def test_login_stores_password_and_credential_only() -> None:
|
||||
def test_login_stores_password_and_credential_only(monkeypatch) -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
@@ -119,11 +119,17 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
self._token = "yxt-2"
|
||||
return super().home_summary()
|
||||
|
||||
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,
|
||||
"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: service_module.fetch_home_summary(
|
||||
db, employee_id, RefreshingClient
|
||||
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"})
|
||||
@@ -177,14 +183,18 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
assert "测试用户" not in decrypt_secret(account.password_cipher)
|
||||
|
||||
|
||||
def test_qr_mark_cannot_password_login_and_unicode_password_is_safe() -> None:
|
||||
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
|
||||
|
||||
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,
|
||||
"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:
|
||||
@@ -206,7 +216,7 @@ def test_qr_mark_cannot_password_login_and_unicode_password_is_safe() -> None:
|
||||
assert second.status_code == 200
|
||||
|
||||
|
||||
def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
||||
def test_manual_jigsaw_keeps_image_pixels_and_retries(monkeypatch) -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
@@ -267,10 +277,14 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
||||
"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
|
||||
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
|
||||
),
|
||||
)
|
||||
api_module.submit_jigsaw = service_module.submit_jigsaw
|
||||
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
|
||||
@@ -295,7 +309,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
||||
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||
|
||||
|
||||
def test_browser_session_logout_and_revoke() -> None:
|
||||
def test_browser_session_logout_and_revoke(monkeypatch) -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
@@ -306,8 +320,12 @@ def test_browser_session_logout_and_revoke() -> None:
|
||||
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
|
||||
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"})
|
||||
@@ -342,12 +360,16 @@ def test_browser_session_logout_and_revoke() -> None:
|
||||
assert account.password_cipher == ""
|
||||
|
||||
|
||||
def test_logout_keeps_the_other_browser_until_revoke() -> None:
|
||||
def test_logout_keeps_the_other_browser_until_revoke(monkeypatch) -> 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
|
||||
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
|
||||
@@ -496,16 +518,20 @@ def test_exam_and_training_details() -> None:
|
||||
}
|
||||
|
||||
|
||||
def test_home_sections_are_separate() -> None:
|
||||
def test_home_sections_are_separate(monkeypatch) -> 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
|
||||
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
|
||||
),
|
||||
)
|
||||
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": "一门培训"}]}
|
||||
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
|
||||
@@ -535,12 +561,16 @@ def test_period_page_is_not_fetched_twice() -> None:
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
def test_user_can_set_proxy_with_or_without_password(monkeypatch) -> 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
|
||||
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
|
||||
@@ -585,12 +615,16 @@ def test_user_can_set_proxy_with_or_without_password() -> None:
|
||||
assert cleared.json()["scheme"] == "off"
|
||||
|
||||
|
||||
def test_user_can_set_course_workers() -> None:
|
||||
def test_user_can_set_course_workers(monkeypatch) -> 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
|
||||
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
|
||||
@@ -604,12 +638,16 @@ def test_user_can_set_course_workers() -> None:
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_user_can_set_monthly_study_start() -> None:
|
||||
def test_user_can_set_monthly_study_start(monkeypatch) -> 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
|
||||
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
|
||||
@@ -652,8 +690,12 @@ def test_user_can_start_and_stop_study_immediately(monkeypatch) -> 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
|
||||
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)
|
||||
@@ -679,12 +721,16 @@ def test_user_can_start_and_stop_study_immediately(monkeypatch) -> None:
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_study_control_stays_stopped_when_month_hours_met() -> None:
|
||||
def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> 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
|
||||
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
|
||||
@@ -706,8 +752,12 @@ def test_study_control_websocket_sends_snapshot(monkeypatch) -> None:
|
||||
import euniv.service as service_module
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
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,
|
||||
"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)
|
||||
@@ -730,15 +780,21 @@ def test_study_control_websocket_sends_snapshot(monkeypatch) -> None:
|
||||
assert pong["started"] is False
|
||||
|
||||
|
||||
def test_user_can_read_study_history() -> None:
|
||||
def test_user_can_read_study_history(monkeypatch) -> 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
|
||||
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
|
||||
),
|
||||
)
|
||||
api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history(
|
||||
db, employee_id, FakeClient
|
||||
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
|
||||
@@ -768,14 +824,22 @@ def test_home_and_history_hours_follow_source(monkeypatch) -> 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
|
||||
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
|
||||
),
|
||||
)
|
||||
api_module.fetch_home_summary = lambda db, employee_id: service_module.fetch_home_summary(
|
||||
db, employee_id, FakeClient
|
||||
monkeypatch.setattr(
|
||||
api_module,
|
||||
"fetch_home_summary",
|
||||
lambda db, employee_id: service_module.fetch_home_summary(db, employee_id, FakeClient),
|
||||
)
|
||||
api_module.fetch_study_history = lambda db, employee_id: service_module.fetch_study_history(
|
||||
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
|
||||
|
||||
@@ -209,6 +209,7 @@ def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None:
|
||||
def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None:
|
||||
saved: list[tuple[str, str]] = []
|
||||
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours)))
|
||||
monkeypatch.setattr("admin.settings.hours_source_of", lambda: "history")
|
||||
|
||||
class _HistorySession:
|
||||
async def month_history_minutes(self) -> int:
|
||||
@@ -219,7 +220,7 @@ def test_hours_watcher_history_source_uses_month_history(monkeypatch) -> None:
|
||||
|
||||
async def main() -> None:
|
||||
user_stop = asyncio.Event()
|
||||
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop, source="history")
|
||||
watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop)
|
||||
assert await watcher.refresh() is True
|
||||
assert watcher.reached
|
||||
assert saved == [("u1", "600")]
|
||||
|
||||
@@ -309,6 +309,9 @@ def test_admin_can_probe_one_and_all_proxies(monkeypatch) -> None:
|
||||
def test_is_proxy_failure_detects_connect_errors() -> None:
|
||||
assert is_proxy_failure(httpx.ConnectError("boom"))
|
||||
assert is_proxy_failure(httpx.ConnectTimeout("late"))
|
||||
assert is_proxy_failure(httpx.ReadTimeout("slow"))
|
||||
assert is_proxy_failure(httpx.ReadError("reset"))
|
||||
assert is_proxy_failure(httpx.RemoteProtocolError("bad"))
|
||||
assert not is_proxy_failure(RuntimeError("登录需要重新验证"))
|
||||
|
||||
|
||||
@@ -343,7 +346,7 @@ def test_admin_proxy_page_and_pool_assignment() -> None:
|
||||
assert detail.json()["enabled"] is True
|
||||
|
||||
|
||||
def test_user_can_enable_pool_proxy() -> None:
|
||||
def test_user_can_enable_pool_proxy(monkeypatch) -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
@@ -386,8 +389,12 @@ def test_user_can_enable_pool_proxy() -> None:
|
||||
def credential_alive(self) -> bool:
|
||||
return True
|
||||
|
||||
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,
|
||||
"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
|
||||
|
||||
Reference in New Issue
Block a user