Add simulated challenges to selected uncleared maps

This commit is contained in:
AttilaNet
2026-11-09 08:11:57 +08:00
parent df0259febf
commit f9631c3363
11 changed files with 628 additions and 47 deletions
+99
View File
@@ -2,6 +2,7 @@ import copy
import json
import os
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
@@ -258,6 +259,104 @@ class ActivityGuiTests(unittest.TestCase):
from PySide6.QtWidgets import QApplication
cls.app = QApplication.instance() or QApplication([])
def wait(self, predicate):
from PySide6.QtTest import QTest
for _ in range(700):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Qt worker or autosave did not finish")
def test_challenge_checkbox_autosave_import_restore_and_legacy_default(self):
from ranch_assistant.gui import Window
from ranch_assistant.policy_io import portable_config
with workspace_temp() as folder:
window = Window(state_root=folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
self.assertTrue(window.map_allow_challenge.isChecked())
self.assertEqual(window.map_allow_challenge.text(), "未满星时自动挑战")
self.assertEqual(window.tabs.tabText(window.tabs.indexOf(window.map_page)), "自动扫荡")
window.map_enabled.setChecked(True)
window.map_keep_ti.setValue(17)
window.map_team.setCurrentIndex(window.map_team.findData("teamB"))
window.map_rules = {"0102": {"enabled": True, "level": "2", "limit": 12}}
window.map_allow_challenge.click()
self.assertTrue(window.auto_save_timer.isActive())
self.wait(lambda: not window.auto_save_timer.isActive())
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))["sweep_policy"]
self.assertFalse(saved["allow_challenge"])
self.assertFalse(window.engine.sweep_policy.allow_challenge)
self.assertEqual((saved["keep_stamina"], saved["team"], saved["rules"]["0102"]["limit"]), (17, "teamB", 12))
exported = portable_config(window.config_value(), window.engine.snapshot)
self.assertFalse(exported["sweep_policy"]["allow_challenge"])
path = folder / "import.json"
for allowed in (True, False):
with self.subTest(imported_challenge=allowed):
exported["sweep_policy"]["allow_challenge"] = allowed
path.write_text(json.dumps(exported), encoding="utf-8")
with patch("ranch_assistant.gui.W.QFileDialog.getOpenFileName", return_value=(str(path), "")):
window.import_policies()
self.assertEqual(window.map_allow_challenge.isChecked(), allowed)
self.assertEqual(window.read_sweep_policy().allow_challenge, allowed)
self.assertEqual(window.engine.sweep_policy.allow_challenge, allowed)
self.assertFalse(window.strategy_toggle.isChecked())
self.assertEqual(window.map_rules["0102"], {"enabled": True, "level": "2", "limit": 12})
finally:
window.close()
restored = Window(state_root=folder)
restored.timer.stop()
try:
self.wait(lambda: not restored.busy and restored.engine.snapshot is not None)
self.assertFalse(restored.map_allow_challenge.isChecked())
self.assertFalse(restored.read_sweep_policy().allow_challenge)
legacy = restored.config_value()
del legacy["sweep_policy"]["allow_challenge"]
restored.load_config(legacy)
self.assertTrue(restored.map_allow_challenge.isChecked())
self.assertTrue(restored.read_sweep_policy().allow_challenge)
self.assertFalse(restored.auto_save_timer.isActive())
finally:
restored.close()
def test_map_stop_cancels_only_pending_map_battles(self):
from ranch_assistant.gui import Window
with workspace_temp() as folder:
window = Window(state_root=folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
window.busy = True
for kind in (None, "progression_battle", "map_battle"):
for control, field in ((window.map_allow_challenge, "allow_challenge"), (window.map_enabled, "enabled")):
window.map_enabled.setChecked(True)
window.map_allow_challenge.setChecked(True)
window.engine.sweep_policy = window.read_sweep_policy()
window.update_policy()
pending = {"kind": kind} if kind else None
with self.subTest(pending=kind, stopped=field), \
patch.object(window.engine.battle_journal, "pending", return_value=pending), \
patch.object(window.engine, "cancel_progression", wraps=window.engine.cancel_progression) as cancel:
window.engine.auto = True
control.setChecked(False)
self.assertFalse(getattr(window.engine.sweep_policy, field))
self.assertFalse(getattr(window.pending_policy["sweep_policy"], field))
if kind == "map_battle":
self.assertFalse(window.engine.auto)
cancel.assert_called_once_with()
else:
self.assertTrue(window.engine.auto)
cancel.assert_not_called()
self.assertTrue(window.auto_save_timer.isActive())
with patch.object(window.engine, "cancel_progression") as cancel:
window.map_keep_ti.setValue(10)
cancel.assert_not_called()
finally:
window.busy = False
window.close()
def test_tree_rules_daily_page_and_scroll_layout(self):
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
+81 -1
View File
@@ -5,7 +5,7 @@ import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.engine import Engine
@@ -60,6 +60,86 @@ class MapCacheGuiTests(unittest.TestCase):
return
self.fail("Qt worker did not finish")
def test_map_request_error_keeps_read_only_background_reconciliation(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
catalog, snapshot = scenario()
client = FakeClient(snapshot)
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
client.persist_session = lambda: None
client.close = lambda: None
window.engine = Engine(catalog, client, folder / "purchase.json")
window.engine.snapshot = snapshot
with patch.object(window.engine.battle_journal, "pending", return_value={"kind": "map_battle"}):
window.error("挑战结算回包尚未确认")
self.assertTrue(window.monitoring)
self.assertFalse(window.engine.auto)
self.assertFalse(window.strategy_toggle.isChecked())
with patch.object(window.engine, "pending_recovery_due", return_value=True), patch.object(window, "refresh") as refresh:
window.schedule()
refresh.assert_called_once_with(automated=True)
self.assertFalse(client.calls)
finally:
window.close()
def test_unlocked_uncleared_difficulty_and_cached_challenge_status(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
catalog, snapshot = scenario()
snapshot.raw["history"]["unlockStage"]["0102"] = ["1", "2"]
client = FakeClient(snapshot)
window.catalog = catalog
window.engine = Engine(catalog, client, folder / "purchase.json")
window.engine.snapshot = snapshot
window.map_rules = {"0102": {"enabled": False, "level": "1", "limit": 3}}
original = window.engine.stage_cache.get(snapshot)
statuses = {"bd00": "特殊关卡暂不支持自动挑战"}
def reason(current, stage, policy, *, team_ids=None):
self.assertIs(current, snapshot)
self.assertTrue(policy.allow_challenge)
self.assertEqual(team_ids, [900])
return statuses.get(stage.stage_id, "")
with patch.object(window.engine, "map_stage_reason", side_effect=reason) as cached_reason, \
patch.object(window.engine.sweeper, "reason", side_effect=AssertionError("UI used sweep-only reason")), \
patch.object(window.engine.battles, "inspect", side_effect=AssertionError("UI inspected runtime")), \
patch.object(window.engine.battles, "run", side_effect=AssertionError("UI ran a battle")), \
patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("UI rebuilt cached maps")):
window.tabs.setCurrentWidget(window.map_page)
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(window._map_items["0101"].text(5), "可扫荡")
item = window._map_items["0102"]
difficulty = window.maps_tree.itemWidget(item, 3)
self.assertTrue(difficulty.model().item(difficulty.findData("2")).isEnabled())
self.assertFalse(difficulty.model().item(difficulty.findData("3")).isEnabled())
self.assertNotIn("已通关", difficulty.itemText(difficulty.findData("2")))
item.setCheckState(0, C.Qt.CheckState.Checked)
difficulty.setCurrentIndex(difficulty.findData("2"))
self.app.processEvents()
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(window.map_rules["0102"], {"enabled": True, "level": "2", "limit": 3})
self.assertEqual(item.text(5), "将模拟挑战")
self.assertTrue(any(call.args[1].stage_id == "0102" and call.args[1].level == "2"
and call.args[2].rules["0102"]["enabled"] for call in cached_reason.call_args_list))
for status in ("打不过;调整战队或提升魔物属性后自动重试", "暂不支持的战斗机制:召唤"):
with self.subTest(status=status):
statuses["0102"] = status
window.render_maps()
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(item.text(5), status)
self.assertEqual(item.toolTip(5), status)
self.assertEqual(window._map_items["bd00"].text(5), statuses["bd00"])
self.assertIs(window.engine.stage_cache.rows, original)
self.assertEqual(client.calls, [])
finally:
window.engine.client = None
window.close()
def test_collapsed_maps_remain_cached_on_page_switch_and_poll_manual_refresh_updates(self):
with workspace_temp() as folder:
window = Window(folder)
@@ -0,0 +1,208 @@
"""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)