覆盖 screenshot_manager.save_files / reservation_logic._common / logging_wrapper_pkg._common 共 14 个测试。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
234 lines
9.8 KiB
Python
234 lines
9.8 KiB
Python
"""更多 _pkg 子模块的单元测试(save_files / reservation_logic._common /
|
||
logging_wrapper_pkg._common)。
|
||
|
||
覆盖:
|
||
- screenshot_manager.save_files:4 个 save_* 函数 + cleanup_ocr_dir
|
||
- reservation_logic._common:ReservationItem / 错误处理占位
|
||
- logging_wrapper_pkg._common:Fore/Style/占位日志类
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
from PIL import Image
|
||
|
||
|
||
# ============================================================
|
||
# screenshot_manager.save_files
|
||
# ============================================================
|
||
|
||
class TestSaveFiles:
|
||
"""save_latest_attempt / save_last_success / save_*_from_file / cleanup_ocr_dir。"""
|
||
|
||
def test_save_latest_attempt(self, tmp_path, monkeypatch):
|
||
# 用 monkeypatch 把 OCR 目录改到 tmp_path/ocr,避免污染真实环境
|
||
from douyin.handlers.screenshot_manager import save_files, paths
|
||
ocr_dir = tmp_path / "ocr"
|
||
|
||
monkeypatch.setattr(paths, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(save_files, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(
|
||
save_files, "get_latest_attempt_path",
|
||
lambda op: str(ocr_dir / f"latest_attempt_{op or 'general'}.png"),
|
||
)
|
||
|
||
img = Image.new("RGB", (10, 10), (255, 0, 0))
|
||
result = save_files.save_latest_attempt(img, "ocr")
|
||
assert result is True
|
||
# 文件应该真的存在
|
||
target = ocr_dir / "latest_attempt_ocr.png"
|
||
assert target.exists()
|
||
|
||
def test_save_last_success(self, tmp_path, monkeypatch):
|
||
from douyin.handlers.screenshot_manager import save_files, paths
|
||
ocr_dir = tmp_path / "ocr"
|
||
|
||
monkeypatch.setattr(paths, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(save_files, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(
|
||
save_files, "get_last_success_path",
|
||
lambda op: str(ocr_dir / f"last_success_{op or 'general'}.png"),
|
||
)
|
||
|
||
img = Image.new("RGB", (10, 10), (0, 255, 0))
|
||
result = save_files.save_last_success(img, "pixel")
|
||
assert result is True
|
||
target = ocr_dir / "last_success_pixel.png"
|
||
assert target.exists()
|
||
|
||
def test_save_attempt_from_file(self, tmp_path, monkeypatch):
|
||
from douyin.handlers.screenshot_manager import save_files, paths
|
||
ocr_dir = tmp_path / "ocr"
|
||
|
||
monkeypatch.setattr(paths, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(save_files, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(
|
||
save_files, "get_latest_attempt_path",
|
||
lambda op: str(ocr_dir / f"latest_attempt_{op or 'general'}.png"),
|
||
)
|
||
|
||
# 准备一个源文件
|
||
src = tmp_path / "source.png"
|
||
Image.new("RGB", (5, 5), (0, 0, 255)).save(str(src), "PNG")
|
||
# save_attempt_from_file 应能读 src 并复制到 latest_attempt
|
||
result = save_files.save_attempt_from_file(str(src), "general")
|
||
assert result is True
|
||
target = ocr_dir / "latest_attempt_general.png"
|
||
assert target.exists()
|
||
|
||
def test_save_from_missing_file_returns_false(self, tmp_path):
|
||
from douyin.handlers.screenshot_manager import save_files
|
||
# 不存在的源文件
|
||
result = save_files.save_attempt_from_file(str(tmp_path / "nonexistent.png"), "")
|
||
assert result is False
|
||
|
||
def test_cleanup_ocr_dir(self, tmp_path, monkeypatch):
|
||
"""构造 60 个 .png 文件 + 一些特殊文件,验证 cleanup 删除超过 max_files 的部分。"""
|
||
from douyin.handlers.screenshot_manager import save_files, paths
|
||
ocr_dir = tmp_path / "ocr"
|
||
ocr_dir.mkdir()
|
||
monkeypatch.setattr(paths, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(save_files, "get_ocr_dir", lambda: str(ocr_dir))
|
||
|
||
# 普通文件 60 个
|
||
for i in range(60):
|
||
(ocr_dir / f"normal_{i}.png").write_bytes(b"\x89PNG\r\n\x1a\n")
|
||
# 受保护文件
|
||
(ocr_dir / "latest_attempt_pixel.png").write_bytes(b"\x89PNG\r\n\x1a\n")
|
||
(ocr_dir / "last_success_ocr.png").write_bytes(b"\x89PNG\r\n\x1a\n")
|
||
(ocr_dir / "test_success.png").write_bytes(b"\x89PNG\r\n\x1a\n")
|
||
|
||
# max_files=50:应删 10 个普通文件
|
||
deleted = save_files.cleanup_ocr_dir(max_files=50)
|
||
assert deleted == 10
|
||
|
||
# 受保护文件应保留
|
||
assert (ocr_dir / "latest_attempt_pixel.png").exists()
|
||
assert (ocr_dir / "last_success_ocr.png").exists()
|
||
assert (ocr_dir / "test_success.png").exists()
|
||
|
||
def test_cleanup_nonexistent_dir(self, tmp_path, monkeypatch):
|
||
"""OCR 目录不存在时应返回 0,不抛。"""
|
||
from douyin.handlers.screenshot_manager import save_files, paths
|
||
ocr_dir = tmp_path / "nonexistent_ocr_dir"
|
||
monkeypatch.setattr(paths, "get_ocr_dir", lambda: str(ocr_dir))
|
||
monkeypatch.setattr(save_files, "get_ocr_dir", lambda: str(ocr_dir))
|
||
|
||
assert save_files.cleanup_ocr_dir() == 0
|
||
|
||
|
||
# ============================================================
|
||
# reservation_logic._common
|
||
# ============================================================
|
||
|
||
class TestReservationLogicCommon:
|
||
def test_reservation_item_alias(self):
|
||
from douyin.reservation.reservation_logic._common import ReservationItem
|
||
# ReservationItem = Dict[str, Any],应能正常用作类型注解
|
||
# 运行时是 Dict,能正常构造(虽然 typing alias 一般不直接调 __init__)
|
||
# 我们只验证它可以被导入
|
||
assert ReservationItem is not None
|
||
|
||
def test_error_utils_callable(self):
|
||
"""4 个函数都应可调用(真实实现或占位)。
|
||
|
||
注意:测试不假设是占位 — _common.py 在导入成功时会用真实实现,
|
||
否则用占位。两种情况都应该不抛。
|
||
"""
|
||
from douyin.reservation.reservation_logic._common import (
|
||
_RESERVATION_ERROR_UTILS_AVAILABLE,
|
||
format_reservation_context,
|
||
log_reservation_error,
|
||
safe_write_state,
|
||
validate_reservation_item,
|
||
)
|
||
# 4 个函数都应该是可调用对象
|
||
for fn in (log_reservation_error, safe_write_state,
|
||
format_reservation_context, validate_reservation_item):
|
||
assert callable(fn)
|
||
|
||
# safe_write_state 可单参调用(写回调函数);占位实现忽略所有参数返回 True
|
||
# 用一个简单的写回调作为参数(真实实现需要它)
|
||
def _noop(): pass
|
||
try:
|
||
result = safe_write_state(_noop)
|
||
assert isinstance(result, bool)
|
||
except TypeError:
|
||
# 真实签名不接受这个调用方式,跳过
|
||
pass
|
||
|
||
# format_reservation_context 接受任意 kwargs,返回 dict
|
||
try:
|
||
result = format_reservation_context(reason="test", path="/tmp")
|
||
assert isinstance(result, dict)
|
||
except TypeError:
|
||
pass
|
||
|
||
# validate_reservation_item 接受一个 dict,返回 bool 或 (bool, str) 元组
|
||
try:
|
||
result = validate_reservation_item({})
|
||
assert isinstance(result, (bool, tuple))
|
||
except TypeError:
|
||
pass
|
||
|
||
def test_availability_flag_is_bool(self):
|
||
from douyin.reservation.reservation_logic._common import (
|
||
_RESERVATION_ERROR_UTILS_AVAILABLE,
|
||
)
|
||
assert isinstance(_RESERVATION_ERROR_UTILS_AVAILABLE, bool)
|
||
|
||
|
||
# ============================================================
|
||
# logging_wrapper_pkg._common
|
||
# ============================================================
|
||
|
||
class TestLoggingWrapperCommon:
|
||
def test_fore_constants(self):
|
||
from douyin.logging.douyin_logging_wrapper_pkg._common import Fore
|
||
# colorama 真实加载或我们的占位类,都应有 RED/GREEN 等常量
|
||
for color in ("RED", "GREEN", "YELLOW", "BLUE", "MAGENTA", "CYAN"):
|
||
assert hasattr(Fore, color), f"Fore 缺 {color}"
|
||
assert isinstance(getattr(Fore, color), str)
|
||
|
||
def test_style_constants(self):
|
||
from douyin.logging.douyin_logging_wrapper_pkg._common import Style
|
||
# colorama 真实加载时 RESET_ALL/BRIGHT 都有;占位类也提供
|
||
for attr in ("RESET_ALL", "BRIGHT"):
|
||
assert hasattr(Style, attr), f"Style 缺 {attr}"
|
||
assert isinstance(getattr(Style, attr), str)
|
||
|
||
def test_module_instances_exist(self):
|
||
from douyin.logging.douyin_logging_wrapper_pkg._common import (
|
||
_action_logger, _debug_logger, _error_logger, _performance_tracker,
|
||
)
|
||
# 4 个全局实例(真实 / 占位)都应有对应方法
|
||
assert hasattr(_action_logger, "log_step")
|
||
assert hasattr(_debug_logger, "log_variable")
|
||
assert hasattr(_error_logger, "log_exception")
|
||
assert hasattr(_performance_tracker, "get_statistics")
|
||
|
||
def test_placeholder_classes_callable(self):
|
||
"""4 个占位类(或真实类)的关键方法都应可调用。"""
|
||
from douyin.logging.douyin_logging_wrapper_pkg._common import (
|
||
ActionLogger, DebugLogger, ErrorLogger, PerformanceTracker,
|
||
)
|
||
a = ActionLogger()
|
||
d = DebugLogger()
|
||
e = ErrorLogger()
|
||
p = PerformanceTracker()
|
||
# 调用一次确认不抛
|
||
a.log_step("test")
|
||
d.log_variable("k", "v")
|
||
try:
|
||
raise ValueError("test")
|
||
except ValueError as exc:
|
||
e.log_exception(exc)
|
||
p.end_timer("test")
|
||
assert isinstance(p.get_statistics(), dict)
|
||
|
||
def test_availability_flags_are_bool(self):
|
||
from douyin.logging.douyin_logging_wrapper_pkg._common import (
|
||
COLORAMA_AVAILABLE, LOGGING_MODULES_AVAILABLE,
|
||
)
|
||
assert isinstance(COLORAMA_AVAILABLE, bool)
|
||
assert isinstance(LOGGING_MODULES_AVAILABLE, bool)
|