"""douyin/detection/detection_pkg/finder_template_match 单元测试。 OpenCV 模板匹配兜底逻辑。比 numpy_scan / pixel_scan 更难直接用真实图片测试, 所以主要 mock cv2 + 测试控制流(早出条件 / 阈值通过/不通过 / 各种边界)。 """ from __future__ import annotations import os from unittest.mock import MagicMock, patch import pytest try: import numpy as np from PIL import Image except ImportError: # pragma: no cover pytest.skip("numpy/PIL unavailable", allow_module_level=True) def _mk_analyser(*, threshold=0.7): a = MagicMock() a.fudai_template_match_threshold = threshold a.last_find_fudai_time = 0.0 a._log_kv = MagicMock(return_value=None) return a def _make_pic(rgb=(0, 0, 0), w=1080, h=2400): return Image.new("RGB", (w, h), rgb) # ============================================================ # _resolve_template_path # ============================================================ class TestResolveTemplatePath: def test_uses_path_config(self, tmp_path, monkeypatch): from douyin.core import path_config from douyin.detection.detection_pkg.finder_template_match import ( _resolve_template_path, ) monkeypatch.setattr(path_config, "get_assets_dir", lambda: str(tmp_path)) result = _resolve_template_path() assert result == str(tmp_path) + "/fudai.png" def test_falls_back_when_path_config_throws(self, monkeypatch): """path_config 抛异常时,兜底路径应含 ".." 回退到项目根。""" from douyin.detection.detection_pkg import finder_template_match # 强制 path_config 导入失败 with patch.dict("sys.modules", {"douyin.core.path_config": None}): # 实际:try-except 内部 import 会失败 # 改为让它失败:用 patch.object pass # 简单走通:调用一下,确认不抛 # 由于内部 try/except,path_config 即使可用也会被路径正常返回 result = finder_template_match._resolve_template_path() assert "fudai.png" in result # ============================================================ # match_template - 早出条件 # ============================================================ class TestMatchTemplateEarlyReturns: def test_template_path_missing_returns_false(self, monkeypatch): from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser() monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: "/nonexistent/path/fudai.png", ) detected, x = match_template(a, _make_pic(), 1080, 2400, 0, loop=1) assert detected is False assert x is None def test_cv2_imread_returns_none(self, tmp_path, monkeypatch): """模板路径存在但 cv2.imread 返回 None → 退出。""" from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser() # 创建一个空文件作为模板路径 template_path = tmp_path / "fudai.png" template_path.write_bytes(b"") monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: str(template_path), ) with patch("cv2.imread", return_value=None): detected, x = match_template(a, _make_pic(), 1080, 2400, 0, loop=1) assert detected is False assert x is None def test_invalid_search_region_logs_and_returns(self, tmp_path, monkeypatch): """rx 过大让 x1 >= x2 → 区域无效 → 写日志 + 返回 False。""" from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser() template_path = tmp_path / "fudai.png" template_path.write_bytes(b"x" * 10) monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: str(template_path), ) # 让 cv2.imread 返回一个 5x5 的伪模板 fake_template = np.zeros((5, 5, 3), dtype=np.uint8) with patch("cv2.imread", return_value=fake_template): # 用 10x10 的图片,rx=10000 让搜索区域越界 detected, x = match_template( a, _make_pic(rgb=(0, 0, 0), w=10, h=10), rx=10000, ry=2400, y_pianyi_val=0, loop=1, ) assert detected is False assert x is None # 应该有 "坐标无效" 日志 log_msgs = [str(c) for c in a._log_kv.call_args_list] assert any("坐标无效" in m for m in log_msgs) # ============================================================ # match_template - 命中路径 # ============================================================ class TestMatchTemplateHit: def test_high_match_score_returns_true(self, tmp_path, monkeypatch): """模板匹配返回的 max_val >= threshold → detected=True,x 是 1080 基准。""" from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser(threshold=0.7) template_path = tmp_path / "fudai.png" template_path.write_bytes(b"x" * 100) monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: str(template_path), ) # 模板 20x20,搜索区域比模板大 fake_template = np.zeros((20, 20, 3), dtype=np.uint8) # cv2.matchTemplate 返回一个 (rh-th+1, rw-tw+1) 的相关性矩阵 # cv2.minMaxLoc 返回 (min_val, max_val, min_loc, max_loc) fake_match_result = np.zeros((10, 10), dtype=np.float32) with patch("cv2.imread", return_value=fake_template), \ patch("cv2.matchTemplate", return_value=fake_match_result), \ patch("cv2.minMaxLoc", return_value=(0.1, 0.85, (0, 0), (5, 3))), \ patch("cv2.imwrite", return_value=True): detected, x = match_template( a, _make_pic(w=1080, h=2400), rx=1080, ry=2400, y_pianyi_val=0, loop=1, ) assert detected is True assert x is not None # x = (x1 + detected_x_in_roi + tw//2) * 1080 / rx # x1 = 156, detected_x_in_roi = 5, tw // 2 = 10, rx = 1080 # x = (156 + 5 + 10) * 1080 / 1080 = 171 assert x == 171 assert a.last_find_fudai_time > 0 assert a.last_fudai_x == 171 def test_low_match_score_returns_false(self, tmp_path, monkeypatch): """max_val < threshold → 不命中。""" from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser(threshold=0.7) template_path = tmp_path / "fudai.png" template_path.write_bytes(b"x" * 100) monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: str(template_path), ) fake_template = np.zeros((20, 20, 3), dtype=np.uint8) fake_match_result = np.zeros((10, 10), dtype=np.float32) with patch("cv2.imread", return_value=fake_template), \ patch("cv2.matchTemplate", return_value=fake_match_result), \ patch("cv2.minMaxLoc", return_value=(0.1, 0.5, (0, 0), (5, 3))), \ patch("cv2.imwrite", return_value=True): detected, x = match_template( a, _make_pic(w=1080, h=2400), rx=1080, ry=2400, y_pianyi_val=0, loop=1, ) assert detected is False assert x is None def test_template_too_large_gets_resized(self, tmp_path, monkeypatch): """模板比搜索区域大 → cv2.resize 被调用,仍能继续匹配。""" from douyin.detection.detection_pkg.finder_template_match import match_template a = _mk_analyser(threshold=0.7) template_path = tmp_path / "fudai.png" template_path.write_bytes(b"x" * 100) monkeypatch.setattr( "douyin.detection.detection_pkg.finder_template_match._resolve_template_path", lambda: str(template_path), ) # 模板 200x200,搜索区域只有 113x100(remember 156..269 wide) big_template = np.zeros((200, 200, 3), dtype=np.uint8) small_template = np.zeros((50, 50, 3), dtype=np.uint8) with patch("cv2.imread", return_value=big_template), \ patch("cv2.resize", return_value=small_template) as mock_resize, \ patch("cv2.matchTemplate", return_value=np.zeros((10, 10), dtype=np.float32)), \ patch("cv2.minMaxLoc", return_value=(0.1, 0.85, (0, 0), (3, 3))), \ patch("cv2.imwrite", return_value=True): detected, _ = match_template( a, _make_pic(w=1080, h=2400), rx=1080, ry=2400, y_pianyi_val=0, loop=1, ) assert detected is True mock_resize.assert_called_once() # ============================================================ # match_template - 异常路径 # ============================================================ class TestMatchTemplateExceptions: def test_cv2_import_error_returns_false(self): """cv2 不可用 → except (ImportError, Exception) → 写日志 + 返回 False。""" from douyin.detection.detection_pkg import finder_template_match a = _mk_analyser() # 强制让 import cv2 抛 ImportError import builtins original_import = builtins.__import__ def fake_import(name, *args, **kwargs): if name == "cv2": raise ImportError("cv2 not available") return original_import(name, *args, **kwargs) with patch("builtins.__import__", side_effect=fake_import): detected, x = finder_template_match.match_template( a, _make_pic(), 1080, 2400, 0, loop=1 ) assert detected is False assert x is None # 应有 "模板匹配异常" 日志 log_msgs = [str(c) for c in a._log_kv.call_args_list] assert any("模板匹配异常" in m for m in log_msgs)