"""Offline integration: only the current primary may receive automatic resources.""" from copy import deepcopy from dataclasses import asdict, replace import json from pathlib import Path from tempfile import TemporaryDirectory import time import unittest from unittest.mock import patch from ranch_assistant.breakthrough import PATH, POTENTIAL_PATH from ranch_assistant.engine import Engine from ranch_assistant.model import Action, Catalog, Policy, Snapshot from ranch_web.policies import default_config, export_config from ranch_web.views import build_view, schema SPECIES = 1001010 MAIN, BACKUP, EXTRA = 900, 901, 902 FEED = "monsterService/monsterIntensify" GIFT = "monsterService/monsterSendGift" RECIPIENT_KEYS = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"} def monster(catalog, mid, *, level=1, quality=0, **values): species = values.get("typeId", SPECIES) info = catalog.monster(species) mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level, "potentialLevel": 1, "pAtk": 3, "pDef": 8, "pHp": 105, "pDex": 1, "feel": 0, "giftTime": 0, "exp": 0, "tpLevel": 0, "tpExp": 0, "roomId": 1, "lock": 0} for stat in ("atk", "def", "hp", "dex"): low, high = info[stat + "_grow_min"], info[stat + "_grow_max"] mon["g" + stat.capitalize()] = low + quality * (high - low) return mon | values class OfflineClient: """In-memory server with a recorded write/read boundary; never opens a socket.""" def __init__(self, catalog, *, complete=False): self.raw = {"master": {"id": 1, "level": 30, "ti": 100, "money": 0, "ke": 0}, "monsters": [monster(catalog, MAIN, level=9, lock=1, pAtk=4 if complete else 3), monster(catalog, BACKUP, quality=1), monster(catalog, EXTRA, level=2)], "items": [{"id": 600, "typeId": 30058, "num": 100}, {"id": 601, "typeId": 30005, "num": 10}], "rooms": [{"id": 1, "typeId": 1000}], "teams": [], "stacks": [], "currentTasks": [], "history": {}, "activityHistory": {}, "exploreTeams": []} self.calls, self.events = [], [] self.apply_writes = True def snapshot(self): self.events.append("snapshot") return Snapshot(deepcopy(self.raw)) def call(self, path, payload): self.calls.append((path, deepcopy(payload))) self.events.append(path) if not self.apply_writes: return {"resCode": 0} monsters = {int(mon["id"]): mon for mon in self.raw["monsters"]} if path == POTENTIAL_PATH: mon = monsters[payload["monId"]] mon["p" + payload["monsterAttr"].capitalize()] += 1 elif path == PATH: monsters[payload["monId"]]["potentialLevel"] += 1 elif path == GIFT: mon = monsters[payload["monsterId"]] mon.update(feel=mon["feel"] + 10, giftTime=int(time.time()) * 1000) return {"feel": mon["feel"], "giftDate": mon["giftTime"], "resCode": 0} elif path in (FEED, "monsterService/monsterSell"): consumed = set(payload["foods"] if path == FEED else payload["monsterIds"]) self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in consumed] else: raise AssertionError("Unexpected offline write: " + path) return {"resCode": 0} class PrimaryResourceAdmissionTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.catalog = Catalog() def engine(self, *, complete=False): temporary = TemporaryDirectory(prefix="primary-admission-") self.addCleanup(temporary.cleanup) client = OfflineClient(self.catalog, complete=complete) engine = Engine(self.catalog, client, Path(temporary.name) / "budget.json") engine.master_sync.settle = lambda *args: None engine.settle_pending_growth = lambda *args, **kwargs: False engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False, manual_eggs=True, protect_star=6, protect_quality=5, keep_better_quality=False, gift_auto_representative=False, egg_rules={str(SPECIES): {"enabled": True, "action": "feed", "keep_count": 0}}) engine.snapshot = client.snapshot() engine.auto = True return engine, client def action(self, kind, recipient): payload = {RECIPIENT_KEYS[kind]: recipient} if kind == "feed": payload["foods"] = [EXTRA] elif kind == "gift": payload["itemId"] = 601 elif kind == "potential": payload.update(itemId=600, monsterAttr="atk", traceInfo={"itemTypeId": 600, "itemNum": 100}) else: payload["itemIds"] = [600] return Action(kind, "offline " + kind, {"feed": FEED, "gift": GIFT, "potential": POTENTIAL_PATH, "breakthrough": PATH}[kind], payload) def config(self, engine): config = default_config() config["policy"] = asdict(engine.policy) return config def test_stale_breakthrough_targets_never_spend_or_enable_the_unchecked_primary(self): for complete in (False, True): for fast in (False, True): with self.subTest(complete=complete, fast=fast): engine, client = self.engine(complete=complete) engine.policy.breakthrough_targets = {str(BACKUP): 1} before = asdict(engine.policy) _, plans, message = engine.poll_automation("breakthrough") if fast else engine.poll() self.assertEqual(client.calls, []) self.assertFalse(any(action.kind in ("potential", "breakthrough") for action in plans)) self.assertIn("非主培养", message) self.assertIn("#900", message) self.assertEqual(asdict(engine.policy), before) self.assertIsNone(engine._breakthrough_pending) self.assertFalse(engine.last_executed) def test_stale_priority_cannot_bypass_primary_admission_on_either_scheduler(self): for complete in (False, True): for fast in (False, True): with self.subTest(complete=complete, fast=fast): engine, client = self.engine(complete=complete) engine.policy.breakthrough_targets = {str(BACKUP): 1, str(MAIN): 2} before = asdict(engine.policy) engine.poll_automation("breakthrough") if fast else engine.poll() self.assertEqual(client.calls, [(PATH if complete else POTENTIAL_PATH, {"monId": MAIN, "itemIds": [600]} if complete else {"monId": MAIN, "itemId": 600, "monsterAttr": "atk", "traceInfo": {"itemTypeId": 600, "itemNum": 100}})]) self.assertEqual(client.events[-1], "snapshot") self.assertIsNone(engine._breakthrough_pending) self.assertEqual(asdict(engine.policy), before) def test_engine_filters_stale_actions_even_if_a_source_planner_returns_them(self): for kind in RECIPIENT_KEYS: with self.subTest(kind=kind): engine, client = self.engine() source = engine.planner if kind == "feed" else engine.gift_planner if kind == "gift" else engine.breakthrough_planner stale = self.action(kind, BACKUP) if kind in ("potential", "breakthrough"): engine.policy.breakthrough_targets = {str(BACKUP): 1} with patch.object(source, "plan", return_value=stale if kind in ("potential", "breakthrough") else [stale]): _, plans, message = engine.poll() self.assertFalse(any(action.kind == kind for action in plans)) self.assertEqual(client.calls, []) self.assertIn("非主培养", message) def test_current_recipient_is_checked_after_planning_on_both_dispatch_paths(self): for kind in RECIPIENT_KEYS: for fast in (False, True): if fast and kind == "feed": continue with self.subTest(kind=kind, fast=fast): engine, client = self.engine() engine.cultivation.select(engine.snapshot) action = self.action(kind, MAIN) def stale_plan(): # A newer roster makes the queued recipient a duplicate. engine.snapshot.monsters[BACKUP]["level"] = 30 return [action] with patch.object(engine, "plans", side_effect=stale_plan): _, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll() self.assertEqual(client.calls, []) self.assertIn("非主培养", message) self.assertFalse(engine.last_executed) self.assertIsNone(engine._breakthrough_pending) self.assertEqual(engine.gift_planner.confirmed, {}) def test_busy_primary_blocks_real_resource_plans_without_falling_back(self): for busy in ("team_list", "team_string", "inExploreTeam", "inBuild", "sysLock"): for complete in (False, True): for scheduler in ("poll", "gift", "breakthrough"): with self.subTest(busy=busy, complete=complete, scheduler=scheduler): engine, client = self.engine(complete=complete) client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5, lock=1, pAtk=4 if complete else 3) client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125) if busy.startswith("team_"): # Authoritative team membership can arrive without the per-monster marker. client.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": [MAIN] if busy == "team_list" else str(MAIN)}] else: client.raw["monsters"][0][busy] = 1 targets = {str(MAIN): 1, str(BACKUP): 2} engine.policy = replace(engine.policy, feed=True, feed_targets=targets, gift_enabled=True, gift_targets=targets, gift_liked_only=False, gift_items={"30005": {"enabled": True, "reserve": 0}}, breakthrough_targets=targets) engine.planner.managed.add(EXTRA) before = asdict(engine.policy) _, plans, _ = engine.poll() if scheduler == "poll" else engine.poll_automation(scheduler) self.assertEqual(client.calls, []) self.assertFalse(any(action.kind in RECIPIENT_KEYS for action in plans)) self.assertEqual(engine.cultivation.select(engine.snapshot)[str(SPECIES)]["id"], MAIN) self.assertEqual(asdict(engine.policy), before) self.assertIsNone(engine._breakthrough_pending) def test_exploration_becoming_active_after_planning_blocks_queued_resources(self): for kind in RECIPIENT_KEYS: for fast in (False, True): if fast and kind == "feed": continue with self.subTest(kind=kind, fast=fast): engine, client = self.engine() action = self.action(kind, MAIN) def busy_plan(): engine.snapshot.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}] return [action] with patch.object(engine, "plans", side_effect=busy_plan): _, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll() self.assertEqual(client.calls, []) self.assertIn("正在探险", message) self.assertFalse(engine.last_executed) self.assertIsNone(engine._breakthrough_pending) def test_material_recipient_is_rechecked_after_unsent_intent_is_persisted(self): engine, client = self.engine() action = self.action("potential", MAIN) save = engine._save_automation_state def newer_roster_after_save(): save() engine.snapshot.monsters[BACKUP]["level"] = 30 with patch.object(engine, "_save_automation_state", side_effect=newer_roster_after_save): _, _, message = engine._execute_breakthrough(action) self.assertEqual(client.calls, []) self.assertIn("非主培养", message) self.assertIsNone(engine._breakthrough_pending) self.assertIsNone(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"]) self.assertFalse(engine.last_executed) def test_existing_pending_evidence_survives_loss_of_primary_and_restart(self): for complete in (False, True): with self.subTest(complete=complete): engine, client = self.engine(complete=complete) client.apply_writes = False engine.policy.breakthrough_targets = {str(MAIN): 1} engine.poll_automation("breakthrough") pending = deepcopy(engine._breakthrough_pending) self.assertIsNotNone(pending) client.raw["monsters"][1]["level"] = 30 engine.poll_automation("breakthrough") self.assertEqual(engine._breakthrough_pending, pending) self.assertEqual(len(client.calls), 1) self.assertEqual(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"], pending) restored = Engine(self.catalog, client, engine.automation_state_path.parent / "budget.json") restored.master_sync.settle = lambda *args: None restored.policy, restored.auto = engine.policy, True restored.poll_automation("breakthrough") self.assertEqual(restored._breakthrough_pending["payload"], pending["payload"]) self.assertEqual(len(client.calls), 1) # Confirmation belongs to the original recipient, even now a backup. original = client.raw["monsters"][0] original["potentialLevel" if complete else "pAtk"] += 1 restored.poll_automation("breakthrough") self.assertIsNone(restored._breakthrough_pending) self.assertEqual(len(client.calls), 1) def test_preexisting_pending_record_is_not_discarded_when_rejecting_a_new_target(self): engine, client = self.engine() pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "retain evidence"} engine._breakthrough_pending = deepcopy(pending) engine._save_automation_state() persisted = engine.automation_state_path.read_bytes() engine._execute_breakthrough(self.action("potential", BACKUP)) self.assertEqual(engine._breakthrough_pending, pending) self.assertEqual(engine.automation_state_path.read_bytes(), persisted) self.assertEqual(client.calls, []) def test_actual_gift_dispatch_uses_only_checked_primary_without_enabling_it(self): for fast in (False, True): for include_primary in (False, True): with self.subTest(fast=fast, include_primary=include_primary): engine, client = self.engine() targets = {str(BACKUP): 1} | ({str(MAIN): 2} if include_primary else {}) engine.policy = replace(engine.policy, gift_enabled=True, gift_targets=targets, gift_liked_only=False, gift_items={"30005": {"enabled": True, "reserve": 0}}) before = asdict(engine.policy) _, _, message = engine.poll_automation("gift") if fast else engine.poll() self.assertEqual([payload["monsterId"] for path, payload in client.calls if path == GIFT], [MAIN] if include_primary else []) if not include_primary: self.assertIn("非主培养", message) self.assertEqual(asdict(engine.policy), before) def test_actual_feeding_dispatches_only_the_primary_with_legacy_flags_off(self): for explicit in (False, True): with self.subTest(explicit=explicit): engine, client = self.engine() # Equal-quality extras are dispatched; this case exercises feeding inferior material. client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5, lock=1) client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125) engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True, feed_targets={str(BACKUP): 1, str(MAIN): 2} if explicit else {}) engine.planner.managed.add(EXTRA) before = asdict(engine.policy) engine.poll() self.assertEqual(client.calls, [(FEED, {"targetId": MAIN, "foods": [EXTRA]})]) self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP}) self.assertEqual(client.events[-1], "snapshot") self.assertEqual(asdict(engine.policy), before) def test_full_primary_and_stale_explicit_selection_cannot_feed_a_backup(self): for explicit in (False, True): with self.subTest(explicit=explicit): engine, client = self.engine() engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True, feed_targets={str(BACKUP): 1} if explicit else {}) if not explicit: main = client.raw["monsters"][0] main.update(level=self.catalog.max_level(main), tpLevel=4, tpExp=engine.planner.tp_thresholds(main)[4]) engine.planner.managed.add(EXTRA) before = asdict(engine.policy) engine.poll() self.assertEqual(client.calls, []) self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP, EXTRA}) self.assertEqual(asdict(engine.policy), before) def test_manual_explicit_feed_can_still_target_a_backup(self): engine, client = self.engine() engine.manage_monsters("feed", [EXTRA], BACKUP) self.assertEqual(client.calls, [(FEED, {"targetId": BACKUP, "foods": [EXTRA]})]) self.assertNotIn(EXTRA, engine.snapshot.monsters) self.assertFalse(engine.auto) def test_web_roles_disable_stale_selections_but_preserve_config_and_manual_targets(self): engine, client = self.engine() engine.policy = replace(engine.policy, feed_targets={str(BACKUP): 1}, gift_targets={str(BACKUP): 2}, breakthrough_targets={str(BACKUP): 3}) before = asdict(engine.policy) config = self.config(engine) config_before = deepcopy(config) dto = build_view(engine, "ranch", config) rows = {row["id"]: row for row in dto["rows"]} self.assertEqual([rows[str(mid)]["cultivation_role_key"] for mid in (MAIN, BACKUP, EXTRA)], ["primary", "backup", "duplicate"]) for prefix in ("feed", "gift", "breakthrough"): self.assertTrue(rows[str(BACKUP)][prefix + "_selected"]) self.assertFalse(rows[str(MAIN)][prefix + "_selected"]) for mid in (BACKUP, EXTRA): edit = rows[str(mid)]["edits"][prefix + "_selected"] self.assertTrue(edit["disabled"]) self.assertIn("#900", edit["reason"]) self.assertFalse(rows[str(MAIN)]["edits"][prefix + "_selected"]["disabled"]) self.assertIn(BACKUP, [option["value"] for option in dto["feed_targets"]]) self.assertEqual(asdict(engine.policy), before) self.assertEqual(config, config_before) self.assertEqual(client.calls, []) def test_web_retention_is_fixed_and_legacy_values_round_trip_without_a_toggle(self): for stored in (0, 1, 8): with self.subTest(stored=stored): engine, client = self.engine() engine.policy.egg_rules[str(SPECIES)]["keep_count"] = stored config = self.config(engine) before = deepcopy(config) dto = build_view(engine, "bag", config, {"category": "eggs"}) row = next(row for row in dto["rows"] if row["id"] == str(SPECIES)) column = next(column for column in dto["columns"] if column["key"] == "retention_text") self.assertEqual(row["retention_text"], "主培养1 + 更优备选≤1") self.assertFalse(column.get("edit")) self.assertFalse(any(column["key"] == "keep_count" and column.get("edit") for column in dto["columns"])) fields = [field for page in schema(self.catalog)["pages"] for field in page["form"]] self.assertFalse(any(field["path"] == ["policy", "keep_better_quality"] for field in fields)) self.assertEqual(export_config(config, engine.snapshot)["policy"]["egg_rules"][str(SPECIES)]["keep_count"], stored) self.assertEqual(config, before) self.assertEqual(client.calls, []) def test_busy_primary_keeps_its_web_role_while_automatic_controls_are_disabled(self): engine, client = self.engine() client.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}] engine.snapshot = client.snapshot() engine.policy = replace(engine.policy, feed_targets={str(MAIN): 1}, gift_targets={str(MAIN): 1}, breakthrough_targets={str(MAIN): 1}) rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]} self.assertEqual(rows[MAIN]["cultivation_role_key"], "primary") self.assertEqual(rows[MAIN]["cultivation_role"], "主培养") self.assertEqual(rows[MAIN]["primary_id"], MAIN) self.assertFalse(rows[MAIN]["automatic_eligible"]) self.assertIn("正在探险", rows[MAIN]["automatic_reason"]) self.assertEqual(rows[BACKUP]["cultivation_role_key"], "backup") for prefix in ("feed", "gift", "breakthrough"): self.assertTrue(rows[MAIN][prefix + "_selected"]) self.assertTrue(rows[MAIN]["edits"][prefix + "_selected"]["disabled"]) self.assertEqual(client.calls, []) def test_web_existing_extras_report_protection_and_dispatch_off_without_managed_history(self): engine, client = self.engine() client.raw["monsters"] += [monster(self.catalog, 903, lock=1), monster(self.catalog, 904, equip1=123), monster(self.catalog, 905, typeId=1030010)] engine.snapshot = client.snapshot() self.assertEqual(engine.planner.managed, set()) rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]} self.assertIn("自动派遣", rows[EXTRA]["scope"]) self.assertIn("关闭", rows[EXTRA]["scope"]) self.assertNotIn("已有:不自动处理", rows[EXTRA]["scope"]) self.assertIn("已锁定", rows[903]["scope"]) self.assertIn("携带装备", rows[904]["scope"]) self.assertIn("规则未启用", rows[905]["scope"]) self.assertEqual(client.calls, []) def test_web_uses_the_retention_planners_reserve_when_replacement_is_still_incubating(self): engine, client = self.engine() client.raw["monsters"][1] = monster(self.catalog, BACKUP, quality=.5) client.raw["monsters"].append(monster(self.catalog, 903, quality=1, process=2)) engine.snapshot = client.snapshot() rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]} self.assertEqual(rows[BACKUP]["cultivation_role_key"], "duplicate") self.assertEqual(rows[903]["cultivation_role_key"], "backup") self.assertIn("待收取", rows[903]["cultivation_role"]) self.assertFalse(rows[903]["automatic_eligible"]) self.assertTrue(rows[903]["edits"]["feed_selected"]["disabled"]) self.assertEqual(client.calls, []) def test_same_name_variants_have_independent_primary_admission_and_web_roles(self): engine, client = self.engine() for mid, species in enumerate((1030010, 1030012, 1030013, 1030014), 1000): client.raw["monsters"].append(monster(self.catalog, mid, typeId=species, level=1)) engine.snapshot = client.snapshot() rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]} for mid in range(1000, 1004): self.assertEqual(rows[mid]["cultivation_role_key"], "primary") self.assertTrue(rows[mid]["automatic_eligible"]) self.assertEqual(client.calls, []) if __name__ == "__main__": unittest.main()