Files
douyi_guaji_main/tests/test_web_gui_pkg.py
T
CodexandClaude Opus 4.7 e417acfb7c 为 10 个已拆出的子包补单元测试(+226 用例)
新增 tests/ 下 10 个测试文件,把已拆出的子包从"被外部测试间接覆盖"提升到
"独立可测":

- test_web_gui_pkg (52)
  覆盖 logger / ansi / adb_compat / nested / stats_helpers
  含 _wg_log/_LOGGER 日志、ANSI 清理、点号路径、_parse_countdown_seconds 等
- test_underlying_operations_pkg (35)
  覆盖 adb_helpers / bounds / countdown / ocr_content / pic_path
  含 _adb_path 环境变量覆盖、check_countdown 多种格式、OCR 字符纠错
- test_reservation_logic_helpers (21)
  覆盖 helpers.py 5 个纯函数(_now_ts / _normalize_room_title /
  _calculate_string_similarity / _extract_content_core /
  _sort_reservations_inplace 排序稳定性)
- test_screenshot_manager_pkg (47)
  覆盖 paths.get_category_for_picname(5 类关键词分类)+
  get_latest_attempt_path / get_last_success_path(按 operation_type 路径推断)
  + 异步计数器
- test_gui_core_pkg (13)
  覆盖 RunParams dataclass 28 字段构造 + adb 函数 + read_config / write_config
  roundtrip
- test_fudai_core_pkg (17)
  覆盖 _FudaiOcrExecutorState 单例 + _get_fudai_ocr_executor 缓存复用 + 11
  个 thin_wrappers 与原实现等价行为
- test_handler_shells (8)
  覆盖 ReservationHandler / StageHandler / LoggingWrapper 三个薄壳类的
  staticmethod forwarding 完整性
- test_yanghao_pkg (14)
  覆盖 _yanghao_log(_log_kv 优先 + logger fallback + broken analyser
  兜底 + 未知 level 不抛)+ yanghao_get_recommend_seconds 默认值
- test_pixel_common (6)
  覆盖 _safe_open_screenshot_rgb 用 tmp_path 构造合法/损坏/截断/RGBA PNG
- test_fudai_finder_pkg (13)
  覆盖 5 个类(FudaiImageAcquirer / FudaiDetector / FudaiClickExecutor /
  FudaiDetailVerifier / FudaiFinder)实例化与组合关系,verify
  detect_by_template 类方法签名仍兼容(拆出后)

回归:
- 全套测试 355 → 581(+226 用例)
- 全部 581 passed / 1 skipped in 27s
- 新拆出的 12 个子包现在都有专门的单元测试覆盖

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 20:54:35 +08:00

239 lines
7.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""gui/web_gui_pkg/ 子包单元测试。
覆盖:logger / ansi / adb_compat / nested / stats_helpers 5 个子模块。
"""
from __future__ import annotations
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}")