"""gui/web_gui_pkg/ 子包单元测试。 覆盖:logger / ansi / adb_compat / nested / stats_helpers 5 个子模块。 """ from __future__ import annotations import io import logging import pytest from gui.web_gui_pkg import ( _bucket, _inc_map, _LOGGER, _parse_countdown_seconds, _wg_log, find_adb_executable, get_nested_value, list_adb_devices, read_config, resolve_adb_device, strip_ansi_escape_codes, write_config, ) # ============================================================ # logger.py # ============================================================ class TestWgLog: """_wg_log 应该不抛异常,未知 level 走 INFO。""" def test_default_level_info(self, caplog): with caplog.at_level(logging.INFO, logger="gui.web_gui"): _wg_log("[smoke] hello") assert any("[smoke] hello" in r.getMessage() for r in caplog.records) @pytest.mark.parametrize("level", ["INFO", "WARNING", "ERROR", "DEBUG"]) def test_known_levels(self, level, caplog): with caplog.at_level(logging.DEBUG, logger="gui.web_gui"): _wg_log(f"[smoke] {level}", level=level) # 至少应捕获到一条记录(DEBUG 默认可能被过滤,但 caplog 设了 DEBUG) assert any(level in r.levelname or "[smoke]" in r.getMessage() for r in caplog.records) def test_unknown_level_does_not_raise(self): # 传未知 level(如 "FOOBAR")应当不抛 _wg_log("[smoke] unknown level", level="FOOBAR") def test_logger_name(self): assert _LOGGER.name == "gui.web_gui" # ============================================================ # ansi.py — strip_ansi_escape_codes # ============================================================ class TestStripAnsiEscapeCodes: @pytest.mark.parametrize( "input_str,expected", [ ("\x1b[31mred\x1b[0m", "red"), ("\x1b[1;32mbold green\x1b[0m", "bold green"), ("plain text", "plain text"), ("", ""), ("\x1b[33mwarn\x1b[0m and \x1b[31merror\x1b[0m", "warn and error"), ], ) def test_strip(self, input_str, expected): assert strip_ansi_escape_codes(input_str) == expected def test_non_str_coerced(self): # int / None 等会被转为 str assert strip_ansi_escape_codes(None) == "None" assert strip_ansi_escape_codes(123) == "123" def test_no_ansi_passthrough(self): s = "abc\ndef\t123" assert strip_ansi_escape_codes(s) == s # ============================================================ # nested.py — get_nested_value # ============================================================ class TestGetNestedValue: @pytest.mark.parametrize( "obj,key,expected", [ ({"a": 1}, "a", 1), ({"a": {"b": 2}}, "a.b", 2), ({"a": {"b": {"c": 3}}}, "a.b.c", 3), ({"logging": {"keep_days": 7}}, "logging.keep_days", 7), ], ) def test_existing_keys(self, obj, key, expected): assert get_nested_value(obj, key) == expected def test_missing_returns_default(self): assert get_nested_value({"a": 1}, "b") is None assert get_nested_value({"a": 1}, "b", default=42) == 42 def test_partial_path_missing(self): # 中间某段不是 dict assert get_nested_value({"a": 1}, "a.b") is None # 中间段缺 assert get_nested_value({"a": {"b": 1}}, "a.c.d") is None def test_empty_obj(self): assert get_nested_value({}, "a") is None assert get_nested_value({}, "a", default="d") == "d" def test_none_obj_does_not_raise(self): # 不应抛 result = get_nested_value(None, "a", default="x") # None.get(...) 会失败,函数兜底应 catch assert result == "x" # ============================================================ # stats_helpers.py # ============================================================ class TestParseCountdownSeconds: """_parse_countdown_seconds 解析倒计时文本到秒数。""" @pytest.mark.parametrize( "text,expected", [ ("1:30", 90), ("0:00", 0), ("10:00", 600), ("1:00:00", 3600), ("0:01:30", 90), ("90", 90), # 兜底纯数字当秒 ("3小时", 3 * 3600), ("5分", 5 * 60), ("30秒", 30), ("1小时2分3秒", 3600 + 120 + 3), ], ) def test_valid(self, text, expected): assert _parse_countdown_seconds(text) == expected @pytest.mark.parametrize("text", ["", None, "abc", "::"]) def test_invalid_returns_none(self, text): assert _parse_countdown_seconds(text) is None class TestBucket: """_bucket 把数值落到指定的边界桶内。""" @pytest.mark.parametrize( "value,edges,expected", [ (5, [0, 10, 50, 100], "0-10"), (15, [0, 10, 50, 100], "10-50"), (75, [0, 10, 50, 100], "50-100"), (150, [0, 10, 50, 100], "100+"), (10, [0, 10, 50, 100], "10-50"), # 边界归右 ], ) def test_bucket(self, value, edges, expected): assert _bucket(value, edges) == expected def test_empty_edges_returns_all(self): assert _bucket(123, []) == "all" class TestIncMap: """_inc_map 字典内累加(缺失 key 当 0)。""" def test_increment_existing(self): m = {"a": 5} _inc_map(m, "a", 3) assert m == {"a": 8} def test_increment_missing(self): m = {} _inc_map(m, "x", 7) assert m == {"x": 7} def test_default_n_is_1(self): m = {} _inc_map(m, "y") assert m == {"y": 1} def test_returns_none(self): m = {} assert _inc_map(m, "k", 1) is None # ============================================================ # adb_compat.py — 5 个 thin wrapper(forwarding 到 gui.gui_core_pkg) # ============================================================ class TestAdbCompat: """5 个 thin wrapper 应该转发到 gui_core_pkg 的同名函数。""" def test_find_adb_executable_callable(self): # 不真的跑 adb,仅验证可调用并返回 str from gui.gui_core_pkg import find_adb_executable as v2 assert find_adb_executable.__module__ == "gui.web_gui_pkg.adb_compat" # 调用一次确认不抛 result = find_adb_executable() assert isinstance(result, str) def test_list_adb_devices_callable(self): # 传一个空字符串作为 adb_exe,应不抛(实际不会执行) result = list_adb_devices("") assert isinstance(result, list) def test_resolve_adb_device(self): # 传不存在的 device_id 时实际行为是抛 RuntimeError with pytest.raises(RuntimeError): resolve_adb_device("", "nonexistent") def test_resolve_adb_device_empty_string_or_raise(self): # 不指定 device_id:有设备时返回首个 str,无设备时抛 RuntimeError try: result = resolve_adb_device("", "") assert isinstance(result, str) except RuntimeError: pass # 没设备是合理结果 def test_read_config(self): # read_config 应返回 dict(或空 dict) result = read_config() assert isinstance(result, dict) def test_write_config_roundtrip(self): """write_config 写入后 read_config 应能读到(有副作用,但项目中已存在该行为)。""" # 仅确认 write_config 不抛即可(避免污染真实 config.json) cur = read_config() try: write_config(cur) # 写回原值,不改任何东西 except Exception as e: pytest.fail(f"write_config 不应抛: {e}") class TestRequestParsing: def test_read_json_invalid_content_length_returns_empty(self): from gui.web_gui_pkg.request_parsing import read_json class _Dummy: headers = {"Content-Length": "abc"} rfile = io.BytesIO(b'{"x":1}') assert read_json(_Dummy()) == {} @pytest.mark.parametrize( "exc_type", [BrokenPipeError, ConnectionAbortedError, ConnectionResetError], ) def test_send_json_ignores_client_disconnect(self, exc_type): from gui.web_gui_pkg.request_parsing import send_json class _Dummy: def __init__(self): self.wfile = self self.status = None self.headers = [] self.header_finished = False def send_response(self, status): self.status = status def send_header(self, key, value): self.headers.append((key, value)) def end_headers(self): self.header_finished = True def write(self, _data): raise exc_type("client disconnected") dummy = _Dummy() send_json(dummy, {"ok": True}) assert dummy.status == 200 assert dummy.header_finished is True