"""单元测试:douyin/core/fudai_modules/fudai_image_helpers.py 只覆盖纯逻辑分支与异常吞噬路径;完整图片读取链路依赖 ADB + 真实 PNG 文件, 不在单元测试范围内。 """ from __future__ import annotations import io from unittest.mock import MagicMock, patch import pytest from douyin.core.fudai_modules import fudai_image_helpers def _make_analyser(): a = MagicMock() a.device_id = "test" a._run_id = "test_run" a._log_kv = MagicMock() a.operation = MagicMock() a.operation.get_screenshot = MagicMock() return a def test_capture_roi_no_screenshot_path_returns_empty(monkeypatch): """screenshot_path 不存在时直接返回空字符串""" a = _make_analyser() monkeypatch.setattr("os.path.exists", lambda _p: False) result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50) assert result == "" def test_capture_roi_with_invalid_path_returns_empty(monkeypatch): a = _make_analyser() monkeypatch.setattr("os.path.exists", lambda _p: False) result = fudai_image_helpers.capture_roi_screenshot( a, "label", 100, 100, 50, screenshot_path="/no/such/file.png" ) assert result == "" def test_capture_roi_outer_exception_swallowed(monkeypatch): """获取 path_config 抛错时也应吞噬异常并写日志""" a = _make_analyser() # 让 path_config 导入抛错 monkeypatch.setattr("os.path.exists", lambda _p: True) with patch.object( fudai_image_helpers, "_read_screenshot_with_validation", side_effect=RuntimeError("boom"), ): result = fudai_image_helpers.capture_roi_screenshot(a, "label", 100, 100, 50) assert result == "" # 应记录失败日志 a._log_kv.assert_called() def test_read_screenshot_returns_none_when_path_missing(monkeypatch, tmp_path): """文件不存在时多次重试后返回 None""" a = _make_analyser() monkeypatch.setattr("time.sleep", lambda _s: None) fake_path = str(tmp_path / "no.png") result = fudai_image_helpers._read_screenshot_with_validation( a, fake_path, max_attempts=2 ) assert result is None def test_read_screenshot_validates_png_header(monkeypatch, tmp_path): """非 PNG 头时拒绝""" a = _make_analyser() monkeypatch.setattr("time.sleep", lambda _s: None) bad_file = tmp_path / "bad.png" bad_file.write_bytes(b"\x00" * 2048) result = fudai_image_helpers._read_screenshot_with_validation( a, str(bad_file), max_attempts=2 ) assert result is None def test_read_screenshot_validates_iend_tail(monkeypatch, tmp_path): """PNG 头但缺失 IEND 尾时拒绝""" a = _make_analyser() monkeypatch.setattr("time.sleep", lambda _s: None) bad_file = tmp_path / "bad.png" # 有效 PNG header 但没 IEND bad_file.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 2048) result = fudai_image_helpers._read_screenshot_with_validation( a, str(bad_file), max_attempts=2 ) assert result is None def test_read_screenshot_skips_tiny_file(monkeypatch, tmp_path): """文件 < 1024 字节时跳过""" a = _make_analyser() monkeypatch.setattr("time.sleep", lambda _s: None) tiny = tmp_path / "tiny.png" tiny.write_bytes(b"\x89PNG\r\n\x1a\n") # 8 字节 result = fudai_image_helpers._read_screenshot_with_validation( a, str(tiny), max_attempts=2 ) assert result is None def test_read_screenshot_returns_data_for_valid_png(monkeypatch, tmp_path): """生成有效 PNG → _read_screenshot_with_validation 返回字节""" from PIL import Image import random a = _make_analyser() monkeypatch.setattr("time.sleep", lambda _s: None) pic_path = tmp_path / "ok.png" # 用随机像素生成大于 1024 字节的 PNG(白色图压缩后过小被 size guard 拒绝) rng = random.Random(0) pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(100 * 100)] img = Image.new("RGB", (100, 100)) img.putdata(pixels) img.save(str(pic_path)) assert pic_path.stat().st_size >= 1024 result = fudai_image_helpers._read_screenshot_with_validation( a, str(pic_path), max_attempts=2 ) assert result is not None assert result.startswith(b"\x89PNG") assert b"IEND" in result[-512:] def test_open_image_or_retry_with_valid_data(): a = _make_analyser() from PIL import Image img = Image.new("RGB", (50, 50), color="white") buf = io.BytesIO() img.save(buf, format="PNG") data = buf.getvalue() result = fudai_image_helpers._open_image_or_retry(a, data, "/tmp/x.png") assert result is not None def test_open_image_or_retry_unidentified_returns_none(): a = _make_analyser() result = fudai_image_helpers._open_image_or_retry(a, b"not_a_png", "/no/path.png") assert result is None def test_capture_roi_end_to_end_with_real_png(monkeypatch, tmp_path): """端到端:写一个真实 PNG,capture_roi_screenshot 应返回有效 ROI 路径""" from PIL import Image import random a = _make_analyser() pic_path = tmp_path / "screenshot.png" rng = random.Random(42) pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(200 * 200)] img = Image.new("RGB", (200, 200)) img.putdata(pixels) img.save(str(pic_path)) out_dir = tmp_path / "out" out_dir.mkdir() fake_path_config = MagicMock() fake_path_config.get_screenshot_path = lambda: str(pic_path) fake_path_config.get_pic_dir = lambda: str(out_dir) monkeypatch.setattr("douyin.core.path_config", fake_path_config) monkeypatch.setattr("time.sleep", lambda _s: None) result = fudai_image_helpers.capture_roi_screenshot(a, "test", 100, 100, 50) assert result assert "roi_test_test_run" in result # ---- _correlation_score ---- # def test_correlation_score_identical_arrays(): import numpy as np a = np.array([1.0, 2.0, 3.0, 4.0]) score = fudai_image_helpers._correlation_score(a, a) assert abs(score - 1.0) < 1e-6 def test_correlation_score_constant_arrays_returns_minus_one(): """相同常数数组 → 范数为 0 → 返回 -1.0""" import numpy as np a = np.array([5.0, 5.0, 5.0]) b = np.array([5.0, 5.0, 5.0]) score = fudai_image_helpers._correlation_score(a, b) assert score == -1.0 def test_correlation_score_anticorrelated(): import numpy as np a = np.array([1.0, 2.0, 3.0]) b = np.array([3.0, 2.0, 1.0]) score = fudai_image_helpers._correlation_score(a, b) assert abs(score - (-1.0)) < 1e-6 # ---- match_icon_template ---- # def test_match_icon_missing_roi_returns_false(): a = _make_analyser() detected, score = fudai_image_helpers.match_icon_template( a, "/no/such/roi.png", "/no/such/tpl.png" ) assert detected is False assert score == 0.0 def test_match_icon_empty_paths_returns_false(): a = _make_analyser() assert fudai_image_helpers.match_icon_template(a, "", "x") == (False, 0.0) assert fudai_image_helpers.match_icon_template(a, "x", "") == (False, 0.0) def test_match_icon_same_image_high_score(tmp_path): """同一张图作为 ROI 与模板 → 完美匹配,score=1.0""" from PIL import Image import random a = _make_analyser() rng = random.Random(0) pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(60 * 60)] img = Image.new("RGB", (60, 60)) img.putdata(pixels) same = tmp_path / "same.png" img.save(str(same)) detected, score = fudai_image_helpers.match_icon_template( a, str(same), str(same), threshold=0.5 ) assert detected is True assert abs(score - 1.0) < 1e-3 def test_match_icon_template_larger_than_roi_gets_resized(tmp_path): """模板比 ROI 大 → 自动缩放,仍能比对""" from PIL import Image a = _make_analyser() roi = Image.new("RGB", (50, 50), color="white") tpl = Image.new("RGB", (200, 200), color="white") roi_path = tmp_path / "roi.png" tpl_path = tmp_path / "tpl.png" roi.save(str(roi_path)) tpl.save(str(tpl_path)) # 不抛错就算通过;都是白色范数为 0,会回到 -1 detected, score = fudai_image_helpers.match_icon_template( a, str(roi_path), str(tpl_path) ) # 白色图分母为 0 → score=-1,detected=False assert detected is False def test_match_icon_threshold_param_overrides_attr(tmp_path): """threshold=0 时即使分数较低也判定为 detected""" from PIL import Image import random a = _make_analyser() a.yanghao_icon_match_threshold = 0.99 # 默认很高 rng = random.Random(0) pixels = [(rng.randint(0, 255), rng.randint(0, 255), rng.randint(0, 255)) for _ in range(40 * 40)] img = Image.new("RGB", (40, 40)) img.putdata(pixels) same = tmp_path / "same.png" img.save(str(same)) # threshold=0 → 任何 score >= 0 都算命中 detected, _ = fudai_image_helpers.match_icon_template( a, str(same), str(same), threshold=0.0 ) assert detected is True