Files
douyi_guaji_main/tests/test_web_gui_routes_logic.py
T

588 lines
19 KiB
Python

"""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"):
class OkStatus:
ok = True
monkeypatch.setattr(routes, "check_license", lambda: OkStatus())
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]
def _post_without_license(path: str, body: dict, monkeypatch, csrf: str = "token"):
class MissingStatus:
ok = False
reason = "missing"
message = "缺少授权文件"
monkeypatch.setattr(routes, "check_license", lambda: MissingStatus())
monkeypatch.setattr(
routes,
"get_license_status_payload",
lambda: {"ok": False, "required": True, "reason": "missing", "message": "缺少授权文件"},
)
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]
def _get(path: str, monkeypatch, query: str = ""):
handler = _DummyHandler()
runner = _DummyRunner()
u = SimpleNamespace(path=path, query=query)
routes.handle_get(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_license_status_route_returns_public_payload(monkeypatch):
monkeypatch.setattr(
routes,
"get_license_status_payload",
lambda: {"ok": True, "reason": "ok", "customer": "demo"},
)
status, obj = _get("/api/license", monkeypatch)
assert status == 200
assert obj == {"ok": True, "reason": "ok", "customer": "demo"}
def test_license_install_route_accepts_code(monkeypatch):
calls = {}
class _Status:
ok = True
reason = "ok"
message = "授权有效"
payload = {"customer": "demo"}
def fake_install(text, **_kwargs):
calls["text"] = text
return _Status()
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
status, obj = _post("/api/license", {"license_text": "DYGJ-demo"}, monkeypatch)
assert status == 200
assert obj["ok"] is True
assert obj["reason"] == "ok"
assert calls["text"] == "DYGJ-demo"
def test_license_install_route_uses_activation_url(monkeypatch):
calls = {}
class _Status:
ok = True
reason = "ok"
message = "授权有效"
payload = {}
def fake_install(text, *, activation_url="", timeout_seconds=10):
calls["text"] = text
calls["activation_url"] = activation_url
calls["timeout_seconds"] = timeout_seconds
return _Status()
monkeypatch.setattr(
routes,
"read_config",
lambda: {"license": {"activation_url": "https://license.example/api/v1/activate", "timeout_seconds": 7}},
)
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
status, obj = _post("/api/license", {"license_text": "DG-DEMO"}, monkeypatch)
assert status == 200
assert obj["ok"] is True
assert calls == {
"text": "DG-DEMO",
"activation_url": "https://license.example/api/v1/activate",
"timeout_seconds": 7,
}
def test_license_install_route_uses_default_activation_url(monkeypatch):
calls = {}
class _Status:
ok = True
reason = "ok"
message = "授权有效"
payload = {}
def fake_install(text, *, activation_url="", timeout_seconds=10):
calls["text"] = text
calls["activation_url"] = activation_url
calls["timeout_seconds"] = timeout_seconds
return _Status()
monkeypatch.setattr(routes, "read_config", lambda: {})
monkeypatch.setattr(routes, "get_default_activation_url", lambda: "http://default/api/v1/activate")
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
status, obj = _post("/api/license", {"license_text": "DG-DEMO"}, monkeypatch)
assert status == 200
assert obj["ok"] is True
assert calls == {
"text": "DG-DEMO",
"activation_url": "http://default/api/v1/activate",
"timeout_seconds": 10,
}
def test_license_install_route_rejects_empty_code(monkeypatch):
status, obj = _post("/api/license", {"license_text": " "}, monkeypatch)
assert status == 400
assert obj["ok"] is False
assert obj["error"] == "missing license_text"
def test_runtime_actions_require_license_but_license_route_stays_available(monkeypatch):
calls = []
def fake_install(*_args, **_kwargs):
calls.append("install")
return SimpleNamespace(ok=False, reason="bad", message="bad license")
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
status, obj = _post_without_license("/api/start-run", {}, monkeypatch)
assert status == 403
assert obj["error"] == "license_required"
assert obj["reason"] == "missing"
status, obj = _post_without_license("/api/license", {"license_text": "DG-DEMO"}, monkeypatch)
assert status == 400
assert obj["reason"] == "bad"
assert calls == ["install"]
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",
"region_coords_edit_enabled": "true",
"fudai_detail_body_bluepurple_threshold": "0.46",
"fudai_detail_body_dark_threshold": "0.36",
"fudai_task_status_template_threshold": "0.27",
}
},
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
assert written["region_coords_edit_enabled"] is True
assert written["fudai_detail_body_bluepurple_threshold"] == 0.46
assert written["fudai_detail_body_dark_threshold"] == 0.36
assert written["fudai_task_status_template_threshold"] == 0.27
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.fudai_task_status": [820, 1815, 1050, 2035],
"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"]["fudai_task_status"] == [820, 1815, 1050, 2035]
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_lightweight_ports(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 captured.get("ports") == [39601, 5555, 44219]
def test_wifi_auto_reconnect_connects_last_target_even_when_other_device_exists(monkeypatch):
monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb")
monkeypatch.setattr(routes, "list_adb_devices", lambda adb: ["192.168.10.200:5555"]) # 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:44219", "model": "PEPM00"},
)
monkeypatch.setattr(scan_mod, "verify_adb_target", lambda adb, target: ("connected", "ok")) # noqa: ARG005
status, obj = _post("/api/wifi/auto-reconnect", {}, monkeypatch)
assert status == 200
assert obj.get("ok") is True
assert obj.get("action") == "reconnected_background"
assert obj.get("target") == "192.168.10.105:44219"
assert obj.get("selected_target") == "192.168.10.200:5555"
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 == []