import asyncio 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, _planned_beats, _finish_user, _interval_plan, _jitter, _job_from_account, snapshot_courses, _package_chapter_path, _parse_minutes, _play_path, _set_user_status, _set_worker_status, _Stall, _pace_after, _study_document, _study_video, autostudy_status, wait_stop, ) 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, 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, expire_pause, 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: assert parse_proxy(None) is None assert parse_proxy("") is None assert parse_proxy("127.0.0.1:7890") == "http://127.0.0.1:7890" assert parse_proxy("http://user:pass@10.0.0.1:8080") == "http://user:pass@10.0.0.1:8080" assert parse_proxy("https://10.0.0.1:8443") == "https://10.0.0.1:8443" assert parse_proxy("socks4://127.0.0.1:1080") == "socks4://127.0.0.1:1080" assert parse_proxy("socks5://user:pass@127.0.0.1:1080") == "socks5://user:pass@127.0.0.1:1080" def test_build_proxy_url_auth_is_optional_and_quoted() -> None: assert build_proxy_url("http", "10.0.0.1", 8080) == "http://10.0.0.1:8080" assert build_proxy_url("socks5", "127.0.0.1", 1080, "u", "p@ss") == "socks5://u:p%40ss@127.0.0.1:1080" assert build_proxy_url("http", "10.0.0.1", 8080, "u", "") == "http://u:@10.0.0.1:8080" assert build_proxy_url("socks4", "127.0.0.1", 1080, "", "s3cret") == "socks4://:s3cret@127.0.0.1:1080" with pytest.raises(ProxyError): build_proxy_url("ss", "127.0.0.1", 1080) def test_parse_proxy_rejects_other_schemes() -> None: with pytest.raises(ValueError): parse_proxy("ss://secret") with pytest.raises(ValueError): parse_proxy("openvpn://gateway") with pytest.raises(ValueError): 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 assert _parse_minutes("600分钟") == 600 def test_wait_stop_timeout_and_event() -> None: async def main() -> None: event = asyncio.Event() 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_stall_gives_up_after_five_minutes_without_progress() -> None: stall = _Stall() assert stall.stuck(10, 120) is False assert stall.stuck(10, 120) is False assert stall.stuck(10, 120) is True moved = _Stall() assert moved.stuck(10, 120) is False assert moved.stuck(40, 200) is False assert moved.stuck(40, 99) is False assert moved.stuck(40, 1) is True credited = _Stall() assert credited.stuck(8.33, 30, 4) is False assert credited.stuck(8.33, 200, 5) is False assert credited.stuck(10.41, 30, 5) is False def test_rejected_heartbeat_keeps_the_configured_interval() -> None: stall = _Stall() for offset in range(12): landed, give_up, pause = _pace_after( stall, 16.67, 16.67, 2, 2, {}, video=True, step=30, interval=1, now=1000 + offset, ) assert landed is False assert give_up is False assert pause == 1 landed, give_up, pause = _pace_after( stall, 16.67, 25, 2, 3, {"studySchedule": 25}, video=True, step=30, interval=1, now=1400, ) assert landed is True assert give_up is False assert pause == 1 landed, give_up, pause = _pace_after( stall, 25, 25, 3, 3, {}, video=True, step=30, interval=1, now=1401, ) assert give_up is False assert pause == 1 assert stall.quiet(1701) is True def test_unchanged_official_percent_is_not_new_progress() -> None: stall = _Stall() for offset in range(12): landed, give_up, pause = _pace_after( stall, 1.85, 1.85, 1, 1, {"studySchedule": 1.85}, video=True, step=30, interval=1, now=1000 + offset, ) assert landed is False assert give_up is False assert pause == 1 def test_worker_adopts_official_minutes_and_percent() -> None: from euniv.autostudy import WorkerView _clear_user_status("u-official") view = WorkerView("u-official", 1) view.adopt( { "studyschedule": 1.85, "actualstudyhours": 1, "standardstudyhours": 54, "status": "Studying", }, course="甲", knowledge_id="k-official", ok=True, ) row = autostudy_status()["users"]["u-official"]["workers"][0] assert row["progress"] == 1.85 assert row["sent"] == 1 assert row["total"] == 54 view.adopt( { "studyschedule": 100, "actualstudyhours": 3, "standardstudyhours": 3, "status": "Completed", }, knowledge_id="k-official", ok=True, ) row = autostudy_status()["users"]["u-official"]["workers"][0] assert row["progress"] == 100 assert row["sent"] == 3 assert row["total"] == 3 _clear_user_status("u-official") def test_fast_video_survives_a_burst_of_empty_heartbeats(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) class Session: def __init__(self) -> None: self.submits = 0 async def update_progress(self, _kid: str, _pkg: str) -> dict: if self.submits >= 10: return { "studyschedule": 100, "status": "Completed", "actualstudyhours": 3, "viewSchedule": 300, } return { "studyschedule": 16.67, "status": "Studying", "actualstudyhours": 2, "viewSchedule": 89, } async def submit_video_heartbeat(self, _kid: str, _pkg: str, _study_time: int, _view: int) -> dict: self.submits += 1 if self.submits >= 10: return {"studySchedule": 100} return {} async def month_hours_text(self) -> str: return "10" async def main() -> None: session = Session() watcher = HoursWatcher(session, "u-burst", 600, asyncio.Event()) await _study_video( session, "kid", "", 1, asyncio.Event(), watcher, study_time=30, snapshot={ "studyschedule": 16.67, "status": "Studying", "actualstudyhours": 2, "viewSchedule": 89, }, video_cap=720, ) assert session.submits == 10 assert waits == [1] * 9 asyncio.run(main()) def test_jitter_never_sends_early() -> None: assert _jitter(0) == 1 assert _jitter(-1) == 1 for _ in range(30): wait = _jitter(1) assert 1.3 <= wait <= 4 for _ in range(30): wait = _jitter(10) assert 10.3 <= wait <= 13.3 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="甲", knowledge_id="k-jia", 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_worker_view_does_not_raise_total_when_progress_lags() -> None: from euniv.autostudy import WorkerView _clear_user_status("u-lag") view = WorkerView("u-lag", 1) view.update(course="甲", knowledge_id="k-lag", progress=2) view.after_beat(2.1, ok=True) frozen = view.total assert frozen == 980 view.after_beat(2.1, ok=True) view.after_beat(2.12, ok=True) assert view.sent == 3 assert view.total == frozen _clear_user_status("u-lag") def test_planned_beats_follows_course_length() -> None: assert _planned_beats(0, 0, 1) == 0 assert _planned_beats(4190, 0, 1) == 4190 assert _planned_beats(3600, 0, 30) == 120 assert _planned_beats(100, 90, 30) == 1 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 self.calls = 0 async def month_hours_text(self) -> str: self.calls += 1 return self.hours def test_hours_watcher_stops_when_target_reached(monkeypatch) -> None: saved: list[tuple[str, str]] = [] monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda eid, hours: saved.append((eid, hours))) async def main() -> None: session = _HourSession("600") user_stop = asyncio.Event() watcher = HoursWatcher(session, "u1", 600, user_stop) assert await watcher.refresh() is True assert watcher.reached assert user_stop.is_set() assert saved == [("u1", "600")] asyncio.run(main()) 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: return 600 async def month_hours_text(self) -> str: raise AssertionError("history 模式不应读接口本月学时") async def main() -> None: user_stop = asyncio.Event() watcher = HoursWatcher(_HistorySession(), "u1", 600, user_stop) assert await watcher.refresh() is True assert watcher.reached assert saved == [("u1", "600")] asyncio.run(main()) def test_accumulate_month_minutes_stops_at_previous_month() -> None: pages = [ [ {"title": "a", "minutes": 10, "studied_at": "2026-11-15 09:00:00"}, {"title": "b", "minutes": 20, "studied_at": "2026-11-02 09:00:00"}, ], [ {"title": "c", "minutes": 5, "studied_at": "2026-11-01 09:00:00"}, {"title": "d", "minutes": 99, "studied_at": "2026-10-31 23:00:00"}, {"title": "e", "minutes": 1, "studied_at": "2026-10-01 00:00:00"}, ], [ {"title": "should-not", "minutes": 1000, "studied_at": "2026-09-01 00:00:00"}, ], ] calls: list[tuple[int, int]] = [] def fetch(offset: int, limit: int): calls.append((offset, limit)) return pages[offset // limit] assert accumulate_month_minutes(fetch, 2026, 11, page_size=2) == (35, False) assert calls == [(0, 2), (2, 2)] dumped = [ {"title": "a", "minutes": 8, "studied_at": "2026-11-14 10:00:00"}, {"title": "b", "minutes": 4, "studied_at": "2026-10-30 10:00:00"}, ] assert fold_month_minutes(dumped, 2026, 11) == (8, True) assert accumulate_month_minutes(lambda _offset, _limit: dumped, 2026, 11, page_size=100) == (8, False) 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="学习中") _set_worker_status("u1", 2, course="乙", progress=80, ok=True) _set_worker_status("u1", 1, course="甲", progress=10, ok=False) users = autostudy_status()["users"]["u1"] assert [row["id"] for row in users["workers"]] == [1, 2] assert users["workers"][0]["ok"] is False assert users["course"] == "甲" _clear_user_status("u1") def test_hours_watcher_continues_below_target(monkeypatch) -> None: monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None) async def main() -> None: session = _HourSession("100") user_stop = asyncio.Event() watcher = HoursWatcher(session, "u1", 600, user_stop) assert await watcher.refresh() is False assert not user_stop.is_set() asyncio.run(main()) def test_hours_ticker_refreshes_while_running(monkeypatch) -> None: monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None) async def main() -> None: session = _HourSession("10") user_stop = asyncio.Event() global_stop = asyncio.Event() watcher = HoursWatcher(session, "u1", 600, user_stop, interval=0.05) task = asyncio.create_task(watcher.ticker(global_stop)) await asyncio.sleep(0.14) global_stop.set() await task assert session.calls >= 1 asyncio.run(main()) class _VideoSession: def __init__(self, hours: str) -> None: self.hours = hours self.progress_calls = 0 self.hour_calls = 0 async def update_progress(self, _kid: str, _pkg: str) -> dict: self.progress_calls += 1 if self.progress_calls == 1: return {"studyschedule": 90, "viewSchedule": 30} return {"studyschedule": 100, "viewSchedule": 60} async def submit_video_heartbeat(self, *_args, **_kwargs) -> dict: return {"studySchedule": 100} async def month_hours_text(self) -> str: self.hour_calls += 1 return self.hours def test_video_refresh_hours_when_finished(monkeypatch) -> None: monkeypatch.setattr("euniv.autostudy._update_month_hours", lambda *_args: None) async def no_wait(*_args, **_kwargs) -> bool: return False monkeypatch.setattr("euniv.autostudy._heartbeat_wait", no_wait) async def main() -> None: session = _VideoSession("700") global_stop = asyncio.Event() user_stop = asyncio.Event() watcher = HoursWatcher(session, "u1", 600, user_stop) await _study_video(session, "kid", "", 30, global_stop, watcher) assert session.hour_calls == 1 assert watcher.reached assert user_stop.is_set() asyncio.run(main()) class _AlreadyDoneSession: async def update_progress(self, _kid: str, _pkg: str) -> dict: return {"studyschedule": 100, "viewSchedule": 0} async def month_hours_text(self) -> str: raise AssertionError("跳过已完成视频时不应刷新学时") def test_video_skip_already_complete_does_not_refresh() -> None: async def main() -> None: session = _AlreadyDoneSession() global_stop = asyncio.Event() user_stop = asyncio.Event() watcher = HoursWatcher(session, "u1", 600, user_stop) await _study_video(session, "kid", "", 30, global_stop, watcher) assert not watcher.reached asyncio.run(main()) class _Start: def __init__(self, day: int, hour: int = 16, minute: int = 0, second: int = 0) -> None: self.study_start_day = day self.study_start_hour = hour 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: account = _Start(5, 16, 0, 0) assert window_open(account, datetime(2026, 11, 5, 15, 59, 59, tzinfo=CN_TZ)) is False assert window_open(account, datetime(2026, 11, 5, 16, 0, 0, tzinfo=CN_TZ)) is True assert window_open(account, datetime(2026, 11, 15, 1, 24, 0, tzinfo=CN_TZ)) is True assert window_open(account, datetime(2026, 12, 5, 15, 0, 0, tzinfo=CN_TZ)) is False def test_study_window_clamps_day_into_allowed_range() -> None: account = _Start(31, 16, 0, 0) assert window_open(account, datetime(2026, 2, 8, 15, 59, 59, tzinfo=CN_TZ)) is False assert window_open(account, datetime(2026, 2, 8, 16, 0, 0, tzinfo=CN_TZ)) is True early = _Start(1, 16, 0, 0) assert window_open(early, datetime(2026, 11, 8, 15, 59, 59, tzinfo=CN_TZ)) is False assert window_open(early, datetime(2026, 11, 8, 16, 0, 0, tzinfo=CN_TZ)) is True def test_immediate_start_skips_monthly_window() -> None: frozen = datetime(2026, 11, 15, 12, 0, tzinfo=CN_TZ) account = _Start(25, 23, 59, 59) assert study_eligible(account, frozen) is False start_now(account) assert account.study_paused is False assert account.study_ignore_window is True assert study_eligible(account, frozen) is True 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_manual_start_expires_when_the_month_changes() -> None: account = _Start(15, 0, 0, 0) account.study_schedule_enabled = False start_now(account, datetime(2026, 11, 20, tzinfo=CN_TZ)) assert study_eligible(account, datetime(2026, 11, 21, tzinfo=CN_TZ)) is True assert expire_pause(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is True assert account.study_ignore_window is False assert study_eligible(account, datetime(2026, 12, 1, tzinfo=CN_TZ)) is False def test_assemble_reports_hours_refresh_countdown(monkeypatch) -> None: import time monkeypatch.setattr("euniv.autostudy.work_running", lambda _eid: True) account = _Start(1, 0, 0, 0) account.employee_id = "u-hours" payload = assemble(account, {"hours_refresh_at": time.time() + 40}) assert 1 <= payload["hours_refresh_in"] <= 40 monkeypatch.setattr("euniv.autostudy.work_running", lambda _eid: False) stopped = assemble(account, {"hours_refresh_at": time.time() + 40}) assert stopped["hours_refresh_in"] == 0 def test_frames_carry_a_boot_id_so_pages_can_reset_after_restart() -> None: from euniv.study_control import stamp_frame first = stamp_frame("u-boot", {}) second = stamp_frame("u-boot", {}) assert second["seq"] == first["seq"] + 1 assert isinstance(first["boot"], str) and len(first["boot"]) == 16 assert first["boot"] == second["boot"] def test_every_frame_carries_the_time_left_before_the_next_heartbeat(monkeypatch) -> None: import time monkeypatch.setattr("euniv.autostudy.work_running", lambda _eid: True) account = _Start(1, 0, 0, 0) account.employee_id = "u-beat" clock = {"now": 1000.0} monkeypatch.setattr(time, "time", lambda: clock["now"]) live = {"workers": [{"id": 1, "interval": 5, "heartbeat_at": 1005.4, "heartbeat_in": 5}]} assert assemble(account, live)["workers"][0]["heartbeat_in"] == 5 clock["now"] = 1003.6 assert assemble(account, live)["workers"][0]["heartbeat_in"] == 2 clock["now"] = 1006.0 assert assemble(account, live)["workers"][0]["heartbeat_in"] == 0 assert live["workers"][0]["heartbeat_in"] == 5 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(5, 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, 5, 0, 0, tzinfo=CN_TZ))["paused"] is False assert study_eligible(account, datetime(2026, 12, 5, 0, 0, tzinfo=CN_TZ)) is True def test_stale_month_hours_do_not_block_next_month() -> None: account = _Start(5, 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, 5, tzinfo=CN_TZ)) is False assert study_eligible(account, datetime(2026, 12, 5, 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_intervals_of_uses_that_account() -> None: from euniv.heartbeat import intervals_of class Account: heartbeat_mode = "manual" heartbeat_video_seconds = 1 heartbeat_document_seconds = 2 heartbeat_scorm_seconds = 3 intervals, auto = intervals_of(Account()) assert auto is False assert intervals == {"video": 1, "document": 2, "scorm": 3} 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 == 30 assert page == 1 wait, step, page = _interval_plan( "document", {"document": 1}, False, {"validtimeSpan": 120, "pageSize": 12}, ) assert wait == 1 assert step == 120 assert page == 12 def test_wanted_account_without_credential_is_dropped() -> None: from euniv.autostudy import AutoStudyWorker, is_wanted, want_work want_work("missing-user") AutoStudyWorker()._collect() assert is_wanted("missing-user") is False info = autostudy_status()["users"]["missing-user"] assert info["message"] == "登录凭证待校验" assert info["state"] == "学习失败" 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" account.hours_month = "2026-10" account.month_hours = "88" assert assemble(account, {}, datetime(2026, 11, 2, tzinfo=CN_TZ))["month_hours"] == "" stale = assemble( account, {"state": "已达标", "month": "2026-10", "month_hours": "600", "message": "本月目标已达到"}, datetime(2026, 11, 2, tzinfo=CN_TZ), ) assert stale["state"] == "" assert stale["month_hours"] == "" assert stale["message"] == "" 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")) failed = autostudy_status()["users"]["u2"] assert failed["state"] == "学习失败" assert failed["message"] == "学习没有完成" _clear_user_status("u2") def test_study_window_rejects_invalid_parts() -> None: with pytest.raises(StudyWindowError): validate_start(4, 0, 0, 0) with pytest.raises(StudyWindowError): validate_start(26, 0, 0, 0) with pytest.raises(StudyWindowError): validate_start(8, 24, 0, 0) assert validate_start(5, 0, 0, 0) == (5, 0, 0, 0) assert validate_start(25, 23, 59, 59) == (25, 23, 59, 59) def test_course_workers_default_and_range() -> None: class Account: course_workers = 1 assert workers_of(Account()) == 1 assert validate_workers(8) == 8 with pytest.raises(CourseWorkersError): validate_workers(0) with pytest.raises(CourseWorkersError): 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", "课程")]) seen: list[str] = [] async def worker() -> None: while True: item = await cursor.take() if item is None: return seen.append(item[0]) await asyncio.sleep(0) await asyncio.gather(worker(), worker(), worker()) assert sorted(seen) == ["a", "b", "c"] asyncio.run(main()) class _ProxyAccount: def __init__(self) -> None: self.proxy_scheme = "http" self.proxy_host = "10.0.0.1" self.proxy_port = 8080 self.proxy_username = "u" self.proxy_password_cipher = "cipher" def test_proxy_off_scheme_clears_settings() -> None: account = _ProxyAccount() apply_proxy(account, "off") view = proxy_view(account) assert view["enabled"] is False assert view["scheme"] == "off" assert account.proxy_scheme == "" assert account.proxy_host == "" assert account.proxy_port is None def test_proxy_pool_scheme_enables_auto() -> None: account = _ProxyAccount() apply_proxy(account, "pool") view = proxy_view(account) assert view["enabled"] is True assert view["scheme"] == "pool" assert account.use_proxy_pool is True apply_proxy(account, "http", "1.1.1.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 len(session.heartbeats) == 1 assert session.heartbeats[0][0] == 30 assert abs(session.heartbeats[0][1] - 30) <= 1 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()) def test_completed_course_skips_the_play_page(monkeypatch) -> None: from euniv.autostudy import AutoStudyWorker async def no_wait(*_args, **_kwargs) -> bool: return False monkeypatch.setattr("euniv.autostudy.wait_stop", no_wait) monkeypatch.setattr("euniv.autostudy._remember_finished", lambda *_args, **_kwargs: None) opened: list[str] = [] async def open_play(*_args, **_kwargs): opened.append("opened") return {} monkeypatch.setattr("euniv.autostudy._open_play", open_play) class DoneSession: async def update_progress(self, _kid: str, _pkg: str) -> dict: return {"studyschedule": 100, "status": "Completed"} class Host: _async_stop = asyncio.Event() async def main() -> None: watcher = HoursWatcher(DoneSession(), "u1", 600, asyncio.Event()) result = await AutoStudyWorker._study_one_course( Host(), DoneSession(), "u1", f"/kng/view/video/{COMPACT_KID}.html", "已完成", "视频", watcher, "", "", None, set(), ) assert result == "done" 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)