feat: 每门课用独立会话学习,间隔改动即时生效,间隔为 0 时不显示倒计时

This commit is contained in:
2026-11-17 17:06:19 +08:00
parent e98cc13061
commit 42b29fb4d6
6 changed files with 424 additions and 53 deletions
+1
View File
@@ -49,6 +49,7 @@ def fresh_database():
autostudy_mod._retry_count.clear()
autostudy_mod._done_month.clear()
autostudy_mod._targets.clear()
autostudy_mod._paces.clear()
autostudy_mod._user_halts.clear()
users = autostudy_mod._status.get("users")
if isinstance(users, dict):
+35
View File
@@ -694,6 +694,9 @@ def test_heartbeat_interval_belongs_to_the_user(monkeypatch) -> None:
assert omitted.json()["heartbeat_video_seconds"] == 1
current = client.get("/api/settings/heartbeat")
assert current.json()["heartbeat_mode"] == "manual"
from euniv.autostudy import _pace_of
assert _pace_of("6650000146") == ({"video": 1, "document": 2, "scorm": 3}, False)
intervals, auto = _current_intervals("6650000146")
assert auto is False
assert intervals == {"video": 1, "document": 2, "scorm": 3}
@@ -882,6 +885,38 @@ def test_start_saves_the_settings_sent_with_it(monkeypatch) -> None:
assert work_running("6650000146") is False
def test_changing_the_course_count_restarts_a_running_study(monkeypatch) -> None:
import euniv.api as api_module
import euniv.autostudy as autostudy_module
import euniv.service as service_module
monkeypatch.setattr(
api_module,
"login_and_store",
lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
),
)
restarted: list[str] = []
original = autostudy_module.restart_work
def record(employee_id: str) -> None:
restarted.append(employee_id)
original(employee_id)
monkeypatch.setattr(autostudy_module, "restart_work", record)
client = TestClient(api_module.app)
_freeze_beijing(monkeypatch, 2026, 11, 15)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
started = client.post("/api/settings/study-control", json={"action": "start", "settings": _study_body(workers=2)})
assert started.status_code == 200
assert client.put("/api/settings/study", json=_study_body(workers=2, monthly_target=700)).status_code == 200
assert restarted == []
assert client.put("/api/settings/study", json=_study_body(workers=3, monthly_target=700)).status_code == 200
assert restarted == ["6650000146"]
assert autostudy_module.work_running("6650000146") is True
def test_study_control_stays_stopped_when_month_hours_met(monkeypatch) -> None:
import euniv.api as api_module
import euniv.service as service_module
+239
View File
@@ -1177,3 +1177,242 @@ def test_completed_course_skips_the_play_page(monkeypatch) -> None:
assert opened == []
asyncio.run(main())
def test_each_course_has_its_own_play_page_state() -> None:
async def main() -> None:
base = StudySession("token-1", [])
seen: list[tuple[str, str]] = []
async def fake_http(_method: str, url: str, **kw: object):
seen.append((url, str(dict(kw.get("headers") or {}).get("Referer") or "")))
return None
base._client = object()
base._http = fake_http
first = base.for_course()
second = base.for_course()
first._referer = "https://euniv.zte.com.cn/kng/view/video/aaa.html"
first._video_cap = 60
first._single_limit = True
first._play_logged = True
first._submit_logs = 9
assert second._referer == "https://euniv.zte.com.cn/"
assert (second._video_cap, second._single_limit, second._play_logged, second._submit_logs) == (0, False, False, 0)
assert base._referer == "https://euniv.zte.com.cn/"
assert first._token == "token-1"
base._token = "token-2"
assert second._token == "token-2"
await first.post_site_log("CreateSubmitLog", {})
await second.post_site_log("CreateSubmitLog", {})
assert [referer for _url, referer in seen] == [
"https://euniv.zte.com.cn/kng/view/video/aaa.html",
"https://euniv.zte.com.cn/",
]
asyncio.run(main())
def test_courses_studied_together_do_not_disturb_each_other(monkeypatch) -> None:
from euniv.autostudy import AutoStudyWorker
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
monkeypatch.setattr("euniv.autostudy._load_finished", lambda _eid: set())
monkeypatch.setattr("euniv.autostudy._remember_finished", lambda *_args, **_kwargs: None)
async def no_wait(*_args, **_kwargs) -> bool:
await asyncio.sleep(0)
return False
monkeypatch.setattr("euniv.autostudy.wait_stop", no_wait)
short, long, later = "a" * 32, "b" * 32, "c" * 32
need = {short: 1, long: 12, later: 1}
length = {short: 60, long: 600, later: 90}
sent = {kid: 0 for kid in need}
order: list[str] = []
gate: dict[str, asyncio.Event] = {}
async def open_play(_session, path: str) -> dict:
kid = path.rsplit("/", 1)[-1].split(".")[0]
return {"submitProTimes": 30, "standardStudyHours": length[kid], "pageSize": 1}
monkeypatch.setattr("euniv.autostudy._open_play", open_play)
class Course:
def __init__(self) -> None:
self._employee_id = "u-split"
self.kids: set[str] = set()
self.views: list[int] = []
async def update_progress(self, kid: str, _pkg: str) -> dict:
self.kids.add(kid)
done = sent[kid] >= need[kid]
return {
"studyschedule": 100 if done else sent[kid] * 5,
"status": "Completed" if done else "Studying",
"viewSchedule": sent[kid] * 30,
"actualstudyhours": sent[kid],
"standardstudyhours": need[kid],
}
async def submit_video_heartbeat(self, kid: str, _pkg: str, _study_time: int, view: int) -> dict:
if kid == long and sent[kid] == 2:
await asyncio.wait_for(gate["later"].wait(), timeout=5)
self.kids.add(kid)
self.views.append(view)
sent[kid] += 1
order.append(kid)
if kid == later:
gate["later"].set()
return {"studySchedule": 100 if sent[kid] >= need[kid] else sent[kid] * 5}
async def post_site_log(self, *_args, **_kwargs) -> None:
return None
class Login:
def __init__(self) -> None:
self.made: list[Course] = []
def for_course(self) -> Course:
course = Course()
self.made.append(course)
return course
async def month_hours_text(self) -> str:
return "10"
async def main() -> None:
gate["later"] = asyncio.Event()
login = Login()
host = AutoStudyWorker()
host._async_stop = asyncio.Event()
hours = HoursWatcher(login, "u-split", 600, asyncio.Event())
courses = [
(f"/kng/view/video/{short}.html", "短课", "视频"),
(f"/kng/view/video/{long}.html", "长课", "视频"),
(f"/kng/view/video/{later}.html", "后一门", "视频"),
]
failed = await host._study_courses(login, "u-split", courses, hours, "", "", 2)
assert failed == 0
assert sent == need
assert len(login.made) == 3
assert all(len(course.kids) == 1 for course in login.made)
by_kid = {next(iter(course.kids)): course for course in login.made}
steady = by_kid[long]
assert steady._referer.endswith(f"/kng/view/video/{long}.html")
assert steady._video_cap == 600
assert len(steady.views) == 12
assert 90 < max(steady.views) <= 600
assert by_kid[short]._video_cap == 60
assert by_kid[later]._video_cap == 90
assert sorted(order[:3]) == [short, long, long]
assert order[3] == later
assert order[4:] == [long] * 10
_clear_user_status("u-split")
asyncio.run(main())
def test_zero_interval_waits_a_second_and_hides_the_countdown(monkeypatch) -> None:
import time
from euniv.autostudy import WorkerView, _heartbeat_wait
delays: list[float] = []
async def capture(delay: float, *_events) -> bool:
delays.append(delay)
return False
monkeypatch.setattr("euniv.autostudy.wait_stop", capture)
async def main() -> None:
_clear_user_status("u-zero")
view = WorkerView("u-zero", 1)
view.update(course="甲", knowledge_id="k-zero", progress=1)
hours = HoursWatcher(object(), "u-zero", 600, asyncio.Event())
await _heartbeat_wait(view, 0, asyncio.Event(), hours, 1.0)
row = autostudy_status()["users"]["u-zero"]["workers"][0]
assert (row["interval"], row["heartbeat_at"], row["heartbeat_in"]) == (0, 0, 0)
assert delays == [1.0]
await _heartbeat_wait(view, 5, asyncio.Event(), hours, 1.0)
row = autostudy_status()["users"]["u-zero"]["workers"][0]
assert row["interval"] == 5
assert 1 <= row["heartbeat_in"] <= 5
assert row["heartbeat_at"] > time.time()
assert 5.3 <= delays[1] <= 5.5
_clear_user_status("u-zero")
asyncio.run(main())
def test_interval_change_applies_on_the_next_beat(monkeypatch) -> None:
monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None)
waits: list[int] = []
async def capture_wait(_worker, interval, _stop, _hours, _progress) -> bool:
waits.append(interval)
return False
monkeypatch.setattr("euniv.autostudy._heartbeat_wait", capture_wait)
current = {"gap": 1}
class Session:
def __init__(self) -> None:
self.submits = 0
self.reads = 0
async def update_progress(self, _kid: str, _pkg: str) -> dict:
self.reads += 1
done = self.submits >= 4
return {
"studyschedule": 100 if done else self.submits * 20,
"status": "Completed" if done else "Studying",
"actualstudyhours": self.submits,
"viewSchedule": self.submits * 30,
}
async def submit_video_heartbeat(self, _kid: str, _pkg: str, _study_time: int, _view: int) -> dict:
self.submits += 1
if self.submits == 2:
current["gap"] = 7
return {"studySchedule": self.submits * 20}
async def month_hours_text(self) -> str:
return "10"
async def main() -> None:
session = Session()
watcher = HoursWatcher(session, "u-live", 600, asyncio.Event())
await _study_video(
session, "kid", "", 1, asyncio.Event(), watcher,
study_time=30,
snapshot={"studyschedule": 0, "status": "Studying", "actualstudyhours": 0, "viewSchedule": 0},
video_cap=600,
pace=lambda: current["gap"],
)
assert waits == [1, 1, 7]
assert session.submits == 4
assert session.reads == 4
asyncio.run(main())
def test_saved_interval_is_kept_in_memory_for_running_courses() -> None:
from euniv.autostudy import _course_plan, _pace_of, _remember_pace
class Row:
employee_id = "u-pace"
heartbeat_mode = "manual"
heartbeat_video_seconds = 0
heartbeat_document_seconds = 4
heartbeat_scorm_seconds = 6
assert _pace_of("u-pace-unknown") == ({"video": 30, "document": 120, "scorm": 120}, True)
_remember_pace(Row())
intervals, auto = _pace_of("u-pace")
assert auto is False
assert intervals == {"video": 0, "document": 4, "scorm": 6}
assert _course_plan("video", intervals, auto, {"submitProTimes": 30})[:2] == (0, 30)
assert _course_plan("document", intervals, auto, {"validtimeSpan": 120, "submitIsOpen": "1"})[:2] == (4, 120)
assert _course_plan("document", intervals, True, {"submitProTimes": 30, "submitIsOpen": "1"})[:2] == (30, 30)