test_battle_wait.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. from contextvars import copy_context
  2. from types import SimpleNamespace
  3. import pytest
  4. from tasks.Component.GeneralBattle.battle_wait import (
  5. BattleResult,
  6. BattleWait,
  7. BattleWaitPlan,
  8. HookSignal,
  9. OptionCompletionDefault,
  10. OptionPrepareDefault,
  11. OptionSetupDefault,
  12. OptionSuccessDefault,
  13. PerBattlePrepare,
  14. PerBattleState,
  15. PerTaskPreset,
  16. PerTaskState,
  17. battle_wait_options,
  18. battle_wait_strategy,
  19. runtime,
  20. _OPTION_CLASSES,
  21. )
  22. @pytest.fixture(autouse=True)
  23. def reset_battle_wait_plan(monkeypatch):
  24. monkeypatch.setattr(battle_wait_options, 'options', {
  25. event: cls() for event, cls in _OPTION_CLASSES.items()
  26. })
  27. monkeypatch.setattr(runtime, 'task_owner', None)
  28. monkeypatch.setattr(runtime, 'pub_ctx', None)
  29. monkeypatch.setattr(runtime, 'pri_ctx', {})
  30. contexts = (
  31. battle_wait_strategy._context,
  32. battle_wait_options._context,
  33. battle_wait_options._decorator_options,
  34. )
  35. tokens = [context.set(None) for context in contexts]
  36. yield
  37. for context, token in zip(contexts, tokens):
  38. context.reset(token)
  39. def capture(owner, *, battle_wait_plan, options):
  40. return battle_wait_plan, options
  41. def test_default_plan_contains_default_hooks_and_sequence():
  42. plan = BattleWaitPlan()
  43. assert all(getattr(plan, hook) == 'default' for hook in plan.HOOKS_DEFAULT)
  44. assert plan.sequence == (
  45. 'completion>interrupt>prepare>preset>green>red>echo>success>failure>idle'
  46. )
  47. assert plan.function_setup_name == '_bw_setup_default'
  48. def test_decorator_passes_its_plan_to_the_wrapped_function():
  49. strategy = battle_wait_strategy('reserve_default', 'idle_default', failure='custom')
  50. plan, _ = strategy(capture)(object())
  51. assert plan.reserve == 'default'
  52. assert plan.idle == 'default'
  53. assert plan.failure == 'custom'
  54. def test_with_context_uses_a_temporary_plan_and_restores_the_default_plan():
  55. strategy = battle_wait_strategy('success_default')
  56. wait = strategy(capture)
  57. with battle_wait_strategy('success_default', failure='custom'):
  58. assert wait(object())[0].failure == 'custom'
  59. assert battle_wait_strategy._context.get() is None
  60. assert wait(object())[0] is strategy.battle_wait_plan
  61. @pytest.mark.parametrize('strategies', [('default', 'activity'), ('activity', 'default')])
  62. @pytest.mark.parametrize('random_click', [False, True])
  63. def test_task_strategies_are_independent_of_decoration_order(strategies, random_click):
  64. tasks = {name: battle_wait_strategy(success=name)(capture) for name in strategies}
  65. for name, wait in tasks.items():
  66. plan, _ = wait(object(), random_click_swipt_enable=random_click)
  67. assert plan.success == name
  68. assert hasattr(plan, 'randomclick') is random_click
  69. for name, wait in tasks.items():
  70. assert wait(object())[0].success == name
  71. def test_event_and_strategy_can_be_configured_with_both_supported_forms():
  72. plan = BattleWaitPlan('yyy_default', abcd='edf')
  73. assert plan.yyy == 'default'
  74. assert plan.abcd == 'edf'
  75. assert plan.sequence_function_names()[-3:-1] == ['_bw_yyy_default', '_bw_abcd_edf']
  76. def test_an_event_cannot_be_configured_with_two_strategies():
  77. with pytest.raises(ValueError, match='configured more than once'):
  78. BattleWaitPlan('success_default', success='custom')
  79. def test_custom_sequence_controls_hook_order():
  80. sequence = 'failure>yyy>completion>interrupt>prepare>preset>green>red>echo>success>idle'
  81. plan = BattleWaitPlan('yyy_default', sequence=sequence)
  82. assert plan.sequence_function_names() == [f'_bw_{event}_default' for event in sequence.split('>')]
  83. def test_custom_events_without_sequence_are_inserted_before_idle_in_argument_order():
  84. plan = BattleWaitPlan('yyy_default', 'abcd_edf')
  85. assert plan.sequence.endswith('failure>yyy>abcd>idle')
  86. def test_dynamic_override_is_only_valid_for_the_current_call():
  87. strategy = battle_wait_strategy('success_default')
  88. wait = strategy(capture)
  89. overridden, options = wait(object(), random_click_swipt_enable=True)
  90. assert overridden is not strategy.battle_wait_plan
  91. assert overridden.randomclick == 'default'
  92. assert 'randomclick' in options
  93. assert not hasattr(strategy.battle_wait_plan, 'randomclick')
  94. assert wait(object(), random_click_swipt_enable=False)[0] is strategy.battle_wait_plan
  95. def test_nested_context_restores_each_task_strategy_even_after_an_exception():
  96. ordinary = battle_wait_strategy()(capture)
  97. activity = battle_wait_strategy(success='activity')(capture)
  98. outer = battle_wait_strategy(success='outer')
  99. inner = battle_wait_strategy(success='inner')
  100. assert ordinary(object())[0].success == 'default'
  101. assert activity(object())[0].success == 'activity'
  102. with outer:
  103. assert activity(object())[0].success == 'outer'
  104. with pytest.raises(RuntimeError, match='interrupted'):
  105. with inner:
  106. assert ordinary(object())[0].success == 'inner'
  107. raise RuntimeError('interrupted')
  108. assert activity(object())[0].success == 'outer'
  109. assert ordinary(object())[0].success == 'default'
  110. assert activity(object())[0].success == 'activity'
  111. def test_same_context_manager_can_be_nested_and_used_in_independent_contexts():
  112. strategy = battle_wait_strategy(success='activity')
  113. options = battle_wait_options(prepare={'lock_team': True})
  114. wait = battle_wait_strategy()(capture)
  115. first, second = copy_context(), copy_context()
  116. first.run(strategy.__enter__)
  117. second.run(strategy.__enter__)
  118. first.run(options.__enter__)
  119. second.run(options.__enter__)
  120. first.run(options.__exit__, None, None, None)
  121. first.run(strategy.__exit__, None, None, None)
  122. assert first.run(wait, object())[0].success == 'default'
  123. assert second.run(wait, object())[0].success == 'activity'
  124. assert second.run(wait, object())[1]['prepare'].lock_team is True
  125. second.run(options.__exit__, None, None, None)
  126. second.run(strategy.__exit__, None, None, None)
  127. with strategy, options:
  128. with strategy, options:
  129. assert wait(object())[0].success == 'activity'
  130. assert wait(object())[1]['prepare'].lock_team is True
  131. assert wait(object())[0].success == 'default'
  132. assert wait(object())[1]['prepare'].lock_team is False
  133. def test_options_decorator_and_with_are_scoped_to_the_current_call():
  134. wait = battle_wait_options(
  135. success={'excludes_1': ['C_REWARD_1']}, prepare={'lock_team': True}
  136. )(battle_wait_strategy()(capture))
  137. assert wait(object())[1]['success'].excludes_1 == ['C_REWARD_1']
  138. with battle_wait_options(success={'excludes_1': ['C_END_MESSAGE_RIGHT_TOP']}):
  139. options = wait(object())[1]
  140. assert options['success'].excludes_1 == ['C_END_MESSAGE_RIGHT_TOP']
  141. assert options['prepare'].lock_team is True
  142. with pytest.raises(RuntimeError):
  143. with battle_wait_options(prepare={'lock_team': False}):
  144. assert wait(object())[1]['prepare'].lock_team is False
  145. raise RuntimeError('interrupted')
  146. assert wait(object())[1]['prepare'].lock_team is True
  147. assert wait(object())[1]['success'].excludes_1 == ['C_REWARD_1']
  148. assert battle_wait_options._context.get() is None
  149. assert battle_wait_options._decorator_options.get() is None
  150. def test_cross_task_options_do_not_leak_between_tasks_or_calls():
  151. ordinary = battle_wait_options(success={'excludes_1': ['C_REWARD_1']})(
  152. battle_wait_strategy()(capture)
  153. )
  154. activity = battle_wait_options(success={'excludes_1': ['C_END_ACTIVITY_REWARD']})(
  155. battle_wait_strategy(success='activity')(capture)
  156. )
  157. assert ordinary(object())[0].success == 'default'
  158. assert activity(object())[0].success == 'activity'
  159. ordinary(object())[1]['success'].excludes_1.clear()
  160. assert ordinary(object())[1]['success'].excludes_1 == ['C_REWARD_1']
  161. assert activity(object())[1]['success'].excludes_1 == ['C_END_ACTIVITY_REWARD']
  162. assert battle_wait_strategy()(capture)(object())[1]['success'] == OptionSuccessDefault()
  163. def test_options_decorator_restores_context_after_exception():
  164. @battle_wait_options(prepare={'lock_team': True})
  165. def fail(owner):
  166. assert battle_wait_options.current()['prepare'].lock_team is True
  167. raise RuntimeError('interrupted')
  168. with battle_wait_options(success={'excludes_1': ['C_REWARD_1']}):
  169. with pytest.raises(RuntimeError):
  170. fail(object())
  171. options = battle_wait_options.current()
  172. assert options['prepare'].lock_team is False
  173. assert options['success'].excludes_1 == ['C_REWARD_1']
  174. class ReplayBattle(BattleWait):
  175. def __init__(self):
  176. self.events = []
  177. self.frames = 0
  178. def screenshot(self):
  179. self.frames += 1
  180. assert self.frames < 5, 'battle did not complete'
  181. self.events.append('screenshot')
  182. def _bw_setup_record(self, pub, pri):
  183. self.events.append('setup')
  184. return HookSignal.DONE
  185. def _bw_prepare_default(self, pub, pri):
  186. return HookSignal.CONTINUE
  187. def _bw_success_record(self, pub, pri):
  188. self.events.append('success')
  189. pub.per_battle.success = BattleResult.SUCCESS
  190. return runtime.hook_enabled_update(enable=('completion',), disable=('success', 'failure'))
  191. def _bw_completion_record(self, pub, pri):
  192. self.events.append('completion')
  193. return HookSignal.DONE
  194. @battle_wait_strategy(setup='record', success='record', completion='record')
  195. def battle_wait(self, *args, **kwargs):
  196. return self.battle_wait_with_strategy(*args, **kwargs)
  197. def test_setup_runs_before_the_wait_loop_and_completion_waits_for_settlement():
  198. battle = ReplayBattle()
  199. assert battle.battle_wait() is True
  200. assert battle.events == ['setup', 'screenshot', 'success', 'screenshot', 'completion']
  201. def test_custom_hook_is_resolved_and_executed_in_the_configured_sequence():
  202. class CustomBattle(ReplayBattle):
  203. def _bw_yyy_multi_word(self, pub, pri):
  204. self.events.append('yyy')
  205. pub.per_battle.success = BattleResult.SUCCESS
  206. return runtime.hook_enabled_update(enable=('completion',), disable=())
  207. battle = CustomBattle()
  208. with battle_wait_strategy(
  209. setup='record', success='record', completion='record', yyy='multi_word',
  210. sequence='yyy>completion>interrupt>prepare>preset>green>red>echo>success>failure>idle',
  211. ):
  212. assert battle.battle_wait() is True
  213. assert battle.events == ['setup', 'screenshot', 'yyy', 'completion']
  214. def test_activity_reward_is_collected_after_another_task_is_decorated(monkeypatch):
  215. ordinary = battle_wait_strategy()(capture)
  216. class ActivityBattle(BattleWait):
  217. def __init__(self):
  218. self.reward_visible = True
  219. self.frames = 0
  220. self.clicks = []
  221. self.device = SimpleNamespace(
  222. stuck_record_add=lambda name: None,
  223. click_record_clear=lambda: None,
  224. )
  225. def screenshot(self):
  226. self.frames += 1
  227. assert self.frames < 10, 'Activity reward was not collected'
  228. def is_in_real_battle(self, is_screenshot=False):
  229. return False
  230. def appear(self, asset, **kwargs):
  231. return asset is self.I_UI_REWARD and self.reward_visible
  232. def appear_then_click(self, asset, **kwargs):
  233. return False
  234. def click(self, asset, **kwargs):
  235. self.clicks.append(asset.name)
  236. self.reward_visible = False
  237. @battle_wait_strategy(success='activity')
  238. def battle_wait(self, *args, **kwargs):
  239. return self.battle_wait_with_strategy(*args, **kwargs)
  240. monkeypatch.setattr('tasks.Component.GeneralBattle.battle_wait.random.random', lambda: 1)
  241. task = ActivityBattle()
  242. assert task.battle_wait(random_click_swipt_enable=False) is True
  243. assert task.clicks == ['exclude_click_activity']
  244. assert runtime.pub_ctx.per_task.count == 1
  245. assert ordinary(object())[0].success == 'default'
  246. def _make_runtime_probe():
  247. class RuntimeProbe(BattleWait):
  248. def __init__(self):
  249. self.calls = []
  250. def _bw_setup_probe(self, pub, pri):
  251. self.calls.append(('setup', pub, pri))
  252. return HookSignal.DONE
  253. def _bw_completion_probe(self, pub, pri):
  254. self.calls.append(('completion', pub, pri))
  255. return HookSignal.DONE
  256. def _bw_success_probe(self, pub, pri):
  257. self.calls.append(('success', pub, pri))
  258. return HookSignal.DONE
  259. return RuntimeProbe()
  260. def test_runtime_injects_shared_pub_and_per_hook_pri():
  261. battle = _make_runtime_probe()
  262. battle._bw_setup_probe()
  263. battle._bw_completion_probe()
  264. _, setup_pub, setup_pri = battle.calls[0]
  265. _, completion_pub, completion_pri = battle.calls[1]
  266. assert setup_pub is completion_pub is runtime.pub_ctx
  267. assert setup_pri is runtime.pri_ctx['_bw_setup_probe']
  268. assert completion_pri is runtime.pri_ctx['_bw_completion_probe']
  269. assert setup_pri is not completion_pri
  270. assert battle._bw_completion_probe.__name__ == '_bw_completion_probe'
  271. def test_runtime_task_owner_switch_resets_per_task():
  272. battle = _make_runtime_probe()
  273. battle._bw_setup_probe()
  274. runtime.pub_ctx.cross['keep'] = 1
  275. runtime.pub_ctx.per_task.count = 4
  276. runtime._ensure_pri_default('_bw_preset_default')
  277. runtime.pri_ctx['_bw_preset_default'].per_task.done = True
  278. _make_runtime_probe()._bw_setup_probe()
  279. assert runtime.pub_ctx.cross == {'keep': 1}
  280. assert runtime.pub_ctx.per_task == PerTaskState()
  281. assert runtime.pri_ctx['_bw_preset_default'].per_task == PerTaskPreset()
  282. def test_runtime_reset_per_battle_keeps_cross_and_per_task():
  283. battle = _make_runtime_probe()
  284. battle._bw_setup_probe()
  285. runtime.pub_ctx.cross['c'] = 1
  286. runtime.pub_ctx.per_task.count = 2
  287. runtime.pub_ctx.per_battle.success = BattleResult.SUCCESS
  288. runtime._ensure_pri_default('_bw_prepare_default')
  289. runtime.pri_ctx['_bw_prepare_default'].per_battle.done = True
  290. runtime.reset_per_battle()
  291. assert runtime.pub_ctx.cross == {'c': 1}
  292. assert runtime.pub_ctx.per_task.count == 2
  293. assert runtime.pub_ctx.per_battle == PerBattleState()
  294. assert runtime.pri_ctx['_bw_prepare_default'].per_battle == PerBattlePrepare()
  295. def test_runtime_update_options_distributes_by_hook_event_name_and_resets_defaults():
  296. plan = BattleWaitPlan(setup='probe', completion='probe', success='multi_word')
  297. options = {
  298. 'setup': OptionSetupDefault(excludes=['C_REWARD_1']),
  299. 'completion': OptionCompletionDefault(excludes=['C_REWARD_2']),
  300. 'success': OptionSuccessDefault(excludes_1=['C_REWARD_3']),
  301. }
  302. runtime.update_options(options, plan=plan)
  303. assert runtime.pub_ctx.options == options
  304. for hook in ('_bw_setup_probe', '_bw_completion_probe', '_bw_success_multi_word'):
  305. assert runtime.pri_ctx[hook].options is options[runtime.hook2event(hook)]
  306. runtime.update_options({}, plan=plan)
  307. assert runtime.pri_ctx['_bw_setup_probe'].options == OptionSetupDefault()
  308. assert runtime.pri_ctx['_bw_success_multi_word'].options == OptionSuccessDefault()
  309. def test_runtime_str_shows_hook_name_and_state_fields():
  310. battle = _make_runtime_probe()
  311. battle._bw_setup_probe()
  312. text = str(battle.__class__._bw_setup_probe)
  313. assert '_bw_setup_probe' in text
  314. assert 'count' in text
  315. assert 'hook_enabled' in text
  316. @pytest.mark.parametrize('locked', [False, True])
  317. def test_prepare_dismisses_soul_mismatch_dialog_before_progressing(locked):
  318. class PrepareBattle(BattleWait):
  319. def __init__(self):
  320. self.visible = [self.I_DISABLE_7DAYS_DIFF_SOUL, self.I_CONFIRM_CLOSE_DIFF_SOUL]
  321. self.clicked = []
  322. def appear_then_click(self, target, **kwargs):
  323. if self.visible and target is self.visible[0]:
  324. self.clicked.append(target)
  325. self.visible.pop(0)
  326. return True
  327. return False
  328. def is_in_real_battle(self, is_screenshot=False):
  329. return True
  330. battle = PrepareBattle()
  331. runtime.update_options({'prepare': OptionPrepareDefault(lock_team=locked)}, BattleWaitPlan())
  332. for _ in range(2):
  333. assert battle._bw_prepare_default() == HookSignal.CONTINUE
  334. assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is False
  335. assert battle.clicked == [battle.I_DISABLE_7DAYS_DIFF_SOUL, battle.I_CONFIRM_CLOSE_DIFF_SOUL]
  336. battle._bw_prepare_default()
  337. assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is True