import copy import json import time import unittest from unittest.mock import patch 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 def species_monster(catalog, mid, grades, *, level=10, species=1030010, **values): row = catalog.monster(species) mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level, "exp": 0, "potentialLevel": 2, "tpLevel": 4, "tpExp": 9999, "feel": 0, "giftTime": 0, "entangleLevel": 0, "lock": 0, "roomId": 1} for stat, grade in zip(("atk", "def", "hp", "dex"), grades): low, high = row[stat + "_grow_min"], row[stat + "_grow_max"] mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade] return mon | values 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 StatefulRanchClient(FakeClient): def call(self, path, payload): super().call(path, copy.deepcopy(payload)) monsters = {int(mon["id"]): mon for mon in self.value["monsters"]} removed = [] if path == "monsterService/monsterSell": removed = payload["monsterIds"] elif path == "stackService/stackTransferMonster": for data in payload["datas"]: for mid in data["monsterId"]: monsters[mid].update(process=3, roomId=data["roomId"]) for stack in self.value["stacks"]: if stack.get("monsterId") == mid: stack["monsterId"] = 0 elif path == "monsterService/monsterIntensify": removed = payload["foods"] elif path == "monsterService/monsterSendGift": mon = monsters[payload["monsterId"]] mon.update(feel=int(mon.get("feel") or 0) + 1, giftTime=int(time.time() * 1000)) return {"feel": mon["feel"], "giftDate": mon["giftTime"]} elif path == POTENTIAL_PATH: mon = monsters[payload["monId"]] stat = "p" + payload["monsterAttr"].capitalize() mon[stat] += 1 else: raise AssertionError(f"Unexpected offline ranch operation: {path}") self.value["monsters"] = [mon for mon in self.value["monsters"] if mon["id"] not in removed] for stack in self.value["stacks"]: if stack.get("monsterId") in removed: stack["monsterId"] = 0 return {"resCode": 0} class RanchAutomationIntegrationTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.catalog = Catalog() def engine(self, folder, value=None, client_type=FakeClient): client = client_type(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_screenshot_lv20_sass_primary_never_spends_on_four_lesser_duplicates(self): primary = species_monster(self.catalog, 900, "SASS", level=20, pAtk=44, pDef=10, pHp=180, pDex=9) primary["feel"] = self.catalog.max_feel(primary) duplicates = [species_monster(self.catalog, 901 + index, grades, level=9 + index % 2, tpLevel=0, tpExp=0, pAtk=1, pDef=1, pHp=1, pDex=1) for index, grades in enumerate(("SAAA", "ASAS", "AASS", "AAAS"))] duplicate_ids = {mon["id"] for mon in duplicates} cases = [({}, False, {}), ({"900": 1, "901": 2, "902": 3, "903": 4, "904": 5}, False, {}), ({}, True, {}), ({}, False, {"901": 1})] for feed_targets, manual_gifts, potential_targets in cases: with self.subTest(feed_targets=feed_targets, manual_gifts=manual_gifts, potential_targets=potential_targets): with workspace_temp() as folder: value = raw(self.catalog) value.update(monsters=copy.deepcopy([primary, *duplicates]), items=[{"id": 600, "typeId": 30058, "num": 100}, {"id": 601, "typeId": 30005, "num": 10}]) engine, client = self.engine(folder, value, StatefulRanchClient) engine.policy = Policy(enabled=True, dispatch=True, feed=True, manual_eggs=True, fill=False, protect_star=4, protect_quality=5, keep_better_quality=False, egg_rules={"1030010": {"enabled": True, "action": "feed", "keep_count": 1}}, feed_targets=feed_targets, breakthrough_targets=potential_targets, gift_enabled=manual_gifts, gift_auto_representative=not manual_gifts, gift_targets={str(mid): mid for mid in duplicate_ids | {900}}, gift_liked_only=False, gift_items={"30005": {"enabled": True}}) engine.planner.managed.update(duplicate_ids | {900}) engine.auto = True _, plans, _ = engine.poll() for path, payload in client.calls: target = payload.get("targetId", payload.get("monsterId", payload.get("monId"))) self.assertNotIn(target, duplicate_ids, (path, payload)) self.assertNotIn(900, payload.get("foods", []) + payload.get("monsterIds", [])) for action in plans: if action.kind in ("feed", "gift", "potential", "breakthrough"): target = action.payload.get("targetId", action.payload.get("monsterId", action.payload.get("monId"))) self.assertNotIn(target, duplicate_ids, action) self.assertIn(900, engine.snapshot.monsters) def test_existing_enabled_duplicates_cleanup_without_managed_and_preserve_constraints(self): for constraint in (None, "lock", "sysLock", "equip1", "team", "entangle", "inExploreTeam", "inBuild", "unknown_quality", "active_exploration_team", "active_exploration_team_csv", "stale_targets_high_rarity"): with self.subTest(constraint=constraint): with workspace_temp() as folder: value = raw(self.catalog) stale_targets = constraint == "stale_targets_high_rarity" species = next(int(key) for key, row in self.catalog.monsters.items() if row.get("star") == 5 and not row.get("npc") and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex"))) if stale_targets else 1030010 rows = [species_monster(self.catalog, 900, "SASS", level=20, species=species)] rows += [species_monster(self.catalog, mid, "CCCC", species=species) for mid in range(901, 905)] rows += [species_monster(self.catalog, 950 + index, "CCCC", species=species) for index, species in enumerate((1030012, 1030013, 1030014))] value.update(monsters=rows, teams=[]) if constraint == "team": value["teams"] = [{"monsters": [901]}] elif constraint in ("active_exploration_team", "active_exploration_team_csv"): value["exploreTeams"][0].update(status=1, monsters="901" if constraint.endswith("_csv") else [901], endTime=9999999999999) elif constraint == "unknown_quality": rows[1]["gAtk"] = None elif constraint and not stale_targets: rows[1][constraint] = 1 engine, client = self.engine(folder, value, StatefulRanchClient) engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5, keep_better_quality=False, gift_auto_representative=False, egg_rules={str(species): {"enabled": True, "action": "sell", "keep_count": 0}}, feed_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {}, gift_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {}, breakthrough_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {}) self.assertEqual(engine.planner.managed, set()) engine.auto = True for _ in range(5): engine.poll() expected = {900, 950, 951, 952} | ({901} if constraint and not stale_targets else set()) self.assertEqual(set(engine.snapshot.monsters), expected) self.assertTrue(client.calls) self.assertTrue(all(path == "monsterService/monsterSell" for path, _ in client.calls)) if constraint and not stale_targets: self.assertTrue(engine.planner.statuses.get(901)) if constraint == "lock": self.assertEqual(engine.snapshot.monsters[901]["lock"], 1) if constraint in ("active_exploration_team", "active_exploration_team_csv"): client.value["exploreTeams"][0]["status"] = 0 engine.poll() self.assertEqual(set(engine.snapshot.monsters), {900, 950, 951, 952}) self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [901]})) def test_successive_quality_backups_replace_before_collect_and_new_mature_ties_dispatch(self): with workspace_temp() as folder: value = raw(self.catalog) room_type = next(key for key, row in self.catalog.data["room_info"].items() if row.get("maxNum", 0) >= 2) value.update(monsters=[species_monster(self.catalog, 900, "SASS", level=20, lock=1), species_monster(self.catalog, 901, "SSSA"), species_monster(self.catalog, 902, "SSSS", level=1, process=2, roomId=None)], rooms=[{"id": 1, "typeId": int(room_type)}], stacks=[{"id": 1, "position": 0, "monsterId": 902}]) row = self.catalog.monster(1030010) for stat, scale in zip(("atk", "def", "hp", "dex"), (.95, .95, .95, .7)): value["monsters"][1]["g" + stat.capitalize()] = row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"]) engine, client = self.engine(folder, value, StatefulRanchClient) engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5, keep_better_quality=False, gift_auto_representative=False, egg_rules={"1030010": {"enabled": True, "action": "sell", "keep_count": 4}}) engine.auto = True with patch.dict(self.catalog.data["room_info"][room_type], {"maxNum": 2}): engine.poll() self.assertEqual(client.calls, [("monsterService/monsterSell", {"monsterIds": [901]})]) engine.poll() self.assertEqual(client.calls[-1], ("stackService/stackTransferMonster", {"datas": [{"monsterId": [902], "roomId": 1}]})) self.assertEqual(set(engine.snapshot.monsters), {900, 902}) client.value["monsters"].insert(0, species_monster(self.catalog, 903, "SSSS", level=1, process=2, roomId=None)) client.value["stacks"][0]["monsterId"] = 903 engine.poll() self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [903]})) self.assertEqual(set(engine.snapshot.monsters), {900, 902}) engine.poll() self.assertEqual(len(client.calls), 3) 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()