Add hatch retention, automatic breakthroughs and exploration
This commit is contained in:
@@ -161,6 +161,8 @@ class AutomationTests(unittest.TestCase):
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
|
||||
self.assertIn("上限 20", self.planner.feed_status(snapshot, policy)[1])
|
||||
target["level"] = 19
|
||||
snapshot.raw["monsters"][1].update(process=3, roomId=1)
|
||||
snapshot.raw["monsters"][2].update(process=3, roomId=1)
|
||||
self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
|
||||
policy.target_level = 19
|
||||
self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
|
||||
@@ -297,7 +299,7 @@ class AutomationTests(unittest.TestCase):
|
||||
client = Client(Session(f"http://127.0.0.1:{server.server_port}/", "synthetic-test-token"))
|
||||
try:
|
||||
engine = Engine(catalog, client, budget_path)
|
||||
engine.policy = replace(self.policy, manual_eggs=True, egg_rules={"1001010": asdict(EggRule(enabled=True, priority=1, refill_target=12, market_id="sc_city1"))})
|
||||
engine.policy = replace(self.policy, manual_eggs=True, egg_rules={"1001010": asdict(EggRule(enabled=True, priority=1, refill_target=12, market_id="sc_city1", keep_count=0))})
|
||||
engine.policy.egg_stock = 12
|
||||
engine.policy.buy_batch = 5
|
||||
engine.policy.daily_buy_money = 1000
|
||||
@@ -376,7 +378,7 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
self.assertIn("自动孵蛋", [window.tabs.tabText(i) for i in range(window.tabs.count())])
|
||||
window.gold_preset()
|
||||
self.wait(window)
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.fill.setChecked(False)
|
||||
window.buy_eggs.setChecked(False)
|
||||
before = len(window.engine.snapshot.raw["monsters"])
|
||||
@@ -428,7 +430,7 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(window)
|
||||
window.strategy.setCurrentIndex(window.strategy.findData("gold"))
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.fill.setChecked(False)
|
||||
before = len(window.engine.snapshot.raw["monsters"])
|
||||
window.refresh()
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import copy
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.breakthrough import (
|
||||
BreakthroughPlanner, PATH, POTENTIAL_PATH, plan_breakthrough,
|
||||
)
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def snapshot_with(**monster):
|
||||
mon = {"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
|
||||
"potentialLevel": 1, "level": 1, "pAtk": 4, "pDef": 8,
|
||||
"pHp": 105, "pDex": 1}
|
||||
mon.update(monster)
|
||||
return Snapshot({"master": {"id": 1}, "monsters": [mon], "items": [
|
||||
{"id": 600, "typeId": 30058, "num": 100}], "stacks": [],
|
||||
"rooms": [{"id": 1, "typeId": 1000}], "teams": []})
|
||||
|
||||
|
||||
class BreakthroughTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.snapshot = snapshot_with()
|
||||
self.policy = Policy(feed_targets={"900": 1})
|
||||
self.planner = BreakthroughPlanner(self.catalog)
|
||||
|
||||
def test_original_first_breakthrough_payload_and_chinese_description(self):
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.path, PATH)
|
||||
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600]})
|
||||
self.assertEqual(action.kind, "breakthrough")
|
||||
self.assertIn("突破", action.description)
|
||||
self.assertIn("2 阶段", action.description)
|
||||
self.assertNotIn("monsterPotential", action.description)
|
||||
|
||||
def test_incomplete_potential_first_consumes_one_item_on_original_path(self):
|
||||
self.snapshot.monsters[900]["pAtk"] = 2
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.kind, "potential")
|
||||
self.assertEqual(action.path, POTENTIAL_PATH)
|
||||
self.assertEqual(action.payload, {"monId": 900, "itemId": 600, "monsterAttr": "atk",
|
||||
"traceInfo": {"itemTypeId": 600, "itemNum": 100}})
|
||||
self.assertIn("消耗", action.description)
|
||||
self.assertIn("重新读取", action.description)
|
||||
|
||||
def test_potential_trace_info_uses_selected_stack_instance_id(self):
|
||||
self.snapshot.monsters[900]["pAtk"] = 2
|
||||
self.assertEqual(self.snapshot.raw["items"], [{"id": 600, "typeId": 30058, "num": 100}])
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload["itemId"], 600)
|
||||
self.assertEqual(action.payload["traceInfo"], {"itemTypeId": 600, "itemNum": 100})
|
||||
|
||||
def test_potential_reserve_allows_partial_consumption_of_one_stack(self):
|
||||
self.snapshot.monsters[900]["pAtk"] = 2
|
||||
self.policy.gift_items = {"30058": {"enabled": False, "reserve": 10}}
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload["itemId"], 600)
|
||||
self.policy.gift_items["30058"]["reserve"] = 100
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
|
||||
def test_potential_proceeds_even_at_ordinary_level_cap(self):
|
||||
self.snapshot.monsters[900].update(pAtk=3, level=10)
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.kind, "potential")
|
||||
|
||||
def test_ordinary_level_below_cap_does_not_block_full_potential(self):
|
||||
self.assertEqual(self.snapshot.monsters[900]["level"], 1)
|
||||
self.assertIsNotNone(self.planner.plan(self.snapshot, self.policy))
|
||||
|
||||
def test_stage_reserve_uses_total_stock_and_one_sufficient_stack(self):
|
||||
self.policy.gift_items = {"30058": {"enabled": False, "reserve": 96}}
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload["itemIds"], [600])
|
||||
self.policy.gift_items["30058"]["reserve"] = 97
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIn("单堆", " ".join(self.planner.notes))
|
||||
|
||||
def test_missing_or_insufficient_material_never_returns_action(self):
|
||||
self.snapshot.raw["items"][0]["num"] = 3
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIn("3/4", self.planner.notes[0])
|
||||
self.snapshot.raw["items"] = []
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
|
||||
def test_multiple_stacks_choose_a_sufficient_id_not_aggregate_ids(self):
|
||||
self.snapshot.raw["items"] = [
|
||||
{"id": 600, "typeId": 30058, "num": 1},
|
||||
{"id": 601, "typeId": 30058, "num": 2},
|
||||
{"id": 602, "typeId": 30058, "num": 8},
|
||||
]
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload["itemIds"], [602])
|
||||
|
||||
def test_locked_stock_is_not_counted_toward_reserves_or_requests(self):
|
||||
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 100, "lock": 1}]
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.snapshot.raw["items"][0].pop("lock")
|
||||
self.assertIsNotNone(self.planner.plan(self.snapshot, self.policy))
|
||||
|
||||
def test_priority_skips_blocked_candidate_and_uses_next(self):
|
||||
other = copy.deepcopy(self.snapshot.monsters[900])
|
||||
other.update(id=901, pAtk=3)
|
||||
self.snapshot.raw["monsters"].append(other)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, targets={"901": 2, "900": 1}).payload["monId"], 900)
|
||||
|
||||
def test_independent_targets_replace_feed_targets_and_empty_is_empty(self):
|
||||
other = copy.deepcopy(self.snapshot.monsters[900])
|
||||
other["id"] = 901
|
||||
self.snapshot.raw["monsters"].append(other)
|
||||
action = self.planner.plan(self.snapshot, self.policy, targets={"901": 1})
|
||||
self.assertEqual(action.payload["monId"], 901)
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, targets={}))
|
||||
|
||||
def test_exploration_build_non_ranch_disabled_and_maximum_do_not_plan(self):
|
||||
for flags in ({"process": 1}, {"process": 2}, {"inExploreTeam": True}, {"inBuild": True}):
|
||||
self.snapshot.monsters[900].update(flags)
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.snapshot.monsters[900].update(process=3, inExploreTeam=False, inBuild=False)
|
||||
self.snapshot.monsters[900]["potentialLevel"] = 7
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, enabled=False))
|
||||
self.policy.enabled = False
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
|
||||
def test_tp_level_and_exp_do_not_gate_material_breakthrough(self):
|
||||
self.snapshot.monsters[900].update(tpLevel=4, tpExp=33, potentialLevel=1)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy).kind, "breakthrough")
|
||||
self.snapshot.monsters[900].update(tpLevel=0, tpExp=0, pAtk=0)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy).kind, "potential")
|
||||
|
||||
def test_invalid_and_incomplete_snapshots_are_safe(self):
|
||||
for field in ("potentialLevel", "pAtk", "pDef", "pHp", "pDex"):
|
||||
snapshot = snapshot_with()
|
||||
snapshot.monsters[900][field] = None
|
||||
self.assertIsNone(BreakthroughPlanner(self.catalog).plan(snapshot, self.policy))
|
||||
snapshot = snapshot_with()
|
||||
snapshot.monsters[900]["typeId"] = 999999999
|
||||
self.assertIsNone(BreakthroughPlanner(self.catalog).plan(snapshot, self.policy))
|
||||
|
||||
def test_duplicate_item_instances_block_instead_of_double_spending(self):
|
||||
self.snapshot.raw["items"] = [
|
||||
{"id": 600, "typeId": 30058, "num": 2},
|
||||
{"id": 600, "typeId": 30058, "num": 2},
|
||||
]
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIn("实例重复", self.planner.notes[0])
|
||||
|
||||
def test_second_stage_matches_original_element_table(self):
|
||||
self.snapshot.monsters[900].update(potentialLevel=2, pAtk=16, pDef=28, pHp=345, pDex=4)
|
||||
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 4},
|
||||
{"id": 601, "typeId": 30041, "num": 1}]
|
||||
action = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600, 601]})
|
||||
|
||||
def test_same_type_requirements_are_combined_and_instance_sent_once(self):
|
||||
info = copy.deepcopy(self.catalog.data["potential_info"])
|
||||
info["elementItem"]["4"]["lv2"] = 30058
|
||||
catalog = copy.copy(self.catalog)
|
||||
catalog.data = copy.deepcopy(self.catalog.data) | {"potential_info": info}
|
||||
self.snapshot.monsters[900].update(potentialLevel=2, pAtk=16, pDef=28, pHp=345, pDex=4)
|
||||
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 5}]
|
||||
action = BreakthroughPlanner(catalog).plan(self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600]})
|
||||
self.snapshot.raw["items"][0]["num"] = 4
|
||||
self.assertIsNone(BreakthroughPlanner(catalog).plan(self.snapshot, self.policy))
|
||||
|
||||
def test_chain_replans_fresh_snapshot_without_mutating_state(self):
|
||||
self.snapshot.monsters[900]["pAtk"] = 0
|
||||
original = copy.deepcopy(self.snapshot.raw)
|
||||
first = self.planner.plan(self.snapshot, self.policy, targets={"900": 1})
|
||||
self.assertEqual(first.kind, "potential")
|
||||
self.assertEqual(self.snapshot.raw, original)
|
||||
# Simulate a subsequent server read, not client-side success inference.
|
||||
fresh = snapshot_with(pAtk=2)
|
||||
second = self.planner.plan(fresh, self.policy, targets={"900": 1})
|
||||
self.assertEqual(second.kind, "potential")
|
||||
final = self.planner.plan(snapshot_with(), self.policy, targets={"900": 1})
|
||||
self.assertEqual(final.kind, "breakthrough")
|
||||
self.assertEqual(original["monsters"][0]["pAtk"], 0)
|
||||
|
||||
def test_functional_integration_is_pure_and_makes_no_client_call(self):
|
||||
with patch("ranch_assistant.api.Client.call") as call:
|
||||
action = plan_breakthrough(self.catalog, self.snapshot, self.policy)
|
||||
self.assertEqual(action.payload["monId"], 900)
|
||||
call.assert_not_called()
|
||||
|
||||
|
||||
class CatalogBuildTests(unittest.TestCase):
|
||||
def test_local_build_is_valid_and_preserves_unrelated_top_level_data(self):
|
||||
if not list(ROOT.glob("*_1.9.68.apk")):
|
||||
self.skipTest("Local source APK is not present")
|
||||
before = json.loads(subprocess.check_output(
|
||||
["git", "show", "HEAD:ranch_assistant/data/catalog.json"], cwd=ROOT).decode("utf-8"))
|
||||
with workspace_temp() as directory:
|
||||
destination = directory / "catalog.json"
|
||||
destination.write_text(json.dumps(before, ensure_ascii=False), encoding="utf-8")
|
||||
source_apk = next(ROOT.glob("*_1.9.68.apk"))
|
||||
live_catalog = ROOT / "ranch_assistant" / "data" / "catalog.json"
|
||||
live_bytes = live_catalog.read_bytes()
|
||||
result = subprocess.run([sys.executable, str(ROOT / "tools" / "extract_ranch_catalog.py"),
|
||||
"--apk", str(source_apk), "--output", str(destination)],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(live_catalog.read_bytes(), live_bytes)
|
||||
after = json.loads(destination.read_text(encoding="utf-8"))
|
||||
changed = {"monster_info", "potential_info", "game_setting", "client_constants"}
|
||||
self.assertEqual({key: value for key, value in after.items() if key not in changed},
|
||||
{key: value for key, value in before.items() if key not in changed})
|
||||
self.assertTrue(all({"job", "element"} <= set(row)
|
||||
for row in after["monster_info"].values() if isinstance(row, dict)))
|
||||
self.assertEqual(after["client_constants"], {"maxTpLevel": 4})
|
||||
self.assertTrue(after["game_setting"]["tpExp"])
|
||||
self.assertIn("specialFood", after["game_setting"])
|
||||
self.assertIn("specialFood14", after["game_setting"])
|
||||
self.assertNotIn("maxTpLevel", after["game_setting"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -70,6 +70,10 @@ class CoreTests(unittest.TestCase):
|
||||
mon = snapshot.raw["monsters"][0]
|
||||
mon.update(process=3, roomId=1)
|
||||
snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
snapshot.raw["monsters"][1].update(process=3, roomId=1)
|
||||
cap = self.catalog.max_level(snapshot.monsters[900])
|
||||
snapshot.monsters[900].update(level=cap - 1,
|
||||
exp=int(self.catalog.data["monster_level"][str(cap)]) - 1)
|
||||
plans = planner.plan(snapshot, policy)
|
||||
feeding = next(a for a in plans if a.kind == "feed")
|
||||
self.assertEqual(feeding.payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
|
||||
@@ -9,23 +9,32 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
from PySide6 import QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant.cultivation import CultivationSelector, growth_score
|
||||
from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.gifts import GiftPlanner
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
|
||||
from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
|
||||
from ranch_assistant.policy_io import import_config, portable_config
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
||||
from ranch_assistant.api import Session
|
||||
|
||||
|
||||
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3):
|
||||
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3, **values):
|
||||
row = catalog.monster(species)
|
||||
return {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
|
||||
"feel": feel, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0,
|
||||
**{"g" + stat.capitalize(): row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
|
||||
for stat in ("atk", "def", "hp", "dex")}}
|
||||
for stat in ("atk", "def", "hp", "dex")}, **values}
|
||||
|
||||
|
||||
def graded_monster(catalog, mid, grades, **values):
|
||||
mon = monster(catalog, mid, **values)
|
||||
row = catalog.monster(mon["typeId"])
|
||||
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
|
||||
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
|
||||
return mon
|
||||
|
||||
|
||||
class CultivationTests(unittest.TestCase):
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Offline exploration policy, pending-send, snapshot and data tests."""
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from ranch_assistant.exploration import ExplorePlanner, ExplorePolicy, ExploreTeamRule, load_exploration_areas
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
NOW = 1_700_000_000
|
||||
AREAS = {
|
||||
"1": {"id": "1", "name": "测试矿洞", "passStage": "0101", "costTi": 20,
|
||||
"costTime": 3600, "level": [5, 1, 1], "team": "normal"},
|
||||
"2": {"id": "2", "name": "测试森林", "passStage": "0102", "costTi": 30,
|
||||
"costTime": 7200, "level": [10, 2, 2], "team": "normal"},
|
||||
}
|
||||
|
||||
|
||||
def monster(mid, level, **changes):
|
||||
return {"id": mid, "typeId": "1001010", "level": level, "process": 3,
|
||||
"mode": 2, "lock": False, **changes}
|
||||
|
||||
|
||||
def make_snapshot(**changes):
|
||||
value = {"master": {"id": 11, "ti": 100}, "serverId": 7, "areaId": 1,
|
||||
"items": [], "stacks": [], "rooms": [], "teams": [],
|
||||
"monsters": [monster(mid, level) for mid, level in ((1, 20), (2, 15), (3, 10), (4, 8), (5, 7), (6, 6), (7, 5))],
|
||||
"history": {"passTask": {"1001008": True},
|
||||
"passStage": {"0101": {"1": True}, "0102": {"1": True}}},
|
||||
"exploreTeams": [{"id": 1, "status": 0, "area": "", "monsters": ""}], **changes}
|
||||
snapshot = Snapshot(value, received_at=NOW)
|
||||
return patch("time.time", return_value=NOW), snapshot
|
||||
|
||||
|
||||
def policy(**team):
|
||||
values = {"enabled": True, "area": "1", "monsters": []} | team
|
||||
return ExplorePolicy(True, {"1": ExploreTeamRule(**values)})
|
||||
|
||||
|
||||
class ExplorationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.clock, self.snapshot = make_snapshot()
|
||||
self.clock.start()
|
||||
self.addCleanup(self.clock.stop)
|
||||
self.ranch = Policy(protect_star=6, protect_quality=5, keep_better_quality=False)
|
||||
self.planner = ExplorePlanner(self.catalog, areas=AREAS)
|
||||
|
||||
def action(self, snapshot=None, planner=None, explore_policy=None):
|
||||
return (planner or self.planner).plan(snapshot or self.snapshot, explore_policy or policy(), self.ranch)[0]
|
||||
|
||||
def start_confirmed(self, team, end=NOW + 3600):
|
||||
team.update(status=1, area="1", monsters="1,2,3", endTime=end * 1000)
|
||||
|
||||
def test_static_data_and_source_extractor(self):
|
||||
areas = load_exploration_areas()
|
||||
self.assertEqual(len(areas), 22)
|
||||
self.assertEqual(areas["1"]["name"], "废弃矿洞")
|
||||
self.assertEqual(areas["1"]["level"], [4, 1, 1])
|
||||
self.assertEqual(areas["1"]["passStage"], "0109")
|
||||
self.assertTrue(all(row["team"] == "normal" and len(row["level"]) == 3 for row in areas.values()))
|
||||
|
||||
def test_policy_roundtrip_and_strict_validation(self):
|
||||
configured = policy(monsters=[1, 2, 3])
|
||||
self.assertEqual(ExplorePolicy.from_dict(json.loads(json.dumps(configured.to_dict()))), configured)
|
||||
for value in ({"enabled": 1}, {"reserve_ti": -1}, {"reserve_ti": True},
|
||||
{"teams": {"0": {"enabled": True, "area": "1", "monsters": []}}},
|
||||
{"teams": {"1": {"enabled": True, "area": "bad", "monsters": []}}},
|
||||
{"teams": {"1": {"enabled": True, "area": "1", "monsters": [1]}}},
|
||||
{"teams": {"1": {"enabled": True, "area": "1", "monsters": [1, 1, 2]}}},
|
||||
{"teams": {"1": {"enabled": True, "area": "1", "unknown": 1}}}):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
ExplorePolicy(**(asdict(ExplorePolicy()) | value))
|
||||
|
||||
def test_original_monster_eligibility_does_not_protect_lock_star_or_equipment(self):
|
||||
selected = policy(monsters=[1, 2, 3])
|
||||
for mid in (1, 2, 3):
|
||||
self.snapshot.raw["monsters"][mid - 1].update(lock=True, sysLock=True, equip1=7)
|
||||
action = self.action(explore_policy=selected)
|
||||
self.assertEqual(action.payload["monsters"], [1, 2, 3])
|
||||
self.assertEqual(self.planner.rows(self.snapshot, selected, self.ranch)[0]["state"], "可出发")
|
||||
options = self.planner.member_options(self.snapshot, 1, selected, self.ranch)
|
||||
self.assertTrue(all(option["automatic"] for option in options))
|
||||
|
||||
def test_automatic_excludes_battle_feed_gift_and_breakthrough_targets(self):
|
||||
self.snapshot.raw["teams"] = [{"teamType": "battleTeam", "teamName": "teamA", "monsters": [1]}]
|
||||
self.ranch.feed_targets = {"2": 1}
|
||||
self.ranch.gift_targets = {"3": 1}
|
||||
self.ranch.breakthrough_targets = {"4": 1}
|
||||
action = self.action()
|
||||
self.assertEqual(action.payload["monsters"], [5, 6, 7])
|
||||
|
||||
def test_manual_remains_available_when_automatic_targets_exhausted(self):
|
||||
self.snapshot.raw["teams"] = [{"teamType": "battleTeam", "monsters": [1]}]
|
||||
self.ranch.feed_targets = {str(mid): 1 for mid in (2, 3, 4, 5, 6, 7)}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
|
||||
row = self.planner.rows(self.snapshot, policy(), self.ranch)[0]
|
||||
self.assertIn("手动", row["reason"])
|
||||
manual = policy(monsters=[1, 2, 3])
|
||||
self.assertEqual(self.action(explore_policy=manual).payload["monsters"], [1, 2, 3])
|
||||
options = self.planner.member_options(self.snapshot, 1, manual, self.ranch)
|
||||
self.assertEqual(len(options), 7)
|
||||
self.assertTrue(all(not option["automatic"] for option in options))
|
||||
|
||||
def test_manual_missing_leader_and_other_team_members_do_not_raise(self):
|
||||
for ids in ([99, 2, 3], [1, 2, 2]):
|
||||
if len(set(ids)) == 3:
|
||||
selected = policy(monsters=ids)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, selected, self.ranch), [])
|
||||
row = self.planner.rows(self.snapshot, selected, self.ranch)[0]
|
||||
self.assertIn("不存在", row["reason"])
|
||||
self.snapshot.raw["exploreTeams"].append({"id": 2, "status": 1, "area": "2", "monsters": "2", "endTime": (NOW + 30) * 1000})
|
||||
selected = policy(monsters=[1, 2, 3])
|
||||
self.assertIn("其他探险队", self.planner.rows(self.snapshot, selected, self.ranch)[0]["reason"])
|
||||
|
||||
def test_raw_string_members_unlock_stamina_and_finish_priority(self):
|
||||
self.assertFalse(self.planner.area_unlocked(self.snapshot, AREAS["1"] | {"passStage": "0103"}))
|
||||
self.snapshot.raw["history"]["passStage"]["0101"] = {"2": True}
|
||||
self.assertFalse(self.planner.area_unlocked(self.snapshot, AREAS["1"]))
|
||||
self.snapshot.raw["history"]["passStage"]["0101"]["1"] = True
|
||||
self.snapshot.raw["master"]["ti"] = 19
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
|
||||
self.snapshot.raw["master"]["ti"] = 100
|
||||
self.snapshot.raw["exploreTeams"].append({"id": 2, "status": 1, "area": "1", "endTime": (NOW + 60) * 1000})
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
|
||||
self.snapshot.raw["exploreTeams"].pop()
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", monsters="1,2,3", endTime=(NOW - 1) * 1000)
|
||||
self.assertEqual(self.action().kind, "explore_finish")
|
||||
self.assertEqual(self.planner.rows(self.snapshot, policy(), self.ranch)[0]["monster_ids"], [1, 2, 3])
|
||||
|
||||
def test_active_zero_or_missing_deadline_is_unknown_and_never_finished(self):
|
||||
for value in (None, 0, "", "not-a-time"):
|
||||
with self.subTest(value=value):
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=1, endTime=value, monsters="1,2,3")
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
|
||||
self.assertEqual(self.planner.rows(self.snapshot, policy(), self.ranch)[0]["state"], "状态待同步")
|
||||
|
||||
def test_success_with_stale_snapshot_never_repeats_start_even_after_restart(self):
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "exploration-state.json"
|
||||
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
|
||||
action = self.action(planner=planner)
|
||||
response = planner.execute(self.snapshot, action, Mock(return_value={"resCode": 0}))
|
||||
self.assertEqual(response, {"resCode": 0})
|
||||
for _ in range(3):
|
||||
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
|
||||
self.assertFalse(planner.reconcile(self.snapshot))
|
||||
restored = ExplorePlanner(self.catalog, areas=AREAS, path=path)
|
||||
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
|
||||
self.assertTrue(restored.pending(self.snapshot)["confirmed"])
|
||||
self.start_confirmed(self.snapshot.raw["exploreTeams"][0])
|
||||
self.assertTrue(restored.reconcile(self.snapshot))
|
||||
self.assertIsNone(restored.pending(self.snapshot))
|
||||
|
||||
def test_success_with_stale_snapshot_never_repeats_finish_even_after_restart(self):
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", monsters="1,2,3", endTime=(NOW - 1) * 1000)
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "state.json"
|
||||
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
|
||||
action = self.action(planner=planner)
|
||||
planner.execute(self.snapshot, action, Mock(return_value={"resCode": 0}))
|
||||
for _ in range(3):
|
||||
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
|
||||
self.assertFalse(planner.reconcile(self.snapshot))
|
||||
restored = ExplorePlanner(self.catalog, areas=AREAS, path=path)
|
||||
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=0, monsters="", endTime=0)
|
||||
self.assertTrue(restored.reconcile(self.snapshot))
|
||||
self.assertEqual(self.action(planner=restored).kind, "explore_start")
|
||||
|
||||
def test_unknown_write_requires_authoritative_matching_snapshot(self):
|
||||
with workspace_temp() as folder:
|
||||
planner = ExplorePlanner(self.catalog, areas=AREAS, path=folder / "state.json")
|
||||
action = self.action(planner=planner)
|
||||
planner.mark_started(self.snapshot, action)
|
||||
planner.mark_uncertain(self.snapshot, action)
|
||||
restored = ExplorePlanner(self.catalog, areas=AREAS, path=folder / "state.json")
|
||||
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
|
||||
self.start_confirmed(self.snapshot.raw["exploreTeams"][0])
|
||||
self.assertTrue(restored.reconcile(self.snapshot))
|
||||
self.assertFalse(restored.reconcile(self.snapshot))
|
||||
|
||||
def test_unknown_action_cannot_be_forged_or_confirmed(self):
|
||||
from ranch_assistant.model import Action
|
||||
action = self.action()
|
||||
forged = Action("explore_start", "forged", "exploreService/start", deepcopy(action.payload))
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.mark_started(self.snapshot, forged)
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
self.assertTrue(self.planner.pending(self.snapshot))
|
||||
self.planner._accounts.clear()
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.mark_started(self.snapshot, forged)
|
||||
|
||||
def test_pending_persistence_hashed_role_and_has_no_credentials(self):
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "state.json"
|
||||
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path, account_key="profile-only")
|
||||
action = self.action(planner=planner)
|
||||
planner.mark_started(self.snapshot, action)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
state = json.loads(text)
|
||||
key = next(iter(state["accounts"]))
|
||||
self.assertRegex(key, r"^[0-9a-f]{64}$")
|
||||
self.assertNotIn("11", key)
|
||||
for secret in ("password", "token", "sdkToken", "account_name", "session_token"):
|
||||
self.assertNotIn(secret, text)
|
||||
other_clock, other = make_snapshot(master={"id": 12, "ti": 100})
|
||||
with other_clock:
|
||||
self.assertIsNone(planner.pending(other))
|
||||
self.assertEqual(planner.plan(other, policy(), self.ranch)[0].kind, "explore_start")
|
||||
|
||||
def test_corrupt_state_blocks_instead_of_replaying(self):
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "state.json"
|
||||
path.write_text("{broken", encoding="utf-8")
|
||||
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
|
||||
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
|
||||
|
||||
def test_worker_rows_are_compact_plain_data(self):
|
||||
from ranch_assistant.exploration_gui import prepare_exploration_rows, prepare_exploration_members
|
||||
from types import SimpleNamespace
|
||||
engine = SimpleNamespace(snapshot=self.snapshot, explore_planner=self.planner, explore_policy=policy(), policy=self.ranch)
|
||||
rows = prepare_exploration_rows(engine)
|
||||
self.assertEqual(rows[0]["monster_labels"], ["#1 绿色史莱姆 Lv.20", "#2 绿色史莱姆 Lv.15", "#3 绿色史莱姆 Lv.10"])
|
||||
self.assertEqual(rows[0]["remaining_text"], "—")
|
||||
json.dumps(rows)
|
||||
options = prepare_exploration_members(engine, 1)
|
||||
self.assertLess(len(json.dumps(options)), 4000)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Repeated native Qt rendering, manual drafts and account isolation."""
|
||||
import os
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from dataclasses import replace
|
||||
import copy
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant import gui
|
||||
from ranch_assistant.exploration import ExplorePlanner
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
from ranch_assistant.tests.test_exploration import AREAS, make_snapshot, policy
|
||||
|
||||
|
||||
class ExplorationGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window, predicate=lambda: True, timeout=8):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if (not window.busy and not window.exploration_table.row_batch.running
|
||||
and not window._exploration_member_busy and predicate()):
|
||||
return
|
||||
self.fail("Offline exploration Qt job did not finish")
|
||||
|
||||
def setUp(self):
|
||||
self.folder = self.enterContext(workspace_temp())
|
||||
self.qt_messages = []
|
||||
self.qt_handler = C.qInstallMessageHandler(lambda kind, context, message: self.qt_messages.append(message))
|
||||
self.window = gui.Window(self.folder)
|
||||
self.window.timer.stop()
|
||||
self.window.auto_save_timer.stop()
|
||||
self.clock, self.snapshot = make_snapshot()
|
||||
self.clock.start()
|
||||
self.addCleanup(self.clock.stop)
|
||||
self.window.engine.snapshot = self.snapshot
|
||||
self.window.engine.explore_planner = ExplorePlanner(self.window.catalog, areas=AREAS)
|
||||
self.window.engine.explore_policy = policy()
|
||||
self.window.apply_explore_policy(policy())
|
||||
self.window.presentation_active = True
|
||||
self.window.pending_exploration_view = False
|
||||
self.window.tabs.setCurrentWidget(self.window.exploration_page)
|
||||
|
||||
def tearDown(self):
|
||||
self.window.pool.clear()
|
||||
self.window.pool.waitForDone(3000)
|
||||
self.window.close()
|
||||
self.app.processEvents()
|
||||
C.qInstallMessageHandler(self.qt_handler)
|
||||
self.assertFalse([message for message in self.qt_messages if "Traceback" in message or "QTableWidgetItem" in message], self.qt_messages)
|
||||
|
||||
def controls(self):
|
||||
return self.window.exploration_table._controls["1"]
|
||||
|
||||
def test_real_window_three_selections_and_busy_policy_queue(self):
|
||||
window = self.window
|
||||
window.refresh_exploration()
|
||||
self.wait(window, lambda: bool(window._exploration_member_options))
|
||||
control = self.controls()
|
||||
window.busy = True
|
||||
before = window.engine.explore_policy.to_dict()
|
||||
saved = []
|
||||
with patch.object(window, "settings_changed", side_effect=lambda: saved.append(window.read_explore_policy().to_dict())):
|
||||
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
|
||||
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
|
||||
self.assertEqual(window.engine.explore_policy.to_dict(), before)
|
||||
for _ in range(5):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
self.assertEqual(window._exploration_drafts["1"], [1, None, None])
|
||||
control["members"][1].setCurrentIndex(control["members"][1].findData(2))
|
||||
self.assertEqual(window._exploration_drafts["1"][:2], [1, 2])
|
||||
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
|
||||
control["members"][2].setCurrentIndex(control["members"][2].findData(3))
|
||||
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [1, 2, 3])
|
||||
self.assertNotIn("1", window._exploration_drafts)
|
||||
# The module signals only; host update_policy owns engine writes.
|
||||
self.assertEqual(window.engine.explore_policy.to_dict(), before)
|
||||
self.assertEqual(saved[-1]["teams"]["1"]["monsters"], [1, 2, 3])
|
||||
control["auto"].click()
|
||||
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
|
||||
window.busy = False
|
||||
|
||||
def test_real_window_update_policy_waits_for_job(self):
|
||||
window = self.window
|
||||
window.refresh_exploration()
|
||||
self.wait(window, lambda: bool(window._exploration_member_options))
|
||||
configured = policy(monsters=[1, 2, 3])
|
||||
window.apply_explore_policy(configured)
|
||||
window.busy = True
|
||||
window.pending_policy = None
|
||||
self.assertFalse(window.update_policy())
|
||||
self.assertEqual(window.pending_policy["explore_policy"].teams["1"].monsters, [1, 2, 3])
|
||||
self.assertEqual(window.engine.explore_policy.to_dict(), policy().to_dict())
|
||||
window.busy = False
|
||||
|
||||
def test_repeated_render_keeps_owned_items_and_drafts_and_captures_no_qt_warning(self):
|
||||
window = self.window
|
||||
window.refresh_exploration()
|
||||
self.wait(window, lambda: bool(window._exploration_member_options))
|
||||
rows = copy.deepcopy(window._exploration_rows)
|
||||
identities = [window.exploration_table.item(0, column) for column in range(7)]
|
||||
control = self.controls()
|
||||
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
|
||||
warnings = []
|
||||
handler = C.qInstallMessageHandler(lambda kind, context, message: warnings.append(message))
|
||||
try:
|
||||
with patch.object(gui, "prepare_exploration_rows", wraps=gui.prepare_exploration_rows) as worker:
|
||||
for _ in range(12):
|
||||
# Prevent member refetch jobs so this test repeatedly renders
|
||||
# a stable already-prepared small DTO in the GUI thread.
|
||||
window._exploration_member_options["1"] = [{"id": 1, "level": 20, "label": "one", "automatic": True, "reason": ""}]
|
||||
window.render_exploration(copy.deepcopy(rows))
|
||||
while window.exploration_table.row_batch.running:
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
worker.assert_not_called()
|
||||
finally:
|
||||
C.qInstallMessageHandler(handler)
|
||||
self.assertEqual([window.exploration_table.item(0, column) for column in range(7)], identities)
|
||||
self.assertEqual(window._exploration_drafts["1"], [1, None, None])
|
||||
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
|
||||
self.assertFalse(warnings)
|
||||
|
||||
def test_account_switch_drops_drafts_and_cached_candidates(self):
|
||||
window = self.window
|
||||
window.refresh_exploration()
|
||||
self.wait(window, lambda: bool(window._exploration_member_options))
|
||||
control = self.controls()
|
||||
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
|
||||
other_clock, other = make_snapshot(master={"id": 12, "ti": 100})
|
||||
with other_clock:
|
||||
window.engine.snapshot = other
|
||||
window.render_exploration([])
|
||||
self.assertFalse(window._exploration_drafts)
|
||||
self.assertFalse(window._exploration_member_options)
|
||||
self.assertEqual(window.exploration_table.rowCount(), 0)
|
||||
|
||||
def test_hidden_team_rules_survive_render_and_worker_returns_plain_rows(self):
|
||||
configured = policy(monsters=[1, 2, 3])
|
||||
configured.teams["99"] = replace(configured.teams["1"], area="2", monsters=[4, 5, 6])
|
||||
self.window.apply_explore_policy(configured)
|
||||
self.window.render_exploration([])
|
||||
self.assertEqual(self.window.read_explore_policy(), configured)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -71,7 +71,7 @@ class GrowthTests(unittest.TestCase):
|
||||
def engine(self, client):
|
||||
engine = Engine(self.catalog, client)
|
||||
engine.policy = Policy(manual_eggs=True, fill=False, buy=False, collect=False, protect_star=4, protect_quality=3,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell"))})
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))})
|
||||
engine.auto = True
|
||||
return engine
|
||||
|
||||
@@ -194,7 +194,7 @@ class GrowthGuiTests(unittest.TestCase):
|
||||
client = GrowthClient(window.catalog, age=610, grade="S")
|
||||
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
|
||||
window.engine = Engine(window.catalog, client)
|
||||
window.egg_rules = {"1001010": asdict(EggRule(enabled=True, action="sell"))}
|
||||
window.egg_rules = {"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))}
|
||||
window.engine.policy = window.read_policy()
|
||||
window.engine.snapshot = client.snapshot()
|
||||
window.render(window.engine.snapshot, window.engine.plans())
|
||||
|
||||
@@ -45,7 +45,7 @@ class GuiTests(unittest.TestCase):
|
||||
self.assertNotIn(removed, buttons)
|
||||
self.assertNotIn("自动执行已启用策略", {check.text() for check in window.findChildren(QCheckBox)})
|
||||
window.strategy.setCurrentIndex(window.strategy.findData("gold"))
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
|
||||
window.protect_star.setValue(6)
|
||||
window.protect_quality.setCurrentIndex(window.protect_quality.findData(5))
|
||||
window.fill.setChecked(False)
|
||||
|
||||
@@ -53,7 +53,7 @@ class HatchClient:
|
||||
|
||||
def policy_for(client):
|
||||
return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True,
|
||||
egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell"))})
|
||||
egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell", keep_count=0))})
|
||||
|
||||
|
||||
class HatchTimingTests(unittest.TestCase):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from dataclasses import asdict
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import unittest
|
||||
@@ -21,7 +22,7 @@ from ranch_assistant.tests.test_core import workspace_temp
|
||||
class UnifiedPolicyTests(unittest.TestCase):
|
||||
def config(self):
|
||||
return {"policy": asdict(Policy(buy=True, gift_enabled=True, feed_target=900, room_id=999999,
|
||||
gift_targets={"900": 2}, gift_items={"30001": {"enabled": True, "reserve": 5}})),
|
||||
gift_targets={"900": 2}, breakthrough_targets={"900": 3}, gift_items={"30001": {"enabled": True, "reserve": 5}})),
|
||||
"quest_policy": asdict(QuestPolicy(enabled=True, max_money=100, item_reserves={"30001": 6})),
|
||||
"daily_policy": asdict(DailyPolicy(enabled=True, selected=["mail"])),
|
||||
"sweep_policy": asdict(SweepPolicy(enabled=True, rules={"0101": {"enabled": True, "level": 3, "limit": 5}}, keep_stamina=22)),
|
||||
@@ -38,6 +39,7 @@ class UnifiedPolicyTests(unittest.TestCase):
|
||||
config = import_config(exported, snapshot)
|
||||
self.assertEqual(config["policy"]["feed_targets"], {"999": 1})
|
||||
self.assertEqual(config["policy"]["gift_targets"], {"999": 2})
|
||||
self.assertEqual(config["policy"]["breakthrough_targets"], {"999": 3})
|
||||
self.assertEqual(config["policy"]["feed_target"], 0)
|
||||
self.assertEqual(config["policy"]["room_id"], 0)
|
||||
self.assertTrue(config["policy"]["gift_enabled"])
|
||||
@@ -50,6 +52,31 @@ class UnifiedPolicyTests(unittest.TestCase):
|
||||
self.assertEqual(config["policy"]["protect_quality"], 6)
|
||||
self.assertFalse(config["policy"]["enabled"])
|
||||
|
||||
def test_explore_round_trip_rebinds_team_order_and_species_without_instance_ids(self):
|
||||
snapshot = demo_snapshot(Catalog())
|
||||
snapshot.raw["exploreTeams"] = [{"id": 800, "status": 0}, {"id": 700, "status": 0}]
|
||||
snapshot.monsters[900].update(id=900, typeId=1001010)
|
||||
snapshot.monsters[101].update(id=101, typeId=1001010, process=3)
|
||||
snapshot.monsters[102].update(id=102, typeId=1001010, process=3)
|
||||
config = self.config() | {"explore_policy": {"enabled": True, "reserve_ti": 21,
|
||||
"teams": {"800": {"enabled": True, "area": "1", "monsters": [900, 101, 102]}}}}
|
||||
exported = portable_config(config, snapshot)
|
||||
text = json.dumps(exported)
|
||||
self.assertNotIn('"800"', text)
|
||||
self.assertNotIn('"900"', text)
|
||||
snapshot.raw["exploreTeams"] = [{"id": 90, "status": 0}, {"id": 80, "status": 0}]
|
||||
for mon in snapshot.raw["monsters"]:
|
||||
mon["process"] = 2
|
||||
for index, mid in enumerate((901, 902, 903), 1):
|
||||
mon = copy.deepcopy(snapshot.monsters[900])
|
||||
mon.update(id=mid, process=3)
|
||||
snapshot.raw["monsters"].append(mon)
|
||||
snapshot.monsters[mid] = mon
|
||||
imported = import_config(exported, snapshot)
|
||||
self.assertEqual(imported["explore_policy"]["teams"]["80"]["monsters"], [901, 902, 903])
|
||||
self.assertFalse(imported["explore_policy"]["enabled"])
|
||||
self.assertNotIn("800", imported["explore_policy"]["teams"])
|
||||
|
||||
def test_invalid_bundle_rejected_before_applying(self):
|
||||
exported = portable_config(self.config())
|
||||
for value in (exported | {"schema": 100}, exported | {"interval": 0},
|
||||
@@ -98,11 +125,23 @@ class StrategyGuiTests(unittest.TestCase):
|
||||
self.assertEqual(window.engine.sweep_policy.keep_stamina, 22)
|
||||
self.assertEqual(window.engine.daily_policy.selected, ["mail"])
|
||||
self.assertEqual(window.interval.currentData(), 120)
|
||||
self.assertLess(window.tabs.indexOf(window.map_page), window.tabs.indexOf(window.analysis_page))
|
||||
self.assertEqual(window.tabs.indexOf(window.analysis_page) - window.tabs.indexOf(window.map_page), 1)
|
||||
window.quest_money.setValue(42)
|
||||
window.gift_liked_only.setChecked(False)
|
||||
QTest.qWait(400)
|
||||
self.assertEqual(window.engine.quest_policy.max_money, 42)
|
||||
self.assertFalse(window.engine.policy.gift_liked_only)
|
||||
window.monster_breakthrough_changed("900", True, 6)
|
||||
window._exploration_policy = window.read_explore_policy()
|
||||
window._exploration_policy.enabled = True
|
||||
window._exploration_policy.reserve_ti = 9
|
||||
window._save_exploration_policy()
|
||||
QTest.qWait(400)
|
||||
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["policy"]["breakthrough_targets"], {"900": 6})
|
||||
self.assertTrue(saved["explore_policy"]["enabled"])
|
||||
self.assertEqual(saved["explore_policy"]["reserve_ti"], 9)
|
||||
with patch("ranch_assistant.gui.W.QFileDialog.getSaveFileName", return_value=(str(path), "")):
|
||||
window.export_policies()
|
||||
exported = json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import copy
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.breakthrough import POTENTIAL_PATH
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.exploration import ExplorePolicy
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
def raw(catalog):
|
||||
value = {"master": {"id": 1, "ti": 100, "money": 0, "ke": 0},
|
||||
"monsters": [{"id": mid, "typeId": 1001010, "process": 3, "mode": 2, "level": 10,
|
||||
"potentialLevel": 1, "pAtk": 2, "pDef": 8, "pHp": 105, "pDex": 1} for mid in (900, 901, 902)],
|
||||
"items": [{"id": 600, "typeId": 30058, "num": 100}], "stacks": [], "rooms": [], "teams": [],
|
||||
"currentTasks": [], "history": {"passTask": {"1001008": True}, "passStage": {"0109": {"1": True}}},
|
||||
"activityHistory": {}, "monsterAttributes": [],
|
||||
"exploreTeams": [{"id": 77, "status": 0, "monsters": [], "area": "", "endTime": 0}]}
|
||||
return value
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, value):
|
||||
self.value, self.calls = value, []
|
||||
self.response = {"resCode": 0}
|
||||
|
||||
def snapshot(self):
|
||||
return Snapshot(copy.deepcopy(self.value))
|
||||
|
||||
def call(self, path, payload):
|
||||
self.calls.append((path, payload))
|
||||
if isinstance(self.response, Exception):
|
||||
raise self.response
|
||||
return copy.deepcopy(self.response)
|
||||
|
||||
|
||||
class RanchAutomationIntegrationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def engine(self, folder, value=None):
|
||||
client = FakeClient(value or raw(self.catalog))
|
||||
engine = Engine(self.catalog, client, folder / "budget.json")
|
||||
engine.master_sync.settle = lambda *args: None
|
||||
engine.settle_pending_growth = lambda *args, **kwargs: False
|
||||
return engine, client
|
||||
|
||||
def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
engine.policy = Policy(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
engine.poll()
|
||||
self.assertEqual([path for path, _ in client.calls], [POTENTIAL_PATH])
|
||||
self.assertEqual(client.calls[0][1]["itemId"], 600)
|
||||
self.assertIsNotNone(engine._breakthrough_pending)
|
||||
# An acknowledged response with an unchanged snapshot cannot repeat.
|
||||
engine.poll()
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
client.value["monsters"][0]["pAtk"] += 1
|
||||
client.value["monsters"][0]["pDef"] -= 1
|
||||
engine.auto = True
|
||||
engine.poll()
|
||||
self.assertEqual(len(client.calls), 2)
|
||||
restored, _ = self.engine(folder, client.value)
|
||||
self.assertEqual(restored._breakthrough_pending["role_id"], "1")
|
||||
self.assertTrue(restored._breakthrough_pending["uncertain"])
|
||||
|
||||
def test_stop_during_snapshot_and_pending_block_every_new_write(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
engine.policy = Policy(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
read = client.snapshot
|
||||
def stopped():
|
||||
engine.auto = False
|
||||
return read()
|
||||
client.snapshot = stopped
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
engine, client = self.engine(folder)
|
||||
engine._breakthrough_pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "待核对"}
|
||||
engine.policy = Policy(enabled=True, dispatch=True, egg_rules={"1001010": {"enabled": True, "action": "sell"}})
|
||||
engine.auto = True
|
||||
_, plans, _ = engine.poll()
|
||||
self.assertEqual((client.calls, plans), ([], []))
|
||||
|
||||
def test_pre_dispatch_persistence_failure_never_sends(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
engine.policy = Policy(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
engine.automation_state_path = folder / "missing" / "state.json"
|
||||
original = engine._save_automation_state
|
||||
def fail():
|
||||
original()
|
||||
raise OSError("synthetic disk failure")
|
||||
engine._save_automation_state = fail
|
||||
with self.assertRaises(OSError):
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertFalse(engine.auto)
|
||||
|
||||
def test_locked_exploration_is_diagnostic_and_does_not_block_ranch(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
client.value["history"]["passTask"] = {}
|
||||
client.value["monsters"].append({"id": 101, "typeId": 1001010, "process": 3, "mode": 2, "level": 1})
|
||||
for stat in ("atk", "def", "hp", "dex"):
|
||||
client.value["monsters"][-1]["g" + stat.capitalize()] = self.catalog.monster(1001010)[stat + "_grow_min"]
|
||||
engine.policy = Policy(enabled=True, dispatch=True, fill=False, collect=False,
|
||||
egg_rules={"1001010": {"enabled": True, "action": "sell", "keep_count": 0}})
|
||||
engine.planner.managed.add(101)
|
||||
engine.explore_policy = ExplorePolicy(True)
|
||||
engine.auto = True
|
||||
_, plans, _ = engine.poll()
|
||||
self.assertEqual([path for path, _ in client.calls], ["monsterService/monsterSell"])
|
||||
self.assertTrue(any(action.kind == "explore_blocked" and "探险功能尚未解锁" in action.description for action in plans))
|
||||
self.assertFalse(any(action.kind == "explore_start" for action in plans))
|
||||
|
||||
def test_unknown_result_survives_restart_and_owner_mismatch_cannot_confirm(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
engine.policy = Policy(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
client.response = TimeoutError("synthetic lost reply")
|
||||
with self.assertRaises(TimeoutError):
|
||||
engine.poll()
|
||||
other = copy.deepcopy(client.value)
|
||||
other["master"]["id"] = 2
|
||||
other["monsters"][0]["pAtk"] += 1
|
||||
restored, other_client = self.engine(folder, other)
|
||||
restored.policy = Policy(breakthrough_targets={"900": 1})
|
||||
restored.auto = True
|
||||
restored.poll()
|
||||
self.assertEqual(other_client.calls, [])
|
||||
self.assertEqual(restored._breakthrough_pending["role_id"], "1")
|
||||
|
||||
def test_stop_after_durable_prepare_before_dispatch_rolls_back_without_write(self):
|
||||
with workspace_temp() as folder:
|
||||
for explore in (False, True):
|
||||
engine, client = self.engine(folder)
|
||||
if 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(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
save = engine._save_automation_state
|
||||
def stop_after_save():
|
||||
save()
|
||||
engine.cancel_progression()
|
||||
engine._save_automation_state = stop_after_save
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
self.assertIsNone(engine.explore_planner.pending(engine.snapshot))
|
||||
|
||||
def test_corrupt_state_preserves_barrier_and_file(self):
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "automation_state.json"
|
||||
path.write_text('{"version":0,"breakthrough":{}}', encoding="utf-8")
|
||||
engine, client = self.engine(folder)
|
||||
engine.policy = Policy(breakthrough_targets={"900": 1})
|
||||
engine.auto = True
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertEqual(path.read_text(encoding="utf-8"), '{"version":0,"breakthrough":{}}')
|
||||
|
||||
def test_explore_executes_then_reconciles_and_pending_is_not_rolled_back(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
engine.explore_policy = ExplorePolicy(True, {"77": {"enabled": True, "area": "1", "monsters": []}}, 0)
|
||||
engine.auto = True
|
||||
area = next(row for row in engine.explore_planner.areas.values() if row["id"] == "1")
|
||||
client.value["history"]["passStage"] = {area["passStage"]: {"1": True}}
|
||||
client.value["monsters"][0]["level"] = 60
|
||||
engine.poll()
|
||||
self.assertEqual([call[0] for call in client.calls], ["exploreService/start"])
|
||||
self.assertIsNotNone(engine.explore_planner.pending(engine.snapshot))
|
||||
engine.poll()
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
action = engine.explore_planner.pending(engine.snapshot)
|
||||
team = client.value["exploreTeams"][0]
|
||||
team.update(status=1, area="1", monsters=action["payload"]["monsters"], endTime=9999999999999)
|
||||
engine.poll()
|
||||
self.assertIsNone(engine.explore_planner.pending(engine.snapshot))
|
||||
self.assertEqual(json.loads((folder / "automation_state.json").read_text(encoding="utf-8"))["version"], 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -37,8 +37,8 @@ class RanchTreeTests(unittest.TestCase):
|
||||
snapshot.raw["monsters"].append(snapshot.monsters[900] | {"id": 901, "roomId": 2})
|
||||
return catalog, snapshot
|
||||
|
||||
def render(self, tree, snapshot, feeds=None, gifts=None):
|
||||
tree.set_data(snapshot, monster_rows(tree.catalog, snapshot, set()), feeds or {}, gifts or {})
|
||||
def render(self, tree, snapshot, feeds=None, gifts=None, breakthroughs=None):
|
||||
tree.set_data(snapshot, monster_rows(tree.catalog, snapshot, set()), feeds or {}, gifts or {}, breakthroughs or {})
|
||||
self.drain(tree)
|
||||
|
||||
def test_ranch_headers_children_and_refresh_preserve_controls_and_collapse(self):
|
||||
@@ -69,6 +69,16 @@ class RanchTreeTests(unittest.TestCase):
|
||||
self.assertFalse(tree.group_items["room:1"].isExpanded())
|
||||
self.assertEqual(tree.selected_monster_ids(), [900])
|
||||
self.assertTrue(item.text(15).startswith("30 /"))
|
||||
self.assertEqual(tree.columnCount(), 23)
|
||||
self.assertEqual(tree.headerItem().text(17), "赠礼")
|
||||
self.assertEqual(tree.headerItem().text(18), "赠礼优先级")
|
||||
self.assertEqual(tree.headerItem().text(10), "潜能阶段")
|
||||
self.assertEqual(tree.headerItem().text(21), "同种突破")
|
||||
self.assertEqual(tree.headerItem().text(22), "突破经验")
|
||||
self.assertEqual(item.text(21), "0 / 4")
|
||||
self.render(tree, updated, {"900": 2}, {"900": 3}, {"900": 7})
|
||||
self.assertTrue(tree.itemWidget(item, 19).isChecked())
|
||||
self.assertEqual(tree.itemWidget(item, 20).value(), 7)
|
||||
finally:
|
||||
tree.row_batch.stop()
|
||||
tree.close()
|
||||
@@ -133,6 +143,10 @@ class RanchTreeTests(unittest.TestCase):
|
||||
tree.itemWidget(item, 18).setValue(5)
|
||||
self.assertEqual(window.read_policy().feed_targets, {"900": 4})
|
||||
self.assertEqual(window.read_policy().gift_targets, {"900": 5})
|
||||
tree.itemWidget(item, 19).setChecked(True)
|
||||
tree.itemWidget(item, 20).setValue(6)
|
||||
self.assertEqual(window.read_policy().breakthrough_targets, {"900": 6})
|
||||
self.assertTrue(window.read_policy().gift_enabled)
|
||||
tree.setCurrentItem(item)
|
||||
with patch("PySide6.QtWidgets.QMenu.popup"):
|
||||
window.page_menu(tree.viewport(), C.QPoint(-1, -1), window.monster_page)
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
import unittest
|
||||
from dataclasses import asdict
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.cultivation import quality_rank
|
||||
from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
|
||||
|
||||
|
||||
def graded_monster(catalog, mid, grades, *, level=10, species=1001010, process=3, **values):
|
||||
row = catalog.monster(species)
|
||||
mon = {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
|
||||
"feel": 0, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0, **values}
|
||||
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
|
||||
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
|
||||
return mon
|
||||
|
||||
|
||||
class RanchRetentionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
room_type = next(iter(self.catalog.data["room_info"]))
|
||||
self.catalog.data["room_info"][room_type]["maxNum"] = 10
|
||||
self.snapshot = Snapshot({"master": {"id": 1}, "monsters": [], "teams": [], "stacks": [],
|
||||
"items": [], "rooms": [{"id": 1, "typeId": int(room_type)}], "history": {}, "activityHistory": {}})
|
||||
self.planner = Planner(self.catalog)
|
||||
|
||||
def policy(self, action="sell", count=1, **values):
|
||||
values.setdefault("protect_star", 6)
|
||||
return Policy(manual_eggs=True, fill=False, protect_quality=6, keep_better_quality=True,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action=action, keep_count=count))}, **values)
|
||||
|
||||
def plan(self, rows, policy=None, managed=None):
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update(managed if managed is not None else [row["id"] for row in rows])
|
||||
self.planner.cultivation.choices["1001010"] = 1
|
||||
self.planner.cultivation.signature = None
|
||||
return self.planner.plan(self.snapshot, policy or self.policy())
|
||||
|
||||
def test_quality_uses_s_then_a_then_b_before_normalized_growth(self):
|
||||
aasa, ssas = graded_monster(self.catalog, 1, "AASA", level=50), graded_monster(self.catalog, 2, "SSAS")
|
||||
self.assertLess(quality_rank(self.catalog, aasa), quality_rank(self.catalog, ssas))
|
||||
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
|
||||
quality_rank(self.catalog, graded_monster(self.catalog, 4, "BBAA")))
|
||||
self.assertFalse(any(a.kind == "sell" for a in self.plan([aasa, ssas])))
|
||||
reason = self.planner.protection_reason(ssas, self.snapshot, self.policy())
|
||||
self.assertIn("SSAS", reason)
|
||||
self.assertIn("S项3", reason)
|
||||
|
||||
def test_quota_zero_one_two_apply_to_every_enabled_action(self):
|
||||
for action in ("sell", "feed", "keep"):
|
||||
for quota, disposed in ((0, 3), (1, 2), (2, 1)):
|
||||
with self.subTest(action=action, quota=quota):
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", tpLevel=4) for mid in (1, 2, 3)]
|
||||
if action == "feed":
|
||||
target = graded_monster(self.catalog, 99, "SSSS", species=1002010,
|
||||
level=1, exp=0, potentialLevel=2, tpLevel=4, tpExp=33)
|
||||
rows.append(target)
|
||||
elif action == "keep":
|
||||
disposed = 0
|
||||
policy = self.policy(action=action, count=quota,
|
||||
feed_targets={"99": 1} if action == "feed" else {})
|
||||
actions = self.plan(rows, policy)
|
||||
sold = [mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]]
|
||||
fed = [mid for a in actions if a.kind == "feed" for mid in a.payload["foods"] if mid != 99]
|
||||
self.assertEqual(len(sold + fed), disposed)
|
||||
for target in (a.payload["targetId"] for a in actions if a.kind == "feed"):
|
||||
self.assertNotIn(target, fed)
|
||||
|
||||
def test_same_batch_and_locked_ranch_monsters_share_one_quota(self):
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", roomId=mid) for mid in (1, 2)]
|
||||
rows += [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (3, 4)]
|
||||
for row in rows[:2]:
|
||||
row["lock"] = 1
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
|
||||
|
||||
def test_incubator_batch_fills_quota_and_keeps_same_ids_after_collection(self):
|
||||
for quota in (2, 3):
|
||||
with self.subTest(quota=quota):
|
||||
self.setUp()
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2, 3)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, set(range(1, quota + 1)))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
for row in rows:
|
||||
row.update(process=3, roomId=1)
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
sold = {mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]}
|
||||
self.assertEqual(sold, set(range(1, 4)) - collected)
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
self.assertTrue(all(mid not in collected for a in actions for mid in a.payload.get("foods", [])))
|
||||
|
||||
def test_ranch_and_incubator_share_quota_before_and_after_collection(self):
|
||||
ranch = graded_monster(self.catalog, 1, "CCCC")
|
||||
rows = [ranch] + [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (2, 3, 4)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3, 4)]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, {2})
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
for row in rows[1:]:
|
||||
row.update(process=3, roomId=1)
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
|
||||
|
||||
def test_initial_incubator_quota_prefers_best_quality_last_in_raw(self):
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2)]
|
||||
rows.append(graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None))
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, {1, 3})
|
||||
self.assertEqual(self.planner.retained, {1, 3})
|
||||
|
||||
def test_incubator_quota_quality_prevents_equal_quality_extra_retention(self):
|
||||
rows = [graded_monster(self.catalog, 1, "AASA")]
|
||||
rows += [graded_monster(self.catalog, mid, "SSAS", process=2, roomId=None) for mid in (2, 3)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3)]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
collected = [mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]]
|
||||
self.assertEqual(collected, [2])
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
|
||||
|
||||
def test_zero_quota_still_protects_better_incubator_above_locked_ranch(self):
|
||||
locked = graded_monster(self.catalog, 1, "AASA", lock=1)
|
||||
better = graded_monster(self.catalog, 2, "SSAS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": 2, "position": 0, "monsterId": 2}]
|
||||
actions = self.plan([locked, better], self.policy(count=0))
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [2])
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
|
||||
|
||||
def test_three_collection_rounds_keep_only_best_ssas_above_locked_aasa(self):
|
||||
locked = graded_monster(self.catalog, 1, "AASA", level=50, lock=1)
|
||||
first = graded_monster(self.catalog, 2, "SSAS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 2}]
|
||||
policy = self.policy()
|
||||
self.assertEqual(self.plan([locked, first], policy)[0].kind, "collect")
|
||||
first.update(process=3, roomId=1)
|
||||
self.assertFalse(any(a.kind == "sell" for a in self.plan([locked, first], policy)))
|
||||
second = graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"][0]["monsterId"] = 3
|
||||
self.assertEqual([a.payload["monsterIds"] for a in self.plan([locked, first, second], policy)
|
||||
if a.kind == "sell"], [[3]])
|
||||
second.update(process=3, roomId=1)
|
||||
actions = self.plan([locked, first, second], policy)
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3])
|
||||
self.assertTrue(all(2 not in a.payload.get("monsterIds", []) and 2 not in a.payload.get("foods", []) for a in actions))
|
||||
|
||||
def test_same_species_tp_batch_ignores_potential_cap_and_never_swaps_representative(self):
|
||||
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=5, potentialLevel=1)
|
||||
rows = [target, graded_monster(self.catalog, 2, "CCCC"), graded_monster(self.catalog, 3, "CCCC")]
|
||||
self.assertEqual(self.plan(rows, self.policy(action="feed"))[0].payload, {"targetId": 1, "foods": [2, 3]})
|
||||
target.update(tpLevel=4, tpExp=self.catalog.data["game_setting"]["tpExp"]["1"]["4"])
|
||||
self.assertFalse(any(a.kind == "feed" and 1 in a.payload["foods"] for a in self.plan(rows, self.policy(action="feed"))))
|
||||
|
||||
def test_normal_cap_still_allows_tp_food_until_cumulative_exp_is_full(self):
|
||||
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=6,
|
||||
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
|
||||
food = graded_monster(self.catalog, 2, "CCCC")
|
||||
self.assertEqual(self.plan([target, food], self.policy(action="feed"))[0].payload["foods"], [2])
|
||||
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"] - 1
|
||||
self.assertEqual(self.plan([target, food], self.policy(action="feed"))[0].payload["foods"], [2])
|
||||
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"]
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
|
||||
|
||||
def test_unmanaged_protected_and_other_feed_targets_are_not_materials(self):
|
||||
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
|
||||
other = graded_monster(self.catalog, 2, "SSSA", tpLevel=0, tpExp=0)
|
||||
food = graded_monster(self.catalog, 3, "SSSB")
|
||||
action = self.plan([target, other, food], self.policy(action="feed", count=0), managed=[3])[0]
|
||||
self.assertEqual(action.payload, {"targetId": 1, "foods": [3]})
|
||||
self.planner.managed.discard(2)
|
||||
other["lock"] = 1
|
||||
action = self.plan([target, other, food], self.policy(action="feed", count=0))[0]
|
||||
self.assertEqual(action.payload["foods"], [3])
|
||||
|
||||
def test_direct_protected_and_disposition_prepare_quota_before_first_call(self):
|
||||
rows = [graded_monster(self.catalog, 1, "CCCC"), graded_monster(self.catalog, 2, "CCCC")]
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
policy = self.policy()
|
||||
self.planner.cultivation.choices["1001010"] = 1
|
||||
self.planner.cultivation.signature = None
|
||||
self.planner.managed.update((1, 2))
|
||||
with patch.object(self.planner, "prepare_retention", wraps=self.planner.prepare_retention) as prepare:
|
||||
protected = [self.planner.protected(row, self.snapshot, policy) for row in rows]
|
||||
self.assertEqual(protected.count(True), 1)
|
||||
self.assertEqual(self.planner.disposition(rows[0], self.snapshot, policy), "keep" if protected[0] else "sell")
|
||||
self.assertEqual(self.planner.disposition(rows[1], self.snapshot, policy), "keep" if protected[1] else "sell")
|
||||
self.assertEqual(prepare.call_count, 1)
|
||||
|
||||
def test_missing_tp_fields_pause_special_feed_but_not_legacy_experience(self):
|
||||
target = graded_monster(self.catalog, 1, "SCCC", level=10,
|
||||
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
|
||||
food = graded_monster(self.catalog, 2, "CCCC")
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
|
||||
target.update(tpLevel=0, tpExp=0, level=1, exp=0)
|
||||
policy = Policy(strategy="experience", feed_target=1, fill=False, protect_star=6, protect_quality=6)
|
||||
self.assertEqual(self.plan([target, food], policy)[0].payload, {"targetId": 1, "foods": [2]})
|
||||
|
||||
def test_special_food_tp_count_matches_client_rules(self):
|
||||
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
|
||||
settings = self.catalog.data["game_setting"]
|
||||
special = graded_monster(self.catalog, 2, "CCCC", species=int(settings["specialFood"]))
|
||||
special14 = graded_monster(self.catalog, 3, "CCCC", species=int(settings["specialFood14"]))
|
||||
self.assertEqual((self.planner.tp_food_value(target, special), self.planner.tp_food_value(target, special14)), (1, 1))
|
||||
five_star = next(int(key) for key, row in self.catalog.monsters.items()
|
||||
if int(row.get("star") or 0) == 5 and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex")))
|
||||
target = graded_monster(self.catalog, 1, "SSSS", species=five_star, tpLevel=0, tpExp=0)
|
||||
self.assertEqual((self.planner.tp_food_value(target, special), self.planner.tp_food_value(target, special14)), (1, 0))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -48,6 +48,13 @@ class RuleEditingTests(unittest.TestCase):
|
||||
self.assertEqual([table.cellWidget(i, 5).currentText() for i in range(3)], ["保留", "喂养", "派遣"])
|
||||
table.sortItems(3, C.Qt.SortOrder.DescendingOrder)
|
||||
self.assertEqual([table.cellWidget(i, 3).isChecked() for i in range(3)], [True, True, False])
|
||||
table.sortItems(15, C.Qt.SortOrder.AscendingOrder)
|
||||
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
|
||||
table.cellWidget(0, 15).setValue(2)
|
||||
self.assertEqual(table.rules[key]["keep_count"], 2)
|
||||
self.assertTrue(table.cellWidget(0, 15).alignment() & C.Qt.AlignmentFlag.AlignHCenter)
|
||||
self.assertEqual(table.horizontalHeaderItem(14).text(), "物品ID")
|
||||
self.assertEqual(table.horizontalHeaderItem(15).text(), "牧场保留")
|
||||
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
|
||||
table.cellWidget(0, 3).setChecked(False)
|
||||
self.assertFalse(table.rules[key]["enabled"])
|
||||
|
||||
@@ -44,7 +44,7 @@ class ManualRuleTests(unittest.TestCase):
|
||||
secondary = dict(primary, id=901, level=9, potentialLevel=1)
|
||||
self.snapshot.raw["monsters"].append(secondary)
|
||||
policy = Policy(manual_eggs=True, strategy="gold", fill=False, protect_star=6, protect_quality=5,
|
||||
egg_rules={str(food["typeId"]): self.rule(action="feed")}, feed_targets={"900": 1, "901": 2})
|
||||
egg_rules={str(food["typeId"]): self.rule(action="feed", keep_count=0)}, feed_targets={"900": 1, "901": 2})
|
||||
action = self.planner.plan(self.snapshot, policy)[0]
|
||||
self.assertEqual(action.kind, "feed")
|
||||
self.assertEqual(action.payload["targetId"], 901)
|
||||
@@ -83,6 +83,19 @@ class ManualRuleTests(unittest.TestCase):
|
||||
with self.assertRaises(ValueError):
|
||||
Policy(egg_rules={"1001010": {"refill_below": 5, "refill_target": 2}})
|
||||
|
||||
def test_quota_and_breakthrough_targets_validate_instead_of_silently_dropping_bad_values(self):
|
||||
self.assertEqual(EggRule().keep_count, 1)
|
||||
self.assertEqual(EggRule(keep_count="2").keep_count, 2)
|
||||
for value in (True, 1.0, 1.5, "1.0", " 1", "+1", -1, 1001, None):
|
||||
with self.subTest(keep_count=value), self.assertRaises(ValueError):
|
||||
EggRule(keep_count=value)
|
||||
self.assertEqual(Policy(breakthrough_targets={"900": 2}).breakthrough_targets, {"900": 2})
|
||||
self.assertTrue(self.planner.protected(self.snapshot.monsters[900], self.snapshot,
|
||||
Policy(protect_star=6, protect_quality=6, breakthrough_targets={"900": 2})))
|
||||
for targets in ([], {"0": 1}, {"900": 0}, {"900": 1000}, {"900": True}, {"900": 1.5}, {"x": 1}):
|
||||
with self.subTest(targets=targets), self.assertRaises(ValueError):
|
||||
Policy(breakthrough_targets=targets)
|
||||
|
||||
|
||||
class ManagementTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
|
||||
Reference in New Issue
Block a user