test_script_anti_ban.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. from datetime import datetime, time, timedelta
  2. from types import SimpleNamespace
  3. from unittest.mock import Mock, call
  4. import pytest
  5. import script as script_module
  6. from module.config import anti_ban as anti_ban_module
  7. from tasks.Script.config_antiban import AntiBan
  8. from tasks.Script.config_optimization import Optimization, WhenTaskQueueEmpty
  9. @pytest.fixture
  10. def scheduler(monkeypatch):
  11. clock = SimpleNamespace(now=datetime(2026, 10, 23, 3))
  12. class Clock(datetime):
  13. @classmethod
  14. def now(cls):
  15. return clock.now
  16. monkeypatch.setattr(script_module, 'datetime', Clock)
  17. monkeypatch.setattr(anti_ban_module, 'datetime', Clock)
  18. task = SimpleNamespace(command='Exploration', next_run=clock.now - timedelta(minutes=1))
  19. script = object.__new__(script_module.Script)
  20. script._emulator_down = False
  21. script.instance_guard = None
  22. script.state_queue = None
  23. script.anti_ban_guard = anti_ban_module.AntiBanGuard()
  24. script.config = SimpleNamespace(
  25. script=SimpleNamespace(
  26. anti_ban=AntiBan(enable=True),
  27. optimization=Optimization(
  28. close_game_wait_duration=time(12),
  29. close_emulator_wait_duration=time(0, 1),
  30. ),
  31. ),
  32. get_next=Mock(return_value=task),
  33. )
  34. script._try_acquire_queue_token = Mock(return_value=True)
  35. script.device = Mock()
  36. script.run = Mock(return_value=True)
  37. script._wait_until_with_emulator_preheat = Mock(return_value=True)
  38. def finish_wait(future):
  39. clock.now = future + timedelta(seconds=1)
  40. return True
  41. script.wait_until = Mock(side_effect=finish_wait)
  42. events = Mock()
  43. events.attach_mock(script.device.app_stop, 'close_game')
  44. events.attach_mock(script.device.emulator_stop, 'close_emulator')
  45. events.attach_mock(script.device.release_during_wait, 'release')
  46. events.attach_mock(script.run, 'run')
  47. events.attach_mock(script.wait_until, 'wait')
  48. return script, clock, task, events
  49. @pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
  50. @pytest.mark.parametrize('trigger', ['sleep_window', 'active_limit'])
  51. def test_anti_ban_finishes_using_selected_action_before_waiting(scheduler, method, trigger):
  52. script, clock, task, events = scheduler
  53. script.config.script.optimization.when_task_queue_empty = method
  54. original_next_run = task.next_run
  55. if trigger == 'active_limit':
  56. config = script.config.script.anti_ban
  57. config.sleep_start = config.sleep_end = time(0)
  58. config.daily_active_limit = timedelta(hours=1)
  59. config.long_rest_duration = timedelta(minutes=5)
  60. script.anti_ban_guard.record_active(3600)
  61. wake = clock.now + config.long_rest_duration
  62. else:
  63. wake = clock.now.replace(hour=8)
  64. assert script.get_next_task() == 'Exploration'
  65. # Both ordinary idle thresholds would change the requested action:
  66. # the game-close threshold is longer than the rest, the emulator threshold shorter.
  67. if method == WhenTaskQueueEmpty.CLOSE_GAME:
  68. assert events.mock_calls == [
  69. call.close_game(), call.release(), call.wait(wake), call.run('Restart'),
  70. ]
  71. else:
  72. assert events.mock_calls == [
  73. call.run('GotoMain'), call.release(), call.wait(wake),
  74. ]
  75. assert script.config.get_next.call_count == 2
  76. assert task.next_run == original_next_run
  77. script._wait_until_with_emulator_preheat.assert_not_called()
  78. @pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
  79. @pytest.mark.parametrize('trigger', ['sleep_window', 'active_limit'])
  80. def test_anti_ban_waits_for_running_task_to_finish(scheduler, monkeypatch, method, trigger):
  81. script, clock, task, events = scheduler
  82. clock.now = datetime(2026, 10, 23, 1, 59, 30)
  83. task.next_run = clock.now - timedelta(minutes=1)
  84. script.config_name = 'anti_ban_test'
  85. script.is_first_task = False
  86. script.failure_record = {}
  87. script.config.model = SimpleNamespace(running_task='')
  88. script.config.script.device = SimpleNamespace(run_background_only=True)
  89. script.config.script.optimization.when_task_queue_empty = method
  90. script.device.is_desktop = False
  91. if trigger == 'active_limit':
  92. config = script.config.script.anti_ban
  93. config.sleep_start = config.sleep_end = time(0)
  94. config.daily_active_limit = timedelta(minutes=1)
  95. config.long_rest_duration = timedelta(minutes=5)
  96. check_anti_ban = Mock(wraps=script.anti_ban_guard.wake_time)
  97. monkeypatch.setattr(script.anti_ban_guard, 'wake_time', check_anti_ban)
  98. monkeypatch.setattr(script_module.logger, 'set_file_logger', Mock())
  99. monkeypatch.setattr(script_module, 'del_cached_property', Mock())
  100. task_finished = False
  101. def run(command):
  102. nonlocal task_finished
  103. if command == 'Exploration':
  104. assert script.config.model.running_task == 'Exploration'
  105. # Cross the sleep start / active limit while the same task is still running.
  106. clock.now += timedelta(minutes=1)
  107. assert check_anti_ban.call_count == 1
  108. assert events.mock_calls == [call.run('Exploration')]
  109. clock.now += timedelta(minutes=1)
  110. task_finished = True
  111. events.task_complete()
  112. else:
  113. assert command == 'GotoMain'
  114. assert task_finished
  115. return True
  116. class RestStarted(Exception):
  117. pass
  118. def wait(future):
  119. assert task_finished
  120. assert script.config.model.running_task == ''
  121. assert check_anti_ban.call_count == 2
  122. raise RestStarted
  123. script.run.side_effect = run
  124. script.wait_until.side_effect = wait
  125. with pytest.raises(RestStarted):
  126. script.loop()
  127. wake = (clock.now + timedelta(minutes=5) if trigger == 'active_limit'
  128. else clock.now.replace(hour=8, minute=0, second=0))
  129. cleanup = call.close_game() if method == WhenTaskQueueEmpty.CLOSE_GAME else call.run('GotoMain')
  130. assert events.mock_calls == [
  131. call.run('Exploration'), call.task_complete(), cleanup, call.release(), call.wait(wake),
  132. ]
  133. @pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
  134. def test_disabling_anti_ban_during_wait_reloads_without_delaying_pending_task(
  135. scheduler, monkeypatch, method):
  136. script, clock, task, events = scheduler
  137. script.config.script.optimization.when_task_queue_empty = method
  138. original_next_run = task.next_run
  139. script.wait_until.side_effect = None
  140. script.wait_until.return_value = False
  141. def reload_config(instance, name):
  142. assert instance is script
  143. assert name == 'config'
  144. script.config.script.anti_ban.enable = False
  145. reload = Mock(side_effect=reload_config)
  146. monkeypatch.setattr(script_module, 'del_cached_property', reload)
  147. assert script.get_next_task() == 'Exploration'
  148. reload.assert_called_once_with(script, 'config')
  149. script.wait_until.assert_called_once_with(clock.now.replace(hour=8))
  150. assert task.next_run == original_next_run
  151. assert call.run('Restart') not in events.mock_calls
  152. @pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
  153. def test_anti_ban_keeps_stopped_emulator_off_without_preheating(scheduler, method):
  154. script, clock, task, events = scheduler
  155. script.config.script.optimization.when_task_queue_empty = method
  156. script._emulator_down = True
  157. assert script.get_next_task() == 'Exploration'
  158. assert events.mock_calls == [call.wait(datetime(2026, 10, 23, 8))]
  159. script._wait_until_with_emulator_preheat.assert_not_called()
  160. assert script._emulator_down is True
  161. def test_ordinary_short_idle_keeps_game_open_below_close_threshold(scheduler):
  162. script, clock, task, events = scheduler
  163. script.config.script.optimization.when_task_queue_empty = WhenTaskQueueEmpty.CLOSE_GAME
  164. next_run = clock.now + timedelta(seconds=30)
  165. assert script._handle_wait_during_idle(next_run) is True
  166. assert events.mock_calls == [call.release(), call.wait(next_run)]
  167. @pytest.mark.parametrize('method', list(WhenTaskQueueEmpty))
  168. def test_ordinary_long_idle_still_closes_emulator_at_configured_threshold(scheduler, method):
  169. script, clock, task, events = scheduler
  170. script.config.script.optimization.when_task_queue_empty = method
  171. next_run = clock.now + timedelta(minutes=5)
  172. assert script._handle_wait_during_idle(next_run) is True
  173. assert events.mock_calls == [call.close_emulator(), call.run('Restart')]
  174. script._wait_until_with_emulator_preheat.assert_called_once_with(next_run)