test_battle_wait.py 18 KB

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