把 finder.py 中两个像素扫描兜底块抽到 template_match_helpers: - numpy_pixel_scan:numpy 加速水平带扫描(126 行) - per_pixel_scan_fallback:numpy 失败时的逐像素扫描(166 行) - _is_target_pixel / _scan_one_row / _save_per_pixel_success:辅助函数 新增 10 个单元测试覆盖:无匹配 / 命中 / 无效 ROI / last_fudai_x 复用 / 异常吞噬 / 目标颜色范围判定。1320 → 1330 用例全过。 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
288 lines
8.9 KiB
Python
288 lines
8.9 KiB
Python
"""单元测试: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
|
||
|
||
|
||
# ---- numpy_pixel_scan ---- #
|
||
|
||
def test_numpy_pixel_scan_no_match(tmp_path):
|
||
"""全黑图像 → numpy 扫描不会命中目标颜色范围"""
|
||
pytest.importorskip("numpy")
|
||
import numpy as np
|
||
from PIL import Image
|
||
|
||
a = _make_analyser()
|
||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||
pic_arr[..., 3] = 255
|
||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||
|
||
detected, x = h.numpy_pixel_scan(
|
||
a, pic, rx=1080, ry=2400,
|
||
width=1080, height=2400, y_pianyi_val=0,
|
||
optimal_x_scaled=169,
|
||
)
|
||
assert detected is False
|
||
assert x is None
|
||
|
||
|
||
def test_numpy_pixel_scan_with_match(tmp_path):
|
||
"""构造目标颜色 → numpy 扫描命中"""
|
||
pytest.importorskip("numpy")
|
||
import numpy as np
|
||
from PIL import Image
|
||
|
||
a = _make_analyser()
|
||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||
pic_arr[..., 3] = 255
|
||
# 目标颜色 R=200, G=185, B=240(在范围内:R[190-206], G[173-196], B[234-250])
|
||
# 在搜索区域 X=157-410, Y=354 附近放一列像素(每列至少 2 个像素,valid_cols >= 2)
|
||
target_x = 250
|
||
pic_arr[353:355, target_x, 0] = 200
|
||
pic_arr[353:355, target_x, 1] = 185
|
||
pic_arr[353:355, target_x, 2] = 240
|
||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||
|
||
detected, x = h.numpy_pixel_scan(
|
||
a, pic, rx=1080, ry=2400,
|
||
width=1080, height=2400, y_pianyi_val=0,
|
||
optimal_x_scaled=target_x,
|
||
)
|
||
assert detected is True
|
||
assert x == target_x
|
||
|
||
|
||
def test_numpy_pixel_scan_invalid_roi():
|
||
"""搜索区域无效(width < 157)→ 直接返回 False"""
|
||
a = _make_analyser()
|
||
pic = MagicMock()
|
||
detected, x = h.numpy_pixel_scan(
|
||
a, pic, rx=1080, ry=2400,
|
||
width=100, height=2400, y_pianyi_val=0, # width < 157
|
||
optimal_x_scaled=169,
|
||
)
|
||
assert detected is False
|
||
|
||
|
||
# ---- per_pixel_scan_fallback ---- #
|
||
|
||
def test_per_pixel_scan_no_match():
|
||
"""全白图 → 像素逐行扫描找不到目标颜色"""
|
||
import numpy as np
|
||
from PIL import Image
|
||
|
||
a = _make_analyser()
|
||
pic_arr = np.full((2400, 1080, 4), 255, dtype=np.uint8)
|
||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||
|
||
detected, x = h.per_pixel_scan_fallback(
|
||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||
)
|
||
assert detected is False
|
||
assert x is None
|
||
|
||
|
||
def test_per_pixel_scan_with_match():
|
||
"""构造目标像素 → 逐行扫描命中"""
|
||
import numpy as np
|
||
from PIL import Image
|
||
|
||
a = _make_analyser()
|
||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||
pic_arr[..., 3] = 255
|
||
# 在 scan_y=403, scan_x=200 处放目标像素
|
||
pic_arr[403, 200] = (200, 185, 240, 255)
|
||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||
|
||
detected, x = h.per_pixel_scan_fallback(
|
||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||
)
|
||
assert detected is True
|
||
assert x == 200
|
||
|
||
|
||
def test_per_pixel_scan_uses_last_fudai_x():
|
||
"""analyser.last_fudai_x 设置时,从该位置开始搜索"""
|
||
import numpy as np
|
||
from PIL import Image
|
||
|
||
a = _make_analyser()
|
||
a.last_fudai_x = 250
|
||
pic_arr = np.zeros((2400, 1080, 4), dtype=np.uint8)
|
||
pic_arr[..., 3] = 255
|
||
pic_arr[403, 250] = (200, 185, 240, 255)
|
||
pic = Image.fromarray(pic_arr, mode="RGBA")
|
||
|
||
detected, x = h.per_pixel_scan_fallback(
|
||
a, pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||
)
|
||
assert detected is True
|
||
assert x == 250
|
||
|
||
|
||
def test_per_pixel_scan_swallows_exception():
|
||
"""pic.load() 抛错时不应崩"""
|
||
a = _make_analyser()
|
||
bad_pic = MagicMock()
|
||
bad_pic.load.side_effect = RuntimeError("boom")
|
||
detected, x = h.per_pixel_scan_fallback(
|
||
a, bad_pic, rx=1080, ry=2400, y_pianyi_val=0,
|
||
)
|
||
assert detected is False
|
||
assert x is None
|
||
|
||
|
||
# ---- _is_target_pixel ---- #
|
||
|
||
def test_is_target_pixel_in_range():
|
||
assert h._is_target_pixel((200, 185, 240)) is True
|
||
assert h._is_target_pixel((190, 173, 234)) is True
|
||
assert h._is_target_pixel((206, 196, 250)) is True
|
||
|
||
|
||
def test_is_target_pixel_out_of_range():
|
||
assert h._is_target_pixel((189, 185, 240)) is False
|
||
assert h._is_target_pixel((200, 197, 240)) is False
|
||
assert h._is_target_pixel((200, 185, 233)) is False
|
||
|
||
|
||
def test_is_target_pixel_non_tuple():
|
||
assert h._is_target_pixel(None) is False
|
||
assert h._is_target_pixel((100,)) is False # 长度不够
|
||
assert h._is_target_pixel("not_tuple") is False
|