Просмотр исходного кода

fix(SwitchOnmyoji): give both switch_role loops a bounded exit

Both while True loops in switch_role could spin indefinitely. When the game is left on a sub-page of the onmyoji screen (e.g. the hero-exchange page), I_ONMYOJI_SWITCH never opens the role list, so the loop kept clicking until the global ~2min GameStuckError watchdog fired, losing the actual cause. Each loop now raises a ScriptError naming the failure after 20s.
Enough1122 1 месяц назад
Родитель
Сommit
929c6a1122
2 измененных файлов с 123 добавлено и 0 удалено
  1. 18 0
      tasks/Component/SwitchOnmyoji/switch_onmyoji.py
  2. 105 0
      tests/test_switch_onmyoji.py

+ 18 - 0
tasks/Component/SwitchOnmyoji/switch_onmyoji.py

@@ -1,4 +1,6 @@
 from module.atom.image import RuleImage
+from module.base.timer import Timer
+from module.exception import ScriptError
 from tasks.Component.SwitchOnmyoji.assets import SwitchOnmyojiAssets
 from tasks.Component.SwitchOnmyoji.config import Onmyoji
 from tasks.base_task import BaseTask
@@ -6,6 +8,10 @@ from module.logger import logger
 
 
 class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
+    # 上限用来给两个 while 循环兜底:资源坐标过期或页面不对时不再无限点,
+    # 改为抛出带上下文的 ScriptError,让上层决定重启还是人工接管。
+    SWITCH_TAB_TIMEOUT = 20
+    SWITCH_BATTLE_TIMEOUT = 20
 
     def switch_onmyoji(self, onmyoji: Onmyoji):
         """
@@ -29,7 +35,14 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         :param battle_dict: 角色与战斗图标的映射
         :param check_img: 检查是否回到主界面的图标
         """
+        # 两个循环都必须在超时后抛出,而不是继续点击
+        tab_timer = Timer(self.SWITCH_TAB_TIMEOUT).start()
         while True:
+            if tab_timer.reached():
+                raise ScriptError('Switch onmyoji: cannot reach the role list, '
+                                  'the onmyoji tab was not opened after '
+                                  f'{self.SWITCH_TAB_TIMEOUT}s. '
+                                  'Check whether the onmyoji/hero assets still match the game UI')
             self.screenshot()
             if any(self.appear(battle_icon) for battle_icon in battle_dict.values()):
                 break
@@ -37,7 +50,12 @@ class SwitchOnmyoji(BaseTask, SwitchOnmyojiAssets):
         battle_img = battle_dict.get(role, None)
         if not battle_img:
             raise ValueError('Incorrect role type')
+        battle_timer = Timer(self.SWITCH_BATTLE_TIMEOUT).start()
         while True:
+            if battle_timer.reached():
+                raise ScriptError(f'Switch onmyoji: cannot select {role}, '
+                                  'the role list stayed unconfirmed after '
+                                  f'{self.SWITCH_BATTLE_TIMEOUT}s')
             self.screenshot()
             if self.appear(check_img, interval=0.8):
                 break

+ 105 - 0
tests/test_switch_onmyoji.py

@@ -0,0 +1,105 @@
+"""SwitchOnmyoji must have a bounded exit path.
+
+Both loops in `SwitchOnmyoji.switch_role` used to be unconditional `while True`.
+When the onmyoji/hero tab cannot be reached (stale asset coordinates after a
+game UI update, emulator showing a different page, ...), they kept clicking
+forever until the global `GameStuckError` watchdog fired roughly two minutes
+later, discarding all context about what actually went wrong.
+
+These tests pin the exit conditions: a loop that never finds its target has to
+raise a named, catchable `ScriptError` instead of spinning, and the happy path
+must keep working unchanged.
+"""
+import pytest
+
+from module.base.timer import Timer
+from module.exception import ScriptError
+from tasks.Component.SwitchOnmyoji.config import Onmyoji
+from tasks.Component.SwitchOnmyoji.switch_onmyoji import SwitchOnmyoji
+
+
+class ScriptedSwitch(SwitchOnmyoji):
+    """Double that replays a fixed sequence of `appear` results.
+
+    `screenshot` and every click are no-ops, so the test exercises the real
+    loop control flow of `switch_role` without a Config, a Device or a game.
+    """
+
+    def __init__(self, appear_results, timeout=0):
+        # deliberately skip BaseTask.__init__: it needs a real Config/Device
+        self._appear_results = list(appear_results)
+        self._appear_calls = 0
+        self.switch_clicks = 0
+        self.battle_clicks = 0
+        self.ui_clicks = 0
+        # override the real 20s guards so the test does not have to wait
+        self.SWITCH_TAB_TIMEOUT = timeout
+        self.SWITCH_BATTLE_TIMEOUT = timeout
+
+    def _next_appear(self, button):
+        self._appear_calls += 1
+        if not self._appear_results:
+            return False
+        return self._appear_results.pop(0)
+
+    def screenshot(self):
+        pass
+
+    def appear(self, button, interval=None, **kwargs):
+        return self._next_appear(button)
+
+    def appear_then_click(self, button, interval=None, **kwargs):
+        self.switch_clicks += 1
+        return True
+
+    def click(self, button, interval=None, **kwargs):
+        self.battle_clicks += 1
+        return True
+
+    def ui_click(self, button1, button2, interval=None, **kwargs):
+        self.ui_clicks += 1
+        return True
+
+
+def test_switch_role_raises_when_battle_list_never_appears():
+    task = ScriptedSwitch(appear_results=[])
+
+    with pytest.raises(ScriptError):
+        task.switch_role(role=None, battle_dict={'x': object()}, check_img=object())
+
+
+def test_switch_role_raises_when_check_icon_never_appears():
+    # battle icon visible, confirm icon never does
+    task = ScriptedSwitch(appear_results=[True])
+
+    with pytest.raises(ScriptError):
+        task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+
+def test_switch_role_still_switches_when_the_flow_is_healthy():
+    # appear order: battle icon, then confirm icon -> no extra clicks needed
+    task = ScriptedSwitch(appear_results=[True, True])
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.battle_clicks == 0
+    assert task.ui_clicks == 0
+
+
+def test_switch_role_clicks_the_battle_icon_when_confirm_icon_is_absent():
+    # appear order: battle icon, not-confirm, battle icon -> ui_click back path
+    task = ScriptedSwitch(appear_results=[True, False, True])
+
+    task.switch_role(role=Onmyoji.KAGURA, battle_dict={Onmyoji.KAGURA: object()}, check_img=object())
+
+    assert task.switch_clicks == 0
+    assert task.ui_clicks == 1
+
+
+def test_timeouts_are_not_shared_between_instances():
+    a = ScriptedSwitch(appear_results=[])
+    b = ScriptedSwitch(appear_results=[])
+
+    assert a.SWITCH_TAB_TIMEOUT is not None
+    assert b.SWITCH_TAB_TIMEOUT is not None