import asyncio import pytest from datetime import datetime from euniv.autostudy import ( CourseCursor, HoursWatcher, _clear_user_status, _parse_minutes, _set_user_status, _set_worker_status, _study_video, autostudy_status, wait_stop, ) from euniv.client import accumulate_month_minutes, fold_month_minutes 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 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_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 asyncio.run(main()) 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))) 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, source="history") 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 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 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 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_ignore_window = False 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_missing_day() -> None: account = _Start(31, 16, 0, 0) assert window_open(account, datetime(2026, 2, 28, 15, 59, 59, tzinfo=CN_TZ)) is False assert window_open(account, datetime(2026, 2, 28, 16, 0, 0, tzinfo=CN_TZ)) is True def test_immediate_start_skips_monthly_window() -> None: account = _Start(28, 23, 59, 59) assert study_eligible(account) is False start_now(account) assert account.study_paused is False assert account.study_ignore_window is True assert study_eligible(account) is True stop_now(account) assert account.study_paused is True assert account.study_ignore_window is False assert study_eligible(account) is False def test_study_window_rejects_invalid_parts() -> None: with pytest.raises(StudyWindowError): validate_start(32, 0, 0, 0) with pytest.raises(StudyWindowError): validate_start(1, 24, 0, 0) 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_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", "10.0.0.1", 8080) assert account.use_proxy_pool is False assert proxy_view(account)["scheme"] == "http"