"""单元测试:douyin/detection/detection_pkg/template_match_helpers.py 只覆盖纯逻辑路径与异常吞噬: - 模板文件不存在 → 返回 (False, None) - OpenCV 导入失败 / 模板读取失败 → 异常吞噬 - 命中/未命中分数对比 """ from __future__ import annotations import os from unittest.mock import MagicMock, patch import pytest from douyin.detection.detection_pkg import template_match_helpers as h def _make_analyser(): a = MagicMock() a._log_kv = MagicMock() a.fudai_template_match_threshold = 0.7 return a def test_template_match_missing_template_file_returns_false(monkeypatch, tmp_path): a = _make_analyser() fake_assets = tmp_path / "no_assets" monkeypatch.setattr( "douyin.core.path_config.get_assets_dir", lambda: str(fake_assets), ) pic = MagicMock() detected, x = h.template_match_fallback( a, pic, rx=1080, ry=2400, width=1080, height=2400, y_pianyi_val=0, loop=0, ) assert detected is False assert x is None def test_template_match_outer_exception_swallowed(monkeypatch): a = _make_analyser() # 让 cv2 import 抛错触发外层 except monkeypatch.setitem(__import__("sys").modules, "cv2", None) pic = MagicMock() detected, x = h.template_match_fallback( a, pic, rx=1080, ry=2400, width=1080, height=2400, y_pianyi_val=0, loop=0, ) # cv2=None 时 .imread 调用抛 AttributeError → 被吞噬 assert detected is False assert x is None def test_template_match_threshold_attr_not_a_number(monkeypatch, tmp_path): """threshold 异常时回退到 0.7""" a = _make_analyser() a.fudai_template_match_threshold = "not_a_number" fake_assets = tmp_path / "assets" fake_assets.mkdir() (fake_assets / "fudai.png").write_bytes(b"not_a_real_png") monkeypatch.setattr( "douyin.core.path_config.get_assets_dir", lambda: str(fake_assets), ) pic = MagicMock() # cv2.imread 会返回 None(不是真 PNG),触发"模板读取失败"分支 detected, x = h.template_match_fallback( a, pic, rx=1080, ry=2400, width=1080, height=2400, y_pianyi_val=0, loop=0, ) assert detected is False def test_template_match_full_pipeline_no_match(tmp_path, monkeypatch): """阈值设到 1.01(不可达)→ 必然不匹配,验证阈值分支。""" cv2 = pytest.importorskip("cv2") import numpy as np from PIL import Image a = _make_analyser() a.fudai_template_match_threshold = 1.01 # 不可达,必然不匹配 fake_assets = tmp_path / "assets" fake_assets.mkdir() np.random.seed(7) template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8) cv2.imwrite(str(fake_assets / "fudai.png"), template) monkeypatch.setattr( "douyin.core.path_config.get_assets_dir", lambda: str(fake_assets), ) pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8) pic = Image.fromarray(pic_arr, mode="RGBA") detected, x = h.template_match_fallback( a, pic, rx=1080, ry=2400, width=1080, height=2400, y_pianyi_val=0, loop=0, ) assert detected is False assert x is None def test_template_match_full_pipeline_perfect_match(tmp_path, monkeypatch): """构造一张包含模板的图像 → 模板匹配应命中""" cv2 = pytest.importorskip("cv2") import numpy as np from PIL import Image a = _make_analyser() fake_assets = tmp_path / "assets" fake_assets.mkdir() # 创建一个 30x30 的明显图案作为模板 np.random.seed(0) template = np.random.randint(0, 255, (30, 30, 3), dtype=np.uint8) cv2.imwrite(str(fake_assets / "fudai.png"), template) monkeypatch.setattr( "douyin.core.path_config.get_assets_dir", lambda: str(fake_assets), ) # 构造一张图:把模板嵌入到搜索区域内(X=156-269, Y=351-451) pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8) pic_arr[..., 3] = 255 # alpha embed_y, embed_x = 380, 200 # 都在搜索区域内 # cv2 imread 是 BGR,put 时转回 RGB;这里直接用 numpy 嵌入相同 BGR 数组 pic_arr[embed_y:embed_y + 30, embed_x:embed_x + 30, :3] = template[..., ::-1] pic = Image.fromarray(pic_arr, mode="RGBA") detected, x = h.template_match_fallback( a, pic, rx=1080, ry=2400, width=1080, height=2400, y_pianyi_val=0, loop=0, ) assert detected is True # 检测到的 x 应当在嵌入位置附近(embed_x + tw//2 = 200 + 15 = 215,1080 基准下相同) assert x is not None assert abs(x - (embed_x + 15)) <= 5