"""Fast GUI timers must not dispatch unrelated account automation.""" import os import threading import time import unittest from types import SimpleNamespace from unittest.mock import Mock os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") from PySide6 import QtWidgets as W from PySide6.QtTest import QTest from ranch_assistant import gui from ranch_assistant.model import Action from ranch_assistant.tests.test_core import workspace_temp class FakeAutomationEngine: """A plan-first-mainline fake which records the Engine dispatch seam.""" def __init__(self, snapshot, actions): self.snapshot = snapshot self.actions = actions self.calls = [] self.pending_hatches = [] self.gift_planner = SimpleNamespace(next_ready_at=None) self.demo = False self.auto = True self.heartbeat_enabled = False self.last_heartbeat = time.monotonic() def __getattr__(self, name): # Window still uses the real offline Engine for rendering and policy state. return getattr(self.offline, name) def poll(self, **kwargs): self.calls.append(("poll", kwargs)) return self.snapshot, self.actions, "unfiltered poll" def poll_automation(self, kind): self.calls.append(("poll_automation", kind)) return self.snapshot, self.actions, f"isolated {kind}" def pending_recovery_due(self): return False def master_sync_due(self): return False def growth_sync_due(self): return False class AutomationSchedulingTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.app = W.QApplication.instance() or W.QApplication([]) def setUp(self): self.folder = self.enterContext(workspace_temp()) self.window = gui.Window(self.folder) self.window.timer.stop() self.window.auto_save_timer.stop() self.wait() def tearDown(self): self.window.stop_workflow() self.window.pool.clear() self.window.pool.waitForDone(3000) self.window.close() self.app.processEvents() def wait(self, predicate=lambda: True, timeout=5): deadline = time.monotonic() + timeout while time.monotonic() < deadline: self.app.processEvents() QTest.qWait(2) if not self.window.busy and predicate(): return self.fail("Real Window/fake Engine Qt scheduling did not settle") def action(self, kind): return Action(kind=kind, description=kind, path="synthetic/" + kind, payload={}) def install_engine(self, *kinds): actions = [self.action("progression"), self.action("map_challenge"), self.action("sweep")] actions.extend(self.action(kind) for kind in kinds) offline = self.window.engine engine = FakeAutomationEngine(offline.snapshot, actions) engine.offline = offline engine.demo = True self.window.engine = engine self.window.latest_render = (engine.snapshot, actions) self.window.monitoring = True self.window.set_strategy_checked(True) self.window.next_poll = float("inf") return engine def install_engine_policy(self): self.window.engine.policy = self.window.read_policy() self.window.apply_explore_policy(self.window.read_explore_policy()) def drain(self): """Let already queued real Jobs start after a stop request.""" self.window.pool.waitForDone(3000) self.wait() def test_real_window_expired_extended_timer_never_uses_full_poll(self): engine = self.install_engine("explore_start") self.window.explore_enabled.setChecked(True) self.window.arm_extended_automation() self.window.next_explore = time.monotonic() - 1 self.window.schedule() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll_automation", "explore")]) def test_each_due_extended_kind_is_dispatched_separately(self): engine = self.install_engine("explore_start", "breakthrough") self.window.explore_enabled.setChecked(True) self.window.breakthrough_targets = {"900": 1} self.window.arm_extended_automation() self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1 self.window.run_extended_automation() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll_automation", "explore")]) self.wait() self.window.next_breakthrough = time.monotonic() - 1 self.window.run_extended_automation() self.wait(lambda: len(engine.calls) >= 2) self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"]) def test_finished_team_dispatches_claim_without_restart_opt_in(self): engine = self.install_engine("explore_finish") self.window.explore_enabled.setChecked(False) self.window.arm_extended_automation() self.assertLess(self.window.next_explore, float("inf")) self.window.next_explore = time.monotonic() - 1 self.window.run_extended_automation() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll_automation", "explore")]) def test_idle_team_does_not_arm_when_restart_is_disabled(self): self.install_engine() self.window.explore_enabled.setChecked(False) self.window.next_explore = float("inf") self.window.arm_extended_automation() self.assertEqual(self.window.next_explore, float("inf")) def test_global_stop_blocks_claim_dispatch_and_disarms_timer(self): engine = self.install_engine("explore_finish") self.window.explore_enabled.setChecked(False) self.window.arm_extended_automation() self.assertLess(self.window.next_explore, float("inf")) self.window.stop_workflow() self.assertEqual(self.window.next_explore, float("inf")) self.window.run_extended_automation() self.wait() self.assertEqual(engine.calls, []) def test_pending_reconciliation_defers_claim_timer_and_active_countdown(self): for pending in ("exploration", "battle"): with self.subTest(pending=pending): self.setUp() engine = self.install_engine("explore_finish") self.window.explore_enabled.setChecked(False) if pending == "exploration": engine.explore_planner.pending = Mock(return_value={"uncertain": True}) else: engine._progression_pending = Mock(return_value=True) self.assertEqual(self.window.latest_render[1][-1].kind, "explore_finish") self.window.next_explore = float("inf") self.window.arm_extended_automation() self.assertEqual(self.window.next_explore, float("inf")) self.window.arm_extended_automation() self.assertEqual(self.window.next_explore, float("inf")) engine.pending_recovery_due = Mock(return_value=True) engine.demo = False self.window.monitoring = True self.window.set_strategy_checked(True) self.window.next_breakthrough = float("inf") self.window.schedule() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll", {"hatch_only": False, "defer_hatch": True})]) def test_fast_hatch_and_gift_dispatch_only_their_own_kind(self): for kind in ("hatch", "gift"): with self.subTest(kind=kind): engine = self.install_engine() if kind == "hatch": engine.pending_hatches = [self.action("hatch")] self.window.fill.setChecked(True) self.window.ranch_enabled.setChecked(True) else: self.window.gift_enabled.setChecked(True) setattr(self.window, "next_" + kind, time.monotonic() - 1) self.window.schedule() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll_automation", kind)]) self.wait() def test_disabling_explore_cancels_unsent_queue_before_worker_entry(self): engine = self.install_engine("explore_start") self.window.explore_enabled.setChecked(True) self.window.next_explore = time.monotonic() - 1 release = threading.Event() blocker = threading.Event() def held_job(): blocker.set() if not release.wait(4): raise TimeoutError("test blocker was not released") return "held" queued = [] original_start = self.window.pool.start def hold_next(runnable): queued.append(runnable) try: self.install_engine_policy() self.window.submit("fixture_blocker", held_job) self.assertTrue(blocker.wait(1)) self.window.pool.start = hold_next self.window.schedule() self.assertTrue(self.window.busy) self.window.explore_enabled.setChecked(False) self.window.persist_settings() self.assertEqual(self.window.next_explore, float("inf")) finally: self.window.pool.start = original_start for runnable in queued: original_start(runnable) release.set() self.drain() self.assertNotIn(("poll_automation", "explore"), engine.calls) self.assertFalse(self.window.busy) def test_stop_cancels_every_fast_deadline_and_queued_worker(self): engine = self.install_engine("explore_start", "breakthrough") self.window.explore_enabled.setChecked(True) self.window.fill.setChecked(True) self.window.ranch_enabled.setChecked(True) self.window.gift_enabled.setChecked(True) self.window.breakthrough_targets = {"900": 1} engine.pending_hatches = [self.action("hatch")] self.install_engine_policy() self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1 self.window.next_hatch = self.window.next_gift = time.monotonic() - 1 queued = [] original_start = self.window.pool.start self.window.pool.start = queued.append try: self.window.schedule() self.window.stop_workflow() self.assertTrue(all(getattr(self.window, "next_" + kind) == float("inf") for kind in ("explore", "breakthrough", "hatch", "gift"))) finally: self.window.pool.start = original_start for runnable in queued: original_start(runnable) self.drain() self.assertEqual(engine.calls, []) self.assertFalse(self.window.busy) def test_completed_kind_does_not_postpone_other_due_extended_kind(self): engine = self.install_engine("explore_start", "breakthrough") self.window.explore_enabled.setChecked(True) self.window.breakthrough_targets = {"900": 1} self.window.arm_extended_automation() self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1 due_breakthrough = self.window.next_breakthrough self.window.schedule() self.wait(lambda: bool(engine.calls)) self.assertEqual(self.window.next_breakthrough, due_breakthrough) self.window.schedule() self.wait(lambda: len(engine.calls) == 2) self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"]) def test_gift_completion_preserves_due_hatch_and_gift_is_not_starved(self): engine = self.install_engine() self.window.fill.setChecked(True) self.window.ranch_enabled.setChecked(True) self.window.gift_enabled.setChecked(True) engine.pending_hatches = [self.action("hatch")] self.window.arm_hatching() self.window.arm_gifting() self.window.next_hatch = self.window.next_gift = time.monotonic() - 1 due_hatch = self.window.next_hatch self.window.schedule() self.wait(lambda: bool(engine.calls)) self.assertEqual(engine.calls, [("poll_automation", "hatch")]) engine.gift_planner.next_ready_at = engine.snapshot.now self.window.arm_gifting() self.window.next_gift = time.monotonic() - 1 self.window.schedule() self.wait(lambda: len(engine.calls) == 2) self.assertEqual(engine.calls[-1], ("poll_automation", "gift")) self.assertGreaterEqual(self.window.next_hatch, due_hatch) def test_closing_map_cancels_queued_automatic_poll_before_engine_entry(self): engine = self.install_engine() self.window.map_enabled.setChecked(True) self.install_engine_policy() self.window.next_poll = time.monotonic() - 1 queued = [] original_start = self.window.pool.start self.window.pool.start = queued.append try: self.window.schedule() self.assertTrue(self.window.busy) self.window.map_enabled.setChecked(False) finally: self.window.pool.start = original_start for runnable in queued: original_start(runnable) self.drain() self.assertEqual(engine.calls, []) self.assertFalse(self.window.map_enabled.isChecked()) def test_disabling_while_busy_applies_before_next_fast_dispatch(self): engine = self.install_engine("explore_start") self.window.explore_enabled.setChecked(True) self.install_engine_policy() release = threading.Event() entered = threading.Event() def held_automation(kind): engine.calls.append(("poll_automation", kind)) entered.set() if not release.wait(4): raise TimeoutError("test automation was not released") return engine.snapshot, [], "held automation" engine.poll_automation = held_automation self.window.next_explore = time.monotonic() - 1 self.window.schedule() self.assertTrue(entered.wait(1)) self.window.explore_enabled.setChecked(False) self.window.persist_settings() self.assertIsNotNone(self.window.pending_policy) self.assertEqual(self.window.next_explore, float("inf")) release.set() self.drain() self.window.schedule() self.drain() self.assertEqual(engine.calls, [("poll_automation", "explore")]) self.assertIsNone(self.window.pending_policy) self.assertFalse(self.window.explore_enabled.isChecked()) self.assertEqual(self.window.next_explore, float("inf")) if __name__ == "__main__": unittest.main()