Files

209 lines
11 KiB
Python

"""Offline map challenge routing; all server responses and combat are fakes."""
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.maps import stages
from ranch_assistant.model import Policy, Snapshot
from ranch_assistant.sweeping import SweepPolicy
from ranch_assistant.tests.test_activities import scenario
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
from ranch_assistant.tests.test_core import workspace_temp
class MapChallengeTests(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["history"]["passStage"]["0102"] = []
self.raw["master"].update(ti=1000, timeTi=0)
self.raw["teams"].append({"teamName": "teamB", "teamType": "battleTeam", "monsters": [900]})
stage_info = deepcopy(self.catalog.data["stage_info"])
for row in stage_info.values():
for level in row["level"].values():
level["battle"] = {"fixture": True}
self.data = ProgressionData({"task_info": {}, "stage_info": stage_info,
"game_setting": self.catalog.data["game_setting"]})
self.runtime = ExperimentalRuntime()
self.client = Mock()
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
self.client.call.side_effect = self.respond
self.engine = self.make_engine()
def make_engine(self):
engine = Engine(self.catalog, self.client, self.folder / "purchase.json",
game_data=self.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}}, team="teamB")
engine.master_sync.settle = Mock()
engine.auto = True
return engine
def respond(self, path, payload):
if path.endswith("stageStart"):
return {"resCode": 0, "triggerEvent": False}
if path.endswith("recordBattleResult") and payload["result"]:
passed = self.raw["history"]["passStage"].setdefault(payload["stageId"], [])
if "1" not in passed:
passed.append("1")
return {"resCode": 0, "reward": {"money": 25}}
def stage(self):
return next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0102" and s.level == "1")
def paths(self):
return [call.args[0] for call in self.client.call.call_args_list]
def test_uncleared_map_uses_simulation_and_ordinary_settlement_without_mainline(self):
snapshot, _, message = self.engine.poll()
self.assertFalse(self.engine.progression_policy.enabled)
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
request = self.runtime.run.call_args.args[0]
self.assertEqual(request["context"], "ordinary_stage")
self.assertEqual(request["team"], "teamB")
self.assertIsNone(request["battle_position"]["taskTypeId"])
self.assertIn("胜利", message)
self.assertEqual(self.engine.sweeper.used(snapshot, self.stage()), 1)
self.assertTrue(next(s for s in self.engine.stage_cache.rows if s.stage_id == "0102" and s.level == "1").passed)
def test_three_cleared_difficulties_use_sweep_without_runtime_execution(self):
self.raw["history"]["passStage"]["0102"] = ["1", "2", "3"]
self.engine.poll()
self.runtime.run.assert_not_called()
data = self.client.call.call_args_list[1].args[1]["battleData"]
self.assertEqual(data["totalDamage"], 0) # Existing official sweep payload.
def test_loss_stops_same_team_retries_and_persists_without_blocking_mainline(self):
self.runtime.win = False
_, _, message = self.engine.poll()
self.assertIn("打不过", message)
self.assertNotIn("battleService/battleEnd", self.paths())
self.assertEqual(self.engine.battle_journal.role(self.engine.snapshot)["losses"], 0)
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.assertIn("打不过", self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
self.engine = self.make_engine()
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.raw["monsters"][-1]["level"] += 1
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 2)
def test_unsupported_scenario_never_starts_or_uses_daily_count(self):
self.runtime.supported = False
self.engine.poll()
self.client.call.assert_not_called()
self.runtime.run.assert_not_called()
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 0)
self.assertTrue(self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
def test_unsupported_map_does_not_block_another_selected_map(self):
self.raw["history"]["passStage"]["0101"] = []
self.engine.sweep_policy.rules["0101"] = {"enabled": True, "level": "1", "limit": 1}
self.runtime.inspect.side_effect = lambda request: self.runtime._inspect(request) | {
"supported": request["stage_id"] != "0101"}
self.engine.poll()
started = next(call.args[1] for call in self.client.call.call_args_list if call.args[0].endswith("stageStart"))
self.assertEqual(started["stageTypeId"], "0102")
self.assertEqual(self.runtime.run.call_count, 1)
def test_stopped_closed_locked_low_stamina_and_daily_limit_never_start(self):
for blocked in ("stopped", "disabled", "locked", "stamina", "limit"):
with self.subTest(blocked=blocked):
raw = deepcopy(self.raw)
self.engine = self.make_engine()
if blocked == "stopped": self.engine.auto = False
if blocked == "disabled": self.engine.sweep_policy.allow_challenge = False
if blocked == "locked": self.raw["history"]["unlockStage"]["0102"] = []
if blocked == "stamina": self.engine.sweep_policy.keep_stamina = 1000
if blocked == "limit": self.engine.sweep_policy.rules["0102"]["limit"] = 0
self.client.call.reset_mock()
self.engine.poll()
self.client.call.assert_not_called()
self.raw = raw
def test_current_task_interception_does_not_become_ordinary_map_battle(self):
self.data.tasks["100"] = {"type": 1, "steps": [{"position": "city1_wild_stage0102_level1", "statusType": "passStage"}]}
self.raw["currentTasks"] = [{"id": 81, "typeId": "100", "curStep": 1}]
self.engine.poll()
self.client.call.assert_not_called()
self.assertIn("任务", self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
def test_daily_limit_counts_real_attempts(self):
self.engine.sweep_policy.rules["0102"]["limit"] = 1
self.engine.poll()
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)
def test_reward_event_does_not_run_model_or_resettle(self):
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "triggerEvent": True,
"stageEvent": {"resCode": 0, "result": {"money": 25}}}
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart"])
self.runtime.run.assert_not_called()
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
def test_saved_clock_resumes_without_new_start_simulation_or_count(self):
original = self.runtime._run
self.runtime.run.side_effect = lambda request, cancel_event: original(request, cancel_event=cancel_event) | {
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
self.engine.battles.clock = lambda: 0
cancel = self.engine._progression_cancel
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart"])
record = self.engine.battle_journal.pending(self.engine.snapshot)
record["battle_ready_at"] = 1
self.engine.battle_journal.save()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)
def test_confirmed_settlement_restart_only_finishes_record(self):
with patch.object(self.engine.battles, "_record", side_effect=SystemExit("synthetic process crash")):
with self.assertRaises(SystemExit):
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
self.engine = self.make_engine()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
def test_free_entry_is_not_blocked_by_gold_purchase_reserve(self):
self.engine.policy.keep_money = 10**9
self.engine.poll()
self.assertIn("stageService/stageStart", self.paths())
def test_cancel_before_dispatch_refunds_daily_count(self):
original = self.engine.battles.observer
def cancel_before_send(event, intent, response):
result = original(event, intent, response)
if event == "started":
self.engine._progression_cancel.set()
return result
self.engine.battles.observer = cancel_before_send
self.engine.poll()
self.client.call.assert_not_called()
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 0)
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
def test_uncertain_settlement_never_repeats_entry_or_settlement(self):
original = self.respond
def lost_reply(path, payload):
if path.endswith("battleEnd"):
raise TimeoutError("synthetic lost settlement reply")
return original(path, payload)
self.client.call.side_effect = lost_reply
with self.assertRaises(TimeoutError):
self.engine.poll()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)