fix(web): finalize quick battle and commission procurement for 2.0.9

This commit is contained in:
AttilaNet
2026-11-13 11:28:14 +08:00
parent cfce3e0bc5
commit 7845751cf6
21 changed files with 2442 additions and 117 deletions
@@ -0,0 +1,89 @@
"""Commission diagnostics use offline fake clients and source-derived cities."""
import json
from pathlib import Path
import unittest
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import load_progression_data
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.progression import ProgressionPlanner
from ranch_assistant.quests import QuestPolicy
from ranch_assistant.tests import test_commission_procurement as fixtures
from ranch_assistant.tests.test_progression import snapshot
from ranch_web.policies import default_config
from ranch_web.views import build_view
class CommissionProcurementViewTests(unittest.TestCase):
def test_preparable_is_distinct_from_receivable_and_has_exact_counts(self):
fixture = fixtures.CommissionProcurementTests()
fixture.setUp()
self.addCleanup(fixture.doCleanups)
fixture.catalog.data["task_info"] = fixture.tasks
engine, client = fixture.engine()
dto = build_view(engine, "commissions", default_config())
high = next(r for r in dto["rows"] if r["task_type_id"] == "400")
self.assertEqual(high["status"], "补齐后接取")
self.assertEqual(high["reason_kind"], "temp_resource")
self.assertEqual((high["resources"][0]["needed"], high["resources"][0]["available"]), (1, 0))
self.assertTrue(high["progress_plan"])
self.assertIn("不消耗接取次数", high["reason"])
self.assertEqual(client.writes, [])
engine._run_progression_intent(fixture.intent(engine))
self.assertEqual(engine.commission_history()["summary"]["accepted_count"], 0)
self.assertIn("未消耗接取次数", engine.commission_history()["events"][0]["description"])
def test_packaged_offers_replay_quota_and_city_gates(self):
from unittest.mock import patch
data, catalog = load_progression_data(), Catalog()
cities = (4, 5, 8, 9)
offers = {str(city): [key for key, info in sorted(data.task_info.items())
if info.get("type") == 4 and (info.get("reward") or {}).get("ke") == 20
and any(str(step.get("position") or "").split("_", 1)[0] == f"city{city}"
for step in info.get("steps") or [])] for city in cities}
self.assertTrue(all(offers.values()))
for quota in (0, 4):
with self.subTest(quota=quota), patch("ranch_assistant.model.time.time", return_value=1700000000):
snap = snapshot(currentTasks=[])
snap.raw["history"].update(loopTask=offers, loopTaskNum=quota, loopTaskTime=snap.now,
unlockCity={str(city): False for city in cities})
planner = ProgressionPlanner(catalog, data)
diagnostics = planner.commission_offers(snap, QuestPolicy(enabled=True, allow_items=True, allow_monsters=True),
Policy())
twenty = [row for row in diagnostics if row["expected_ke"] == 20]
self.assertEqual(len(twenty), sum(map(len, offers.values())))
self.assertEqual({row["city"] for row in twenty}, set(cities))
self.assertTrue(all(row["remaining_quota"] == quota for row in diagnostics))
if quota == 0:
self.assertTrue(all(row["reason_kind"] == "quota" and not row["eligible"] and not row["preparable"]
for row in diagnostics))
self.assertEqual(planner.commission_plan(snap, QuestPolicy(enabled=True), Policy()), [])
else:
for row in twenty:
city_info = data.game_setting["cityInfo"][str(row["city"])]
self.assertEqual(row["reason_kind"], "city_locked")
self.assertFalse(row["eligible"] or row["preparable"])
self.assertEqual(row["city_name"], city_info["name"])
self.assertEqual(row["unlock_task_id"], city_info["openTask"])
self.assertTrue(row["unlock_task_id"])
self.assertIn(row["city_name"], row["reason"])
self.assertIn(row["unlock_task_id"], row["reason"])
def test_mainline_controller_reason_is_chinese_and_does_not_claim_victory(self):
engine = Engine(Catalog())
engine.snapshot = snapshot()
engine._progression_rows = [{"task_type_id": "1002013", "name": "猫狗的恩怨", "state": "received", "category": "mainline",
"step_number": 1, "total_steps": 1, "supported": False, "battle_kind": "task",
"block_reason": "Unsupported battle triggers: monDead; Unsupported monster controller: monMaker; Unsupported monster controller: monSteps"}]
dto = build_view(engine, "mainline", default_config())
reason = dto["rows"][0]["support"]
self.assertIn("魔物死亡事件", reason)
self.assertIn("生成魔物", reason)
self.assertIn("脚本行动", reason)
self.assertNotIn("Unsupported", reason)
self.assertNotIn("胜利", reason)
if __name__ == "__main__":
unittest.main()
+10 -4
View File
@@ -790,14 +790,15 @@ class FreshProcessIntegrationTests(unittest.TestCase):
def test_real_engine_battle_worker_subprocess_still_runs_after_web_imports(self):
result = self.child('''
import json, tempfile
import json, sys, tempfile
from pathlib import Path
from unittest.mock import patch
import subprocess
from ranch_web.app import create_app
from ranch_web.service import WebManager
from ranch_web.tests.test_web_integration import NoExternalSockets, real_engine_factory
from ranch_assistant.battle_simulator import combat_tables, simulate
from ranch_assistant.battle_simulator import combat_tables
from ranch_assistant.battle_quick import simulate_quick
row = combat_tables()['monster_info']['1001010']
mon = {'id': 101, 'typeId': 1001010, 'level': 20, 'mode': 2, 'tpLevel': 0, 'feel': 0, 'upStar': 0, 'pAtk': 0, 'pDef': 0, 'pHp': 0, 'pDex': 0}
for name in ('Atk', 'Def', 'Hp', 'Dex'):
@@ -819,15 +820,20 @@ class FreshProcessIntegrationTests(unittest.TestCase):
result = engine.battles.runtime.run(request, timeout=15)
assert launch.call_count == 1
assert 'ranch_assistant.battle_simulator' in launch.call_args.args[0]
assert result == simulate(request), result
expected = simulate_quick(request)
assert {k: v for k, v in result.items() if k != 'wall_time_ms'} == {
k: v for k, v in expected.items() if k != 'wall_time_ms'}, result
assert result['simulation_method'] == 'aggregate_hp_dps', result
assert result['outcome'] == 'win', result
assert not any(n.startswith('PySide6') or n == 'ranch_assistant.gui' or n.endswith('_gui') for n in sys.modules)
assert not network.attempts
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'real_worker_processes': launch.call_count}))
print(json.dumps({'outcome': result['outcome'], 'execution_mode': result['execution_mode'], 'simulation_method': result['simulation_method'], 'real_worker_processes': launch.call_count}))
finally:
manager.close()
''')
self.assertEqual(result["real_worker_processes"], 1)
self.assertEqual(result["outcome"], "win")
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
if __name__ == "__main__":