test_battle_wait.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. import pytest
  2. from tasks.Component.GeneralBattle.battle_wait import (
  3. BattleWait,
  4. BattleWaitPlan,
  5. HookSignal,
  6. battle_wait_strategy,
  7. )
  8. @pytest.fixture(autouse=True)
  9. def reset_battle_wait_plan(monkeypatch):
  10. monkeypatch.setattr(battle_wait_strategy, 'options', None)
  11. token = battle_wait_strategy._context.set(None)
  12. yield
  13. battle_wait_strategy._context.reset(token)
  14. def test_default_plan_contains_default_hooks_and_sequence():
  15. plan = BattleWaitPlan()
  16. assert tuple(getattr(plan, hook) for hook in BattleWaitPlan.HOOKS_DEFAULT) == (
  17. 'default',
  18. 'default',
  19. 'default',
  20. 'default',
  21. 'default',
  22. 'default',
  23. )
  24. assert plan.sequence == 'completion>interrupt>success>failure>idle'
  25. assert plan.function_setup_name == '_bw_setup_default'
  26. def test_decorator_passes_its_plan_to_the_wrapped_function():
  27. strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
  28. @strategy
  29. def battle_wait(owner, *, battle_wait_plan):
  30. return battle_wait_plan
  31. plan = battle_wait(object())
  32. assert plan.reserve == 'default'
  33. assert plan.idle == 'default'
  34. assert plan.failure == 'custom'
  35. def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
  36. strategy = battle_wait_strategy('success_default')
  37. @strategy
  38. def battle_wait(owner, *, battle_wait_plan):
  39. return battle_wait_plan
  40. default_plan = strategy.battle_wait_plan
  41. with battle_wait_strategy('success_default', failure='custom'):
  42. temporary_plan = battle_wait(object())
  43. assert temporary_plan.failure == 'custom'
  44. assert battle_wait_strategy._context.get() is None
  45. assert battle_wait(object()) is default_plan
  46. def test_event_and_strategy_can_be_configured_with_both_supported_forms():
  47. plan = BattleWaitPlan('yyy_default', abcd='edf')
  48. assert plan.yyy == 'default'
  49. assert plan.abcd == 'edf'
  50. assert plan.sequence_function_names()[4:6] == [
  51. '_bw_yyy_default',
  52. '_bw_abcd_edf',
  53. ]
  54. @pytest.mark.parametrize('strategies', [('default', 'activity'), ('activity', 'default')])
  55. @pytest.mark.parametrize('random_click', [False, True])
  56. def test_task_strategies_are_independent_of_decoration_order(strategies, random_click):
  57. def wait(owner, *, battle_wait_plan):
  58. return battle_wait_plan
  59. tasks = {
  60. name: battle_wait_strategy(success=name)(wait)
  61. for name in strategies
  62. }
  63. for name, wait in tasks.items():
  64. plan = wait(object(), random_click_swipt_enable=random_click)
  65. assert plan.success == name
  66. assert hasattr(plan, 'randomclick') is random_click
  67. # A later call must still use the task's own strategy.
  68. for name, wait in tasks.items():
  69. assert wait(object()).success == name
  70. def test_activity_reward_is_collected_after_another_task_is_decorated(monkeypatch):
  71. from types import SimpleNamespace
  72. @battle_wait_strategy()
  73. def ordinary_wait(owner, *, battle_wait_plan):
  74. return battle_wait_plan
  75. class ActivityBattle(BattleWait):
  76. def __init__(self):
  77. self.reward_visible = True
  78. self.frames = 0
  79. self.clicks = []
  80. self.device = SimpleNamespace(
  81. stuck_record_add=lambda name: None,
  82. click_record_clear=lambda: None,
  83. )
  84. def screenshot(self):
  85. self.frames += 1
  86. assert self.frames < 10, 'Activity reward was not collected'
  87. def appear(self, asset, **kwargs):
  88. return asset is self.I_UI_REWARD and self.reward_visible
  89. def appear_then_click(self, asset, **kwargs):
  90. return False
  91. def click(self, asset, **kwargs):
  92. self.clicks.append(asset.name)
  93. self.reward_visible = False
  94. @battle_wait_strategy(success='activity')
  95. def battle_wait(self, *args, **kwargs):
  96. return self.battle_wait_with_strategy(*args, **kwargs)
  97. # Keep the replay on the normal dismissal path, without random item inspection.
  98. monkeypatch.setattr('tasks.Component.GeneralBattle.battle_wait.random.random', lambda: 1)
  99. task = ActivityBattle()
  100. assert task.battle_wait(random_click_swipt_enable=False) is True
  101. assert task.clicks == ['exclude_click_activity']
  102. assert ordinary_wait(object()).success == 'default'
  103. def test_an_event_cannot_be_configured_with_two_strategies():
  104. with pytest.raises(ValueError, match="configured more than once"):
  105. BattleWaitPlan('success_default', success='custom')
  106. def test_setup_runs_before_the_wait_loop():
  107. class OrderedBattleWait(BattleWait):
  108. def __init__(self):
  109. self.events = []
  110. def screenshot(self):
  111. self.events.append('screenshot')
  112. def _bw_setup_record(self, bw_ctx):
  113. self.events.append('setup')
  114. return HookSignal.DONE
  115. def _bw_completion_finish(self, bw_ctx):
  116. self.events.append('completion')
  117. bw_ctx.success = True
  118. return HookSignal.DONE
  119. battle_wait = OrderedBattleWait()
  120. plan = BattleWaitPlan('setup_record', 'completion_finish')
  121. assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
  122. assert battle_wait.events == ['setup', 'screenshot', 'completion']
  123. def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
  124. class CustomBattleWait(BattleWait):
  125. def __init__(self):
  126. self.events = []
  127. def screenshot(self):
  128. pass
  129. def _bw_setup_record(self, bw_ctx):
  130. self.events.append('setup')
  131. return HookSignal.DONE
  132. def _bw_yyy_record(self, bw_ctx):
  133. self.events.append('yyy')
  134. return HookSignal.CONTINUE
  135. def _bw_completion_finish(self, bw_ctx):
  136. self.events.append('completion')
  137. bw_ctx.success = True
  138. return HookSignal.DONE
  139. battle_wait = CustomBattleWait()
  140. plan = BattleWaitPlan(
  141. 'setup_record',
  142. 'yyy_record',
  143. 'completion_finish',
  144. sequence='yyy > completion > interrupt > success > failure > idle',
  145. )
  146. assert battle_wait.battle_wait_with_strategy(battle_wait_plan=plan) is True
  147. assert battle_wait.events == ['setup', 'yyy', 'completion']
  148. def test_custom_sequence_controls_hook_order():
  149. plan = BattleWaitPlan(
  150. 'yyy_default',
  151. sequence='failure > yyy > completion > interrupt > success > idle',
  152. )
  153. assert plan.sequence_function_names() == [
  154. '_bw_failure_default',
  155. '_bw_yyy_default',
  156. '_bw_completion_default',
  157. '_bw_interrupt_default',
  158. '_bw_success_default',
  159. '_bw_idle_default',
  160. ]
  161. def test_custom_events_without_sequence_are_inserted_before_idle_in_argument_order():
  162. plan = BattleWaitPlan('yyy_default', 'abcd_edf')
  163. assert plan.sequence == 'completion>interrupt>success>failure>yyy>abcd>idle'
  164. def test_dynamic_override_does_not_modify_the_default_plan():
  165. strategy = battle_wait_strategy('success_default')
  166. @strategy
  167. def battle_wait(owner, *, battle_wait_plan):
  168. return battle_wait_plan
  169. default_plan = strategy.battle_wait_plan
  170. overridden_plan = battle_wait(object(), random_click_swipt_enable=True)
  171. assert overridden_plan is not default_plan
  172. assert overridden_plan.randomclick == 'default'
  173. assert not hasattr(default_plan, 'randomclick')
  174. assert strategy.battle_wait_plan is default_plan
  175. def test_dynamic_override_is_only_valid_for_the_current_call():
  176. strategy = battle_wait_strategy('success_default')
  177. @strategy
  178. def battle_wait(owner, *, battle_wait_plan):
  179. return battle_wait_plan
  180. battle_wait(object(), random_click_swipt_enable=True)
  181. plan_without_override = battle_wait(object(), random_click_swipt_enable=False)
  182. assert not hasattr(plan_without_override, 'randomclick')
  183. # 验证单层装饰器保存自己的 options,with_options() 只在上下文内临时覆盖,退出后恢复。
  184. def test_decorator_options_and_with_options_are_scoped_to_the_current_call():
  185. received_options = []
  186. decorator_options = {
  187. 'completion': {'source': 'decorator'},
  188. 'success': {'excludes': ['C_REWARD_1']},
  189. }
  190. context_options = {
  191. 'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
  192. }
  193. strategy = battle_wait_strategy(
  194. 'setup_record', 'completion_record', options=decorator_options
  195. )
  196. class OptionBattleWait(BattleWait):
  197. def screenshot(self):
  198. pass
  199. def _bw_setup_record(self, bw_ctx):
  200. return HookSignal.DONE
  201. def _bw_completion_record(self, bw_ctx):
  202. received_options.append(bw_ctx.options)
  203. bw_ctx.success = True
  204. return HookSignal.DONE
  205. @strategy
  206. def battle_wait(self, *args, **kwargs):
  207. return self.battle_wait_with_strategy(*args, **kwargs)
  208. battle_wait = object.__new__(OptionBattleWait)
  209. assert battle_wait.battle_wait() is True
  210. assert received_options[-1] == decorator_options
  211. with strategy.with_options(context_options):
  212. assert battle_wait.battle_wait() is True
  213. assert received_options[-1] == {
  214. 'completion': {'source': 'decorator'},
  215. 'success': {'excludes': ['C_END_MESSAGE_RIGHT_TOP']},
  216. }
  217. strategy_text = str(strategy)
  218. assert 'options=' in strategy_text
  219. assert 'C_END_MESSAGE_RIGHT_TOP' in strategy_text
  220. assert battle_wait.battle_wait() is True
  221. assert received_options[-1] == decorator_options
  222. assert 'C_REWARD_1' in str(strategy)
  223. def test_nested_context_restores_each_task_strategy_even_after_an_exception():
  224. def wait(owner, *, battle_wait_plan, options=None):
  225. return battle_wait_plan.success, options
  226. ordinary_wait = battle_wait_strategy()(wait)
  227. activity_wait = battle_wait_strategy(success='activity')(wait)
  228. outer = battle_wait_strategy(success='outer', options={'success': {'source': 'outer'}})
  229. inner = battle_wait_strategy(success='inner', options={'success': {'source': 'inner'}})
  230. # Merely constructing temporary strategies must not change existing tasks.
  231. assert ordinary_wait(object()) == ('default', None)
  232. assert activity_wait(object()) == ('activity', None)
  233. with outer:
  234. assert activity_wait(object()) == ('outer', {'success': {'source': 'outer'}})
  235. with pytest.raises(RuntimeError, match='interrupted'):
  236. with inner:
  237. assert ordinary_wait(object()) == ('inner', {'success': {'source': 'inner'}})
  238. raise RuntimeError('interrupted')
  239. assert activity_wait(object()) == ('outer', {'success': {'source': 'outer'}})
  240. assert ordinary_wait(object()) == ('default', None)
  241. assert activity_wait(object()) == ('activity', None)
  242. def test_decorator_options_do_not_leak_between_tasks_or_calls():
  243. def wait(owner, *, battle_wait_plan, options):
  244. return options
  245. ordinary_options = {'success': {'excludes': ['C_REWARD_1']}}
  246. activity_options = {'success': {'excludes': ['C_END_ACTIVITY_REWARD']}}
  247. ordinary_wait = battle_wait_strategy(options=ordinary_options)(wait)
  248. activity_wait = battle_wait_strategy(success='activity', options=activity_options)(wait)
  249. assert ordinary_wait(object()) == ordinary_options
  250. assert activity_wait(object()) == activity_options
  251. ordinary_wait(object())['success']['excludes'].clear()
  252. assert ordinary_wait(object()) == ordinary_options
  253. assert activity_wait(object()) == activity_options