Fix fast automation routing and blocked quest navigation loops

Isolate hatch, gift, exploration and breakthrough timers; cancel queued automation after settings change. Check battle readiness before local quest navigation and reject exploring teams or disabled sweeps before entry.
This commit is contained in:
AttilaNet
2026-11-09 12:14:47 +08:00
parent 9f819d828a
commit eaaad3488b
9 changed files with 931 additions and 37 deletions
@@ -0,0 +1,315 @@
"""Fast GUI timers must not dispatch unrelated account automation."""
import os
import threading
import time
import unittest
from types import SimpleNamespace
from unittest.mock import Mock
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant import gui
from ranch_assistant.model import Action
from ranch_assistant.tests.test_core import workspace_temp
class FakeAutomationEngine:
"""A plan-first-mainline fake which records the Engine dispatch seam."""
def __init__(self, snapshot, actions):
self.snapshot = snapshot
self.actions = actions
self.calls = []
self.pending_hatches = []
self.gift_planner = SimpleNamespace(next_ready_at=None)
self.demo = False
self.auto = True
self.heartbeat_enabled = False
self.last_heartbeat = time.monotonic()
def __getattr__(self, name):
# Window still uses the real offline Engine for rendering and policy state.
return getattr(self.offline, name)
def poll(self, **kwargs):
self.calls.append(("poll", kwargs))
return self.snapshot, self.actions, "unfiltered poll"
def poll_automation(self, kind):
self.calls.append(("poll_automation", kind))
return self.snapshot, self.actions, f"isolated {kind}"
def pending_recovery_due(self):
return False
def master_sync_due(self):
return False
def growth_sync_due(self):
return False
class AutomationSchedulingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.window = gui.Window(self.folder)
self.window.timer.stop()
self.window.auto_save_timer.stop()
self.wait()
def tearDown(self):
self.window.stop_workflow()
self.window.pool.clear()
self.window.pool.waitForDone(3000)
self.window.close()
self.app.processEvents()
def wait(self, predicate=lambda: True, timeout=5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
self.app.processEvents()
QTest.qWait(2)
if not self.window.busy and predicate():
return
self.fail("Real Window/fake Engine Qt scheduling did not settle")
def action(self, kind):
return Action(kind=kind, description=kind, path="synthetic/" + kind, payload={})
def install_engine(self, *kinds):
actions = [self.action("progression"), self.action("map_challenge"), self.action("sweep")]
actions.extend(self.action(kind) for kind in kinds)
offline = self.window.engine
engine = FakeAutomationEngine(offline.snapshot, actions)
engine.offline = offline
engine.demo = True
self.window.engine = engine
self.window.latest_render = (engine.snapshot, actions)
self.window.monitoring = True
self.window.set_strategy_checked(True)
self.window.next_poll = float("inf")
return engine
def install_engine_policy(self):
self.window.engine.policy = self.window.read_policy()
self.window.apply_explore_policy(self.window.read_explore_policy())
def drain(self):
"""Let already queued real Jobs start after a stop request."""
self.window.pool.waitForDone(3000)
self.wait()
def test_real_window_expired_extended_timer_never_uses_full_poll(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.window.arm_extended_automation()
self.window.next_explore = time.monotonic() - 1
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "explore")])
def test_each_due_extended_kind_is_dispatched_separately(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
self.window.arm_extended_automation()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
self.window.run_extended_automation()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "explore")])
self.wait()
self.window.next_breakthrough = time.monotonic() - 1
self.window.run_extended_automation()
self.wait(lambda: len(engine.calls) >= 2)
self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"])
def test_fast_hatch_and_gift_dispatch_only_their_own_kind(self):
for kind in ("hatch", "gift"):
with self.subTest(kind=kind):
engine = self.install_engine()
if kind == "hatch":
engine.pending_hatches = [self.action("hatch")]
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
else:
self.window.gift_enabled.setChecked(True)
setattr(self.window, "next_" + kind, time.monotonic() - 1)
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", kind)])
self.wait()
def test_disabling_explore_cancels_unsent_queue_before_worker_entry(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.window.next_explore = time.monotonic() - 1
release = threading.Event()
blocker = threading.Event()
def held_job():
blocker.set()
if not release.wait(4):
raise TimeoutError("test blocker was not released")
return "held"
queued = []
original_start = self.window.pool.start
def hold_next(runnable):
queued.append(runnable)
try:
self.install_engine_policy()
self.window.submit("fixture_blocker", held_job)
self.assertTrue(blocker.wait(1))
self.window.pool.start = hold_next
self.window.schedule()
self.assertTrue(self.window.busy)
self.window.explore_enabled.setChecked(False)
self.window.persist_settings()
self.assertEqual(self.window.next_explore, float("inf"))
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
release.set()
self.drain()
self.assertNotIn(("poll_automation", "explore"), engine.calls)
self.assertFalse(self.window.busy)
def test_stop_cancels_every_fast_deadline_and_queued_worker(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
self.window.gift_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
engine.pending_hatches = [self.action("hatch")]
self.install_engine_policy()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
self.window.next_hatch = self.window.next_gift = time.monotonic() - 1
queued = []
original_start = self.window.pool.start
self.window.pool.start = queued.append
try:
self.window.schedule()
self.window.stop_workflow()
self.assertTrue(all(getattr(self.window, "next_" + kind) == float("inf")
for kind in ("explore", "breakthrough", "hatch", "gift")))
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
self.drain()
self.assertEqual(engine.calls, [])
self.assertFalse(self.window.busy)
def test_completed_kind_does_not_postpone_other_due_extended_kind(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
self.window.arm_extended_automation()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
due_breakthrough = self.window.next_breakthrough
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(self.window.next_breakthrough, due_breakthrough)
self.window.schedule()
self.wait(lambda: len(engine.calls) == 2)
self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"])
def test_gift_completion_preserves_due_hatch_and_gift_is_not_starved(self):
engine = self.install_engine()
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
self.window.gift_enabled.setChecked(True)
engine.pending_hatches = [self.action("hatch")]
self.window.arm_hatching()
self.window.arm_gifting()
self.window.next_hatch = self.window.next_gift = time.monotonic() - 1
due_hatch = self.window.next_hatch
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "hatch")])
engine.gift_planner.next_ready_at = engine.snapshot.now
self.window.arm_gifting()
self.window.next_gift = time.monotonic() - 1
self.window.schedule()
self.wait(lambda: len(engine.calls) == 2)
self.assertEqual(engine.calls[-1], ("poll_automation", "gift"))
self.assertGreaterEqual(self.window.next_hatch, due_hatch)
def test_closing_map_cancels_queued_automatic_poll_before_engine_entry(self):
engine = self.install_engine()
self.window.map_enabled.setChecked(True)
self.install_engine_policy()
self.window.next_poll = time.monotonic() - 1
queued = []
original_start = self.window.pool.start
self.window.pool.start = queued.append
try:
self.window.schedule()
self.assertTrue(self.window.busy)
self.window.map_enabled.setChecked(False)
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
self.drain()
self.assertEqual(engine.calls, [])
self.assertFalse(self.window.map_enabled.isChecked())
def test_disabling_while_busy_applies_before_next_fast_dispatch(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.install_engine_policy()
release = threading.Event()
entered = threading.Event()
def held_automation(kind):
engine.calls.append(("poll_automation", kind))
entered.set()
if not release.wait(4):
raise TimeoutError("test automation was not released")
return engine.snapshot, [], "held automation"
engine.poll_automation = held_automation
self.window.next_explore = time.monotonic() - 1
self.window.schedule()
self.assertTrue(entered.wait(1))
self.window.explore_enabled.setChecked(False)
self.window.persist_settings()
self.assertIsNotNone(self.window.pending_policy)
self.assertEqual(self.window.next_explore, float("inf"))
release.set()
self.drain()
self.window.schedule()
self.drain()
self.assertEqual(engine.calls, [("poll_automation", "explore")])
self.assertIsNone(self.window.pending_policy)
self.assertFalse(self.window.explore_enabled.isChecked())
self.assertEqual(self.window.next_explore, float("inf"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,275 @@
"""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()
@@ -0,0 +1,124 @@
"""Offline regression for restored battle gates preceding local navigation."""
from copy import deepcopy
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.progression import ProgressionPolicy
from ranch_assistant.tests.test_core import workspace_temp
def fixture():
data = ProgressionData({
"task_info": {
"1002003": {"type": 1, "name": "mainline", "steps": [{"statusType": "passStage",
"position": "city2_wild_stage0203_level1", "story": "main_before",
"afterStory": "main_after", "statusValue": {"stage": "0203", "level": 1}}]},
"2001006": {"type": 2, "name": "side battle", "steps": [
{"statusType": "none", "story": "side_before"},
{"statusType": "battle", "position": "city1_wild_stage0109",
"story": "side_before", "afterStory": "side_after", "battle": {"teams": []}}]},
"2001999": {"type": 2, "name": "side dialogue", "steps": [
{"statusType": "none", "position": "city1_market", "story": "side_before"}]},
},
"scripts": {name: {"supported": True} for name in
("main_before", "main_after", "side_before", "side_after")},
"game_setting": {"cityInfo": {"1": {"name": "one"}, "2": {"name": "two"}}},
"stage_info": {key: {"city": city, "cost": {}, "level": {"1": {"cost": 0, "battle_available": True}}}
for key, city in (("0203", 2), ("0109", 1))},
})
raw = {"master": {"id": 71, "level": 30, "ti": 100, "money": 1000},
"currentTasks": [{"id": 51, "typeId": "1002003", "curStep": 1, "stepValue": 0},
{"id": 52, "typeId": "2001006", "curStep": 2, "stepValue": 0}],
"history": {"unlockCity": {"1": True, "2": True},
"unlockStage": {"0203": [1], "0109": [1]}},
"monsters": [], "items": [], "teams": [], "stacks": [], "rooms": []}
return data, raw
class ProgressionReplayLoopTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
@staticmethod
def add_team(raw):
raw["monsters"] = [{"id": 900, "typeId": 1001010, "mode": 2, "process": 3, "level": 1}]
raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [900]}]
def engine(self, raw, data, *, losses=1, runtime=False, position=""):
self.catalog = Catalog()
client = Mock()
client.snapshot.side_effect = lambda: Snapshot(deepcopy(raw))
client.call.side_effect = AssertionError("offline replay must not call the game")
engine = Engine(self.catalog, client, self.folder / "account" / "purchase.json", game_data=data,
battle_runtime=Mock() if runtime else None)
if runtime:
engine.battles.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
"faithful": True, "approximate": False}
engine.progression_policy = ProgressionPolicy(enabled=True, sidequests=True)
engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
engine.snapshot = Snapshot(deepcopy(raw))
engine._ensure_progression()
scope, account = engine.progression_planner._account(engine.snapshot)
account.update(position=position, losses=losses)
engine._persist_progression()
restored = Engine(self.catalog, client, self.folder / "account" / "purchase.json", game_data=data,
battle_runtime=Mock() if runtime else None)
if runtime:
restored.battles.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
"faithful": True, "approximate": False}
restored.progression_policy = ProgressionPolicy(enabled=True, sidequests=True)
restored.policy = Policy(enabled=False, gift_enabled=False, fill=False)
restored.auto = True
restored.refresh_progression()
return restored
def test_restored_loss_blocks_both_battles_before_navigation(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=1, runtime=True, position="city1_wild_stage0109")
before = engine.progression_planner.export_state()
navigations = []
for _ in range(8):
engine.poll()
navigations.extend(r for r in engine.battle_journal.records(engine.snapshot)
if r["kind"] == "progression_navigate")
self.assertEqual(navigations, [])
self.assertEqual(engine.progression_planner.export_state(), before)
def test_runtime_gate_is_position_independent(self):
data, raw = fixture()
reasons = set()
for position in ("", "city2_wild_stage0203_level1", "city1_wild_stage0109"):
with self.subTest(position=position):
self.add_team(raw)
engine = self.engine(raw, data, losses=0, runtime=False, position=position)
self.assertFalse(any(i.kind == "progression_navigate" and not i.blocked
for i in engine._progression_intents))
reasons.add(next(r["block_reason"] for r in engine.progression_rows()
if r["task_type_id"] == "1002003"))
self.assertEqual(len(reasons), 1)
self.assertIn("运行时", reasons.pop())
def test_missing_team_blocks_before_navigation(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=0, runtime=True, position="city2_wild_stage0203_level1")
reason = next(r["block_reason"] for r in engine.progression_rows() if r["task_type_id"] == "1002003")
self.assertIn("队", reason)
self.assertEqual(engine.battle_journal.records(engine.snapshot), [])
def test_stopped_restored_loss_writes_no_journal(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=1, runtime=True, position="city1_wild_stage0109")
engine.cancel_progression()
with patch.object(engine.battle_journal, "save", wraps=engine.battle_journal.save) as save:
for _ in range(8):
engine.poll()
save.assert_not_called()
def test_blocked_mainline_does_not_starve_executable_side_dialogue(self):
data, raw = fixture()
raw["currentTasks"].append({"id": 53, "typeId": "2001999", "curStep": 1, "stepValue": 0})
engine = self.engine(raw, data, losses=1, position="city1_market")
self.assertEqual(engine._progression_intents[0].task_type_id, "2001999")
self.assertEqual(engine._progression_intents[0].kind, "progression_dialogue")