"""web_gui_pkg.routes 关键逻辑单测(无需启动 HTTP 服务)。""" from __future__ import annotations from types import SimpleNamespace import pytest from gui.web_gui_pkg import routes class _DummyHandler: def __init__(self, body=None, csrf_token: str = "token"): self.headers = {"X-CSRF-Token": csrf_token} self._body = body if body is not None else {} self.calls = [] self.client_address = ("127.0.0.1", 12345) self.static_calls = [] def _read_json(self): return self._body def _send_json(self, obj, status: int = 200): self.calls.append((status, obj)) return {"status": status, "obj": obj} def send_error(self, status): self.calls.append((status, {"error": "send_error"})) return None def _serve_static(self, rel_path): self.static_calls.append(rel_path) return None class _DummyRunner: def get_stats(self, include_events=False): # noqa: ARG002 return {"ok": True} def is_running(self): return False def get_reservations(self): return {} def get_high_value_rooms(self): return {} def force_stop(self): return None def stop(self): return None def send_back_key(self, _device_id): # noqa: ARG002 return True def start_main_run(self, _cfg): # noqa: ARG002 return None def _post(path: str, body: dict, monkeypatch, csrf: str = "token"): handler = _DummyHandler(body=body, csrf_token=csrf) runner = _DummyRunner() u = SimpleNamespace(path=path, query="") routes.handle_post(handler, u, runner, "token") assert handler.calls, f"{path} should produce a response" return handler.calls[-1] @pytest.mark.parametrize( "raw,expected", [ (True, True), (False, False), ("true", True), ("TRUE", True), ("1", True), ("yes", True), ("on", True), ("false", False), ("FALSE", False), ("0", False), ("no", False), ("off", False), ("", False), (0, False), (1, True), ], ) def test_coerce_bool(raw, expected): assert routes._coerce_bool(raw) is expected def test_config_bool_string_false_written_as_false(monkeypatch): written = {} monkeypatch.setattr(routes, "read_config", lambda: {"enable_streaming_screenshot": True}) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", {"config": {"enable_streaming_screenshot": "false"}}, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written.get("enable_streaming_screenshot") is False def test_config_accepts_fudai_detail_v2_ocr_switches_and_ui_mode(monkeypatch): written = {} monkeypatch.setattr(routes, "read_config", lambda: {}) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", { "config": { "fudai_detail_ui_mode": "v2_0", "fudai_detail_ocr_content_enabled": "true", "fudai_detail_ocr_value_enabled": "true", "fudai_detail_ocr_countdown_enabled": "true", "fudai_detail_ocr_task_enabled": "true", "fudai_detail_ocr_task_count_enabled": "true", "fudai_detail_ocr_button_enabled": "true", "fudai_detail_ocr_participants_enabled": "false", "fudai_detail_ocr_live_title_enabled": "false", } }, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written["fudai_detail_ui_mode"] == "v2_0" assert written["fudai_detail_ocr_content_enabled"] is True assert written["fudai_detail_ocr_button_enabled"] is True assert written["fudai_detail_ocr_participants_enabled"] is False def test_config_accepts_region_coordinate_arrays(monkeypatch): written = {} monkeypatch.setattr(routes, "read_config", lambda: {}) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", { "config": { "fudai_detail_regions.v2_0_one_task.info_line": [430, 1315, 1055, 1435], "pixel_regions.lottery_result.pixel": ["290", "1300", "790", "1415"], "pixel_regions.live_room_icon_bbox": [999, 172, 1028, 202], } }, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written["fudai_detail_regions"]["v2_0_one_task"]["info_line"] == [430, 1315, 1055, 1435] assert written["pixel_regions"]["lottery_result"]["pixel"] == [290, 1300, 790, 1415] assert written["pixel_regions"]["live_room_icon_bbox"] == [999, 172, 1028, 202] def test_config_rejects_invalid_fudai_detail_ui_mode(monkeypatch): written = {"fudai_detail_ui_mode": "legacy"} monkeypatch.setattr(routes, "read_config", lambda: dict(written)) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", {"config": {"fudai_detail_ui_mode": "unknown"}}, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written["fudai_detail_ui_mode"] == "legacy" def test_config_log_format_mode_is_single_detail_entry(monkeypatch): written = {} monkeypatch.setattr( routes, "read_config", lambda: { "logging": { "log_format_mode": "simple", "debug_detail_level": "normal", "action_log_format": "concise", } }, ) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", { "config": { "logging.log_format_mode": "detailed", "logging.debug_detail_level": "normal", "logging.action_log_format": "concise", } }, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written["logging"]["log_format_mode"] == "detailed" assert written["logging"]["debug_detail_level"] == "detailed" assert written["logging"]["action_log_format"] == "detailed" assert written["logging"]["error_detail_level"] == "full" def test_config_rejects_invalid_log_format_mode(monkeypatch): written = {} monkeypatch.setattr(routes, "read_config", lambda: {"logging": {"log_format_mode": "simple"}}) monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) status, obj = _post( "/api/config", {"config": {"logging.log_format_mode": "verbose"}}, monkeypatch, ) assert status == 200 assert obj.get("ok") is True assert written["logging"]["log_format_mode"] == "simple" assert written["logging"]["debug_detail_level"] == "normal" assert written["logging"]["action_log_format"] == "concise" @pytest.mark.parametrize( "ports_raw,expected_invalid", [ (None, False), ("", False), ("5555", False), ("5555,5556", False), ("5555-5560", False), (["5555", 5556], False), ("abc", True), ("5555,abc", True), ("1-2-3", True), (70000, True), (["x"], True), ], ) def test_is_invalid_ports_spec(ports_raw, expected_invalid): assert routes._is_invalid_ports_spec(ports_raw) is expected_invalid def test_wifi_scan_invalid_ports_returns_400(monkeypatch): monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") status, obj = _post("/api/wifi/scan", {"ports": "abc"}, monkeypatch) assert status == 400 assert obj.get("error") == "invalid ports" def test_wifi_auto_reconnect_without_adb_returns_422(monkeypatch): monkeypatch.setattr(routes, "find_adb_executable", lambda: "") status, obj = _post("/api/wifi/auto-reconnect", {}, monkeypatch) assert status == 422 assert obj.get("error") == "adb not found" def test_wifi_auto_reconnect_uses_auto_full_port_scan(monkeypatch): captured = {} monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001 import gui.gui_core_pkg as core_pkg import gui.gui_core_pkg.wifi_adb_scan as scan_mod monkeypatch.setattr( core_pkg, "get_last_wifi_target", lambda: {"target": "192.168.10.105:39601", "model": "PEPM00"}, ) monkeypatch.setattr(scan_mod, "verify_adb_target", lambda adb, target: ("failed", "refused")) # noqa: ARG005 def fake_discover(adb, **kwargs): # noqa: ARG001 captured.update(kwargs) return [] monkeypatch.setattr(core_pkg, "discover_adb_devices", fake_discover) status, obj = _post("/api/wifi/auto-reconnect", {}, monkeypatch) assert status == 200 assert obj.get("ok") is True assert "ports" not in captured def test_wifi_scan_includes_tried_subnets(monkeypatch): monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001 monkeypatch.setattr(routes, "read_config", lambda: {}) monkeypatch.setattr(routes, "write_config", lambda cfg: None) # noqa: ARG001 import gui.gui_core_pkg as core_pkg monkeypatch.setattr(core_pkg, "parse_port_spec", lambda spec: [5555]) # noqa: ARG001 captured = {} def fake_discover(*a, **k): captured.update(k) return [] monkeypatch.setattr(core_pkg, "discover_adb_devices", fake_discover) monkeypatch.setattr(core_pkg, "get_local_subnet", lambda: "192.168.10.0/24") monkeypatch.setattr(core_pkg, "get_local_subnets", lambda: ["192.168.10.0/24", "10.0.0.0/24"]) status, obj = _post("/api/wifi/scan", {}, monkeypatch) assert status == 200 assert obj.get("ok") is True assert obj.get("subnets") == ["192.168.10.0/24", "10.0.0.0/24"] assert captured.get("ports") is None def test_wifi_disconnect_clears_last_target_only_on_exact_target(monkeypatch): cleared = {"called": False} monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") monkeypatch.setattr(routes, "list_adb_devices", lambda adb: []) # noqa: ARG001 import gui.gui_core as gui_core monkeypatch.setattr(gui_core, "disconnect_wifi_adb", lambda adb, ip, port: (True, "ok")) # noqa: ARG001 import gui.gui_core_pkg as core_pkg monkeypatch.setattr(core_pkg, "get_last_wifi_target", lambda: {"target": "192.168.1.10:37719"}) monkeypatch.setattr(core_pkg, "clear_last_wifi_target", lambda: cleared.__setitem__("called", True)) status, obj = _post("/api/wifi/disconnect", {"ip": "192.168.1.1", "port": "37719"}, monkeypatch) assert status == 200 assert obj.get("ok") is True assert cleared["called"] is False def test_rejects_non_local_post_requests(monkeypatch): monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") handler = _DummyHandler(body={"config": {}}, csrf_token="token") handler.client_address = ("192.168.1.50", 55555) runner = _DummyRunner() u = SimpleNamespace(path="/api/config", query="") routes.handle_post(handler, u, runner, "token") assert handler.calls status, obj = handler.calls[-1] assert status == 403 assert obj.get("error") == "Local access only" def test_rejects_non_local_get_api_requests(monkeypatch): monkeypatch.setattr(routes, "read_config", lambda: {"ok": True}) handler = _DummyHandler() handler.client_address = ("192.168.1.50", 55555) runner = _DummyRunner() u = SimpleNamespace(path="/api/config", query="") routes.handle_get(handler, u, runner, "token") assert handler.calls status, obj = handler.calls[-1] assert status == 403 assert obj.get("error") == "Local access only" def test_rejects_non_local_pic_requests(monkeypatch): handler = _DummyHandler() handler.client_address = ("192.168.1.50", 55555) runner = _DummyRunner() u = SimpleNamespace(path="/pic/screenshot.png", query="") routes.handle_get(handler, u, runner, "token") assert handler.calls status, obj = handler.calls[-1] assert status == 403 assert obj.get("error") == "Local access only" def test_rejects_non_local_static_requests(): handler = _DummyHandler() handler.client_address = ("192.168.1.50", 55555) runner = _DummyRunner() u = SimpleNamespace(path="/", query="") routes.handle_get(handler, u, runner, "token") assert handler.calls status, obj = handler.calls[-1] assert status == 403 assert obj.get("error") == "send_error" assert handler.static_calls == []