feat: 按账号调度自动学习并让首页实时跟上状态
This commit is contained in:
@@ -226,6 +226,17 @@ def test_settings_reject_interval_and_attempts_outside_range() -> None:
|
||||
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:
|
||||
@@ -453,6 +464,7 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
|
||||
"study_start_hour",
|
||||
"study_start_minute",
|
||||
"study_start_second",
|
||||
"study_schedule_enabled",
|
||||
"course_workers",
|
||||
"study_paused",
|
||||
"study_ignore_window",
|
||||
|
||||
+154
-2
@@ -75,6 +75,20 @@ class FakeClient:
|
||||
}
|
||||
]
|
||||
|
||||
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"
|
||||
@@ -121,6 +135,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"last_refresh_at",
|
||||
"credential_valid",
|
||||
"month_hours",
|
||||
"hours_month",
|
||||
"monthly_target",
|
||||
"proxy_scheme",
|
||||
"proxy_host",
|
||||
@@ -134,7 +149,9 @@ def test_login_stores_password_and_credential_only() -> None:
|
||||
"course_workers",
|
||||
"use_proxy_pool",
|
||||
"study_paused",
|
||||
"study_stop_month",
|
||||
"study_ignore_window",
|
||||
"study_schedule_enabled",
|
||||
}
|
||||
|
||||
home = client.get("/api/home")
|
||||
@@ -542,10 +559,20 @@ def test_user_can_set_monthly_study_start() -> None:
|
||||
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": 1, "hour": 0, "minute": 0, "second": 0, "label": "每月1日 00:00:00"}
|
||||
saved = client.put("/api/settings/study-start", json={"day": 5, "hour": 16, "minute": 0, "second": 7})
|
||||
assert empty.json() == {
|
||||
"day": 1,
|
||||
"hour": 0,
|
||||
"minute": 0,
|
||||
"second": 0,
|
||||
"enabled": True,
|
||||
"label": "每月1日 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": 32, "hour": 16, "minute": 0, "second": 0})
|
||||
assert bad.status_code == 400
|
||||
|
||||
@@ -563,11 +590,13 @@ def test_user_can_start_and_stop_study_immediately() -> None:
|
||||
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
|
||||
@@ -578,6 +607,56 @@ def test_user_can_start_and_stop_study_immediately() -> None:
|
||||
assert bad.status_code == 400
|
||||
|
||||
|
||||
def test_study_control_stays_stopped_when_month_hours_met() -> 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
|
||||
)
|
||||
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() -> None:
|
||||
import euniv.api as api_module
|
||||
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
|
||||
)
|
||||
client = TestClient(api_module.app)
|
||||
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": 31, "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() -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
@@ -596,6 +675,79 @@ def test_user_can_read_study_history() -> None:
|
||||
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() -> None:
|
||||
import euniv.api as api_module
|
||||
import euniv.service as service_module
|
||||
|
||||
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
|
||||
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
|
||||
)
|
||||
api_module.fetch_home_summary = lambda db, employee_id: 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
|
||||
)
|
||||
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:
|
||||
|
||||
@@ -1,25 +1,60 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from euniv.autostudy import (
|
||||
CourseCursor,
|
||||
HoursWatcher,
|
||||
StudySession,
|
||||
_HOURS_REFRESH_SECONDS,
|
||||
_clear_user_status,
|
||||
_completed,
|
||||
_count_total,
|
||||
_finish_user,
|
||||
_interval_plan,
|
||||
_jitter,
|
||||
_job_from_account,
|
||||
snapshot_courses,
|
||||
_package_chapter_path,
|
||||
_parse_minutes,
|
||||
_play_path,
|
||||
_set_user_status,
|
||||
_set_worker_status,
|
||||
_study_document,
|
||||
_study_video,
|
||||
autostudy_status,
|
||||
wait_stop,
|
||||
)
|
||||
from euniv.client import accumulate_month_minutes, fold_month_minutes
|
||||
from euniv.client import (
|
||||
accumulate_month_minutes,
|
||||
as_uuid,
|
||||
fold_month_minutes,
|
||||
history_hour_totals,
|
||||
play_page_params,
|
||||
study_progress_fields,
|
||||
)
|
||||
from euniv.course_workers import CourseWorkersError, of as workers_of, validate as validate_workers
|
||||
from euniv.proxy import ProxyError, apply as apply_proxy, build_proxy_url, parse_proxy, view_of as proxy_view
|
||||
from euniv.study_control import eligible as study_eligible, start_now, stop_now
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
|
||||
from euniv.proxy import (
|
||||
ProxyError,
|
||||
apply as apply_proxy,
|
||||
build_proxy_url,
|
||||
client_proxy_args,
|
||||
parse_proxy,
|
||||
sync_httpx_client,
|
||||
view_of as proxy_view,
|
||||
)
|
||||
from euniv.study_control import (
|
||||
assemble,
|
||||
eligible as study_eligible,
|
||||
hours_met,
|
||||
start_now,
|
||||
stop_now,
|
||||
view_of as study_view,
|
||||
)
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, next_fire_at, validate_start, window_open
|
||||
|
||||
|
||||
def test_parse_proxy_accepts_http_and_socks() -> None:
|
||||
@@ -50,6 +85,23 @@ def test_parse_proxy_rejects_other_schemes() -> None:
|
||||
parse_proxy("http://")
|
||||
|
||||
|
||||
def test_socks4_uses_socks_transport_instead_of_httpx_proxy() -> None:
|
||||
from httpx_socks import AsyncProxyTransport, SyncProxyTransport
|
||||
|
||||
http_args = client_proxy_args("http://10.0.0.1:8080")
|
||||
assert http_args == {"proxy": "http://10.0.0.1:8080"}
|
||||
socks_args = client_proxy_args("socks4://127.0.0.1:1080")
|
||||
assert "proxy" not in socks_args
|
||||
assert isinstance(socks_args["transport"], SyncProxyTransport)
|
||||
with pytest.raises(ValueError, match="Unknown scheme"):
|
||||
httpx.Client(proxy="socks4://127.0.0.1:1080", timeout=1)
|
||||
client = sync_httpx_client("socks4://127.0.0.1:1080", timeout=1)
|
||||
client.close()
|
||||
async_args = client_proxy_args("socks5://127.0.0.1:1080", asynchronous=True)
|
||||
assert isinstance(async_args["transport"], AsyncProxyTransport)
|
||||
assert "proxy" not in async_args
|
||||
|
||||
|
||||
def test_parse_minutes() -> None:
|
||||
assert _parse_minutes("") == 0
|
||||
assert _parse_minutes("600") == 600
|
||||
@@ -62,10 +114,59 @@ def test_wait_stop_timeout_and_event() -> None:
|
||||
assert await wait_stop(0.05, event) is False
|
||||
event.set()
|
||||
assert await wait_stop(1, event) is True
|
||||
event.clear()
|
||||
assert await wait_stop(0, event) is False
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
def test_jitter_zero_means_no_wait() -> None:
|
||||
assert _jitter(0) == 0
|
||||
assert _jitter(-1) == 0
|
||||
for _ in range(30):
|
||||
wait = _jitter(1)
|
||||
assert 0 <= wait < 5
|
||||
assert abs(wait - 1) <= 0.3
|
||||
for _ in range(30):
|
||||
wait = _jitter(10)
|
||||
assert 7 <= wait <= 13
|
||||
|
||||
|
||||
def test_count_total_estimates_from_progress() -> None:
|
||||
assert _count_total(0, 10) == 0
|
||||
assert _count_total(1, 0) == 0
|
||||
assert _count_total(2, 100) == 2
|
||||
assert _count_total(1, 10) == 10
|
||||
assert _count_total(3, 40) == 8
|
||||
assert _count_total(1, 39, origin=38) == 62
|
||||
|
||||
|
||||
def test_worker_view_freezes_total_after_first_beat() -> None:
|
||||
from euniv.autostudy import WorkerView, _clear_user_status
|
||||
|
||||
_clear_user_status("u-total")
|
||||
view = WorkerView("u-total", 1)
|
||||
view.update(course="甲", progress=38)
|
||||
view.after_beat(39, ok=True)
|
||||
first = autostudy_status()["users"]["u-total"]["workers"][0]["total"]
|
||||
assert first == 62
|
||||
view.after_beat(50, ok=True)
|
||||
row = autostudy_status()["users"]["u-total"]["workers"][0]
|
||||
assert row["sent"] == 2
|
||||
assert row["total"] == 62
|
||||
view.after_beat(100, ok=True)
|
||||
row = autostudy_status()["users"]["u-total"]["workers"][0]
|
||||
assert row["sent"] == 3
|
||||
assert row["total"] == 3
|
||||
_clear_user_status("u-total")
|
||||
|
||||
|
||||
def test_hours_watcher_default_interval_is_one_minute() -> None:
|
||||
watcher = HoursWatcher(_HourSession("0"), "u1", 600, asyncio.Event())
|
||||
assert _HOURS_REFRESH_SECONDS == 60
|
||||
assert watcher.interval == 60
|
||||
|
||||
|
||||
class _HourSession:
|
||||
def __init__(self, hours: str) -> None:
|
||||
self.hours = hours
|
||||
@@ -144,6 +245,18 @@ def test_accumulate_month_minutes_stops_at_previous_month() -> None:
|
||||
assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == 8
|
||||
|
||||
|
||||
def test_history_hour_totals_splits_year_month_today() -> None:
|
||||
now = datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ)
|
||||
items = [
|
||||
{"minutes": 10, "studied_at": "2026-11-15 09:00"},
|
||||
{"minutes": 4, "studied_at": "2026-11-14 23:55"},
|
||||
{"minutes": 8, "studied_at": "2025-12-01 00:00"},
|
||||
{"minutes": None, "studied_at": "2026-11-15 10:00"},
|
||||
{"minutes": 2, "studied_at": ""},
|
||||
]
|
||||
assert history_hour_totals(items, now) == {"year": 14, "month": 14, "today": 10, "total": 22}
|
||||
|
||||
|
||||
def test_autostudy_status_lists_workers_in_id_order() -> None:
|
||||
_clear_user_status("u1")
|
||||
_set_user_status("u1", state="学习中")
|
||||
@@ -249,7 +362,22 @@ class _Start:
|
||||
self.study_start_minute = minute
|
||||
self.study_start_second = second
|
||||
self.study_paused = False
|
||||
self.study_stop_month = ""
|
||||
self.study_ignore_window = False
|
||||
self.study_schedule_enabled = True
|
||||
self.monthly_target = 600
|
||||
self.month_hours = ""
|
||||
self.hours_month = ""
|
||||
|
||||
|
||||
def test_next_fire_at_this_month_then_next_month() -> None:
|
||||
account = _Start(5, 16, 0, 0)
|
||||
before = datetime(2026, 11, 5, 15, 59, 59, tzinfo=CN_TZ)
|
||||
assert next_fire_at(account, before) == datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)
|
||||
at = datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)
|
||||
assert next_fire_at(account, at) == datetime(2026, 12, 5, 16, 0, 0, tzinfo=CN_TZ)
|
||||
account.study_schedule_enabled = False
|
||||
assert next_fire_at(account, before) is None
|
||||
|
||||
|
||||
def test_study_window_opens_after_configured_time() -> None:
|
||||
@@ -273,10 +401,182 @@ def test_immediate_start_skips_monthly_window() -> None:
|
||||
assert account.study_paused is False
|
||||
assert account.study_ignore_window is True
|
||||
assert study_eligible(account) is True
|
||||
stop_now(account)
|
||||
stop_now(account, datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ))
|
||||
assert account.study_paused is True
|
||||
assert account.study_stop_month == "2026-11"
|
||||
assert account.study_ignore_window is False
|
||||
assert study_eligible(account, datetime(2026, 11, 15, 13, 0, tzinfo=CN_TZ)) is False
|
||||
|
||||
|
||||
def test_hours_met_clears_started_without_pause() -> None:
|
||||
account = _Start(1, 0, 0, 0)
|
||||
start_now(account)
|
||||
account.monthly_target = 70
|
||||
account.month_hours = "78"
|
||||
assert hours_met(account) is True
|
||||
assert study_eligible(account) is False
|
||||
view = study_view(account)
|
||||
assert view["started"] is False
|
||||
assert view["hours_met"] is True
|
||||
assert account.study_paused is False
|
||||
idle = assemble(account, {})
|
||||
assert idle["started"] is False
|
||||
assert idle["active"] is False
|
||||
live = assemble(account, {"state": "学习中", "workers": [{"id": 1, "course": "A"}]})
|
||||
assert live["started"] is False
|
||||
assert live["active"] is False
|
||||
from euniv.study_control import settle
|
||||
assert settle(account, {}) is True
|
||||
assert account.study_ignore_window is False
|
||||
assert settle(account, {}) is False
|
||||
|
||||
|
||||
def test_stop_this_month_does_not_block_next_month_schedule() -> None:
|
||||
account = _Start(1, 0, 0, 0)
|
||||
start_now(account)
|
||||
stop_now(account, datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ))
|
||||
assert study_eligible(account, datetime(2026, 11, 20, 8, 0, tzinfo=CN_TZ)) is False
|
||||
assert study_view(account, datetime(2026, 12, 1, 0, 0, tzinfo=CN_TZ))["paused"] is False
|
||||
assert study_eligible(account, datetime(2026, 12, 1, 0, 0, tzinfo=CN_TZ)) is True
|
||||
|
||||
|
||||
def test_stale_month_hours_do_not_block_next_month() -> None:
|
||||
account = _Start(1, 0, 0, 0)
|
||||
account.monthly_target = 70
|
||||
account.month_hours = "78"
|
||||
account.hours_month = "2026-11"
|
||||
assert hours_met(account, datetime(2026, 11, 20, tzinfo=CN_TZ)) is True
|
||||
assert hours_met(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is False
|
||||
assert study_eligible(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is True
|
||||
|
||||
|
||||
def test_work_running_is_wanted_or_studying() -> None:
|
||||
from euniv.autostudy import drop_work, want_work, work_running
|
||||
|
||||
drop_work("u-want")
|
||||
assert work_running("u-want") is False
|
||||
want_work("u-want")
|
||||
assert work_running("u-want") is True
|
||||
account = _Start(31, 23, 59, 59)
|
||||
account.employee_id = "u-want"
|
||||
payload = assemble(account, {})
|
||||
assert payload["started"] is True
|
||||
assert payload["month_hours"] == ""
|
||||
assert payload["monthly_target"] == 600
|
||||
drop_work("u-want")
|
||||
assert assemble(account, {})["started"] is False
|
||||
|
||||
|
||||
def test_want_and_drop_work_push_home(monkeypatch) -> None:
|
||||
seen: list[str | None] = []
|
||||
monkeypatch.setattr("euniv.study_push.notify", lambda eid=None, urgent=False: seen.append(eid))
|
||||
from euniv.autostudy import drop_work, want_work
|
||||
|
||||
want_work("u-push")
|
||||
drop_work("u-push")
|
||||
assert seen == ["u-push", "u-push"]
|
||||
|
||||
|
||||
def test_interval_plan_manual_one_second_uses_admin_wait() -> None:
|
||||
wait, step, page = _interval_plan(
|
||||
"video", {"video": 1, "document": 1, "scorm": 1}, False, {"submitProTimes": 30, "pageSize": 1},
|
||||
)
|
||||
assert wait == 1
|
||||
assert step == 1
|
||||
assert page == 1
|
||||
|
||||
|
||||
def test_assemble_prefers_live_month_hours() -> None:
|
||||
account = _Start(1, 0, 0, 0)
|
||||
account.month_hours = "10"
|
||||
assert assemble(account, {"month_hours": "68"})["month_hours"] == "68"
|
||||
assert assemble(account, {})["month_hours"] == "10"
|
||||
|
||||
|
||||
def test_schedule_disabled_skips_window_until_started() -> None:
|
||||
account = _Start(1, 0, 0, 0)
|
||||
account.study_schedule_enabled = False
|
||||
assert study_eligible(account, datetime(2026, 11, 15, tzinfo=CN_TZ)) is False
|
||||
start_now(account)
|
||||
assert study_eligible(account, datetime(2026, 11, 15, tzinfo=CN_TZ)) is True
|
||||
|
||||
|
||||
def test_job_from_account_is_collected_when_credentials_ok() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
import euniv.crypto as crypto
|
||||
|
||||
row = SimpleNamespace(
|
||||
employee_id="u1",
|
||||
monthly_target=600,
|
||||
password_cipher="pw",
|
||||
credential_cipher='{"token":"x"}',
|
||||
course_workers=2,
|
||||
use_proxy_pool=False,
|
||||
proxy_scheme="",
|
||||
proxy_host="",
|
||||
proxy_port=None,
|
||||
proxy_username="",
|
||||
proxy_password_cipher="",
|
||||
)
|
||||
original = crypto.decrypt_secret
|
||||
crypto.decrypt_secret = lambda value: value
|
||||
try:
|
||||
job = _job_from_account(row)
|
||||
finally:
|
||||
crypto.decrypt_secret = original
|
||||
assert job is not None
|
||||
assert job[0] == "u1"
|
||||
assert job[1] == 600
|
||||
assert job[2] == "pw"
|
||||
assert job[3] == {"token": "x"}
|
||||
assert job[5] == 2
|
||||
assert job[6] is False
|
||||
|
||||
|
||||
def test_job_from_account_skips_when_decrypt_fails() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
import euniv.crypto as crypto
|
||||
|
||||
row = SimpleNamespace(
|
||||
employee_id="u-fail",
|
||||
monthly_target=600,
|
||||
password_cipher="pw",
|
||||
credential_cipher="bad",
|
||||
course_workers=1,
|
||||
use_proxy_pool=False,
|
||||
proxy_scheme="",
|
||||
proxy_host="",
|
||||
proxy_port=None,
|
||||
proxy_username="",
|
||||
proxy_password_cipher="",
|
||||
)
|
||||
original = crypto.decrypt_secret
|
||||
|
||||
def boom(_value: str) -> str:
|
||||
raise ValueError("bad")
|
||||
|
||||
crypto.decrypt_secret = boom
|
||||
try:
|
||||
assert _job_from_account(row) is None
|
||||
assert autostudy_status()["users"]["u-fail"]["state"] == "学习失败"
|
||||
finally:
|
||||
crypto.decrypt_secret = original
|
||||
_clear_user_status("u-fail")
|
||||
|
||||
|
||||
def test_finish_user_keeps_failure_and_clears_idle() -> None:
|
||||
_clear_user_status("u1")
|
||||
_set_user_status("u1", state="会话失效")
|
||||
_finish_user("u1")
|
||||
assert autostudy_status()["users"]["u1"]["state"] == "会话失效"
|
||||
_set_user_status("u1", state="学习中")
|
||||
_finish_user("u1")
|
||||
assert "u1" not in autostudy_status()["users"]
|
||||
_finish_user("u2", RuntimeError("boom"))
|
||||
assert autostudy_status()["users"]["u2"]["state"] == "学习失败"
|
||||
_clear_user_status("u2")
|
||||
|
||||
|
||||
def test_study_window_rejects_invalid_parts() -> None:
|
||||
@@ -298,6 +598,25 @@ def test_course_workers_default_and_range() -> None:
|
||||
validate_workers(9)
|
||||
|
||||
|
||||
def test_course_snapshot_orders_video_document_package_scorm() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
rows = [
|
||||
SimpleNamespace(path="/c", title="Z课", kind="课程"),
|
||||
SimpleNamespace(path="/a2", title="乙视频", kind="视频"),
|
||||
SimpleNamespace(path="/a1", title="甲视频", kind="视频"),
|
||||
SimpleNamespace(path="/e", title="音频", kind="音频"),
|
||||
SimpleNamespace(path="/d", title="包", kind="课程包"),
|
||||
SimpleNamespace(path="/b", title="文档", kind="文档"),
|
||||
]
|
||||
snapshot = snapshot_courses(rows)
|
||||
assert [item[2] for item in snapshot] == ["视频", "视频", "文档", "课程包", "课程", "音频"]
|
||||
assert [item[1] for item in snapshot[:2]] == ["乙视频", "甲视频"]
|
||||
copied = snapshot_courses([("p", "课", "课程"), ("v", "视", "视频")])
|
||||
assert copied[0][2] == "视频"
|
||||
assert copied[1][2] == "课程"
|
||||
|
||||
|
||||
def test_course_cursor_hands_each_item_once() -> None:
|
||||
async def main() -> None:
|
||||
cursor = CourseCursor([("a", "A", "视频"), ("b", "B", "文档"), ("c", "C", "课程")])
|
||||
@@ -347,3 +666,185 @@ def test_proxy_pool_scheme_enables_auto() -> None:
|
||||
apply_proxy(account, "http", "10.0.0.1", 8080)
|
||||
assert account.use_proxy_pool is False
|
||||
assert proxy_view(account)["scheme"] == "http"
|
||||
|
||||
|
||||
DASHED_KID = "6970e77d-08b3-4c2a-91e8-8471089f4e73"
|
||||
COMPACT_KID = "6970e77d08b34c2a91e88471089f4e73"
|
||||
DASHED_PKG = "00689cb9-1111-4c2a-91e8-8471089f4e73"
|
||||
COMPACT_PKG = "00689cb911114c2a91e88471089f4e73"
|
||||
|
||||
|
||||
def test_as_uuid_matches_capture_dashed_ids() -> None:
|
||||
assert as_uuid(COMPACT_KID) == DASHED_KID
|
||||
assert as_uuid(DASHED_KID) == DASHED_KID
|
||||
assert as_uuid("") == ""
|
||||
|
||||
|
||||
def test_study_progress_fields_match_capture_body() -> None:
|
||||
video = study_progress_fields(COMPACT_KID, "", page_size=1, study_time=30, kind=0, view_schedule=30)
|
||||
assert video["knowledgeId"] == DASHED_KID
|
||||
assert video["packageId"] == ""
|
||||
assert video["type"] == 0
|
||||
assert video["studyTime"] == 30
|
||||
assert video["end"] is False
|
||||
packed = study_progress_fields(COMPACT_KID, COMPACT_PKG, page_size=69, study_time=120, kind=1, view_schedule=1)
|
||||
assert packed["packageId"] == DASHED_PKG
|
||||
assert packed["pageSize"] == packed["studySize"] == 69
|
||||
encrypt = study_progress_fields(
|
||||
COMPACT_KID, "", page_size=-1, study_time=120, kind=2, end=True,
|
||||
chapter_id=COMPACT_KID, for_encrypt=True,
|
||||
)
|
||||
submit = study_progress_fields(
|
||||
COMPACT_KID, "", page_size=-1, study_time=120, kind=2, end=True, chapter_id=COMPACT_KID,
|
||||
)
|
||||
assert encrypt["studyChapterIds"] == DASHED_KID + ";"
|
||||
assert submit["studyChapterIds"] == DASHED_KID
|
||||
|
||||
|
||||
def test_play_page_params_reads_document_page_count() -> None:
|
||||
html = (
|
||||
'var knowledgeType = "DocumentKnowledge";\n'
|
||||
"var pageSize = 69;\n"
|
||||
"var submitProTimes = 30;\n"
|
||||
"var validtimeSpan = 120;\n"
|
||||
f'var kngId = "{DASHED_KID}";\n'
|
||||
)
|
||||
params = play_page_params(html)
|
||||
assert params["pageSize"] == 69
|
||||
assert params["submitProTimes"] == 30
|
||||
assert params["kngId"] == DASHED_KID
|
||||
|
||||
|
||||
def test_play_path_uses_compact_html_id() -> None:
|
||||
assert _play_path("视频", "/knowledge/video/x.html", DASHED_KID) == f"/kng/view/video/{COMPACT_KID}.html"
|
||||
assert _play_path("课程包", "/kng/view/package/x.html", COMPACT_PKG) == f"/kng/view/package/{COMPACT_PKG}.html"
|
||||
assert _package_chapter_path(DASHED_PKG, DASHED_KID, "document") == (
|
||||
f"/kng/course/package/document/{COMPACT_PKG}_{COMPACT_KID}.html"
|
||||
)
|
||||
|
||||
|
||||
def test_completed_uses_progress_or_status() -> None:
|
||||
assert _completed({"studyschedule": 100, "status": "NoStart"}) is True
|
||||
assert _completed({"studyschedule": 0, "status": "Completed"}) is True
|
||||
assert _completed({"studyschedule": 8, "status": "Studying"}) is False
|
||||
assert _completed({"studySchedule": 100}) is True
|
||||
|
||||
|
||||
def test_interval_zero_keeps_payload_time_from_play_page() -> None:
|
||||
wait, step, page = _interval_plan("video", {"video": 0}, False, {"submitProTimes": 30, "pageSize": 1})
|
||||
assert wait == 0
|
||||
assert step == 30
|
||||
wait, step, page = _interval_plan(
|
||||
"document", {"document": 10}, True, {"validtimeSpan": 120, "pageSize": 79},
|
||||
)
|
||||
assert wait == 120
|
||||
assert step == 120
|
||||
assert page == 79
|
||||
|
||||
|
||||
def test_study_session_sends_dashed_ids_to_progress_and_heartbeat() -> None:
|
||||
async def main() -> None:
|
||||
session = StudySession.__new__(StudySession)
|
||||
seen: dict = {}
|
||||
|
||||
async def fake_api(_method: str, url: str, **kw: object):
|
||||
seen["url"] = url
|
||||
if "content" in kw:
|
||||
seen["body"] = json.loads(str(kw["content"]))
|
||||
else:
|
||||
seen["json"] = kw.get("json")
|
||||
|
||||
class Resp:
|
||||
text = '{"studySchedule":1.61}'
|
||||
|
||||
def json(self) -> dict:
|
||||
return {"studySchedule": 1.61, "studyschedule": 0, "status": "NoStart"}
|
||||
|
||||
return Resp()
|
||||
|
||||
async def fake_encrypt(body_json: str) -> str:
|
||||
seen["encrypt"] = json.loads(body_json)
|
||||
return "deadbeef"
|
||||
|
||||
session._api = fake_api
|
||||
session.get_encrypt_request = fake_encrypt
|
||||
await session.update_progress(COMPACT_KID, "")
|
||||
assert seen["json"]["knowledgeId"] == DASHED_KID
|
||||
assert seen["json"]["packageId"] == ""
|
||||
await session.submit_video_heartbeat(COMPACT_KID, COMPACT_PKG, 30, 30)
|
||||
assert seen["encrypt"]["knowledgeId"] == DASHED_KID
|
||||
assert seen["encrypt"]["packageId"] == DASHED_PKG
|
||||
assert "encryption" not in seen["encrypt"]
|
||||
assert seen["body"]["encryption"] == "deadbeef"
|
||||
assert seen["body"]["realHour"] == 30
|
||||
assert seen["url"].endswith("/v1/study/submitpro")
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
class _CaptureVideo:
|
||||
def __init__(self) -> None:
|
||||
self.heartbeats: list[tuple[int, int]] = []
|
||||
self.progress_calls = 0
|
||||
|
||||
async def update_progress(self, _kid: str, _pkg: str) -> dict:
|
||||
self.progress_calls += 1
|
||||
if self.progress_calls == 1:
|
||||
return {"studyschedule": 0, "viewSchedule": 0, "status": "NoStart"}
|
||||
return {"studyschedule": 100, "viewSchedule": 30, "status": "Completed"}
|
||||
|
||||
async def submit_video_heartbeat(self, _kid: str, _pkg: str, study_time: int, view: int) -> dict:
|
||||
self.heartbeats.append((study_time, view))
|
||||
return {"studySchedule": 100}
|
||||
|
||||
async def month_hours_text(self) -> str:
|
||||
return "10"
|
||||
|
||||
|
||||
def test_video_interval_zero_still_sends_study_time(monkeypatch) -> None:
|
||||
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
|
||||
|
||||
async def main() -> None:
|
||||
session = _CaptureVideo()
|
||||
global_stop = asyncio.Event()
|
||||
user_stop = asyncio.Event()
|
||||
watcher = HoursWatcher(session, "u1", 600, user_stop)
|
||||
await _study_video(session, "kid", "", 0, global_stop, watcher, study_time=30)
|
||||
assert session.heartbeats == [(30, 30)]
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
class _CaptureDocument:
|
||||
def __init__(self) -> None:
|
||||
self.submits: list[tuple[int, int, int]] = []
|
||||
self.progress_calls = 0
|
||||
|
||||
async def update_progress(self, _kid: str, _pkg: str) -> dict:
|
||||
self.progress_calls += 1
|
||||
if self.progress_calls == 1:
|
||||
return {"studyschedule": 0, "status": "NoStart", "viewSchedule": 1}
|
||||
return {"studyschedule": 100, "status": "Completed", "viewSchedule": 1}
|
||||
|
||||
async def submit_document_heartbeat(
|
||||
self, _kid: str, _pkg: str, page_size: int, study_time: int, view: int
|
||||
) -> None:
|
||||
self.submits.append((page_size, study_time, view))
|
||||
|
||||
async def month_hours_text(self) -> str:
|
||||
return "10"
|
||||
|
||||
|
||||
def test_document_uses_page_size_and_requeries_after_submit(monkeypatch) -> None:
|
||||
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
|
||||
|
||||
async def main() -> None:
|
||||
session = _CaptureDocument()
|
||||
global_stop = asyncio.Event()
|
||||
user_stop = asyncio.Event()
|
||||
watcher = HoursWatcher(session, "u1", 600, user_stop)
|
||||
await _study_document(session, "kid", "", 69, 0, global_stop, watcher, study_time=120)
|
||||
assert session.submits == [(69, 120, 1)]
|
||||
assert session.progress_calls == 2
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
@@ -196,7 +196,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None:
|
||||
status_code = 200
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **_kwargs) -> None:
|
||||
def __init__(self, *_args, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def __enter__(self):
|
||||
@@ -210,7 +210,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None:
|
||||
return FakeResponse()
|
||||
|
||||
ticks = iter([0.0, 0.12, 0.12, 0.34, 0.34, 0.64])
|
||||
monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient)
|
||||
monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient)
|
||||
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
|
||||
ok, latency, reason = probe("http", "10.0.0.9", 8080)
|
||||
assert seen == list(PROBE_URLS)
|
||||
@@ -221,7 +221,7 @@ def test_probe_averages_euniv_related_sites(monkeypatch) -> None:
|
||||
|
||||
def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None:
|
||||
class FakeClient:
|
||||
def __init__(self, **_kwargs) -> None:
|
||||
def __init__(self, *_args, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def __enter__(self):
|
||||
@@ -234,7 +234,7 @@ def test_probe_instant_connect_error_keeps_elapsed_latency(monkeypatch) -> None:
|
||||
raise httpx.ConnectError("boom")
|
||||
|
||||
ticks = iter([0.0, 0.012, 0.012, 0.018, 0.018, 0.025])
|
||||
monkeypatch.setattr("euniv.proxy_pool.httpx.Client", FakeClient)
|
||||
monkeypatch.setattr("euniv.proxy_pool.sync_httpx_client", FakeClient)
|
||||
monkeypatch.setattr("euniv.proxy_pool.time.perf_counter", lambda: next(ticks))
|
||||
ok, latency, reason = probe("socks4", "10.0.0.9", 1080)
|
||||
assert ok is False
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""与 web/src/shared/studyFields.ts 的 studyPollSeconds 保持一致。"""
|
||||
|
||||
|
||||
def study_poll_seconds(intervals: list[int]) -> int:
|
||||
if any(value <= 0 for value in intervals):
|
||||
return 10
|
||||
positive = [value for value in intervals if value > 0]
|
||||
if not positive:
|
||||
return 10
|
||||
return max(10, min(positive))
|
||||
|
||||
|
||||
def test_study_poll_seconds_floor_and_zero() -> None:
|
||||
assert study_poll_seconds([]) == 10
|
||||
assert study_poll_seconds([0]) == 10
|
||||
assert study_poll_seconds([0, 30]) == 10
|
||||
assert study_poll_seconds([5]) == 10
|
||||
assert study_poll_seconds([30]) == 30
|
||||
assert study_poll_seconds([30, 120]) == 30
|
||||
@@ -0,0 +1,48 @@
|
||||
import asyncio
|
||||
|
||||
from starlette.websockets import WebSocketState
|
||||
|
||||
import euniv.study_push as study_push
|
||||
|
||||
|
||||
class _Socket:
|
||||
client_state = WebSocketState.CONNECTED
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.payloads: list[dict] = []
|
||||
|
||||
async def send_json(self, payload: dict) -> None:
|
||||
self.payloads.append(payload)
|
||||
|
||||
|
||||
def test_study_push_throttles_and_only_sends_latest(monkeypatch) -> None:
|
||||
socket = _Socket()
|
||||
monkeypatch.setattr("euniv.study_control.payload_for", lambda eid: {"eid": eid, "n": len(socket.payloads)})
|
||||
|
||||
async def main() -> None:
|
||||
study_push._pending.clear()
|
||||
study_push._inflight.clear()
|
||||
study_push._dirty.clear()
|
||||
study_push._urgent.clear()
|
||||
study_push._last_flush.clear()
|
||||
study_push._latest.clear()
|
||||
study_push._clients.clear()
|
||||
study_push.attach_loop(asyncio.get_running_loop())
|
||||
study_push.register("u1", socket)
|
||||
try:
|
||||
study_push.notify("u1")
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(socket.payloads) == 1
|
||||
study_push.notify("u1")
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(socket.payloads) == 1
|
||||
study_push.notify("u1", urgent=True)
|
||||
await asyncio.sleep(0.05)
|
||||
assert len(socket.payloads) == 2
|
||||
assert study_push.latest_of("u1") == socket.payloads[-1]
|
||||
finally:
|
||||
for handle in list(study_push._pending.values()):
|
||||
handle.cancel()
|
||||
study_push.unregister("u1", socket)
|
||||
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user