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

feat(GeneralBattle): Add hook options support

neptine 2 месяцев назад
Родитель
Сommit
5a3eaddc57

+ 56 - 6
tasks/Component/GeneralBattle/battle_wait.py

@@ -1,5 +1,6 @@
 import random
 import random
 import time
 import time
+import copy
 
 
 
 
 from functools import wraps
 from functools import wraps
@@ -24,6 +25,7 @@ class HookSignal(Enum):
 
 
 @dataclass
 @dataclass
 class BattleWaitContext:
 class BattleWaitContext:
+    options: dict[str: dict] = None
     completion = False
     completion = False
     success = False
     success = False
 
 
@@ -190,9 +192,22 @@ class battle_wait_strategy:
     首次装饰 func 初始化 battle_wait_plan
     首次装饰 func 初始化 battle_wait_plan
     """
     """
     battle_wait_plan: BattleWaitPlan = None
     battle_wait_plan: BattleWaitPlan = None
+    options: dict[str: dict] = None
 
 
 
 
     def __init__(self, *arg, **kwargs):
     def __init__(self, *arg, **kwargs):
+        self._temp_options = kwargs.pop('options', None)
+        if self._temp_options is not None:
+            if not isinstance(self._temp_options, dict):
+                raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
+            for key, value in self._temp_options.items():
+                if not isinstance(key, str):
+                    raise
+                if not isinstance(value, dict):
+                    raise TypeError(f'temp_options must be a dict, got {self._temp_options!r}')
+            if battle_wait_strategy.options is None:
+                battle_wait_strategy.options = self._temp_options
+
         self._temp_battle_wait_plan = None
         self._temp_battle_wait_plan = None
         if battle_wait_strategy.battle_wait_plan is None:
         if battle_wait_strategy.battle_wait_plan is None:
             # 首次装饰 func 初始化 battle_wait_plan
             # 首次装饰 func 初始化 battle_wait_plan
@@ -251,17 +266,36 @@ class battle_wait_strategy:
                     if key == 'random_click_swipt_enable' and value:
                     if key == 'random_click_swipt_enable' and value:
                         override_kwargs['randomclick'] = 'default'
                         override_kwargs['randomclick'] = 'default'
                         override_args.append('randomclick_default')
                         override_args.append('randomclick_default')
-                battle_wait_strategy.battle_wait_plan =\
-                    battle_wait_strategy.battle_wait_plan.override(*override_args)
+                current_plan = copy.deepcopy(battle_wait_strategy.battle_wait_plan)
+                current_plan = current_plan.override(*override_args)
+            else:
+                current_plan = battle_wait_strategy.battle_wait_plan
             # -----------------------------------------------------------------------
             # -----------------------------------------------------------------------
             # kwargs.setdefault(
             # kwargs.setdefault(
             #     'battle_wait_plan',
             #     'battle_wait_plan',
             #     self.battle_wait_plan,
             #     self.battle_wait_plan,
             # )
             # )
-            return func(owner, battle_wait_plan=battle_wait_strategy.battle_wait_plan)
+            options = self.options if self.options is not None else battle_wait_strategy.options
+            return func(owner, battle_wait_plan=current_plan, options=options) \
+                if options is not None else func(owner, battle_wait_plan=current_plan)
 
 
         return inner
         return inner
 
 
+    def with_options(self, options: dict) -> "battle_wait_strategy":
+        if not isinstance(options, dict):
+            raise
+        for event, v in options.items():
+            if not isinstance(event, str):
+                raise TypeError()
+            if not isinstance(v, dict):
+                raise TypeError()
+        # 先装饰器, 后临时变量
+        if battle_wait_strategy.options is None:
+            battle_wait_strategy.options = options
+        else:
+            self._temp_options = options
+        return self
+
 
 
 class BattleWait(BaseTask):
 class BattleWait(BaseTask):
     # build in
     # build in
@@ -443,15 +477,29 @@ class BattleWait(BaseTask):
         但是必须要实现对应的hook 上面的比如 _bw_yyy_default() 以及 _bw_abcd_edf()
         但是必须要实现对应的hook 上面的比如 _bw_yyy_default() 以及 _bw_abcd_edf()
 
 
         hook 可以自定义顺序,比如 battle_wait_strategy(sequence='completion > interrupt > success > failure > idle')
         hook 可以自定义顺序,比如 battle_wait_strategy(sequence='completion > interrupt > success > failure > idle')
-        如果指定sequence, 新增的event会按照传参时候从左到右排序,左边高优先级,新增的会插入到 failure 和 idle 之间
+        如果没有指定sequence, 新增的event会按照传参时候从左到右排序,左边高优先级,新增的会插入到 failure 和 idle 之间
+
+        如果希望每一个hook带上参数:
+        1. 可以在装饰器定义 @battle_wait_strategy(options = options)
+        2. 上下文带上  with battle_wait_strategy(...).with_options(options)
+        options: dict[str: dict] = {
+            "setup": {...}
+            ...
+        }
+
         """
         """
+        bw_ctx = BattleWaitContext()
+
         battle_wait_plan = kwargs.get('battle_wait_plan')
         battle_wait_plan = kwargs.get('battle_wait_plan')
         if battle_wait_plan is None:
         if battle_wait_plan is None:
             battle_wait_plan = BattleWaitPlan()
             battle_wait_plan = BattleWaitPlan()
         # print(battle_wait_plan)
         # print(battle_wait_plan)
         # print(battle_wait_plan.sequence_function_names())
         # print(battle_wait_plan.sequence_function_names())
+        options = kwargs.get('options', None)
+        if options is not None:
+            bw_ctx.options = options
+            # logger.info('options: {}'.format(options))
 
 
-        bw_ctx = BattleWaitContext()
         setup_func = getattr(self, battle_wait_plan.function_setup_name, self._bw_setup_default)
         setup_func = getattr(self, battle_wait_plan.function_setup_name, self._bw_setup_default)
         setup_func(bw_ctx)
         setup_func(bw_ctx)
         handlers = [getattr(self, func_name, None) for func_name in battle_wait_plan.sequence_function_names()]
         handlers = [getattr(self, func_name, None) for func_name in battle_wait_plan.sequence_function_names()]
@@ -462,6 +510,8 @@ class BattleWait(BaseTask):
                 result = handler(bw_ctx)
                 result = handler(bw_ctx)
                 if handler.__name__.startswith('_bw_completion') and result == HookSignal.DONE:
                 if handler.__name__.startswith('_bw_completion') and result == HookSignal.DONE:
                     return True
                     return True
+                if result == HookSignal.CONTINUE:
+                    continue
 
 
             # bw_ctx.completion = True
             # bw_ctx.completion = True
 
 
@@ -485,7 +535,7 @@ if __name__ == '__main__':
 
 
     test_battle_wait = TestBattleWait(c,d)
     test_battle_wait = TestBattleWait(c,d)
     test_battle_wait.battle_wait(random_click_swipt_enable=1)
     test_battle_wait.battle_wait(random_click_swipt_enable=1)
-    with battle_wait_strategy(sequence='completion > interrupt > success > failure > idle'):
+    with battle_wait_strategy(sequence='completion > interrupt > success > failure > idle').with_options(options={"setup": {"11": "11"}}):
         test_battle_wait.battle_wait()
         test_battle_wait.battle_wait()
 
 
 
 

+ 217 - 0
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -0,0 +1,217 @@
+import pytest
+
+from tasks.Component.GeneralBattle.battle_wait import (
+    BattleWait,
+    BattleWaitPlan,
+    HookSignal,
+    battle_wait_strategy,
+)
+
+
+@pytest.fixture(autouse=True)
+def reset_battle_wait_plan(monkeypatch):
+    monkeypatch.setattr(battle_wait_strategy, 'battle_wait_plan', None)
+    monkeypatch.setattr(battle_wait_strategy, 'options', None)
+
+
+def test_default_plan_contains_default_hooks_and_sequence():
+    plan = BattleWaitPlan()
+
+    assert tuple(getattr(plan, hook) for hook in BattleWaitPlan.HOOKS_DEFAULT) == (
+        'default',
+        'default',
+        'default',
+        'default',
+        'default',
+        'default',
+    )
+    assert plan.sequence == 'completion>interrupt>success>failure>idle'
+    assert plan.function_setup_name == '_bw_setup_default'
+
+
+def test_decorator_passes_its_plan_to_the_wrapped_function():
+    strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    plan = battle_wait(object())
+
+    assert plan.reserve == 'default'
+    assert plan.idle == 'default'
+    assert plan.failure == 'custom'
+
+
+def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    default_plan = battle_wait_strategy.battle_wait_plan
+
+    with battle_wait_strategy('success_default', failure='custom'):
+        temporary_plan = battle_wait(object())
+        assert temporary_plan.failure == 'custom'
+
+    assert battle_wait_strategy.battle_wait_plan is default_plan
+    assert battle_wait(object()) is default_plan
+
+
+def test_event_and_strategy_can_be_configured_with_both_supported_forms():
+    plan = BattleWaitPlan('yyy_default', abcd='edf')
+
+    assert plan.yyy == 'default'
+    assert plan.abcd == 'edf'
+    assert plan.sequence_function_names()[4:6] == [
+        '_bw_yyy_default',
+        '_bw_abcd_edf',
+    ]
+
+
+def test_an_event_cannot_be_configured_with_two_strategies():
+    with pytest.raises(ValueError, match="configured more than once"):
+        BattleWaitPlan('success_default', success='custom')
+
+
+def test_setup_runs_before_the_wait_loop():
+    class OrderedBattleWait(BattleWait):
+        def __init__(self):
+            self.events = []
+
+        def screenshot(self):
+            self.events.append('screenshot')
+
+        def _bw_setup_record(self, bw_ctx):
+            self.events.append('setup')
+            return HookSignal.DONE
+
+        def _bw_completion_finish(self, bw_ctx):
+            self.events.append('completion')
+            return HookSignal.DONE
+
+    battle_wait = OrderedBattleWait()
+    plan = BattleWaitPlan('setup_record', 'completion_finish')
+
+    assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
+    assert battle_wait.events == ['setup', 'screenshot', 'completion']
+
+
+def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
+    class CustomBattleWait(BattleWait):
+        def __init__(self):
+            self.events = []
+
+        def screenshot(self):
+            pass
+
+        def _bw_setup_record(self, bw_ctx):
+            self.events.append('setup')
+            return HookSignal.DONE
+
+        def _bw_yyy_record(self, bw_ctx):
+            self.events.append('yyy')
+            return HookSignal.CONTINUE
+
+        def _bw_completion_finish(self, bw_ctx):
+            self.events.append('completion')
+            return HookSignal.DONE
+
+    battle_wait = CustomBattleWait()
+    plan = BattleWaitPlan(
+        'setup_record',
+        'yyy_record',
+        'completion_finish',
+        sequence='yyy > completion > interrupt > success > failure > idle',
+    )
+
+    assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
+    assert battle_wait.events == ['setup', 'yyy', 'completion']
+
+
+def test_custom_sequence_controls_hook_order():
+    plan = BattleWaitPlan(
+        'yyy_default',
+        sequence='failure > yyy > completion > interrupt > success > idle',
+    )
+
+    assert plan.sequence_function_names() == [
+        '_bw_failure_default',
+        '_bw_yyy_default',
+        '_bw_completion_default',
+        '_bw_interrupt_default',
+        '_bw_success_default',
+        '_bw_idle_default',
+    ]
+
+
+def test_custom_events_without_sequence_are_inserted_before_idle_in_argument_order():
+    plan = BattleWaitPlan('yyy_default', 'abcd_edf')
+
+    assert plan.sequence == 'completion>interrupt>success>failure>yyy>abcd>idle'
+
+
+def test_dynamic_override_does_not_modify_the_default_plan():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    default_plan = battle_wait_strategy.battle_wait_plan
+
+    overridden_plan = battle_wait(object(), random_click_swipt_enable=True)
+
+    assert overridden_plan is not default_plan
+    assert overridden_plan.randomclick == 'default'
+    assert not hasattr(default_plan, 'randomclick')
+    assert battle_wait_strategy.battle_wait_plan is default_plan
+
+
+def test_dynamic_override_is_only_valid_for_the_current_call():
+    strategy = battle_wait_strategy('success_default')
+
+    @strategy
+    def battle_wait(owner, *, battle_wait_plan):
+        return battle_wait_plan
+
+    battle_wait(object(), random_click_swipt_enable=True)
+    plan_without_override = battle_wait(object(), random_click_swipt_enable=False)
+
+    assert not hasattr(plan_without_override, 'randomclick')
+
+
+# 验证单层装饰器保存自己的 options,with_options() 只在上下文内临时覆盖,退出后恢复。
+def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
+    received_options = []
+    decorator_options = {'completion': {'source': 'decorator'}}
+    context_options = {'completion': {'source': 'with'}}
+
+    class OptionBattleWait(BattleWait):
+        def screenshot(self):
+            pass
+
+        def _bw_setup_record(self, bw_ctx):
+            return HookSignal.DONE
+
+        def _bw_completion_record(self, bw_ctx):
+            received_options.append(bw_ctx.options)
+            return HookSignal.DONE
+
+        @battle_wait_strategy('setup_record', 'completion_record', options=decorator_options)
+        def battle_wait(self, *args, **kwargs):
+            return self.battle_wait_with_strategy(*args, **kwargs)
+
+    battle_wait = object.__new__(OptionBattleWait)
+
+    assert battle_wait.battle_wait() is True
+    assert received_options[-1] == decorator_options
+
+    with battle_wait_strategy().with_options(context_options):
+        assert battle_wait.battle_wait() is True
+        assert received_options[-1] == context_options
+
+    assert battle_wait.battle_wait() is True
+    assert received_options[-1] == decorator_options