import copy from dataclasses import asdict import os import time import unittest from unittest.mock import patch os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") from PySide6 import QtWidgets as W from PySide6.QtTest import QTest from ranch_assistant.api import Session from ranch_assistant.engine import Engine, demo_snapshot from ranch_assistant.gui import Window from ranch_assistant.model import Catalog, EggRule, Policy, Snapshot from ranch_assistant.tests.test_core import workspace_temp class HatchClient: def __init__(self, catalog): self.value = copy.deepcopy(demo_snapshot(catalog).raw) self.template = self.value["monsters"][0] | {"mode": 2} self.value["monsters"] = [] self.value["stacks"] = [{"id": 1, "position": 0, "monsterId": -1}, {"id": 2, "position": 1, "monsterId": -1}, {"id": 4, "position": 3, "monsterId": -1}] self.value["items"] = [{"id": 501, "typeId": self.template["typeId"], "num": 5}] self.calls = [] self.session = Session("http://127.0.0.1/", "synthetic-test-token") self.stale = False def snapshot(self): return Snapshot(copy.deepcopy(self.value)) def call(self, path, payload): self.calls.append((path, payload)) if self.stale: return {} if path != "stackService/stackAddMonster": raise AssertionError("Fast hatching executed another action") egg = payload["eggs"][0] mid = 1000 + len(self.calls) next(slot for slot in self.value["stacks"] if slot["id"] == egg["stackId"])["monsterId"] = mid next(item for item in self.value["items"] if item["id"] == egg["itemId"])["num"] -= 1 self.value["monsters"].append(self.template | {"id": mid, "mode": 0, "timeStart": int(time.time() * 1000)}) return {} def persist_session(self): pass def close(self): pass def policy_for(client): return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True, egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell"))}) class HatchTimingTests(unittest.TestCase): def test_fast_hatching_skips_other_actions_and_retains_vip_and_reserve_limits(self): catalog = Catalog() client = HatchClient(catalog) client.value["monsters"].append(client.template) client.value["stacks"][0]["monsterId"] = client.template["id"] engine = Engine(catalog, client) engine.policy = policy_for(client) engine.policy.reserved_eggs = {str(client.template["typeId"]): 4} engine.auto = True engine.read_snapshot() self.assertEqual(engine.plans()[0].kind, "sell") snapshot, _, _ = engine.poll(hatch_only=True) self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"]) self.assertEqual(client.calls[0][1]["eggs"][0]["stackId"], 2) self.assertIn(client.template["id"], snapshot.monsters) self.assertFalse(engine.pending_hatches) self.assertEqual(client.value["stacks"][2]["monsterId"], -1) def test_fast_worker_rechecks_stock_and_never_falls_back_to_buying(self): catalog = Catalog() client = HatchClient(catalog) engine = Engine(catalog, client) engine.policy = policy_for(client) engine.auto = True engine.poll(defer_hatch=True) self.assertEqual(client.calls, []) self.assertTrue(engine.pending_hatches) client.value["items"][0]["num"] = 0 client.value["monsters"].append(client.template | {"mode": 0, "timeStart": 1}) engine.poll(hatch_only=True) self.assertEqual(client.calls, []) self.assertFalse(engine.pending_hatches) def test_unconfirmed_hatch_stops_automation_before_another_fill(self): catalog = Catalog() client = HatchClient(catalog) client.stale = True engine = Engine(catalog, client) engine.policy = policy_for(client) engine.auto = True with self.assertRaisesRegex(ValueError, "坑位状态尚未同步"): engine.poll(hatch_only=True) self.assertFalse(engine.auto) engine.poll(hatch_only=True) self.assertEqual(len(client.calls), 1) class HatchTimerGuiTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.app = W.QApplication.instance() or W.QApplication([]) def wait(self, window): for _ in range(500): self.app.processEvents() QTest.qWait(2) if not window.busy: return self.fail("Background hatch did not finish") def test_short_hatch_timer_does_not_change_poll_deadline_and_stops_on_pause(self): with workspace_temp() as folder: window = Window(folder) window.timer.stop() try: self.wait(window) client = HatchClient(window.catalog) window.engine = Engine(window.catalog, client) window.engine.last_heartbeat = time.monotonic() window.egg_rules = policy_for(client).egg_rules window.monitoring = True window.set_strategy_checked(True) with patch.object(window, "poll_delay", return_value=300), patch("ranch_assistant.gui.random.uniform", return_value=1.5) as draw: window.refresh(automated=True) self.wait(window) deadline = window.next_poll self.assertEqual(client.calls, []) self.assertTrue(window.hatch_timer.isActive()) self.assertEqual(window.hatch_timer.interval(), 1500) self.assertEqual(draw.call_args.args, (1, 2)) hatch_deadline = window.next_hatch window.refresh(automated=True) self.wait(window) self.assertEqual(window.next_hatch, hatch_deadline) self.assertEqual(draw.call_count, 1) deadline = window.next_poll window.next_hatch = time.monotonic() - 1 window.schedule() self.wait(window) self.assertEqual(len(client.calls), 1) self.assertEqual(window.next_poll, deadline) self.assertTrue(window.hatch_timer.isActive()) window.stop_workflow() self.assertFalse(window.hatch_timer.isActive()) window.schedule() self.assertEqual(len(client.calls), 1) finally: window.close() if __name__ == "__main__": unittest.main()