Files
douyi_guaji_main/tests/test_template_match_helpers.py
T
CodexandClaude Opus 4.7 a391c21f47 refactor(detection): 拆出 finder.py 模板匹配兜底(936→719,-217 行)
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"块(226 行)抽到
template_match_helpers.template_match_fallback:
- 模板加载与缩放
- 搜索区域裁剪 + 边界保护
- cv2.matchTemplate + 双阈值判定
- 调试截图保存(last_match.png + 双截图记录)

新增 5 个单元测试覆盖:模板缺失 / 模板读取失败 / 阈值异常 / 不可达阈值 / 完美匹配。
1315 → 1320 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 04:55:08 +08:00

140 lines
4.6 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.
"""单元测试: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