Files
douyi_guaji_main/tests/test_logger_helpers.py
T

152 lines
5.2 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 importlib
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")
@pytest.mark.parametrize(
"module_path,helper_name",
[
("operations.screenshot_service", "_svc_log"),
("operations.ocr_operations", "_ocr_log"),
],
)
def test_logger_failure_falls_back_to_print(module_path, helper_name, monkeypatch):
"""logger 自身异常时,helper 应直接兜底到 print,而不是递归调用自身。"""
mod = importlib.import_module(module_path)
fn = getattr(mod, helper_name)
class BrokenLogger:
def info(self, *_args, **_kwargs):
raise RuntimeError("logger broken")
warning = error = debug = info
printed: list[str] = []
monkeypatch.setattr(mod, "_LOGGER", BrokenLogger())
monkeypatch.setattr("builtins.print", lambda msg: printed.append(str(msg)))
fn("[test] print fallback")
assert printed == ["[test] print fallback"]