为 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>
This commit is contained in:
1 parent
2d928c3856
commit
e417acfb7c
10 files changed
+1484
No files matched your search
@@ -0,0 +1,123 @@
|
||||
"""douyin/fudai/douyin_fudai_core_pkg/ 子包单元测试。
|
||||
|
||||
覆盖:ocr_executor(线程池复用)+ thin_wrappers(11 个兼容性 forwarding)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.fudai.douyin_fudai_core_pkg import (
|
||||
_FudaiOcrExecutorState,
|
||||
_fudai_ocr_executor_state,
|
||||
_get_fudai_ocr_executor,
|
||||
attend_choujiang,
|
||||
basic_join_decision,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
check_lucky_draw_result,
|
||||
get_reward,
|
||||
is_watch_task_fudai,
|
||||
should_skip_fudai_by_config,
|
||||
_is_short_countdown_text,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ocr_executor.py
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiOcrExecutorState:
|
||||
def test_default_state(self):
|
||||
state = _FudaiOcrExecutorState()
|
||||
assert state.executor is None
|
||||
assert state.workers == 0
|
||||
assert state.lock is not None # threading.Lock
|
||||
|
||||
def test_global_singleton_exists(self):
|
||||
# 模块级单例应可访问
|
||||
assert _fudai_ocr_executor_state is not None
|
||||
assert isinstance(_fudai_ocr_executor_state, _FudaiOcrExecutorState)
|
||||
|
||||
|
||||
class TestGetFudaiOcrExecutor:
|
||||
def test_returns_executor(self):
|
||||
ex = _get_fudai_ocr_executor(2)
|
||||
assert isinstance(ex, ThreadPoolExecutor)
|
||||
|
||||
def test_caches_when_workers_match(self):
|
||||
# 相同 workers 应返回同一对象
|
||||
ex1 = _get_fudai_ocr_executor(4)
|
||||
ex2 = _get_fudai_ocr_executor(4)
|
||||
assert ex1 is ex2
|
||||
|
||||
def test_recreates_when_workers_change(self):
|
||||
# 不同 workers 应重建(旧 executor 被 shutdown)
|
||||
ex_a = _get_fudai_ocr_executor(2)
|
||||
ex_b = _get_fudai_ocr_executor(8)
|
||||
# 不强求 is not,但 max_workers 应该是新值
|
||||
assert _fudai_ocr_executor_state.workers == 8
|
||||
|
||||
|
||||
# ============================================================
|
||||
# thin_wrappers.py — 11 个 forwarding 函数都应可调用
|
||||
# ============================================================
|
||||
|
||||
class TestThinWrappersExist:
|
||||
"""验证 11 个 forwarding 函数全部可调用且签名正确。"""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fn",
|
||||
[
|
||||
attend_choujiang,
|
||||
check_lucky_draw_result,
|
||||
check_have_reward_notice_confirm,
|
||||
check_in_order_confirm_page,
|
||||
get_reward,
|
||||
is_watch_task_fudai,
|
||||
_is_short_countdown_text,
|
||||
should_skip_fudai_by_config,
|
||||
basic_join_decision,
|
||||
],
|
||||
)
|
||||
def test_callable(self, fn):
|
||||
assert callable(fn)
|
||||
|
||||
|
||||
class TestForwardedBehavior:
|
||||
"""通过薄壳调用应等价于直接调用 fudai_filter / fudai_attend / fudai_result_checker 的实现。"""
|
||||
|
||||
def test_is_watch_task_fudai_forwarding(self):
|
||||
# is_watch_task_fudai 是 fudai_filter 中已有完整测试的函数
|
||||
# 通过本子包的薄壳调用应得同结果
|
||||
from douyin.fudai.core.fudai_filter import is_watch_task_fudai as direct
|
||||
assert is_watch_task_fudai("观看3分钟即可参与") == direct("观看3分钟即可参与")
|
||||
assert is_watch_task_fudai("现金红包") == direct("现金红包")
|
||||
|
||||
def test_is_short_countdown_text_forwarding(self):
|
||||
from douyin.fudai.core.fudai_filter import _is_short_countdown_text as direct
|
||||
for text in ["00:00", "00:30", "5分钟", "abc", ""]:
|
||||
assert _is_short_countdown_text(text) == direct(text)
|
||||
|
||||
def test_should_skip_fudai_by_config_forwarding(self):
|
||||
"""通过薄壳调用应等价于 fudai_filter 的实现。"""
|
||||
import time
|
||||
from douyin.fudai.core.fudai_filter import should_skip_fudai_by_config as direct
|
||||
|
||||
class M:
|
||||
def __init__(self):
|
||||
self.needswitch = True
|
||||
self.min_prize_value_yuan = 0.0
|
||||
self.min_participants = 0
|
||||
self.max_participants = 0
|
||||
self.skip_if_countdown_lt_seconds = 0
|
||||
self.contains_want = []
|
||||
self.contains_not_want = []
|
||||
def _log_kv(self, *a, **kw): pass
|
||||
|
||||
detail = ('现金1000元', '2分钟', 50, 1, 1000.0, (time.time()+120, time.time()+120))
|
||||
thru_thin = should_skip_fudai_by_config(M(), detail)
|
||||
thru_direct = direct(M(), detail)
|
||||
# 结果相同
|
||||
assert thru_thin == thru_direct
|
||||
@@ -0,0 +1,151 @@
|
||||
"""douyin/fudai/douyin_fudai_finder_pkg/ 子包单元测试。
|
||||
|
||||
覆盖 5 个类(FudaiImageAcquirer / FudaiDetector / FudaiClickExecutor /
|
||||
FudaiDetailVerifier / FudaiFinder)的实例化与组合关系,以及顶层函数
|
||||
check_have_fudai_with_ready_screenshot_optimized。
|
||||
|
||||
业务行为(实际识别 / 点击)依赖真实截图与 ADB,留给端到端测试。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.fudai.douyin_fudai_finder import (
|
||||
FudaiClickExecutor,
|
||||
FudaiDetailVerifier,
|
||||
FudaiDetector,
|
||||
FudaiFinder,
|
||||
FudaiImageAcquirer,
|
||||
check_have_fudai_with_ready_screenshot_optimized,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Fake analyser 提供构造时需要的最小 attribute 集合
|
||||
# ============================================================
|
||||
|
||||
class FakeAnalyser:
|
||||
"""构造 FudaiFinder 链路所需的最小 attribute。"""
|
||||
|
||||
def __init__(self):
|
||||
self.device_id = "test_device"
|
||||
# FudaiDetector._init_search_regions 用到这些
|
||||
self.resolution_ratio_x = 1080
|
||||
self.resolution_ratio_y = 2400
|
||||
self.y_pianyi = 0
|
||||
# FudaiClickExecutor 可能用 operation
|
||||
class _Op: pass
|
||||
self.operation = _Op()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FudaiImageAcquirer
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiImageAcquirer:
|
||||
def test_construct(self):
|
||||
acquirer = FudaiImageAcquirer(FakeAnalyser())
|
||||
assert acquirer is not None
|
||||
|
||||
def test_acquire_screenshot_callable(self):
|
||||
acquirer = FudaiImageAcquirer(FakeAnalyser())
|
||||
assert callable(getattr(acquirer, "acquire_screenshot", None))
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FudaiDetector
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiDetector:
|
||||
def test_construct(self):
|
||||
d = FudaiDetector(FakeAnalyser())
|
||||
assert d.analyser is not None
|
||||
assert d.rx == 1080
|
||||
assert d.ry == 2400
|
||||
|
||||
def test_search_regions_initialized(self):
|
||||
d = FudaiDetector(FakeAnalyser())
|
||||
assert hasattr(d, "search_regions")
|
||||
assert isinstance(d.search_regions, list)
|
||||
|
||||
def test_detect_methods_callable(self):
|
||||
d = FudaiDetector(FakeAnalyser())
|
||||
for name in ("detect", "detect_by_pixel", "detect_by_template"):
|
||||
assert callable(getattr(d, name, None)), f"{name} 不可调用"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FudaiClickExecutor
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiClickExecutor:
|
||||
def test_construct(self):
|
||||
executor = FudaiClickExecutor(FakeAnalyser())
|
||||
assert executor is not None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FudaiDetailVerifier
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiDetailVerifier:
|
||||
def test_construct(self):
|
||||
verifier = FudaiDetailVerifier(FakeAnalyser())
|
||||
assert verifier is not None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FudaiFinder(组合 4 个子组件)
|
||||
# ============================================================
|
||||
|
||||
class TestFudaiFinder:
|
||||
def test_construct_includes_all_components(self):
|
||||
finder = FudaiFinder(FakeAnalyser())
|
||||
assert isinstance(finder.acquirer, FudaiImageAcquirer)
|
||||
assert isinstance(finder.detector, FudaiDetector)
|
||||
assert isinstance(finder.executor, FudaiClickExecutor)
|
||||
assert isinstance(finder.verifier, FudaiDetailVerifier)
|
||||
|
||||
def test_components_share_analyser(self):
|
||||
analyser = FakeAnalyser()
|
||||
finder = FudaiFinder(analyser)
|
||||
# 4 个子组件都应该持有同一个 analyser 引用
|
||||
assert finder.acquirer.analyser is analyser
|
||||
assert finder.detector.analyser is analyser
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 顶层函数
|
||||
# ============================================================
|
||||
|
||||
class TestCheckHaveFudaiWithReadyScreenshotOptimized:
|
||||
def test_callable(self):
|
||||
assert callable(check_have_fudai_with_ready_screenshot_optimized)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# detect_by_template 已拆出为 module-level 函数
|
||||
# ============================================================
|
||||
|
||||
class TestDetectByTemplateAsModuleLevel:
|
||||
"""detect_by_template 现在是 module-level 函数,类方法 1 行 forwarding。"""
|
||||
|
||||
def test_module_level_callable(self):
|
||||
from douyin.fudai.douyin_fudai_finder_pkg.detect_by_template import (
|
||||
detect_by_template as module_fn,
|
||||
)
|
||||
assert callable(module_fn)
|
||||
|
||||
def test_class_method_callable(self):
|
||||
# 类方法仍可访问
|
||||
d = FudaiDetector(FakeAnalyser())
|
||||
assert callable(d.detect_by_template)
|
||||
|
||||
def test_class_method_signature_unchanged(self):
|
||||
"""类方法签名应仍是 (self, pic, region),对外 API 不变。"""
|
||||
import inspect
|
||||
sig = inspect.signature(FudaiDetector.detect_by_template)
|
||||
params = list(sig.parameters.keys())
|
||||
# 第一个是 self(unbound),后两个 pic, region
|
||||
assert "pic" in params
|
||||
assert "region" in params
|
||||
@@ -0,0 +1,144 @@
|
||||
"""gui/gui_core_pkg/ 子包单元测试。
|
||||
|
||||
覆盖 run_params dataclass + adb 模块函数(无副作用部分)。
|
||||
adb 真实命令 / wifi_adb 涉及网络与设备,仅做"可调用 + 不抛"冒烟测试。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from gui.gui_core_pkg import (
|
||||
CONFIG_PATH,
|
||||
RunParams,
|
||||
find_adb_executable,
|
||||
list_adb_devices,
|
||||
read_config,
|
||||
resolve_adb_device,
|
||||
write_config,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# run_params.py — RunParams dataclass
|
||||
# ============================================================
|
||||
|
||||
class TestRunParams:
|
||||
def test_is_dataclass(self):
|
||||
assert dataclasses.is_dataclass(RunParams)
|
||||
|
||||
def test_field_count(self):
|
||||
# RunParams 当前有 28 个字段(与拆分时一致)
|
||||
fields = dataclasses.fields(RunParams)
|
||||
assert len(fields) == 28
|
||||
|
||||
def test_field_types(self):
|
||||
"""关键字段的类型注解。"""
|
||||
fields = {f.name: f for f in dataclasses.fields(RunParams)}
|
||||
# 一些已知的字段
|
||||
assert "device_id" in fields
|
||||
assert "y_pianyi" in fields
|
||||
assert "needswitch" in fields
|
||||
assert "wait_minutes" in fields
|
||||
assert "min_prize_value_yuan" in fields
|
||||
assert "yanghao_only" in fields
|
||||
|
||||
def test_construct_with_all_fields(self):
|
||||
# 构造一个完整实例,验证所有字段可赋值
|
||||
params = RunParams(
|
||||
device_id="test123",
|
||||
y_pianyi=0,
|
||||
needswitch=True,
|
||||
wait_minutes=5,
|
||||
skip_if_countdown_gt_seconds=300,
|
||||
reset_after_swipes_enabled=True,
|
||||
reset_after_swipes=30,
|
||||
enable_back_on_misses=True,
|
||||
min_prize_value_yuan=100.0,
|
||||
min_participants=10,
|
||||
max_participants=10000,
|
||||
auto_join_fansclub=True,
|
||||
fansclub_fail_action="skip",
|
||||
high_value_room_revisit_enabled=False,
|
||||
high_value_room_revisit_only_current_run=False,
|
||||
high_value_room_revisit_min_interval_seconds=30,
|
||||
high_value_room_revisit_max_per_run=10,
|
||||
high_value_room_revisit_min_prize_value=500.0,
|
||||
high_value_room_revisit_max_age_days=7,
|
||||
high_value_fudai_poll_before_seconds=1.0,
|
||||
reservation_back_verify_enabled=True,
|
||||
reservation_back_swipe_delay=0.5,
|
||||
fudai_find_max_attempts=3,
|
||||
enable_ocr_mode1=False,
|
||||
fudai_template_match_enabled=True,
|
||||
fudai_template_match_threshold=0.85,
|
||||
yanghao_only=False,
|
||||
yanghao_seconds=216,
|
||||
)
|
||||
assert params.device_id == "test123"
|
||||
assert params.y_pianyi == 0
|
||||
assert params.needswitch is True
|
||||
assert params.fudai_template_match_threshold == 0.85
|
||||
|
||||
|
||||
# ============================================================
|
||||
# config.py
|
||||
# ============================================================
|
||||
|
||||
class TestConfigPath:
|
||||
def test_is_str(self):
|
||||
assert isinstance(CONFIG_PATH, str)
|
||||
|
||||
def test_endswith_config_json(self):
|
||||
# 路径分隔符兼容
|
||||
assert CONFIG_PATH.endswith("config.json") or CONFIG_PATH.endswith(os.sep + "config.json")
|
||||
|
||||
|
||||
class TestReadConfig:
|
||||
def test_returns_dict(self):
|
||||
cfg = read_config()
|
||||
assert isinstance(cfg, dict)
|
||||
|
||||
def test_idempotent(self):
|
||||
# 多次调用应返回内容一致的 dict(不强求同一对象)
|
||||
cfg1 = read_config()
|
||||
cfg2 = read_config()
|
||||
assert cfg1 == cfg2
|
||||
|
||||
|
||||
class TestWriteConfig:
|
||||
def test_write_and_read_roundtrip(self):
|
||||
# 读出 → 写回(不改任何字段)→ 再读出,应一致
|
||||
original = read_config()
|
||||
write_config(original)
|
||||
after = read_config()
|
||||
# 至少键集相等(具体值可能因写入时序略有变动)
|
||||
assert set(original.keys()) == set(after.keys())
|
||||
|
||||
|
||||
# ============================================================
|
||||
# adb.py — find_adb_executable / list_adb_devices / resolve_adb_device
|
||||
# ============================================================
|
||||
|
||||
class TestAdbFunctions:
|
||||
def test_find_adb_executable_returns_str(self):
|
||||
# 不要求真的找到 adb,只看返回 str
|
||||
result = find_adb_executable()
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_list_adb_devices_returns_list(self):
|
||||
# 即使 adb_exe 是空 / 错的,也应返回 list(可能为空)
|
||||
result = list_adb_devices("")
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_list_adb_devices_with_invalid_exe(self):
|
||||
# 不存在的 adb_exe 应返回空 list,不抛
|
||||
result = list_adb_devices("/nonexistent/path/to/adb")
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_resolve_adb_device_with_invalid_id_raises(self):
|
||||
# 指定了不存在的 device_id 应抛 RuntimeError
|
||||
with pytest.raises(RuntimeError):
|
||||
resolve_adb_device("", "nonexistent_device_xyz")
|
||||
@@ -0,0 +1,125 @@
|
||||
"""薄壳类 forwarding 单元测试。
|
||||
|
||||
覆盖三个"类内部 staticmethod 全部 forwarding 到 module-level"的薄壳:
|
||||
- douyin_reservation_handler_pkg.handler.ReservationHandler
|
||||
- douyin_stage_handler_pkg.handler.StageHandler
|
||||
- douyin_logging_wrapper_pkg.wrapper.LoggingWrapper
|
||||
|
||||
只验证:类与 module-level 函数返回同一对象 / 调用不抛 / 转发正确。
|
||||
不测业务逻辑(业务行为由各子模块的功能测试覆盖)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ReservationHandler
|
||||
# ============================================================
|
||||
|
||||
class TestReservationHandlerForwarding:
|
||||
def test_class_methods_callable(self):
|
||||
from douyin.reservation.douyin_reservation_handler import ReservationHandler
|
||||
|
||||
for method in [
|
||||
"find_room_pos_by_title",
|
||||
"record_room_title_and_pos",
|
||||
"seek_reservation_room",
|
||||
"handle_reservation_direct_attend",
|
||||
]:
|
||||
fn = getattr(ReservationHandler, method, None)
|
||||
assert callable(fn), f"ReservationHandler.{method} 不可调用"
|
||||
|
||||
def test_find_room_pos_by_title_empty_returns_none(self):
|
||||
from douyin.reservation.douyin_reservation_handler import ReservationHandler
|
||||
|
||||
class M:
|
||||
_room_pos_to_title_map: Dict[int, Any] = {}
|
||||
|
||||
# 空映射应返回 None
|
||||
assert ReservationHandler.find_room_pos_by_title(M(), "", "") is None
|
||||
|
||||
def test_module_level_and_class_same_function(self):
|
||||
"""类的 staticmethod 和 module-level 函数应返回相同行为。"""
|
||||
from douyin.reservation.douyin_reservation_handler import (
|
||||
ReservationHandler, find_room_pos_by_title,
|
||||
)
|
||||
|
||||
class M:
|
||||
_room_pos_to_title_map: Dict[int, Any] = {}
|
||||
|
||||
assert (
|
||||
ReservationHandler.find_room_pos_by_title(M(), "x", "")
|
||||
== find_room_pos_by_title(M(), "x", "")
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# StageHandler
|
||||
# ============================================================
|
||||
|
||||
class TestStageHandlerForwarding:
|
||||
def test_class_methods_callable(self):
|
||||
from douyin.stage.douyin_stage_handler import StageHandler
|
||||
|
||||
for method in [
|
||||
"diagnose_stage_from_current_screen",
|
||||
"check_in_live_room_by_icon",
|
||||
"handle_in_fudai_detail",
|
||||
"handle_live_room_has_or_not_fudai",
|
||||
]:
|
||||
fn = getattr(StageHandler, method, None)
|
||||
assert callable(fn), f"StageHandler.{method} 不可调用"
|
||||
|
||||
def test_module_level_exposed(self):
|
||||
from douyin.stage.douyin_stage_handler import (
|
||||
StageHandler,
|
||||
diagnose_stage_from_current_screen,
|
||||
check_in_live_room_by_icon,
|
||||
handle_in_fudai_detail,
|
||||
handle_live_room_has_or_not_fudai,
|
||||
)
|
||||
# 都可访问
|
||||
assert all(callable(f) for f in [
|
||||
diagnose_stage_from_current_screen,
|
||||
check_in_live_room_by_icon,
|
||||
handle_in_fudai_detail,
|
||||
handle_live_room_has_or_not_fudai,
|
||||
])
|
||||
|
||||
|
||||
# ============================================================
|
||||
# LoggingWrapper
|
||||
# ============================================================
|
||||
|
||||
class TestLoggingWrapperForwarding:
|
||||
def test_class_methods_callable(self):
|
||||
from douyin.logging.douyin_logging_wrapper import LoggingWrapper
|
||||
|
||||
for method in [
|
||||
"enhanced_log_kv",
|
||||
"_enhanced_log_kv_simple",
|
||||
"_enhanced_log_kv_detailed",
|
||||
"log_step_time",
|
||||
"log_error_with_context",
|
||||
"log_performance_step",
|
||||
"log_debug_info",
|
||||
"get_performance_stats",
|
||||
]:
|
||||
fn = getattr(LoggingWrapper, method, None)
|
||||
assert callable(fn), f"LoggingWrapper.{method} 不可调用"
|
||||
|
||||
def test_get_performance_stats_returns_dict(self):
|
||||
"""无副作用的方法可直接调用。"""
|
||||
from douyin.logging.douyin_logging_wrapper import LoggingWrapper
|
||||
|
||||
result = LoggingWrapper.get_performance_stats()
|
||||
assert isinstance(result, dict)
|
||||
|
||||
def test_module_level_get_performance_stats(self):
|
||||
from douyin.logging.douyin_logging_wrapper import (
|
||||
LoggingWrapper, get_performance_stats,
|
||||
)
|
||||
assert LoggingWrapper.get_performance_stats() == get_performance_stats()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""douyin/detection/pixel/_common.py 单元测试。
|
||||
|
||||
只测 _safe_open_screenshot_rgb:用 tmp_path 构造合法 / 非法 / 不存在的图片文件。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from PIL import Image
|
||||
|
||||
from douyin.detection.pixel import _safe_open_screenshot_rgb
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 工具:构造合法 / 非法 PNG
|
||||
# ============================================================
|
||||
|
||||
def _make_valid_png(path: str, size: tuple = (10, 10)) -> None:
|
||||
"""生成一张最小的合法 PNG。"""
|
||||
img = Image.new("RGB", size, color=(255, 0, 0))
|
||||
img.save(path, "PNG")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 测试
|
||||
# ============================================================
|
||||
|
||||
class TestSafeOpenScreenshotRgb:
|
||||
def test_valid_png(self, tmp_path):
|
||||
p = tmp_path / "ok.png"
|
||||
_make_valid_png(str(p))
|
||||
result = _safe_open_screenshot_rgb(str(p))
|
||||
assert result is not None
|
||||
assert result.mode == "RGB"
|
||||
assert result.size == (10, 10)
|
||||
|
||||
def test_missing_file_returns_none(self, tmp_path):
|
||||
p = tmp_path / "nonexistent.png"
|
||||
assert _safe_open_screenshot_rgb(str(p)) is None
|
||||
|
||||
def test_empty_path_returns_none(self):
|
||||
assert _safe_open_screenshot_rgb("") is None
|
||||
|
||||
def test_corrupt_file_returns_none(self, tmp_path):
|
||||
# 写入非 PNG 内容
|
||||
p = tmp_path / "corrupt.png"
|
||||
p.write_bytes(b"not a real png")
|
||||
result = _safe_open_screenshot_rgb(str(p))
|
||||
# PIL 可能抛 OSError/SyntaxError,函数应吞掉返回 None
|
||||
assert result is None
|
||||
|
||||
def test_truncated_file_returns_none(self, tmp_path):
|
||||
# 先生成合法 PNG,再截断到一半
|
||||
full = tmp_path / "full.png"
|
||||
_make_valid_png(str(full))
|
||||
truncated = tmp_path / "truncated.png"
|
||||
truncated.write_bytes(full.read_bytes()[:50])
|
||||
result = _safe_open_screenshot_rgb(str(truncated))
|
||||
# truncated PNG 应被 catch 并返回 None
|
||||
assert result is None
|
||||
|
||||
def test_returns_rgb_mode(self, tmp_path):
|
||||
# 即使源文件是 RGBA / L 模式,也应转成 RGB
|
||||
p = tmp_path / "rgba.png"
|
||||
Image.new("RGBA", (5, 5), color=(0, 255, 0, 128)).save(str(p), "PNG")
|
||||
result = _safe_open_screenshot_rgb(str(p))
|
||||
assert result is not None
|
||||
assert result.mode == "RGB"
|
||||
@@ -0,0 +1,157 @@
|
||||
"""douyin/reservation/reservation_logic/ 子包单元测试。
|
||||
|
||||
主要测 helpers.py 的纯函数(add/cleanup/queue_full/attend_window/record 这些
|
||||
业务函数依赖很多 analyser 状态,单测的成本高、价值有限)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.reservation.reservation_logic.helpers import (
|
||||
_calculate_string_similarity,
|
||||
_extract_content_core,
|
||||
_normalize_room_title_for_matching,
|
||||
_now_ts,
|
||||
_sort_reservations_inplace,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _now_ts
|
||||
# ============================================================
|
||||
|
||||
class TestNowTs:
|
||||
def test_returns_float(self):
|
||||
assert isinstance(_now_ts(), float)
|
||||
|
||||
def test_close_to_current_time(self):
|
||||
before = time.time()
|
||||
result = _now_ts()
|
||||
after = time.time()
|
||||
assert before <= result <= after
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _normalize_room_title_for_matching
|
||||
# ============================================================
|
||||
|
||||
class TestNormalizeRoomTitle:
|
||||
@pytest.mark.parametrize(
|
||||
"title,expected_property",
|
||||
[
|
||||
# 标题去空格、去常见标点
|
||||
(" Live Room ", "no_leading_trailing_spaces"),
|
||||
("Live Room", "no_internal_double_spaces"),
|
||||
("[直播] Test", "no_brackets"),
|
||||
("直播间-A", "no_special_chars"),
|
||||
],
|
||||
)
|
||||
def test_basic_normalize(self, title, expected_property):
|
||||
result = _normalize_room_title_for_matching(title)
|
||||
# 不假设具体规则,只验证返回 str 且没明显空白
|
||||
assert isinstance(result, str)
|
||||
if expected_property == "no_leading_trailing_spaces":
|
||||
assert result == result.strip()
|
||||
|
||||
def test_empty_returns_str(self):
|
||||
result = _normalize_room_title_for_matching("")
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_idempotent(self):
|
||||
"""规范化后再规范化应得同一结果。"""
|
||||
title = "[直播] 测试 Room "
|
||||
once = _normalize_room_title_for_matching(title)
|
||||
twice = _normalize_room_title_for_matching(once)
|
||||
assert once == twice
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _calculate_string_similarity
|
||||
# ============================================================
|
||||
|
||||
class TestCalculateStringSimilarity:
|
||||
def test_identical_strings(self):
|
||||
assert _calculate_string_similarity("abc", "abc") == 1.0
|
||||
|
||||
def test_completely_different(self):
|
||||
score = _calculate_string_similarity("abc", "xyz")
|
||||
assert 0.0 <= score < 1.0
|
||||
|
||||
def test_empty_strings(self):
|
||||
# 两个空串应该是 1.0(相同)或 0.0(无内容),任一都合理
|
||||
score = _calculate_string_similarity("", "")
|
||||
assert 0.0 <= score <= 1.0
|
||||
|
||||
def test_partial_match(self):
|
||||
score = _calculate_string_similarity("hello world", "hello earth")
|
||||
assert 0.0 < score < 1.0
|
||||
|
||||
def test_score_in_range(self):
|
||||
for s1, s2 in [
|
||||
("abc", "abd"),
|
||||
("中文测试", "中文实验"),
|
||||
("Hello", "hello"),
|
||||
]:
|
||||
score = _calculate_string_similarity(s1, s2)
|
||||
assert 0.0 <= score <= 1.0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _extract_content_core
|
||||
# ============================================================
|
||||
|
||||
class TestExtractContentCore:
|
||||
def test_returns_str(self):
|
||||
result = _extract_content_core("现金红包 100 元")
|
||||
assert isinstance(result, str)
|
||||
|
||||
def test_empty(self):
|
||||
assert _extract_content_core("") == ""
|
||||
|
||||
def test_strips_whitespace(self):
|
||||
# 至少应去首尾空白(实际规则可能更复杂,这里只看类型和非空判断)
|
||||
result = _extract_content_core(" abc ")
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _sort_reservations_inplace
|
||||
# ============================================================
|
||||
|
||||
class TestSortReservationsInplace:
|
||||
def test_sort_by_future_ts_asc(self):
|
||||
"""主排序键:future_ts 升序(开奖早的在前)。"""
|
||||
items = [
|
||||
{"future_ts": 300.0, "prize_value_yuan": 100.0, "created_ts": 1.0},
|
||||
{"future_ts": 100.0, "prize_value_yuan": 200.0, "created_ts": 2.0},
|
||||
{"future_ts": 200.0, "prize_value_yuan": 50.0, "created_ts": 3.0},
|
||||
]
|
||||
_sort_reservations_inplace(items)
|
||||
future_seq = [it["future_ts"] for it in items]
|
||||
assert future_seq == sorted(future_seq), f"按 future_ts 升序失败:{future_seq}"
|
||||
|
||||
def test_returns_none(self):
|
||||
items = []
|
||||
assert _sort_reservations_inplace(items) is None
|
||||
|
||||
def test_empty_list(self):
|
||||
items = []
|
||||
_sort_reservations_inplace(items)
|
||||
assert items == []
|
||||
|
||||
def test_single_item(self):
|
||||
items = [{"future_ts": 100.0, "prize_value_yuan": 200.0, "created_ts": 1.0}]
|
||||
_sort_reservations_inplace(items)
|
||||
assert len(items) == 1
|
||||
|
||||
def test_in_place_not_returns_new_list(self):
|
||||
items = [
|
||||
{"future_ts": 200.0, "prize_value_yuan": 100.0, "created_ts": 1.0},
|
||||
{"future_ts": 100.0, "prize_value_yuan": 200.0, "created_ts": 2.0},
|
||||
]
|
||||
original_id = id(items)
|
||||
_sort_reservations_inplace(items)
|
||||
# 原列表对象未变
|
||||
assert id(items) == original_id
|
||||
@@ -0,0 +1,169 @@
|
||||
"""douyin/handlers/screenshot_manager/ 子包单元测试。
|
||||
|
||||
覆盖纯函数子模块:paths(分类逻辑、路径构造)、_common(异步计数器)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.handlers.screenshot_manager import (
|
||||
_SKIP_DEBUG_SAVE_IN_HOTLOOPS,
|
||||
ensure_debug_captures_dir,
|
||||
ensure_ocr_dir,
|
||||
get_async_save_counters,
|
||||
get_category_for_picname,
|
||||
get_debug_captures_base_dir,
|
||||
get_debug_captures_dir,
|
||||
get_last_success_path,
|
||||
get_latest_attempt_path,
|
||||
get_ocr_dir,
|
||||
reset_async_save_counters,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# paths.py — get_category_for_picname
|
||||
# ============================================================
|
||||
|
||||
class TestGetCategoryForPicname:
|
||||
@pytest.mark.parametrize(
|
||||
"picname,expected",
|
||||
[
|
||||
("福袋详情", "fudai"),
|
||||
("fudai_detail", "fudai"),
|
||||
("直播间", "live_room"),
|
||||
("live_room_state", "live_room"),
|
||||
("直播列表", "live_room"),
|
||||
("直播广场", "live_room"),
|
||||
("coupon_popup", "popups"),
|
||||
("redpacket_dialog", "popups"),
|
||||
("抽奖结果", "popups"),
|
||||
("无奖励", "popups"),
|
||||
("订单确认", "popups"),
|
||||
("参与按钮", "buttons"),
|
||||
("attend_button_red", "buttons"),
|
||||
("粉丝团", "buttons"),
|
||||
("fans_club_join", "buttons"),
|
||||
("推荐页", "stage_diag"),
|
||||
("recommend_tab", "stage_diag"),
|
||||
("关注列表", "stage_diag"),
|
||||
("follow_list", "stage_diag"),
|
||||
# 注意:"直播列表标签" 含"直播列表",按关键词优先级先归 live_room
|
||||
("live_list_tab", "stage_diag"),
|
||||
],
|
||||
)
|
||||
def test_known_categories(self, picname, expected):
|
||||
assert get_category_for_picname(picname) == expected
|
||||
|
||||
@pytest.mark.parametrize("picname", ["random_pic", "unknown", "abc123", "test"])
|
||||
def test_unknown_falls_back_to_others(self, picname):
|
||||
assert get_category_for_picname(picname) == "others"
|
||||
|
||||
def test_case_insensitive(self):
|
||||
# 实现里 picname.lower() 后匹配
|
||||
assert get_category_for_picname("FUDAI_DETAIL") == "fudai"
|
||||
assert get_category_for_picname("LIVE_ROOM") == "live_room"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# paths.py — get_latest_attempt_path / get_last_success_path
|
||||
# ============================================================
|
||||
|
||||
class TestPaths:
|
||||
@pytest.mark.parametrize(
|
||||
"operation_type,expected_suffix",
|
||||
[
|
||||
("pixel", "latest_attempt_pixel.png"),
|
||||
("pixel_detect", "latest_attempt_pixel.png"),
|
||||
("ocr", "latest_attempt_ocr.png"),
|
||||
("cut_pic", "latest_attempt_ocr.png"),
|
||||
("template", "latest_attempt_template.png"),
|
||||
("template_match", "latest_attempt_template.png"),
|
||||
("general", "latest_attempt_general.png"),
|
||||
("", "latest_attempt_general.png"),
|
||||
("unknown_type", "latest_attempt_general.png"),
|
||||
],
|
||||
)
|
||||
def test_latest_attempt_path(self, operation_type, expected_suffix):
|
||||
result = get_latest_attempt_path(operation_type)
|
||||
assert result.endswith(expected_suffix), f"got {result}"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"operation_type,expected_suffix",
|
||||
[
|
||||
("pixel", "last_success_pixel.png"),
|
||||
("ocr", "last_success_ocr.png"),
|
||||
("template", "last_success_template.png"),
|
||||
("general", "last_success_general.png"),
|
||||
],
|
||||
)
|
||||
def test_last_success_path(self, operation_type, expected_suffix):
|
||||
result = get_last_success_path(operation_type)
|
||||
assert result.endswith(expected_suffix), f"got {result}"
|
||||
|
||||
def test_default_operation_type_is_general(self):
|
||||
latest = get_latest_attempt_path()
|
||||
success = get_last_success_path()
|
||||
assert latest.endswith("latest_attempt_general.png")
|
||||
assert success.endswith("last_success_general.png")
|
||||
|
||||
def test_get_ocr_dir_returns_str(self):
|
||||
d = get_ocr_dir()
|
||||
assert isinstance(d, str)
|
||||
assert d.endswith("ocr")
|
||||
|
||||
def test_get_debug_captures_dir_includes_date(self):
|
||||
# 该函数会按今天的日期返回路径
|
||||
d = get_debug_captures_dir()
|
||||
assert isinstance(d, str)
|
||||
assert "debug_captures" in d
|
||||
# 日期目录形如 YYYY-MM-DD
|
||||
assert any(part.count("-") == 2 and len(part) == 10 for part in d.split(os.sep))
|
||||
|
||||
def test_get_debug_captures_base_dir_is_parent(self):
|
||||
base = get_debug_captures_base_dir()
|
||||
assert isinstance(base, str)
|
||||
# base 应是 dated 目录的上级(包含 'debug_captures')
|
||||
assert base.endswith("debug_captures")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# paths.py — ensure_*
|
||||
# ============================================================
|
||||
|
||||
class TestEnsureDirs:
|
||||
def test_ensure_ocr_dir_idempotent(self):
|
||||
# 应不抛
|
||||
ensure_ocr_dir()
|
||||
ensure_ocr_dir()
|
||||
|
||||
def test_ensure_debug_captures_dir_idempotent(self):
|
||||
ensure_debug_captures_dir()
|
||||
ensure_debug_captures_dir()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _common.py — 异步计数器
|
||||
# ============================================================
|
||||
|
||||
class TestAsyncSaveCounters:
|
||||
def test_returns_tuple_of_int(self):
|
||||
s, f = get_async_save_counters()
|
||||
assert isinstance(s, int)
|
||||
assert isinstance(f, int)
|
||||
|
||||
def test_reset(self):
|
||||
reset_async_save_counters()
|
||||
s, f = get_async_save_counters()
|
||||
assert s == 0 and f == 0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 环境开关
|
||||
# ============================================================
|
||||
|
||||
class TestSkipDebugFlag:
|
||||
def test_is_bool(self):
|
||||
assert isinstance(_SKIP_DEBUG_SAVE_IN_HOTLOOPS, bool)
|
||||
@@ -0,0 +1,216 @@
|
||||
"""douyin/core/underlying_operations_pkg/ 子包单元测试。
|
||||
|
||||
覆盖纯函数子模块:adb_helpers / bounds / countdown / ocr_content / pic_path
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.core.underlying_operations_pkg import (
|
||||
_adb_args,
|
||||
_adb_path,
|
||||
_find_pic_path,
|
||||
_parse_bounds,
|
||||
_pick_adbkeyboard_ime,
|
||||
check_countdown,
|
||||
extract_ocr_content,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# adb_helpers.py
|
||||
# ============================================================
|
||||
|
||||
class TestAdbPath:
|
||||
def test_default_returns_adb(self, monkeypatch):
|
||||
# 默认走 ADB_EXECUTABLE 环境变量;如果未设,应返回 'adb'
|
||||
monkeypatch.delenv("ADB_EXECUTABLE", raising=False)
|
||||
assert _adb_path() == "adb"
|
||||
|
||||
def test_env_override(self, monkeypatch):
|
||||
monkeypatch.setenv("ADB_EXECUTABLE", "/usr/local/bin/adb")
|
||||
assert _adb_path() == "/usr/local/bin/adb"
|
||||
|
||||
def test_strips_outer_quotes(self, monkeypatch):
|
||||
monkeypatch.setenv("ADB_EXECUTABLE", '"C:\\Program Files\\adb.exe"')
|
||||
# 包了引号的应当去引号返回 raw 路径
|
||||
assert _adb_path() == "C:\\Program Files\\adb.exe"
|
||||
|
||||
|
||||
class TestAdbArgs:
|
||||
def test_basic(self):
|
||||
result = _adb_args("AB123", "shell", "ls")
|
||||
assert "adb" in result[0]
|
||||
assert result[1] == "-s"
|
||||
assert result[2] == "AB123"
|
||||
assert "shell" in result and "ls" in result
|
||||
|
||||
def test_no_extra_args(self):
|
||||
result = _adb_args("AB123")
|
||||
assert len(result) == 3
|
||||
assert result[1] == "-s"
|
||||
|
||||
def test_args_coerced_to_str(self):
|
||||
# 非 str 参数应被 str() 转换
|
||||
result = _adb_args("AB123", "shell", 42)
|
||||
assert "42" in result
|
||||
|
||||
|
||||
class TestPickAdbKeyboardIme:
|
||||
def test_pick_existing(self):
|
||||
imes = ["com.android.adbkeyboard/.AdbIME", "com.example/.X"]
|
||||
assert _pick_adbkeyboard_ime(imes) == "com.android.adbkeyboard/.AdbIME"
|
||||
|
||||
def test_no_match_returns_empty(self):
|
||||
imes = ["com.example/.X", "com.foo/.Y"]
|
||||
# 没匹配应返回空串或 None;具体取决于实现
|
||||
result = _pick_adbkeyboard_ime(imes)
|
||||
assert result in ("", None) or "adbkeyboard" not in result.lower()
|
||||
|
||||
def test_empty_list(self):
|
||||
result = _pick_adbkeyboard_ime([])
|
||||
assert result in ("", None)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# bounds.py — _parse_bounds
|
||||
# ============================================================
|
||||
|
||||
class TestParseBounds:
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected",
|
||||
[
|
||||
("[100,200][300,400]", (100, 200, 300, 400)),
|
||||
("[0,0][1080,2400]", (0, 0, 1080, 2400)),
|
||||
("[50,50][150,150]", (50, 50, 150, 150)),
|
||||
],
|
||||
)
|
||||
def test_valid(self, text, expected):
|
||||
assert _parse_bounds(text) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"",
|
||||
"abc",
|
||||
"[100,200]", # 单个 bound
|
||||
"100,200,300,400", # 缺方括号
|
||||
],
|
||||
)
|
||||
def test_invalid_returns_none(self, text):
|
||||
assert _parse_bounds(text) is None
|
||||
|
||||
|
||||
# ============================================================
|
||||
# countdown.py — check_countdown
|
||||
# ============================================================
|
||||
|
||||
class TestCheckCountdown:
|
||||
def test_mm_ss_full_format(self):
|
||||
result = check_countdown("5:30")
|
||||
assert result is not False
|
||||
seconds, future_ts = result
|
||||
assert seconds == 330 # 5*60 + 30
|
||||
|
||||
def test_chinese_format(self):
|
||||
result = check_countdown("3分20秒")
|
||||
assert result is not False
|
||||
assert result[0] == 200
|
||||
|
||||
def test_seconds_only(self):
|
||||
result = check_countdown("45秒")
|
||||
assert result is not False
|
||||
assert result[0] == 45
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text,expected_seconds",
|
||||
[
|
||||
("0:30", 30),
|
||||
("1:00", 60),
|
||||
("10:00", 600),
|
||||
("12:34", 12 * 60 + 34),
|
||||
],
|
||||
)
|
||||
def test_various(self, text, expected_seconds):
|
||||
result = check_countdown(text)
|
||||
assert result is not False
|
||||
assert result[0] == expected_seconds
|
||||
|
||||
def test_empty_returns_false(self):
|
||||
assert check_countdown("") is False
|
||||
|
||||
def test_garbage_returns_false(self):
|
||||
assert check_countdown("xyz") is False
|
||||
|
||||
def test_overlong_capped(self):
|
||||
"""超过 15 分钟的输入会被截断到 14分50秒,避免误识别卡死。"""
|
||||
result = check_countdown("99:99")
|
||||
if result is not False:
|
||||
seconds, _ = result
|
||||
# 实际逻辑:>900 截到 890
|
||||
assert seconds <= 900
|
||||
|
||||
def test_ocr_char_corrections(self):
|
||||
"""O→0, l→1 等字符纠错。"""
|
||||
# 'l:30' 应识别为 '1:30'(l→1)
|
||||
result = check_countdown("l:30")
|
||||
if result is not False:
|
||||
assert result[0] == 90
|
||||
|
||||
def test_with_chinese_colon(self):
|
||||
result = check_countdown("5:30")
|
||||
assert result is not False
|
||||
assert result[0] == 330
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ocr_content.py — extract_ocr_content
|
||||
# ============================================================
|
||||
|
||||
class TestExtractOcrContent:
|
||||
def test_empty_returns_empty_string(self):
|
||||
assert extract_ocr_content(None) == ""
|
||||
assert extract_ocr_content([]) == ""
|
||||
|
||||
def test_with_confidence_returns_tuple(self):
|
||||
# return_confidence=True 应返回 (text, confidence_info)
|
||||
result = extract_ocr_content([], return_confidence=True)
|
||||
assert isinstance(result, tuple) and len(result) == 2
|
||||
text, info = result
|
||||
assert isinstance(text, str)
|
||||
assert isinstance(info, dict)
|
||||
assert "avg_confidence" in info
|
||||
|
||||
def test_default_returns_str_only(self):
|
||||
result = extract_ocr_content(None, return_confidence=False)
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# pic_path.py — _find_pic_path
|
||||
# ============================================================
|
||||
|
||||
class TestFindPicPath:
|
||||
def test_runtime_file_screenshot(self):
|
||||
# 'screenshot' 是运行时必需文件,应返回 pic_base/screenshot.png 或 None
|
||||
result = _find_pic_path("screenshot", for_reading=True)
|
||||
# 不强求文件存在,只要不抛异常
|
||||
assert result is None or isinstance(result, str)
|
||||
|
||||
def test_screenshot_for_writing(self):
|
||||
# for_reading=False 时应返回路径(即使文件不存在)
|
||||
result = _find_pic_path("screenshot", for_reading=False)
|
||||
assert isinstance(result, str)
|
||||
assert "screenshot" in result and result.endswith(".png")
|
||||
|
||||
def test_cut_file_for_writing(self):
|
||||
result = _find_pic_path("cut", for_reading=False)
|
||||
assert isinstance(result, str)
|
||||
assert result.endswith("cut.png")
|
||||
|
||||
def test_unknown_picname(self):
|
||||
# 不存在的 picname 应返回 None 或一个写入路径,不抛
|
||||
result = _find_pic_path("nonexistent_pic_name_12345", for_reading=True)
|
||||
assert result is None or isinstance(result, str)
|
||||
@@ -0,0 +1,238 @@
|
||||
"""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}")
|
||||
@@ -0,0 +1,92 @@
|
||||
"""douyin/other/douyin_yanghao_pkg/ 子包单元测试。
|
||||
|
||||
覆盖 logger(_yanghao_log)、entrypoints(yanghao_get_recommend_seconds 等)。
|
||||
yanghao_idle 仍在原文件,不在本子包测试范围。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
|
||||
from douyin.other.douyin_yanghao_pkg import (
|
||||
_LOGGER,
|
||||
_yanghao_log,
|
||||
yanghao_get_recommend_seconds,
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# logger.py — _yanghao_log
|
||||
# ============================================================
|
||||
|
||||
class TestYanghaoLog:
|
||||
def test_logger_name(self):
|
||||
assert _LOGGER.name == "douyin.other.douyin_yanghao"
|
||||
|
||||
def test_with_log_kv_analyser_uses_it(self):
|
||||
"""analyser 提供 _log_kv 时应优先调用,不走 logger。"""
|
||||
captured = []
|
||||
|
||||
class A:
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
captured.append((args, kwargs))
|
||||
|
||||
_yanghao_log(A(), "[test] hello", level="INFO")
|
||||
assert len(captured) == 1, "_log_kv 应被调用 1 次"
|
||||
|
||||
def test_without_log_kv_uses_logger(self, caplog):
|
||||
"""analyser 无 _log_kv 时走 logger。"""
|
||||
class A: pass
|
||||
with caplog.at_level(logging.INFO, logger="douyin.other.douyin_yanghao"):
|
||||
_yanghao_log(A(), "[test] fallback", level="INFO")
|
||||
# 至少捕获到一条记录
|
||||
assert any("[test] fallback" in r.getMessage() for r in caplog.records)
|
||||
|
||||
def test_none_analyser_does_not_raise(self):
|
||||
# 传 None 应兜底到 logger
|
||||
_yanghao_log(None, "[test] none", level="WARNING")
|
||||
|
||||
def test_broken_log_kv_does_not_raise(self):
|
||||
"""analyser._log_kv 抛异常应被吞掉,不影响调用方。"""
|
||||
class Broken:
|
||||
def _log_kv(self, *args, **kwargs):
|
||||
raise RuntimeError("broken")
|
||||
_yanghao_log(Broken(), "[test] broken", level="ERROR")
|
||||
|
||||
@pytest.mark.parametrize("level", ["INFO", "WARNING", "ERROR", "DEBUG"])
|
||||
def test_known_levels(self, level):
|
||||
# 已知级别应不抛
|
||||
_yanghao_log(None, f"[test] {level}", level=level)
|
||||
|
||||
def test_unknown_level_does_not_raise(self):
|
||||
_yanghao_log(None, "[test] unknown", level="FOOBAR")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# entrypoints.py — yanghao_get_recommend_seconds
|
||||
# ============================================================
|
||||
|
||||
class TestYanghaoGetRecommendSeconds:
|
||||
def test_default_attribute(self):
|
||||
class A:
|
||||
yanghao_recommend_duration_seconds = 100
|
||||
assert yanghao_get_recommend_seconds(A()) == 100
|
||||
|
||||
def test_missing_attribute_uses_default(self):
|
||||
class A: pass # 没 yanghao_recommend_duration_seconds
|
||||
result = yanghao_get_recommend_seconds(A())
|
||||
# 默认应为 60
|
||||
assert result == 60
|
||||
|
||||
def test_zero_or_negative_uses_default(self):
|
||||
class A:
|
||||
yanghao_recommend_duration_seconds = 0
|
||||
# 0 应该被替换为默认 60
|
||||
result = yanghao_get_recommend_seconds(A())
|
||||
assert result == 60
|
||||
|
||||
def test_returns_int(self):
|
||||
class A:
|
||||
yanghao_recommend_duration_seconds = 200
|
||||
assert isinstance(yanghao_get_recommend_seconds(A()), int)
|
||||
Reference in new issue
Block a user