"""douyin/fudai/douyin_fudai_finder_pkg/ 子包单元测试。 覆盖 5 个类(FudaiImageAcquirer / FudaiDetector / FudaiClickExecutor / FudaiDetailVerifier / FudaiFinder)的实例化与组合关系,以及顶层函数 check_have_fudai_with_ready_screenshot_optimized。 业务行为(实际识别 / 点击)依赖真实截图与 ADB,留给端到端测试。 """ from __future__ import annotations import time from pathlib import Path from unittest.mock import MagicMock, patch import pytest try: from PIL import Image except ImportError: pytest.skip("PIL unavailable", allow_module_level=True) from douyin.fudai.douyin_fudai_finder import ( FudaiClickExecutor, FudaiDetailVerifier, FudaiDetector, FudaiFinder, FudaiImageAcquirer, check_have_fudai_with_ready_screenshot_optimized, ) FIXTURE_DIR = Path(__file__).parent / "fixtures" / "fudai_icon_regression" ICON_REGRESSION_CASES = [ ("real_left_x83.png", True, 40, 120), ("real_left_x209.png", True, 150, 230), ("real_clean_countdown_x175.png", True, 140, 210), ("real_light10_x40_120.png", True, 40, 120), ("real_light10_x150_220.png", True, 150, 220), ("false_banner_edge_x292.png", False, None, None), ("false_banner_text_x269.png", False, None, None), ("false_left_coupon_x162.png", "risky_probe", 140, 190), ("false_no_fudai_light10.png", False, None, None), ("false_right_coupon_strip_x366.png", False, None, None), ("false_shopping_redpacket_left_x168.png", "risky_probe", 140, 190), ] # ============================================================ # Fake analyser 提供构造时需要的最小 attribute 集合 # ============================================================ class FakeAnalyser: """构造 FudaiFinder 链路所需的最小 attribute。""" def __init__(self): self.device_id = "test_device" # FudaiDetector._init_search_regions 用到这些 self.resolution_ratio_x = 1080 self.resolution_ratio_y = 2400 self.y_pianyi = 0 self.last_fudai_x = 123 self.pixel_detect_coupon_popup_enabled = True self._log_kv = MagicMock(return_value=None) # FudaiClickExecutor 可能用 operation class _Op: def __init__(self): self.click = MagicMock(return_value=None) self.click_back = MagicMock(return_value=None) self.delay = MagicMock(return_value=None) def delay(self, _seconds): return None self.operation = _Op() # ============================================================ # FudaiImageAcquirer # ============================================================ class TestFudaiImageAcquirer: def test_construct(self): acquirer = FudaiImageAcquirer(FakeAnalyser()) assert acquirer is not None def test_acquire_screenshot_callable(self): acquirer = FudaiImageAcquirer(FakeAnalyser()) assert callable(getattr(acquirer, "acquire_screenshot", None)) # ============================================================ # FudaiDetector # ============================================================ class TestFudaiDetector: def test_construct(self): d = FudaiDetector(FakeAnalyser()) assert d.analyser is not None assert d.rx == 1080 assert d.ry == 2400 def test_search_regions_initialized(self): d = FudaiDetector(FakeAnalyser()) assert hasattr(d, "search_regions") assert isinstance(d.search_regions, list) def test_search_region_stays_on_small_top_left_icon_height(self): d = FudaiDetector(FakeAnalyser()) region = d.search_regions[0] assert region["x1"] == 20 assert region["x2"] == 280 assert region["y_top"] == 348 assert region["y_bottom"] == 455 def test_detect_methods_callable(self): d = FudaiDetector(FakeAnalyser()) for name in ( "detect", "detect_by_pixel", "detect_by_template", "confirm_current_icon_template", "confirm_pixel_candidate_shape", ): assert callable(getattr(d, name, None)), f"{name} 不可调用" @pytest.mark.parametrize( ("sample_name", "should_detect", "min_x", "max_x"), ICON_REGRESSION_CASES, ) def test_icon_regression_samples(self, sample_name, should_detect, min_x, max_x): sample = FIXTURE_DIR / sample_name if not sample.exists(): pytest.skip(f"fixture unavailable: {sample_name}") analyser = FakeAnalyser() d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) if should_detect is True: assert detected_x is not None assert min_x <= detected_x <= max_x assert method in {"pixel", "icon_fallback_template"} elif should_detect == "risky_probe": assert detected_x is not None assert min_x <= detected_x <= max_x assert method == "pixel" warning = getattr(analyser, "_last_fudai_candidate_warning", {}) assert warning.get("commercial_warning") is True else: assert detected_x is None assert method == "" def test_commercial_coupon_overlay_detector_is_structural(self): import numpy as np coupon_sample = FIXTURE_DIR / "false_left_coupon_x162.png" fudai_sample = FIXTURE_DIR / "real_left_x83.png" if not coupon_sample.exists() or not fudai_sample.exists(): pytest.skip("fixture unavailable") d = FudaiDetector(FakeAnalyser()) coupon_img = Image.open(coupon_sample).convert("RGB") coupon_arr = np.asarray(coupon_img.crop((62, 300, 262, 560))) coupon_like, coupon_info = d._is_commercial_coupon_overlay(coupon_arr) fudai_img = Image.open(fudai_sample).convert("RGB") fudai_arr = np.asarray(fudai_img.crop((0, 300, 183, 560))) fudai_like, fudai_info = d._is_commercial_coupon_overlay(fudai_arr) assert coupon_like is True assert coupon_info["warm_area"] >= 900 assert coupon_info["dark_ratio"] >= 0.10 assert fudai_like is False assert fudai_info["dominant_red_badge"] is True def test_commercial_coupon_overlay_detector_is_lightweight(self): import numpy as np sample = FIXTURE_DIR / "false_left_coupon_x162.png" if not sample.exists(): pytest.skip("fixture unavailable") d = FudaiDetector(FakeAnalyser()) img = Image.open(sample).convert("RGB") arr = np.asarray(img.crop((62, 300, 262, 560))) start = time.perf_counter() for _ in range(50): d._is_commercial_coupon_overlay(arr) elapsed_ms = (time.perf_counter() - start) * 1000 / 50 assert elapsed_ms < 5.0 def test_redpacket_neighbor_detector_rejects_shopping_redpacket_entry(self): sample = FIXTURE_DIR / "false_shopping_redpacket_left_x168.png" if not sample.exists(): pytest.skip("fixture unavailable") d = FudaiDetector(FakeAnalyser()) img = Image.open(sample).convert("RGB") redpacket_like, info = d._has_redpacket_neighbor_widget(img, 168) assert redpacket_like is True assert info["white_ratio"] >= 0.35 assert info["pink_ratio"] >= 0.06 def test_real_fudai_is_not_rejected_by_nearby_commercial_widgets(self): sample = Path( "pic/debug_captures/2026-06-19/" "20260619_124446_593474_px_fdicon_ok_x132y373w60h60_" "src_flow_on_detect_click_x_162_click_y_403_detected_x_scaled_162.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.last_fudai_x = 162 d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) assert detected_x is not None assert 140 <= detected_x <= 230 assert method in {"pixel", "icon_fallback_template"} def test_current_icon_template_confirms_clean_countdown_sample(self): sample = Path( "artifacts/live_fudai_flow_20260618_0530_valid/snapshots/" "screen_current_for_icon_template.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.fudai_current_icon_template_threshold = 0.80 d = FudaiDetector(analyser) assert d.confirm_current_icon_template(Image.open(sample).convert("RGB"), 175) def test_current_icon_template_rejects_banner_edge_sample(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_074702_110140_px_fdicon_ok_x262y373w60h60_" "src_flow_on_detect_click_x_292_click_y_403_detected_x_scaled_292.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.fudai_current_icon_template_threshold = 0.80 d = FudaiDetector(analyser) assert not d.confirm_current_icon_template( Image.open(sample).convert("RGB"), 292, ) def test_current_icon_template_rejects_offset_banner_text_sample(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_112103_720256_px_fdicon_ok_x239y373w60h60_" "src_flow_on_detect_click_x_269_click_y_403_detected_x_scaled_269.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.fudai_current_icon_template_threshold = 0.80 d = FudaiDetector(analyser) assert not d.confirm_current_icon_template( Image.open(sample).convert("RGB"), 269, ) def test_detect_rejects_offset_banner_text_false_candidate(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_112103_720256_px_fdicon_ok_x239y373w60h60_" "src_flow_on_detect_click_x_269_click_y_403_detected_x_scaled_269.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.last_fudai_x = 269 d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) assert detected_x is None assert method == "" def test_pixel_candidate_shape_accepts_other_real_icon_style(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_070004_938228_px_fdicon_ok_x53y373w60h60_" "src_flow_on_detect_click_x_83_click_y_403_detected_x_scaled_83.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") d = FudaiDetector(FakeAnalyser()) assert d.confirm_pixel_candidate_shape(Image.open(sample).convert("RGB"), 83) def test_pixel_candidate_shape_rejects_banner_edge_sample(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_074702_110140_px_fdicon_ok_x262y373w60h60_" "src_flow_on_detect_click_x_292_click_y_403_detected_x_scaled_292.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") d = FudaiDetector(FakeAnalyser()) assert not d.confirm_pixel_candidate_shape(Image.open(sample).convert("RGB"), 292) def test_detect_rejects_right_coupon_strip_false_candidate(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_084818_591876_px_fdicon_ok_x336y373w60h60_" "src_flow_on_detect_click_x_366_click_y_403_detected_x_scaled_366.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.last_fudai_x = 366 d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) assert detected_x is None assert method == "" def test_detect_keeps_left_real_fudai_entry(self): from pathlib import Path sample = Path( "pic/debug_captures/2026-06-18/" "20260618_084704_660058_px_fdicon_ok_x179y373w60h60_" "src_flow_on_detect_click_x_209_click_y_403_detected_x_scaled_209.png" ) if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.last_fudai_x = 209 d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) assert detected_x is not None assert 150 <= detected_x <= 230 assert method == "pixel" @pytest.mark.parametrize( ("sample_name", "min_x", "max_x"), [ ( "20260618_095900_710971_px_pxstage_ov_ok_1.png", 40, 120, ), ( "20260618_100307_741261_px_pxstage_ov_ok_1.png", 150, 220, ), ], ) def test_detect_keeps_real_fudai_entries_from_light10_misses( self, sample_name, min_x, max_x ): from pathlib import Path sample = Path("pic/debug_captures/2026-06-18") / sample_name if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() analyser.last_fudai_x = 83 d = FudaiDetector(analyser) detected_x, method = d.detect(Image.open(sample).convert("RGB")) assert detected_x is not None assert min_x <= detected_x <= max_x assert method in {"pixel", "icon_fallback_template"} @pytest.mark.parametrize( "sample_name", [ "20260618_084818_591876_px_fdicon_ok_x336y373w60h60_" "src_flow_on_detect_click_x_366_click_y_403_detected_x_scaled_366.png", "20260618_100333_464357_px_pxstage_ov_ok_1.png", ], ) def test_icon_fallback_template_rejects_coupon_or_no_fudai_samples( self, sample_name ): from pathlib import Path sample = Path("pic/debug_captures/2026-06-18") / sample_name if not sample.exists(): pytest.skip("live debug sample unavailable") analyser = FakeAnalyser() d = FudaiDetector(analyser) assert d.detect_by_icon_fallback_template(Image.open(sample).convert("RGB")) is None def test_coupon_guard_uses_click_close_during_reservation_direct_attend(): from douyin.fudai.douyin_fudai_finder_pkg.finder import ( is_coupon_popup_before_fudai_click, ) analyser = FakeAnalyser() analyser._current_attending_reservation_fudai = True pic = Image.new("RGB", (1080, 2400), "white") with patch( "douyin.detection.pixel.popups.detect_coupon_popup_background", return_value=(True, {"method": "mock_coupon"}), ): detected = is_coupon_popup_before_fudai_click(analyser, pic) assert detected is True analyser.operation.click_back.assert_not_called() analyser.operation.click.assert_called_once_with("test_device", 540, 2006) assert analyser._log_kv.call_args.kwargs["skipped_reason"] == ( "reservation_direct_attend_coupon_click_close" ) # ============================================================ # FudaiClickExecutor # ============================================================ class TestFudaiClickExecutor: def test_construct(self): executor = FudaiClickExecutor(FakeAnalyser()) assert executor is not None # ============================================================ # FudaiDetailVerifier # ============================================================ class TestFudaiDetailVerifier: def test_construct(self): verifier = FudaiDetailVerifier(FakeAnalyser()) assert verifier is not None # ============================================================ # FudaiFinder(组合 4 个子组件) # ============================================================ class TestFudaiFinder: def test_construct_includes_all_components(self): finder = FudaiFinder(FakeAnalyser()) assert isinstance(finder.acquirer, FudaiImageAcquirer) assert isinstance(finder.detector, FudaiDetector) assert isinstance(finder.executor, FudaiClickExecutor) assert isinstance(finder.verifier, FudaiDetailVerifier) def test_components_share_analyser(self): analyser = FakeAnalyser() finder = FudaiFinder(analyser) # 4 个子组件都应该持有同一个 analyser 引用 assert finder.acquirer.analyser is analyser assert finder.detector.analyser is analyser def test_coupon_popup_guard_skips_click(self): analyser = FakeAnalyser() finder = FudaiFinder(analyser) pic = Image.new("RGB", (1080, 2400), (255, 255, 255)) finder.acquirer.acquire_screenshot = MagicMock(return_value=pic) finder.detector.detect = MagicMock(return_value=(83, "pixel")) finder.executor.click = MagicMock(return_value=True) with patch( "douyin.detection.pixel.popups.detect_coupon_popup_background", return_value=(True, {"template_score": 0.9}), ): ok, x = finder.find_and_open() assert ok is False assert x is None assert analyser.last_fudai_x == 0 analyser.operation.click_back.assert_called_once_with(analyser.device_id) finder.detector.detect.assert_not_called() finder.executor.click.assert_not_called() def test_coupon_popup_guard_does_not_press_back_repeatedly(self): analyser = FakeAnalyser() finder = FudaiFinder(analyser) pic = Image.new("RGB", (1080, 2400), (255, 255, 255)) finder.acquirer.acquire_screenshot = MagicMock(return_value=pic) finder.detector.detect = MagicMock(return_value=(83, "pixel")) finder.executor.click = MagicMock(return_value=True) with patch( "douyin.detection.pixel.popups.detect_coupon_popup_background", return_value=(True, {"template_score": 0.9}), ), patch("douyin.fudai.douyin_fudai_finder_pkg.finder.time.time") as mock_time: mock_time.side_effect = [100.0] * 10 + [101.0] * 10 ok1, x1 = finder.find_and_open() ok2, x2 = finder.find_and_open() assert (ok1, x1) == (False, None) assert (ok2, x2) == (False, None) analyser.operation.click_back.assert_called_once_with(analyser.device_id) finder.detector.detect.assert_not_called() finder.executor.click.assert_not_called() # ============================================================ # 顶层函数 # ============================================================ class TestCheckHaveFudaiWithReadyScreenshotOptimized: def test_callable(self): assert callable(check_have_fudai_with_ready_screenshot_optimized) def test_coupon_popup_guard_returns_zero(self): analyser = FakeAnalyser() pic = Image.new("RGB", (1080, 2400), (255, 255, 255)) with patch( "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiImageAcquirer" ) as acquirer_cls, patch( "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiDetector" ) as detector_cls, patch( "douyin.detection.pixel.popups.detect_coupon_popup_background", return_value=(True, {"template_score": 0.9}), ): acquirer_cls.return_value.acquire_screenshot.return_value = pic result = check_have_fudai_with_ready_screenshot_optimized(analyser) assert result == 0 assert analyser.last_fudai_x == 0 analyser.operation.click_back.assert_called_once_with(analyser.device_id) detector_cls.assert_not_called() def test_wrong_target_retry_bypasses_coupon_popup_guard_once(self): analyser = FakeAnalyser() analyser._allow_fudai_click_after_wrong_target_until_ts = time.time() + 5.0 pic = Image.new("RGB", (1080, 2400), (20, 20, 20)) with patch( "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiImageAcquirer" ) as acquirer_cls, patch( "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.FudaiDetector" ) as detector_cls, patch( "douyin.fudai.douyin_fudai_finder_pkg.optimized_entry.is_coupon_popup_before_fudai_click", return_value=True, ) as guard: acquirer_cls.return_value.acquire_screenshot.return_value = pic detector_cls.return_value.detect.return_value = (132, "unit") result = check_have_fudai_with_ready_screenshot_optimized(analyser) assert result == 132 guard.assert_not_called() detector_cls.assert_called_once() # ============================================================ # detect_by_template 已拆出为 module-level 函数 # ============================================================ class TestDetectByTemplateAsModuleLevel: """detect_by_template 现在是 module-level 函数,类方法 1 行 forwarding。""" def test_module_level_callable(self): from douyin.fudai.douyin_fudai_finder_pkg.detect_by_template import ( detect_by_template as module_fn, ) assert callable(module_fn) def test_class_method_callable(self): # 类方法仍可访问 d = FudaiDetector(FakeAnalyser()) assert callable(d.detect_by_template) def test_class_method_signature_unchanged(self): """类方法签名应仍是 (self, pic, region),对外 API 不变。""" import inspect sig = inspect.signature(FudaiDetector.detect_by_template) params = list(sig.parameters.keys()) # 第一个是 self(unbound),后两个 pic, region assert "pic" in params assert "region" in params