# -*- coding: utf-8 -*- """截图连续识别失败熔断。 2026-11-16 实测: 游戏窗口被最小化/关掉后, AALC 每帧在 cv2.matchTemplate 上抛 「corr.rows <= img.rows + templ.rows - 1」断言, 只记 ERROR 继续跑, 第 2 局空转 4.5 小时。 """ import sys import types import unittest from pathlib import Path from unittest import mock REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO)) from lc_mcp import aalc_patches as ap # noqa: E402 class FakeImageUtils: """按顺序返回给定结果; None = 上游的识别失败分支。""" def __init__(self, results): self.results = list(results) self.calls = 0 def match_template(self, screenshot, template, threshold, *args, **kwargs): self.calls += 1 if self.results: return self.results.pop(0) return (1, 1), 0.9 class ImageErrorGuardTest(unittest.TestCase): def install(self, fake, clock=None, window=120, limit=3): self.lines = [] module = types.ModuleType('utils.image_utils') module.ImageUtils = fake with mock.patch.dict(sys.modules, {'utils': types.ModuleType('utils'), 'utils.image_utils': module}): self.assertIsNotNone(ap.install_image_error_guard( log=self.lines.append, clock=clock or (lambda: self.now[0]), window=window, limit=limit)) return fake def setUp(self): self.now = [0.0] def test_ok_results_never_abort(self): fake = self.install(FakeImageUtils([((5, 5), 0.9)] * 10)) for _ in range(10): self.now[0] += 0.1 self.assertEqual(fake.match_template(None, None, 0.8), ((5, 5), 0.9)) def test_sparse_failures_do_not_abort(self): fake = self.install(FakeImageUtils([None, None] + [((1, 1), 0.9)] * 5)) self.lines.clear() # 安装时那行 "patch: 截图连续识别失败…" 不算 fake.match_template(None, None, 0.8) fake.match_template(None, None, 0.8) self.now[0] += 200 # 窗口滑过去 fake.match_template(None, None, 0.8) self.assertEqual(len(self.lines), 0) def test_storm_aborts_with_clear_message(self): fake = self.install(FakeImageUtils([None] * 10), limit=3) with mock.patch.object(ap.decisions, 'record') as record: with self.assertRaises(ap.TaskAbort): for _ in range(3): self.now[0] += 0.05 fake.match_template(None, None, 0.8) self.assertIn('截图连续识别失败', '\n'.join(self.lines)) record.assert_called_once() def test_abort_is_not_a_normal_exception(self): # AALC 的 onetime_mir_process 会吞 Exception 再开一局, 熔断必须穿透 self.assertFalse(issubclass(ap.TaskAbort, Exception)) def test_restores_nothing_when_upstream_has_no_match_template(self): module = types.ModuleType('utils.image_utils') module.ImageUtils = object() with mock.patch.dict(sys.modules, {'utils': types.ModuleType('utils'), 'utils.image_utils': module}): self.assertIsNone(ap.install_image_error_guard(log=lambda *_: None))