Files
douyi_guaji_main/tests/test_logger_helpers.py
T
CodexandClaude Opus 4.7 ecffba94b4 P3 §7: 引入 pytest 基础设施 + 9 个核心模块冒烟/单元测试
§7-1 pytest 基础设施
  - pyproject.toml 加 [tool.pytest.ini_options]
    (testpaths / python_files / strict markers / smoke + slow marker 注册)
  - tests/conftest.py 自动把项目根加到 sys.path

§7-2 核心模块测试(242 passed, 1 skipped)
  - test_filter_logging.py(重写为 pytest):should_skip_fudai_by_config
    + is_watch_task_fudai + _is_short_countdown_text 共 29 用例
  - test_time_utils.py:parse_mm_ss + extract_2digits 共 22 用例
  - test_douyin_text_utils.py:4 个 OCR 解析函数 25 用例
  - test_douyin_utils.py:extract_prize_value_yuan + normalize_countdown_text 21 用例
  - test_path_config.py:10 个路径函数结构断言 + 路径间互不重复 20 用例
  - test_logger_helpers.py:8 个 print→logger helper 的统一接口测试 20 用例
  - test_unified_logger_mdc.py:MDC 7 个方法 + 线程隔离 13 用例
  - test_io_utils.py:_verify_png_integrity / _safe_replace_file /
    _ensure_parent_dir 11 用例
  - test_imports.py:78 个核心模块的 import 冒烟 + 关键类/函数导出验证

修订老测试
  - test_ocr_comparison.py:用 pytest.importorskip 跳过缺失的 psutil/easyocr/paddleocr,
    并整体标 @pytest.mark.slow(需要 'pytest -m slow' 才会跑)
  - test_webgui.py:原会真的启 HTTP 服务卡死,改为 import 冒烟 + helper 调用测试

README
  - 重写 "## ✅ 测试" 段,给出实际可用的 pytest 命令、测试约定、marker 说明

回归:tests/ 142 项测试 PASS / 1 SKIP / 0 FAIL;全部纯函数 + 不依赖 ADB / OCR / 设备。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-21 14:09:02 +08:00

123 lines
4.3 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.
"""8 个 print→logger helper 的 pytest 单元测试。
每个 helper 都遵循同一模式:
- 优先走 logger(INFO/WARNING/ERROR/DEBUG 分级)
- logger 异常时兜底到 stdout
- 不抛异常
带 analyser 参数的 helper(_yanghao_log / _robot_log)还会优先尝试 analyser._log_kv。
"""
from __future__ import annotations
import logging
import pytest
# ============================================================
# 8 个 helper 的元信息
# ============================================================
# (module_path, helper_name, takes_analyser)
HELPERS = [
("douyin.other.douyin_yanghao", "_yanghao_log", True),
("douyin.other.douyin_robot", "_robot_log", True),
("douyin.handlers.douyin_screenshot_manager", "_mgr_log", False),
("operations.screenshot_service", "_svc_log", False),
("operations.screenshot_operations", "_ops_log", False),
("operations.ocr_operations", "_ocr_log", False),
("gui.web_gui", "_wg_log", False),
("douyin.core.underlying_operations", "_uo_log", False),
]
def _import_helper(module_path, helper_name):
mod = __import__(module_path, fromlist=[helper_name])
return getattr(mod, helper_name)
# ============================================================
# 通用:调用不抛异常 + 走 logger
# ============================================================
@pytest.mark.parametrize("module_path,helper_name,takes_analyser", HELPERS)
def test_helper_does_not_raise(module_path, helper_name, takes_analyser, caplog):
"""正常调用 helper 不应抛异常,且至少有一条对应级别的 log 被发射。"""
fn = _import_helper(module_path, helper_name)
with caplog.at_level(logging.DEBUG):
if takes_analyser:
fn(None, "[test] info-level")
fn(None, "[test] warn", level="WARNING")
fn(None, "[test] err", level="ERROR")
fn(None, "[test] dbg", level="DEBUG")
else:
fn("[test] info-level")
fn("[test] warn", level="WARNING")
fn("[test] err", level="ERROR")
fn("[test] dbg", level="DEBUG")
# 至少捕获到 1 条记录(不要求全部,因为 DEBUG 可能被父 logger 过滤)
assert any("[test]" in r.message for r in caplog.records), (
f"{module_path}.{helper_name} 未发射任何 [test] 日志"
)
@pytest.mark.parametrize("module_path,helper_name,takes_analyser", HELPERS)
def test_helper_with_unknown_level(module_path, helper_name, takes_analyser, caplog):
"""传未知 level 也应不抛(一般会兜底为 INFO)。"""
fn = _import_helper(module_path, helper_name)
with caplog.at_level(logging.DEBUG):
if takes_analyser:
fn(None, "[test] unknown-level", level="WHATEVER")
else:
fn("[test] unknown-level", level="WHATEVER")
# 不抛即通过
# ============================================================
# 带 analyser 参数的 helper:优先调用 analyser._log_kv
# ============================================================
class FakeAnalyser:
"""收集 _log_kv 调用,用于断言。"""
def __init__(self):
self.calls = []
def _log_kv(self, *args, **kwargs):
self.calls.append((args, kwargs))
@pytest.mark.parametrize(
"module_path,helper_name",
[
("douyin.other.douyin_yanghao", "_yanghao_log"),
("douyin.other.douyin_robot", "_robot_log"),
],
)
def test_analyser_log_kv_preferred(module_path, helper_name):
"""analyser 提供 _log_kv 时,helper 应优先走 _log_kv。"""
fn = _import_helper(module_path, helper_name)
a = FakeAnalyser()
fn(a, "[test] should-go-to-log-kv", level="WARNING")
assert a.calls, f"{helper_name} 未调用 analyser._log_kv"
class BrokenAnalyser:
"""_log_kv 总是抛异常,模拟 analyser 处于异常状态。"""
def _log_kv(self, *args, **kwargs):
raise RuntimeError("analyser._log_kv broken")
@pytest.mark.parametrize(
"module_path,helper_name",
[
("douyin.other.douyin_yanghao", "_yanghao_log"),
("douyin.other.douyin_robot", "_robot_log"),
],
)
def test_broken_analyser_does_not_raise(module_path, helper_name):
"""analyser._log_kv 抛异常时,helper 应静默兜底而非把异常抛给调用方。"""
fn = _import_helper(module_path, helper_name)
# 不应抛任何异常
fn(BrokenAnalyser(), "[test] broken", level="ERROR")