"""Offline regressions for exploring teams and isolated fast schedulers.""" from copy import deepcopy from types import SimpleNamespace import unittest from unittest.mock import Mock from ranch_assistant.battles import BattleOrchestrator from ranch_assistant.engine import Engine from ranch_assistant.exploration import ExplorePolicy from ranch_assistant.game_data import ProgressionData from ranch_assistant.maps import stages from ranch_assistant.model import Action, Catalog, Policy, Snapshot from ranch_assistant.sweeping import SweepPolicy, SweepRunner from ranch_assistant.team_availability import team_availability_reason from ranch_assistant.tests.test_activities import scenario from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime from ranch_assistant.tests.test_gift_timing import GIFT, GiftClient, gift_policy from ranch_assistant.tests.test_hatch_timing import HatchClient, policy_for as hatch_policy from ranch_assistant.tests.test_ranch_automation_integration import FakeClient as AutomationClient from ranch_assistant.tests.test_ranch_automation_integration import raw as automation_raw from ranch_assistant.tests.test_core import workspace_temp COMBAT_WRITES = {"stageService/stageStart", "battleService/battleStart", "battleService/battleEnd", "taskService/taskCompleteStep"} class BusyTeamTests(unittest.TestCase): def setUp(self): self.folder = self.enterContext(workspace_temp()) self.catalog, snapshot = scenario() self.raw = deepcopy(snapshot.raw) self.raw["currentTasks"] = [] self.raw["teams"][0]["monsters"] = [900, 901, 902] for mid in (901, 902): member = deepcopy(self.raw["monsters"][0]) member["id"] = mid self.raw["monsters"].append(member) self.snapshot = Snapshot(deepcopy(self.raw)) self.client = Mock() self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw)) self.client.call.side_effect = lambda path, payload: ( {"resCode": 0, "triggerEvent": False} if path.endswith("stageStart") else {"resCode": 0, "reward": {}}) self.runtime = ExperimentalRuntime() def occupy(self, count, *, active=False): self.raw = deepcopy(self.snapshot.raw) selected = {int(mid) for mid in self.raw["teams"][0]["monsters"][:count]} for member in (mon for mon in self.raw["monsters"] if int(mon["id"]) in selected): if active: member.pop("inExploreTeam", None) else: member["inExploreTeam"] = 1 if active: self.raw["exploreTeams"] = [{"id": 77, "status": 1, "area": "1", "monsters": ",".join(str(mid) for mid in (900, 901, 902)[:count]), "endTime": 9999999999999}] self.snapshot = Snapshot(deepcopy(self.raw)) def map_engine(self, *, cleared): self.raw["history"]["passStage"]["0102"] = ["1", "2", "3"] if cleared else [] info = deepcopy(self.catalog.data["stage_info"]) for row in info.values(): for level in row["level"].values(): level["battle"] = {"fixture": True} data = ProgressionData({"task_info": {}, "stage_info": info, "game_setting": self.catalog.data["game_setting"]}) engine = Engine(self.catalog, self.client, self.folder / "purchase.json", game_data=data, experimental_runtime=self.runtime) engine.policy = Policy(enabled=False, keep_money=0) engine.sweep_policy = SweepPolicy(True, {"0102": {"enabled": True, "level": "1", "limit": 3}}) engine.master_sync.settle = Mock() engine.auto = True return engine def assert_no_combat_writes(self): paths = [call.args[0] for call in self.client.call.call_args_list] self.assertFalse(COMBAT_WRITES.intersection(paths), paths) self.runtime.run.assert_not_called() def test_shared_reason_is_pure_and_rejects_the_whole_selected_team(self): for active in (False, True): for count, expected in ((0, ""), (1, "1/3"), (3, "3/3")): with self.subTest(active=active, count=count): self.setUp() self.occupy(count, active=active) before = deepcopy(self.raw) reason = team_availability_reason(self.snapshot, "teamA") if expected: self.assertIn("探险", reason) self.assertIn(expected, reason) self.assertIn("整队", reason) else: self.assertEqual(reason, "") self.assertEqual(self.raw, before) self.assertEqual(team_availability_reason(self.snapshot, "missing"), "未找到所选战队") def test_all_sweep_kinds_reject_any_exploring_member_before_writes(self): for cleared in (True, False): for active in (False, True): for count in (1, 3): with self.subTest(cleared=cleared, active=active, count=count): self.setUp() self.occupy(count, active=active) engine = self.map_engine(cleared=cleared) engine.poll() stage = next(stage for stage in stages(self.catalog, engine.snapshot) if stage.stage_id == "0102" and stage.level == "1") reason = engine.map_stage_reason(engine.snapshot, stage, engine.sweep_policy) self.assertIn("探险", reason) self.assertIn("整队", reason) self.assert_no_combat_writes() def test_direct_sweep_rechecks_occupancy_instead_of_filtering_members(self): self.occupy(1, active=True) runner = SweepRunner(self.catalog) policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}) stage = next(stage for stage in stages(self.catalog, self.snapshot) if stage.stage_id == "0101" and stage.level == "3") with self.assertRaisesRegex(ValueError, "探险.*整队"): runner.run(self.client, self.snapshot, stage, policy) self.assert_no_combat_writes() self.assertEqual(runner.used(self.snapshot, stage), 0) def test_task_and_ordinary_battles_reject_either_occupancy_marker(self): for active in (False, True): for task in (False, True): with self.subTest(active=active, task=task): self.setUp() self.occupy(2, active=active) runner = BattleOrchestrator(self.catalog, runtime=self.runtime) intent = {"kind": "progression_battle", "task_id": 5 if task else 0, "task_type_id": "100" if task else "", "step_number": 1, "stage_id": "0101", "difficulty": "1", "battle_kind": "battle" if task else "ordinary_stage"} if task: self.snapshot.raw["currentTasks"] = [{"id": 5, "typeId": "100", "curStep": 1}] message = runner.run(self.client, self.snapshot, intent, SimpleNamespace( enabled=True, team="teamA", stop_after_loss=0, reserve_ti=0, allow_items=True, item_reserves={}, max_money=100000, battle_mode="experimental")) self.assertIn("探险", message) self.assertIn("整队", message) self.assert_no_combat_writes() def test_disabling_sweep_invalidates_old_rules_without_touching_pending_barrier(self): stage = next(stage for stage in stages(self.catalog, self.snapshot) if stage.stage_id == "0101" and stage.level == "3") runner = SweepRunner(self.catalog) runner.state["pending"] = {"stage": "0101", "level": "3", "phase": "扫荡结算待确认"} pending = deepcopy(runner.state["pending"]) policy = SweepPolicy(False, {"0101": {"enabled": True, "level": "3", "limit": 3}}) self.assertIn("关闭", runner.reason(self.snapshot, stage, policy)) self.assertIsNone(runner.next(self.snapshot, policy)) with self.assertRaisesRegex(ValueError, "关闭"): runner.run(self.client, self.snapshot, stage, policy) self.assertEqual(runner.state["pending"], pending) self.client.call.assert_not_called() class FastSchedulingTests(unittest.TestCase): def setUp(self): self.folder = self.enterContext(workspace_temp()) def automation_engine(self): catalog = Catalog() client = AutomationClient(automation_raw(catalog)) engine = Engine(catalog, client, self.folder / "purchase.json") engine.master_sync.settle = Mock() engine.settle_pending_growth = Mock(return_value=False) engine.auto = True return engine, client def test_hatch_only_cannot_execute_a_commission(self): client = HatchClient(Catalog()) engine = Engine(client=client, catalog=Catalog()) engine.policy = hatch_policy(client) engine.auto = True hatch_actions = engine.hatch_planner.hatch_actions engine.hatch_planner.hatch_actions = Mock(return_value=[]) engine.tasks.plan = Mock(return_value=[Action("quest_test", "不应执行委托", "taskService/acceptTask", {"taskId": 1})]) engine.poll(hatch_only=True) self.assertEqual(client.calls, []) engine.hatch_planner.hatch_actions = hatch_actions engine.tasks.plan = Mock(return_value=[]) engine.poll(hatch_only=True) self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"]) def test_hatch_fast_kind_retains_existing_hatch_behavior(self): catalog = Catalog() client = HatchClient(catalog) engine = Engine(catalog, client) engine.policy = hatch_policy(client) engine.auto = True engine.poll_automation("hatch") self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"]) def test_fast_kinds_execute_only_their_own_action(self): for kind in ("explore", "breakthrough"): with self.subTest(kind=kind): self.setUp() engine, client = self.automation_engine() if kind == "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(fill=False, collect=False, dispatch=False, feed=False, breakthrough_targets={"900": 1}) engine.poll_automation(kind) expected = "exploreService/start" if kind == "explore" else "monsterService/monsterPotentialUpgrade" self.assertEqual([path for path, _ in client.calls], [expected]) def test_fast_kind_ignores_another_due_kind_and_all_other_strategies(self): engine, client = self.automation_engine() 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 engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False, breakthrough_targets={"900": 1}) other = Action("progression", "不应执行", "taskService/navigate", {"intent": {}}) engine._execute_legacy_task = Mock() original_plans = engine.plans engine.plans = Mock(side_effect=lambda: [other] + original_plans()) _, _, message = engine.poll_automation("breakthrough") self.assertEqual([path for path, _ in client.calls], ["monsterService/monsterPotentialUpgrade"]) engine._execute_legacy_task.assert_not_called() client.calls.clear() client.value["monsters"][0]["pAtk"] += 1 _, _, message = engine.poll_automation("gift") self.assertEqual(client.calls, []) self.assertIn("赠礼", message) def test_gift_fast_path_does_not_run_progression_or_maps(self): catalog = Catalog() client = GiftClient(catalog) engine = Engine(catalog, client) engine.policy = gift_policy() engine.auto = True forbidden = Action("progression", "不应执行", "taskService/navigate", {"intent": {}}) original_plans = engine.plans engine.plans = Mock(side_effect=lambda: [forbidden] + original_plans()) engine._execute_legacy_task = Mock() snapshot, _, _ = engine.poll_automation("gift") self.assertEqual([path for path, _ in client.calls], [GIFT]) self.assertEqual(snapshot.monsters[1]["feel"], 10) engine._execute_legacy_task.assert_not_called() def test_fast_path_respects_stop_and_cross_kind_pending_barriers(self): for kind in ("explore", "breakthrough", "gift"): with self.subTest(kind=kind, stopped=True): engine, client = self.automation_engine() engine.auto = False engine.poll_automation(kind) self.assertEqual(client.calls, []) with self.subTest(kind=kind, pending=True): engine, client = self.automation_engine() engine._breakthrough_pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "待核对"} _, plans, _ = engine.poll_automation(kind) self.assertEqual((client.calls, plans), ([], [])) def test_unknown_fast_kind_is_rejected(self): engine, _ = self.automation_engine() with self.assertRaises(ValueError): engine.poll_automation("progression") if __name__ == "__main__": unittest.main()