import copy import json import unittest from ranch_assistant.breakthrough import POTENTIAL_PATH from ranch_assistant.engine import Engine from ranch_assistant.exploration import ExplorePolicy from ranch_assistant.model import Catalog, Policy, Snapshot from ranch_assistant.tests.test_core import workspace_temp def raw(catalog): value = {"master": {"id": 1, "ti": 100, "money": 0, "ke": 0}, "monsters": [{"id": mid, "typeId": 1001010, "process": 3, "mode": 2, "level": 10, "potentialLevel": 1, "pAtk": 2, "pDef": 8, "pHp": 105, "pDex": 1} for mid in (900, 901, 902)], "items": [{"id": 600, "typeId": 30058, "num": 100}], "stacks": [], "rooms": [], "teams": [], "currentTasks": [], "history": {"passTask": {"1001008": True}, "passStage": {"0109": {"1": True}}}, "activityHistory": {}, "monsterAttributes": [], "exploreTeams": [{"id": 77, "status": 0, "monsters": [], "area": "", "endTime": 0}]} return value class FakeClient: def __init__(self, value): self.value, self.calls = value, [] self.response = {"resCode": 0} def snapshot(self): return Snapshot(copy.deepcopy(self.value)) def call(self, path, payload): self.calls.append((path, payload)) if isinstance(self.response, Exception): raise self.response return copy.deepcopy(self.response) class RanchAutomationIntegrationTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.catalog = Catalog() def engine(self, folder, value=None): client = FakeClient(value or raw(self.catalog)) engine = Engine(self.catalog, client, folder / "budget.json") engine.master_sync.settle = lambda *args: None engine.settle_pending_growth = lambda *args, **kwargs: False return engine, client def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self): with workspace_temp() as folder: engine, client = self.engine(folder) engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True engine.poll() self.assertEqual([path for path, _ in client.calls], [POTENTIAL_PATH]) self.assertEqual(client.calls[0][1]["itemId"], 600) self.assertIsNotNone(engine._breakthrough_pending) # An acknowledged response with an unchanged snapshot cannot repeat. engine.poll() self.assertEqual(len(client.calls), 1) client.value["monsters"][0]["pAtk"] += 1 client.value["monsters"][0]["pDef"] -= 1 engine.auto = True engine.poll() self.assertEqual(len(client.calls), 2) restored, _ = self.engine(folder, client.value) self.assertEqual(restored._breakthrough_pending["role_id"], "1") self.assertTrue(restored._breakthrough_pending["uncertain"]) def test_stop_during_snapshot_and_pending_block_every_new_write(self): with workspace_temp() as folder: engine, client = self.engine(folder) engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True read = client.snapshot def stopped(): engine.auto = False return read() client.snapshot = stopped engine.poll() self.assertEqual(client.calls, []) engine, client = self.engine(folder) engine._breakthrough_pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "待核对"} engine.policy = Policy(enabled=True, dispatch=True, egg_rules={"1001010": {"enabled": True, "action": "sell"}}) engine.auto = True _, plans, _ = engine.poll() self.assertEqual((client.calls, plans), ([], [])) def test_pre_dispatch_persistence_failure_never_sends(self): with workspace_temp() as folder: engine, client = self.engine(folder) engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True engine.automation_state_path = folder / "missing" / "state.json" original = engine._save_automation_state def fail(): original() raise OSError("synthetic disk failure") engine._save_automation_state = fail with self.assertRaises(OSError): engine.poll() self.assertEqual(client.calls, []) self.assertFalse(engine.auto) def test_locked_exploration_is_diagnostic_and_does_not_block_ranch(self): with workspace_temp() as folder: engine, client = self.engine(folder) client.value["history"]["passTask"] = {} client.value["monsters"].append({"id": 101, "typeId": 1001010, "process": 3, "mode": 2, "level": 1}) for stat in ("atk", "def", "hp", "dex"): client.value["monsters"][-1]["g" + stat.capitalize()] = self.catalog.monster(1001010)[stat + "_grow_min"] engine.policy = Policy(enabled=True, dispatch=True, fill=False, collect=False, egg_rules={"1001010": {"enabled": True, "action": "sell", "keep_count": 0}}) engine.planner.managed.add(101) engine.explore_policy = ExplorePolicy(True) engine.auto = True _, plans, _ = engine.poll() self.assertEqual([path for path, _ in client.calls], ["monsterService/monsterSell"]) self.assertTrue(any(action.kind == "explore_blocked" and "探险功能尚未解锁" in action.description for action in plans)) self.assertFalse(any(action.kind == "explore_start" for action in plans)) def test_unknown_result_survives_restart_and_owner_mismatch_cannot_confirm(self): with workspace_temp() as folder: engine, client = self.engine(folder) engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True client.response = TimeoutError("synthetic lost reply") with self.assertRaises(TimeoutError): engine.poll() other = copy.deepcopy(client.value) other["master"]["id"] = 2 other["monsters"][0]["pAtk"] += 1 restored, other_client = self.engine(folder, other) restored.policy = Policy(breakthrough_targets={"900": 1}) restored.auto = True restored.poll() self.assertEqual(other_client.calls, []) self.assertEqual(restored._breakthrough_pending["role_id"], "1") def test_stop_after_durable_prepare_before_dispatch_rolls_back_without_write(self): with workspace_temp() as folder: for explore in (False, True): engine, client = self.engine(folder) if explore: engine.explore_policy = ExplorePolicy(True, {"77": {"enabled": True, "area": "1", "monsters": []}}) area = engine.explore_planner.areas["1"] client.value["history"]["passStage"] = {area["passStage"]: {"1": True}} client.value["monsters"][0]["level"] = 60 else: engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True save = engine._save_automation_state def stop_after_save(): save() engine.cancel_progression() engine._save_automation_state = stop_after_save engine.poll() self.assertEqual(client.calls, []) self.assertIsNone(engine._breakthrough_pending) self.assertIsNone(engine.explore_planner.pending(engine.snapshot)) def test_corrupt_state_preserves_barrier_and_file(self): with workspace_temp() as folder: path = folder / "automation_state.json" path.write_text('{"version":0,"breakthrough":{}}', encoding="utf-8") engine, client = self.engine(folder) engine.policy = Policy(breakthrough_targets={"900": 1}) engine.auto = True engine.poll() self.assertEqual(client.calls, []) self.assertEqual(path.read_text(encoding="utf-8"), '{"version":0,"breakthrough":{}}') def test_explore_executes_then_reconciles_and_pending_is_not_rolled_back(self): with workspace_temp() as folder: engine, client = self.engine(folder) engine.explore_policy = ExplorePolicy(True, {"77": {"enabled": True, "area": "1", "monsters": []}}, 0) engine.auto = True area = next(row for row in engine.explore_planner.areas.values() if row["id"] == "1") client.value["history"]["passStage"] = {area["passStage"]: {"1": True}} client.value["monsters"][0]["level"] = 60 engine.poll() self.assertEqual([call[0] for call in client.calls], ["exploreService/start"]) self.assertIsNotNone(engine.explore_planner.pending(engine.snapshot)) engine.poll() self.assertEqual(len(client.calls), 1) action = engine.explore_planner.pending(engine.snapshot) team = client.value["exploreTeams"][0] team.update(status=1, area="1", monsters=action["payload"]["monsters"], endTime=9999999999999) engine.poll() self.assertIsNone(engine.explore_planner.pending(engine.snapshot)) self.assertEqual(json.loads((folder / "automation_state.json").read_text(encoding="utf-8"))["version"], 1) if __name__ == "__main__": unittest.main()