fix: keep automatic cultivation on one stable primary per species

This commit is contained in:
AttilaNet
2026-11-13 08:51:03 +08:00
parent 01ad2e3ab9
commit 4fbe895999
35 changed files with 2069 additions and 322 deletions
+9 -4
View File
@@ -252,6 +252,10 @@ class AutomationTests(unittest.TestCase):
def test_encrypted_http_buy_hatch_mature_dispatch_and_balance(self):
state = copy.deepcopy(self.snapshot.raw)
state["stacks"][0]["monsterId"] = -1
state["monsters"] = [{"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
"level": 20, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): self.catalog.monster(1001010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")}}]
initial_money = state["master"]["money"]
calls, catalog = [], self.catalog
with workspace_temp() as folder:
@@ -274,13 +278,13 @@ class AutomationTests(unittest.TestCase):
mon = {"id": 101, "typeId": 1001010, "mode": 0, "process": 2,
"timeStart": time.time() * 1000, "level": 1}
mon.update({"g" + s.capitalize(): catalog.monster(1001010)[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
state["monsters"] = [mon]
state["monsters"].append(mon)
state["stacks"][0]["monsterId"] = 101
elif name == "stackCheckProcess":
state["monsters"][0]["mode"] = 2
next(mon for mon in state["monsters"] if mon["id"] == 101)["mode"] = 2
elif name == "monsterSell":
assert body["monsterIds"] == [101]
state["monsters"] = []
state["monsters"] = [mon for mon in state["monsters"] if mon["id"] != 101]
state["stacks"][0]["monsterId"] = -1
state["master"]["money"] += 150
elif name != "masterQueryDetail":
@@ -310,10 +314,11 @@ class AutomationTests(unittest.TestCase):
self.assertEqual(state["master"]["money"], initial_money - 1000)
self.assertIn("共 11 枚", engine.last_draw)
engine.poll() # Hatch, re-read, wait.
state["monsters"][0]["timeStart"] = (time.time() - 601) * 1000
next(mon for mon in state["monsters"] if mon["id"] == 101)["timeStart"] = (time.time() - 601) * 1000
snapshot, _, _ = engine.poll() # Settle growth, dispatch, re-read.
self.assertEqual(snapshot.raw["master"]["money"], initial_money - 850)
self.assertEqual(snapshot.raw["stacks"][0]["monsterId"], -1)
self.assertEqual(set(snapshot.monsters), {900})
self.assertEqual([n for n, _ in calls if n != "masterQueryDetail"],
["gachaGetEggs", "stackAddMonster", "stackCheckProcess", "monsterSell"])
engine.poll()
+10 -5
View File
@@ -36,12 +36,17 @@ class BatchFeedingTests(unittest.TestCase):
target["level"] = 20
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
def test_full_first_target_advances_to_next_priority(self):
def test_full_primary_skips_duplicate_and_advances_to_different_species_priority(self):
first = self.snapshot.monsters[900]
first.update(level=20, potentialLevel=2)
self.snapshot.raw["monsters"].append(copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0})
self.policy.feed_targets = {"900": 1, "901": 2}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 901)
self.snapshot.raw["monsters"].extend([
copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0},
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
])
self.policy.feed_targets = {"900": 1, "901": 2, "902": 3}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
del self.policy.feed_targets["902"]
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
def test_priority_target_uses_current_cap_instead_of_legacy_stop_level(self):
target = self.snapshot.monsters[900]
@@ -56,7 +61,7 @@ class BatchFeedingTests(unittest.TestCase):
first.update(level=19, potentialLevel=2, exp=self.catalog.data["monster_level"]["20"])
self.snapshot.raw["monsters"].extend([
copy.deepcopy(first) | {"id": 901, "potentialLevel": None},
copy.deepcopy(first) | {"id": 902, "level": 1, "exp": 0},
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
])
self.policy.feed_targets = {"902": 3, "901": 2, "900": 1}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
+5 -1
View File
@@ -117,8 +117,12 @@ class BreakthroughTests(unittest.TestCase):
def test_independent_targets_replace_feed_targets_and_empty_is_empty(self):
other = copy.deepcopy(self.snapshot.monsters[900])
other["id"] = 901
row = self.catalog.monster(1003010)
caps = self.catalog.data["potential_info"]["potential"][str(row["job"])][str(row["star"])]
other.update(id=901, typeId=1003010,
**{"p" + stat.capitalize(): caps[stat] for stat in ("atk", "def", "hp", "dex")})
self.snapshot.raw["monsters"].append(other)
self.assertEqual(self.planner.plan(self.snapshot, self.policy).payload["monId"], 900)
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={}))
+40 -16
View File
@@ -55,20 +55,33 @@ class CultivationTests(unittest.TestCase):
rows[1]["level"] = 12
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
def test_ties_are_chosen_once_persisted_and_do_not_leak_to_other_role(self):
def test_ties_preserve_older_ranch_member_across_refresh_restart_and_role_change(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1), monster(self.catalog, 2)]
with workspace_temp() as folder:
path = folder / "choices.json"
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[-1]) as draw:
selector = CultivationSelector(self.catalog, path)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
selector.select(self.snapshot)
self.assertEqual(draw.call_count, 1)
with patch("ranch_assistant.cultivation.random.choice", side_effect=AssertionError("Re-selected an exact tie")):
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
selector = CultivationSelector(self.catalog, path)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
self.snapshot.raw["monsters"].reverse()
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
self.snapshot.raw["master"]["id"] += 1
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[0]):
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
self.snapshot.raw["monsters"] = [monster(self.catalog, 12), monster(self.catalog, 11)]
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 11)
def test_present_non_ranch_primary_holds_but_confirmed_absence_promotes_once(self):
primary, duplicate = monster(self.catalog, 1, level=20), monster(self.catalog, 2, level=10)
self.snapshot.raw["monsters"] = [primary, duplicate]
with workspace_temp() as folder:
path = folder / "choices.json"
selector = CultivationSelector(self.catalog, path)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
primary["process"] = 2
self.assertNotIn("1001010", selector.select(self.snapshot))
self.assertEqual(selector.choices["1001010"], 1)
self.assertNotIn("1001010", CultivationSelector(self.catalog, path).select(self.snapshot))
self.snapshot.raw["monsters"].remove(primary)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
def test_cached_selection_uses_current_cooldown_and_bond_cap(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1)]
@@ -80,17 +93,24 @@ class CultivationTests(unittest.TestCase):
self.assertIs(chosen, updated.raw["monsters"][0])
self.assertEqual((chosen["giftTime"], chosen["entangleLevel"]), (123456789, 2))
def test_better_growth_is_kept_independently_of_four_s_and_equal_or_worse_is_not(self):
def test_better_backup_is_mandatory_despite_legacy_flags_and_equal_or_worse_is_not(self):
representative = monster(self.catalog, 1, level=50, feel=90, scale=.3)
hatched = monster(self.catalog, 2, level=1, scale=.4, process=2)
self.snapshot.raw["monsters"] = [representative, hatched]
planner = Planner(self.catalog)
policy = Policy(strategy="gold", protect_star=6, protect_quality=6, keep_better_quality=True)
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
self.assertIn("同种培养代表 #1", planner.protection_reason(hatched, self.snapshot, policy))
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
gift_auto_representative=False, keep_better_quality=False,
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=1))})
for keep_better in (False, True):
for keep_count in (0, 1, 4):
with self.subTest(keep_better=keep_better, keep_count=keep_count):
policy.keep_better_quality = keep_better
policy.egg_rules["1001010"]["keep_count"] = keep_count
self.assertEqual(planner.disposition(representative, self.snapshot, policy), "keep")
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
self.assertEqual(planner.retained, {1, 2})
policy.keep_better_quality = False
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "sell")
policy.keep_better_quality = True
policy.egg_rules["1001010"]["keep_count"] = 1
for scale in (.3, .2):
self.snapshot.raw["monsters"][1] = monster(self.catalog, 2, scale=scale, process=2)
self.assertEqual(planner.disposition(self.snapshot.monsters[2], self.snapshot, policy), "sell")
@@ -146,6 +166,10 @@ class CultivationTests(unittest.TestCase):
self.assertAlmostEqual(growth_score(self.catalog, mon), .5, places=3)
mon["gHp"] = self.catalog.monster(1001010)["hp_grow_max"]
self.assertAlmostEqual(growth_score(self.catalog, mon), .625, places=3)
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 2, "SCCC")),
quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")))
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 4, "SSBB")),
quality_rank(self.catalog, graded_monster(self.catalog, 5, "SSAC")))
class CultivationGuiTests(unittest.TestCase):
@@ -9,6 +9,7 @@ class GiftTargetSelectionTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
self.snapshot = gift_snapshot(self.catalog)
self.snapshot.raw["monsters"][0]["level"] += 1
self.planner = GiftPlanner(self.catalog)
self.representative = next(iter(self.planner.cultivation.select(self.snapshot).values()))
self.manual_target = next(mon for mon in self.snapshot.raw["monsters"]
@@ -27,13 +28,20 @@ class GiftTargetSelectionTests(unittest.TestCase):
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
[self.representative["id"]])
def test_manual_mode_uses_gift_targets_instead_of_representative(self):
def test_manual_mode_requires_the_primary_to_be_explicitly_checked(self):
policy = self.policy()
self.assertEqual(self.planner.candidates(self.snapshot, policy), [])
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
policy.gift_targets[str(self.representative["id"])] = 2
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.snapshot, policy)],
[self.manual_target["id"]])
[self.representative["id"]])
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
[self.manual_target["id"]])
[self.representative["id"]])
self.representative["feel"] = self.catalog.max_feel(self.representative)
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
if __name__ == "__main__":
+9 -1
View File
@@ -63,19 +63,27 @@ class GiftTimingTests(unittest.TestCase):
def test_success_response_updates_each_monster_despite_stale_queries(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
client = GiftClient(self.catalog)
client.raw["monsters"][1].update(typeId=1002010,
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")})
engine = Engine(self.catalog, client)
engine.policy = gift_policy()
engine.auto = True
first, _, _ = engine.poll()
self.assertEqual(first.monsters[1]["feel"], 10)
self.assertEqual(first.monsters[1]["giftTime"], NOW)
engine.poll()
second, _, _ = engine.poll()
self.assertEqual(second.monsters[2]["feel"], 10)
self.assertEqual(second.monsters[2]["giftTime"], NOW)
engine.poll()
self.assertEqual([payload["monsterId"] for _, payload in client.calls], [1, 2])
def test_next_due_uses_earliest_eligible_cooldown_and_ignores_full_targets(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
snapshot = gift_snapshot(self.catalog)
snapshot.monsters[2].update(typeId=1002010,
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")})
snapshot.monsters[1]["giftTime"] = (NOW - 7200 + 120) * 1000
snapshot.monsters[2]["giftTime"] = (NOW - 7200 + 15) * 1000
planner = GiftPlanner(self.catalog)
+5 -1
View File
@@ -56,7 +56,7 @@ class GrowthClient:
def call(self, path, payload):
self.calls.append((path, payload))
if path == "monsterService/monsterSell":
self.raw["monsters"] = []
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in payload["monsterIds"]]
self.raw["stacks"][0]["monsterId"] = -1
return {"resCode": 0}
@@ -69,6 +69,10 @@ class GrowthTests(unittest.TestCase):
self.addCleanup(self.clock.stop)
def engine(self, client):
row = self.catalog.monster(1001010)
client.raw["monsters"].append({"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
"level": 20, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}})
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", keep_count=0))})
@@ -60,6 +60,7 @@ class HatchTimingTests(unittest.TestCase):
def test_fast_hatching_skips_other_actions_and_retains_vip_and_reserve_limits(self):
catalog = Catalog()
client = HatchClient(catalog)
client.value["monsters"].append(client.template | {"id": 900, "process": 3, "level": 20, "roomId": 1})
client.value["monsters"].append(client.template)
client.value["stacks"][0]["monsterId"] = client.template["id"]
engine = Engine(catalog, client)
@@ -0,0 +1,319 @@
"""Offline regressions for stable cultivation primaries and gift target consent."""
from copy import deepcopy
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
from ranch_assistant.gifts import GiftPlanner
from ranch_assistant.model import Catalog, Policy, Snapshot
NOW = 1_800_000_000
SPECIES = 1030010
MAIN = 949626937
STATS = ("atk", "def", "hp", "dex")
def monster(catalog, mid, grades="SASS", *, species=SPECIES, level=10, **values):
row = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"feel": 0, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0}
for stat, grade in zip(STATS, grades):
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .125, "B": .375, "A": .625, "S": .875}[grade]
return mon | values
def snapshot(*members, owner=101):
return Snapshot({"master": {"id": owner}, "monsters": list(members), "teams": [], "stacks": [],
"items": [{"id": 91, "typeId": 30005, "num": 10}], "rooms": [{"id": 1}, {"id": 8}]})
def policy(*, auto=False, targets=None, **values):
return Policy(gift_enabled=True, gift_auto_representative=auto, keep_better_quality=False,
gift_targets=targets or {}, gift_liked_only=False,
gift_items={"30005": {"enabled": True, "reserve": 2}}, **values)
class PrimarySelectionTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
def test_highest_level_locked_main_wins_across_rooms_and_incubation(self):
main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
rows = [monster(self.catalog, MAIN + 1, "SSSA", feel=99),
monster(self.catalog, MAIN + 2, "SSSS"), main,
monster(self.catalog, MAIN + 3, "SSSS", level=99, process=2)]
chosen = CultivationSelector(self.catalog).select(snapshot(*rows))
self.assertEqual(chosen, {str(SPECIES): main})
self.assertIs(chosen[str(SPECIES)], main)
def test_initial_selection_uses_level_then_feel_then_letter_grades(self):
low = monster(self.catalog, 1, "SSSS", level=9, feel=100)
no_feel = monster(self.catalog, 2, "SSSS")
high_average = monster(self.catalog, 3, "AAAA", feel=1)
more_s = monster(self.catalog, 4, "SCCC", feel=1)
self.assertGreater(growth_score(self.catalog, high_average), growth_score(self.catalog, more_s))
chosen = CultivationSelector(self.catalog).select(snapshot(low, no_feel, high_average, more_s))
self.assertEqual(chosen[str(SPECIES)]["id"], 4)
def normalized_catalog(self):
# Exact three-decimal values remove client rounding noise from equal-weight comparisons.
self.catalog.overrides[str(SPECIES)] = {
stat + suffix: value for stat, bounds in zip(STATS, ((1, 9), (10, 18), (100, 900), (2, 10)))
for suffix, value in zip(("_grow_min", "_grow_max"), bounds)}
def test_rank_weights_all_four_attributes_equally_without_positional_ties(self):
self.normalized_catalog()
selector = CultivationSelector(self.catalog)
ranks = [selector.rank(monster(self.catalog, index + 1, grades))
for index, grades in enumerate(("SCCC", "CSCC", "CCSC", "CCCS"))]
self.assertTrue(all(rank == ranks[0] for rank in ranks), ranks)
qualities = [quality_rank(self.catalog, monster(self.catalog, 1, grades))
for grades in ("SASS", "SSSA", "SSAS", "ASSS")]
self.assertTrue(all(rank == qualities[0] for rank in qualities), qualities)
def test_normalized_growth_gives_health_the_same_weight_as_other_stats(self):
self.normalized_catalog()
scores = []
for stat in STATS:
mon = monster(self.catalog, 1, "AAAA")
row = self.catalog.monster(SPECIES)
mon["g" + stat.capitalize()] = row[stat + "_grow_max"]
scores.append(growth_score(self.catalog, mon))
self.assertEqual(scores, [.71875] * 4)
def test_equal_s_counts_compare_all_attributes_instead_of_a_count_first(self):
self.normalized_catalog()
balanced = monster(self.catalog, 1, "SSBB")
weaker_average = monster(self.catalog, 2, "SSAC")
row = self.catalog.monster(SPECIES)
weaker_average["gDex"] = row["dex_grow_min"] + .1 * (row["dex_grow_max"] - row["dex_grow_min"])
self.assertEqual(self.catalog.quality(balanced).count(4), self.catalog.quality(weaker_average).count(4))
self.assertGreater(growth_score(self.catalog, balanced), growth_score(self.catalog, weaker_average))
self.assertGreater(quality_rank(self.catalog, balanced), quality_rank(self.catalog, weaker_average))
self.assertGreater(CultivationSelector(self.catalog).rank(balanced), CultivationSelector(self.catalog).rank(weaker_average))
def test_initial_exact_ties_always_choose_the_oldest_id(self):
rows = [monster(self.catalog, mid) for mid in (9, 2, 7)]
with patch("random.choice", side_effect=lambda members: max(members, key=lambda mon: mon["id"])):
for ordered in (rows, list(reversed(rows)), rows[1:] + rows[:1]):
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(*ordered))[str(SPECIES)]["id"], 2)
def test_persisted_same_level_primary_cannot_be_stolen_by_better_newborn(self):
main = monster(self.catalog, MAIN, "CCCC", level=1)
data = snapshot(main)
with TemporaryDirectory() as folder:
path = Path(folder) / "cultivation_choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
newborn = monster(self.catalog, MAIN + 1, "SSSS", level=1)
data.raw["monsters"] = [newborn, main]
self.assertGreater(selector.rank(newborn), selector.rank(main))
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], MAIN)
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], MAIN)
self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["choices"], {str(SPECIES): MAIN})
def test_same_level_feel_change_does_not_replace_an_established_primary(self):
main = monster(self.catalog, 9, "CCCC")
data = snapshot(main)
selector = CultivationSelector(self.catalog)
selector.select(data)
data.raw["monsters"] = [monster(self.catalog, 2, "SSSS", feel=99), main]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 9)
def test_a_strictly_higher_level_mature_monster_can_take_over(self):
main = monster(self.catalog, 1, "SSSS", feel=99)
other = monster(self.catalog, 2, "CCCC", level=9)
data = snapshot(main, other)
selector = CultivationSelector(self.catalog)
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 1)
other["level"] = 11
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
main["level"] = 11
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
def test_cache_rebinds_to_current_cooldown_cap_and_task_flags(self):
main = monster(self.catalog, 1)
data = snapshot(main)
selector = CultivationSelector(self.catalog)
selector.select(data)
fresh = Snapshot(deepcopy(data.raw))
fresh.monsters[1].update(giftTime=NOW, entangleLevel=2, inExploreTeam=1)
selected = selector.select(fresh)[str(SPECIES)]
self.assertIs(selected, fresh.monsters[1])
self.assertEqual((selected["giftTime"], selected["entangleLevel"], selected["inExploreTeam"]), (NOW, 2, 1))
def test_present_non_ranch_primary_never_promotes_a_backup(self):
main = monster(self.catalog, 1, level=20)
backup = monster(self.catalog, 2, "SSSS")
data = snapshot(main, backup)
with TemporaryDirectory() as folder:
path = Path(folder) / "choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
for process in (4, 2):
data.raw["monsters"] = [main | {"process": process}, backup]
self.assertEqual(selector.select(data), {})
self.assertEqual(CultivationSelector(self.catalog, path).select(data), {})
data.raw["monsters"] = [backup, main]
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 1)
def test_confirmed_removal_promotes_one_replacement_and_persists_it(self):
main = monster(self.catalog, 1, level=20)
backup = monster(self.catalog, 2, "AAAA")
data = snapshot(main, backup)
with TemporaryDirectory() as folder:
path = Path(folder) / "choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
data.raw["monsters"] = [main | {"process": 4}, backup]
self.assertEqual(selector.select(data), {})
data.raw["monsters"] = [backup]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
data.raw["monsters"].insert(0, monster(self.catalog, 3, "SSSS"))
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 2)
def test_empty_full_roster_clears_removed_choices_and_allows_a_new_first(self):
data = snapshot(monster(self.catalog, 1))
selector = CultivationSelector(self.catalog)
selector.select(data)
data.raw["monsters"] = []
self.assertEqual(selector.select(data), {})
self.assertEqual(selector.choices, {})
data.raw["monsters"] = [monster(self.catalog, 2)]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
def test_account_paths_and_owner_checks_isolate_prior_choices(self):
with TemporaryDirectory() as folder:
paths = [Path(folder) / account / "roles" / "101" / "choices.json" for account in ("a", "b")]
first, second = monster(self.catalog, 1), monster(self.catalog, 2)
for path, main in zip(paths, (first, second)):
CultivationSelector(self.catalog, path).select(snapshot(main))
for path, expected in zip(paths, (1, 2)):
self.assertEqual(CultivationSelector(self.catalog, path).select(snapshot(second, first))[str(SPECIES)]["id"], expected)
self.assertEqual(CultivationSelector(self.catalog, paths[1]).select(snapshot(second, first, owner=202))[str(SPECIES)]["id"], 1)
def test_unknown_quality_and_incubating_rows_are_not_mutated_or_promoted(self):
main = monster(self.catalog, 1, level=20, gHp=None)
young = monster(self.catalog, 3, "SSSS", level=99, process=2, mode=0)
data = snapshot(monster(self.catalog, 2, "SSSS"), young, main)
before = deepcopy(data.raw)
self.assertIsNone(quality_rank(self.catalog, main))
self.assertIsNone(quality_rank(self.catalog, young))
self.assertEqual(CultivationSelector(self.catalog).select(data)[str(SPECIES)]["id"], 1)
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(young)), {})
self.assertEqual(data.raw, before)
def test_species_variants_with_the_same_name_remain_separate_types(self):
variants = [monster(self.catalog, index + 1, species=species)
for index, species in enumerate((1030010, 1030012, 1030013, 1030014))]
chosen = CultivationSelector(self.catalog).select(snapshot(*variants))
self.assertEqual(set(chosen), {"1030010", "1030012", "1030013", "1030014"})
class PrimaryGiftTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
self.enterContext(patch("ranch_assistant.model.time.time", return_value=NOW))
self.main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
self.backup = monster(self.catalog, MAIN + 1, "SSSS")
self.equal_copy = monster(self.catalog, MAIN + 2, "SSSA")
self.other = monster(self.catalog, 30, "AAAA", species=1002010, level=15)
self.data = snapshot(self.backup, self.equal_copy, self.main, self.other)
self.planner = GiftPlanner(self.catalog)
def action_ids(self, selected_policy):
return [action.payload["monsterId"] for action in self.planner.plan(self.data, selected_policy)]
def test_only_checked_backups_never_authorize_the_unchecked_primary(self):
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.equal_copy["id"]): 2})
before = deepcopy(self.data.raw)
self.assertEqual(self.planner.candidates(self.data, selected_policy), [])
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.data.raw, before)
def test_manual_mode_intersects_primaries_and_keeps_multi_species_priorities(self):
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.other["id"]): 2,
str(self.main["id"]): 3, str(self.equal_copy["id"]): 4})
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.data, selected_policy)], [30, MAIN])
self.assertEqual(self.action_ids(selected_policy), [30, MAIN])
def test_auto_mode_selects_all_species_primaries_under_old_quality_flag(self):
selected_policy = policy(auto=True, targets={str(self.backup["id"]): 1})
self.assertFalse(selected_policy.keep_better_quality)
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
def test_full_cooling_or_busy_main_never_falls_back_in_either_mode(self):
for auto in (False, True):
for flags in ({"feel": self.catalog.max_feel(self.main)}, {"giftTime": NOW * 1000},
{"inExploreTeam": 1}, {"inBuild": 1}):
with self.subTest(auto=auto, flags=flags):
main = self.main | flags
self.data.raw["monsters"] = [self.backup, self.equal_copy, main, self.other]
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [30])
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], MAIN)
def test_active_exploration_team_without_an_individual_flag_has_no_backup_fallback(self):
self.data.raw["exploreTeams"] = [{"id": 7, "status": 1, "monsters": str(MAIN)}]
for auto in (False, True):
with self.subTest(auto=auto):
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [30])
def test_non_ranch_primary_stays_unselected_after_it_was_chosen(self):
selected_policy = policy(auto=True)
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
for process in (4, 2):
self.data.raw["monsters"] = [self.backup, self.main | {"process": process}, self.other]
self.assertEqual(self.action_ids(selected_policy), [30])
def test_removed_primary_does_not_authorize_an_unchecked_replacement_in_manual_mode(self):
selected_policy = policy(targets={str(MAIN): 1})
self.assertEqual(self.action_ids(selected_policy), [MAIN])
self.data.raw["monsters"] = [self.backup, self.other]
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], self.backup["id"])
def test_earliest_due_only_uses_eligible_primaries_and_ignores_backups(self):
self.main["giftTime"] = (NOW - 7200 + 120) * 1000
self.backup["giftTime"] = (NOW - 7200 + 15) * 1000
self.other["giftTime"] = (NOW - 7200 + 60) * 1000
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.next_ready_at, NOW + 60)
self.other["feel"] = self.catalog.max_feel(self.other)
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.next_ready_at, NOW + 120)
self.main["feel"] = self.catalog.max_feel(self.main)
self.assertEqual(self.action_ids(selected_policy), [])
self.assertIsNone(self.planner.next_ready_at)
def test_stock_reserves_and_item_locks_still_block_all_species(self):
selected_policy = policy(auto=True)
self.data.raw["items"][0]["num"] = 2
self.assertEqual(self.action_ids(selected_policy), [])
self.data.raw["items"][0]["num"] = 10
self.data.raw["items"][0]["feedLock"] = 1
self.assertEqual(self.action_ids(selected_policy), [])
self.data.raw["items"][0]["feedLock"] = 0
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
self.assertTrue(all(action.payload["itemId"] == 91 for action in self.planner.plan(self.data, selected_policy)))
def test_current_confirmed_cooldown_prevents_gifts_to_same_species_copies(self):
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2})
action = self.planner.plan(self.data, selected_policy)[0]
self.planner.remember_success(self.data, action, {"feel": 10, "giftDate": NOW * 1000})
stale = Snapshot(deepcopy(self.data.raw))
self.planner.apply_confirmed(stale)
self.assertEqual(self.planner.plan(stale, selected_policy), [])
self.assertEqual(stale.monsters[self.backup["id"]]["giftTime"], 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,437 @@
"""Offline integration: only the current primary may receive automatic resources."""
from copy import deepcopy
from dataclasses import asdict, replace
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import time
import unittest
from unittest.mock import patch
from ranch_assistant.breakthrough import PATH, POTENTIAL_PATH
from ranch_assistant.engine import Engine
from ranch_assistant.model import Action, Catalog, Policy, Snapshot
from ranch_web.policies import default_config, export_config
from ranch_web.views import build_view, schema
SPECIES = 1001010
MAIN, BACKUP, EXTRA = 900, 901, 902
FEED = "monsterService/monsterIntensify"
GIFT = "monsterService/monsterSendGift"
RECIPIENT_KEYS = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}
def monster(catalog, mid, *, level=1, quality=0, **values):
species = values.get("typeId", SPECIES)
info = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"potentialLevel": 1, "pAtk": 3, "pDef": 8, "pHp": 105, "pDex": 1,
"feel": 0, "giftTime": 0, "exp": 0, "tpLevel": 0, "tpExp": 0, "roomId": 1, "lock": 0}
for stat in ("atk", "def", "hp", "dex"):
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + quality * (high - low)
return mon | values
class OfflineClient:
"""In-memory server with a recorded write/read boundary; never opens a socket."""
def __init__(self, catalog, *, complete=False):
self.raw = {"master": {"id": 1, "level": 30, "ti": 100, "money": 0, "ke": 0},
"monsters": [monster(catalog, MAIN, level=9, lock=1, pAtk=4 if complete else 3),
monster(catalog, BACKUP, quality=1), monster(catalog, EXTRA, level=2)],
"items": [{"id": 600, "typeId": 30058, "num": 100}, {"id": 601, "typeId": 30005, "num": 10}],
"rooms": [{"id": 1, "typeId": 1000}], "teams": [], "stacks": [],
"currentTasks": [], "history": {}, "activityHistory": {}, "exploreTeams": []}
self.calls, self.events = [], []
self.apply_writes = True
def snapshot(self):
self.events.append("snapshot")
return Snapshot(deepcopy(self.raw))
def call(self, path, payload):
self.calls.append((path, deepcopy(payload)))
self.events.append(path)
if not self.apply_writes:
return {"resCode": 0}
monsters = {int(mon["id"]): mon for mon in self.raw["monsters"]}
if path == POTENTIAL_PATH:
mon = monsters[payload["monId"]]
mon["p" + payload["monsterAttr"].capitalize()] += 1
elif path == PATH:
monsters[payload["monId"]]["potentialLevel"] += 1
elif path == GIFT:
mon = monsters[payload["monsterId"]]
mon.update(feel=mon["feel"] + 10, giftTime=int(time.time()) * 1000)
return {"feel": mon["feel"], "giftDate": mon["giftTime"], "resCode": 0}
elif path in (FEED, "monsterService/monsterSell"):
consumed = set(payload["foods"] if path == FEED else payload["monsterIds"])
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in consumed]
else:
raise AssertionError("Unexpected offline write: " + path)
return {"resCode": 0}
class PrimaryResourceAdmissionTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def engine(self, *, complete=False):
temporary = TemporaryDirectory(prefix="primary-admission-")
self.addCleanup(temporary.cleanup)
client = OfflineClient(self.catalog, complete=complete)
engine = Engine(self.catalog, client, Path(temporary.name) / "budget.json")
engine.master_sync.settle = lambda *args: None
engine.settle_pending_growth = lambda *args, **kwargs: False
engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False,
manual_eggs=True, protect_star=6, protect_quality=5, keep_better_quality=False,
gift_auto_representative=False,
egg_rules={str(SPECIES): {"enabled": True, "action": "feed", "keep_count": 0}})
engine.snapshot = client.snapshot()
engine.auto = True
return engine, client
def action(self, kind, recipient):
payload = {RECIPIENT_KEYS[kind]: recipient}
if kind == "feed":
payload["foods"] = [EXTRA]
elif kind == "gift":
payload["itemId"] = 601
elif kind == "potential":
payload.update(itemId=600, monsterAttr="atk", traceInfo={"itemTypeId": 600, "itemNum": 100})
else:
payload["itemIds"] = [600]
return Action(kind, "offline " + kind, {"feed": FEED, "gift": GIFT, "potential": POTENTIAL_PATH, "breakthrough": PATH}[kind], payload)
def config(self, engine):
config = default_config()
config["policy"] = asdict(engine.policy)
return config
def test_stale_breakthrough_targets_never_spend_or_enable_the_unchecked_primary(self):
for complete in (False, True):
for fast in (False, True):
with self.subTest(complete=complete, fast=fast):
engine, client = self.engine(complete=complete)
engine.policy.breakthrough_targets = {str(BACKUP): 1}
before = asdict(engine.policy)
_, plans, message = engine.poll_automation("breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertFalse(any(action.kind in ("potential", "breakthrough") for action in plans))
self.assertIn("非主培养", message)
self.assertIn("#900", message)
self.assertEqual(asdict(engine.policy), before)
self.assertIsNone(engine._breakthrough_pending)
self.assertFalse(engine.last_executed)
def test_stale_priority_cannot_bypass_primary_admission_on_either_scheduler(self):
for complete in (False, True):
for fast in (False, True):
with self.subTest(complete=complete, fast=fast):
engine, client = self.engine(complete=complete)
engine.policy.breakthrough_targets = {str(BACKUP): 1, str(MAIN): 2}
before = asdict(engine.policy)
engine.poll_automation("breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [(PATH if complete else POTENTIAL_PATH,
{"monId": MAIN, "itemIds": [600]} if complete else
{"monId": MAIN, "itemId": 600, "monsterAttr": "atk", "traceInfo": {"itemTypeId": 600, "itemNum": 100}})])
self.assertEqual(client.events[-1], "snapshot")
self.assertIsNone(engine._breakthrough_pending)
self.assertEqual(asdict(engine.policy), before)
def test_engine_filters_stale_actions_even_if_a_source_planner_returns_them(self):
for kind in RECIPIENT_KEYS:
with self.subTest(kind=kind):
engine, client = self.engine()
source = engine.planner if kind == "feed" else engine.gift_planner if kind == "gift" else engine.breakthrough_planner
stale = self.action(kind, BACKUP)
if kind in ("potential", "breakthrough"):
engine.policy.breakthrough_targets = {str(BACKUP): 1}
with patch.object(source, "plan", return_value=stale if kind in ("potential", "breakthrough") else [stale]):
_, plans, message = engine.poll()
self.assertFalse(any(action.kind == kind for action in plans))
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
def test_current_recipient_is_checked_after_planning_on_both_dispatch_paths(self):
for kind in RECIPIENT_KEYS:
for fast in (False, True):
if fast and kind == "feed":
continue
with self.subTest(kind=kind, fast=fast):
engine, client = self.engine()
engine.cultivation.select(engine.snapshot)
action = self.action(kind, MAIN)
def stale_plan():
# A newer roster makes the queued recipient a duplicate.
engine.snapshot.monsters[BACKUP]["level"] = 30
return [action]
with patch.object(engine, "plans", side_effect=stale_plan):
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
self.assertFalse(engine.last_executed)
self.assertIsNone(engine._breakthrough_pending)
self.assertEqual(engine.gift_planner.confirmed, {})
def test_busy_primary_blocks_real_resource_plans_without_falling_back(self):
for busy in ("team_list", "team_string", "inExploreTeam", "inBuild", "sysLock"):
for complete in (False, True):
for scheduler in ("poll", "gift", "breakthrough"):
with self.subTest(busy=busy, complete=complete, scheduler=scheduler):
engine, client = self.engine(complete=complete)
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5,
lock=1, pAtk=4 if complete else 3)
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
if busy.startswith("team_"):
# Authoritative team membership can arrive without the per-monster marker.
client.raw["exploreTeams"] = [{"id": 77, "status": 1,
"monsters": [MAIN] if busy == "team_list" else str(MAIN)}]
else:
client.raw["monsters"][0][busy] = 1
targets = {str(MAIN): 1, str(BACKUP): 2}
engine.policy = replace(engine.policy, feed=True, feed_targets=targets,
gift_enabled=True, gift_targets=targets, gift_liked_only=False,
gift_items={"30005": {"enabled": True, "reserve": 0}}, breakthrough_targets=targets)
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
_, plans, _ = engine.poll() if scheduler == "poll" else engine.poll_automation(scheduler)
self.assertEqual(client.calls, [])
self.assertFalse(any(action.kind in RECIPIENT_KEYS for action in plans))
self.assertEqual(engine.cultivation.select(engine.snapshot)[str(SPECIES)]["id"], MAIN)
self.assertEqual(asdict(engine.policy), before)
self.assertIsNone(engine._breakthrough_pending)
def test_exploration_becoming_active_after_planning_blocks_queued_resources(self):
for kind in RECIPIENT_KEYS:
for fast in (False, True):
if fast and kind == "feed":
continue
with self.subTest(kind=kind, fast=fast):
engine, client = self.engine()
action = self.action(kind, MAIN)
def busy_plan():
engine.snapshot.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
return [action]
with patch.object(engine, "plans", side_effect=busy_plan):
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertIn("正在探险", message)
self.assertFalse(engine.last_executed)
self.assertIsNone(engine._breakthrough_pending)
def test_material_recipient_is_rechecked_after_unsent_intent_is_persisted(self):
engine, client = self.engine()
action = self.action("potential", MAIN)
save = engine._save_automation_state
def newer_roster_after_save():
save()
engine.snapshot.monsters[BACKUP]["level"] = 30
with patch.object(engine, "_save_automation_state", side_effect=newer_roster_after_save):
_, _, message = engine._execute_breakthrough(action)
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
self.assertIsNone(engine._breakthrough_pending)
self.assertIsNone(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"])
self.assertFalse(engine.last_executed)
def test_existing_pending_evidence_survives_loss_of_primary_and_restart(self):
for complete in (False, True):
with self.subTest(complete=complete):
engine, client = self.engine(complete=complete)
client.apply_writes = False
engine.policy.breakthrough_targets = {str(MAIN): 1}
engine.poll_automation("breakthrough")
pending = deepcopy(engine._breakthrough_pending)
self.assertIsNotNone(pending)
client.raw["monsters"][1]["level"] = 30
engine.poll_automation("breakthrough")
self.assertEqual(engine._breakthrough_pending, pending)
self.assertEqual(len(client.calls), 1)
self.assertEqual(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"], pending)
restored = Engine(self.catalog, client, engine.automation_state_path.parent / "budget.json")
restored.master_sync.settle = lambda *args: None
restored.policy, restored.auto = engine.policy, True
restored.poll_automation("breakthrough")
self.assertEqual(restored._breakthrough_pending["payload"], pending["payload"])
self.assertEqual(len(client.calls), 1)
# Confirmation belongs to the original recipient, even now a backup.
original = client.raw["monsters"][0]
original["potentialLevel" if complete else "pAtk"] += 1
restored.poll_automation("breakthrough")
self.assertIsNone(restored._breakthrough_pending)
self.assertEqual(len(client.calls), 1)
def test_preexisting_pending_record_is_not_discarded_when_rejecting_a_new_target(self):
engine, client = self.engine()
pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "retain evidence"}
engine._breakthrough_pending = deepcopy(pending)
engine._save_automation_state()
persisted = engine.automation_state_path.read_bytes()
engine._execute_breakthrough(self.action("potential", BACKUP))
self.assertEqual(engine._breakthrough_pending, pending)
self.assertEqual(engine.automation_state_path.read_bytes(), persisted)
self.assertEqual(client.calls, [])
def test_actual_gift_dispatch_uses_only_checked_primary_without_enabling_it(self):
for fast in (False, True):
for include_primary in (False, True):
with self.subTest(fast=fast, include_primary=include_primary):
engine, client = self.engine()
targets = {str(BACKUP): 1} | ({str(MAIN): 2} if include_primary else {})
engine.policy = replace(engine.policy, gift_enabled=True, gift_targets=targets,
gift_liked_only=False, gift_items={"30005": {"enabled": True, "reserve": 0}})
before = asdict(engine.policy)
_, _, message = engine.poll_automation("gift") if fast else engine.poll()
self.assertEqual([payload["monsterId"] for path, payload in client.calls if path == GIFT],
[MAIN] if include_primary else [])
if not include_primary:
self.assertIn("非主培养", message)
self.assertEqual(asdict(engine.policy), before)
def test_actual_feeding_dispatches_only_the_primary_with_legacy_flags_off(self):
for explicit in (False, True):
with self.subTest(explicit=explicit):
engine, client = self.engine()
# Equal-quality extras are dispatched; this case exercises feeding inferior material.
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5, lock=1)
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
feed_targets={str(BACKUP): 1, str(MAIN): 2} if explicit else {})
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
engine.poll()
self.assertEqual(client.calls, [(FEED, {"targetId": MAIN, "foods": [EXTRA]})])
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP})
self.assertEqual(client.events[-1], "snapshot")
self.assertEqual(asdict(engine.policy), before)
def test_full_primary_and_stale_explicit_selection_cannot_feed_a_backup(self):
for explicit in (False, True):
with self.subTest(explicit=explicit):
engine, client = self.engine()
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
feed_targets={str(BACKUP): 1} if explicit else {})
if not explicit:
main = client.raw["monsters"][0]
main.update(level=self.catalog.max_level(main), tpLevel=4,
tpExp=engine.planner.tp_thresholds(main)[4])
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
engine.poll()
self.assertEqual(client.calls, [])
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP, EXTRA})
self.assertEqual(asdict(engine.policy), before)
def test_manual_explicit_feed_can_still_target_a_backup(self):
engine, client = self.engine()
engine.manage_monsters("feed", [EXTRA], BACKUP)
self.assertEqual(client.calls, [(FEED, {"targetId": BACKUP, "foods": [EXTRA]})])
self.assertNotIn(EXTRA, engine.snapshot.monsters)
self.assertFalse(engine.auto)
def test_web_roles_disable_stale_selections_but_preserve_config_and_manual_targets(self):
engine, client = self.engine()
engine.policy = replace(engine.policy, feed_targets={str(BACKUP): 1},
gift_targets={str(BACKUP): 2}, breakthrough_targets={str(BACKUP): 3})
before = asdict(engine.policy)
config = self.config(engine)
config_before = deepcopy(config)
dto = build_view(engine, "ranch", config)
rows = {row["id"]: row for row in dto["rows"]}
self.assertEqual([rows[str(mid)]["cultivation_role_key"] for mid in (MAIN, BACKUP, EXTRA)],
["primary", "backup", "duplicate"])
for prefix in ("feed", "gift", "breakthrough"):
self.assertTrue(rows[str(BACKUP)][prefix + "_selected"])
self.assertFalse(rows[str(MAIN)][prefix + "_selected"])
for mid in (BACKUP, EXTRA):
edit = rows[str(mid)]["edits"][prefix + "_selected"]
self.assertTrue(edit["disabled"])
self.assertIn("#900", edit["reason"])
self.assertFalse(rows[str(MAIN)]["edits"][prefix + "_selected"]["disabled"])
self.assertIn(BACKUP, [option["value"] for option in dto["feed_targets"]])
self.assertEqual(asdict(engine.policy), before)
self.assertEqual(config, config_before)
self.assertEqual(client.calls, [])
def test_web_retention_is_fixed_and_legacy_values_round_trip_without_a_toggle(self):
for stored in (0, 1, 8):
with self.subTest(stored=stored):
engine, client = self.engine()
engine.policy.egg_rules[str(SPECIES)]["keep_count"] = stored
config = self.config(engine)
before = deepcopy(config)
dto = build_view(engine, "bag", config, {"category": "eggs"})
row = next(row for row in dto["rows"] if row["id"] == str(SPECIES))
column = next(column for column in dto["columns"] if column["key"] == "retention_text")
self.assertEqual(row["retention_text"], "主培养1 + 更优备选≤1")
self.assertFalse(column.get("edit"))
self.assertFalse(any(column["key"] == "keep_count" and column.get("edit") for column in dto["columns"]))
fields = [field for page in schema(self.catalog)["pages"] for field in page["form"]]
self.assertFalse(any(field["path"] == ["policy", "keep_better_quality"] for field in fields))
self.assertEqual(export_config(config, engine.snapshot)["policy"]["egg_rules"][str(SPECIES)]["keep_count"], stored)
self.assertEqual(config, before)
self.assertEqual(client.calls, [])
def test_busy_primary_keeps_its_web_role_while_automatic_controls_are_disabled(self):
engine, client = self.engine()
client.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
engine.snapshot = client.snapshot()
engine.policy = replace(engine.policy, feed_targets={str(MAIN): 1},
gift_targets={str(MAIN): 1}, breakthrough_targets={str(MAIN): 1})
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertEqual(rows[MAIN]["cultivation_role_key"], "primary")
self.assertEqual(rows[MAIN]["cultivation_role"], "主培养")
self.assertEqual(rows[MAIN]["primary_id"], MAIN)
self.assertFalse(rows[MAIN]["automatic_eligible"])
self.assertIn("正在探险", rows[MAIN]["automatic_reason"])
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "backup")
for prefix in ("feed", "gift", "breakthrough"):
self.assertTrue(rows[MAIN][prefix + "_selected"])
self.assertTrue(rows[MAIN]["edits"][prefix + "_selected"]["disabled"])
self.assertEqual(client.calls, [])
def test_web_existing_extras_report_protection_and_dispatch_off_without_managed_history(self):
engine, client = self.engine()
client.raw["monsters"] += [monster(self.catalog, 903, lock=1), monster(self.catalog, 904, equip1=123),
monster(self.catalog, 905, typeId=1030010)]
engine.snapshot = client.snapshot()
self.assertEqual(engine.planner.managed, set())
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertIn("自动派遣", rows[EXTRA]["scope"])
self.assertIn("关闭", rows[EXTRA]["scope"])
self.assertNotIn("已有:不自动处理", rows[EXTRA]["scope"])
self.assertIn("已锁定", rows[903]["scope"])
self.assertIn("携带装备", rows[904]["scope"])
self.assertIn("规则未启用", rows[905]["scope"])
self.assertEqual(client.calls, [])
def test_web_uses_the_retention_planners_reserve_when_replacement_is_still_incubating(self):
engine, client = self.engine()
client.raw["monsters"][1] = monster(self.catalog, BACKUP, quality=.5)
client.raw["monsters"].append(monster(self.catalog, 903, quality=1, process=2))
engine.snapshot = client.snapshot()
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "duplicate")
self.assertEqual(rows[903]["cultivation_role_key"], "backup")
self.assertIn("待收取", rows[903]["cultivation_role"])
self.assertFalse(rows[903]["automatic_eligible"])
self.assertTrue(rows[903]["edits"]["feed_selected"]["disabled"])
self.assertEqual(client.calls, [])
def test_same_name_variants_have_independent_primary_admission_and_web_roles(self):
engine, client = self.engine()
for mid, species in enumerate((1030010, 1030012, 1030013, 1030014), 1000):
client.raw["monsters"].append(monster(self.catalog, mid, typeId=species, level=1))
engine.snapshot = client.snapshot()
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
for mid in range(1000, 1004):
self.assertEqual(rows[mid]["cultivation_role_key"], "primary")
self.assertTrue(rows[mid]["automatic_eligible"])
self.assertEqual(client.calls, [])
if __name__ == "__main__":
unittest.main()
@@ -1,6 +1,8 @@
import copy
import json
import time
import unittest
from unittest.mock import patch
from ranch_assistant.breakthrough import POTENTIAL_PATH
from ranch_assistant.engine import Engine
@@ -20,6 +22,17 @@ def raw(catalog):
return value
def species_monster(catalog, mid, grades, *, level=10, species=1030010, **values):
row = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"exp": 0, "potentialLevel": 2, "tpLevel": 4, "tpExp": 9999,
"feel": 0, "giftTime": 0, "entangleLevel": 0, "lock": 0, "roomId": 1}
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 | values
class FakeClient:
def __init__(self, value):
self.value, self.calls = value, []
@@ -35,18 +48,170 @@ class FakeClient:
return copy.deepcopy(self.response)
class StatefulRanchClient(FakeClient):
def call(self, path, payload):
super().call(path, copy.deepcopy(payload))
monsters = {int(mon["id"]): mon for mon in self.value["monsters"]}
removed = []
if path == "monsterService/monsterSell":
removed = payload["monsterIds"]
elif path == "stackService/stackTransferMonster":
for data in payload["datas"]:
for mid in data["monsterId"]:
monsters[mid].update(process=3, roomId=data["roomId"])
for stack in self.value["stacks"]:
if stack.get("monsterId") == mid:
stack["monsterId"] = 0
elif path == "monsterService/monsterIntensify":
removed = payload["foods"]
elif path == "monsterService/monsterSendGift":
mon = monsters[payload["monsterId"]]
mon.update(feel=int(mon.get("feel") or 0) + 1, giftTime=int(time.time() * 1000))
return {"feel": mon["feel"], "giftDate": mon["giftTime"]}
elif path == POTENTIAL_PATH:
mon = monsters[payload["monId"]]
stat = "p" + payload["monsterAttr"].capitalize()
mon[stat] += 1
else:
raise AssertionError(f"Unexpected offline ranch operation: {path}")
self.value["monsters"] = [mon for mon in self.value["monsters"] if mon["id"] not in removed]
for stack in self.value["stacks"]:
if stack.get("monsterId") in removed:
stack["monsterId"] = 0
return {"resCode": 0}
class RanchAutomationIntegrationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def engine(self, folder, value=None):
client = FakeClient(value or raw(self.catalog))
def engine(self, folder, value=None, client_type=FakeClient):
client = client_type(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_screenshot_lv20_sass_primary_never_spends_on_four_lesser_duplicates(self):
primary = species_monster(self.catalog, 900, "SASS", level=20,
pAtk=44, pDef=10, pHp=180, pDex=9)
primary["feel"] = self.catalog.max_feel(primary)
duplicates = [species_monster(self.catalog, 901 + index, grades, level=9 + index % 2,
tpLevel=0, tpExp=0, pAtk=1, pDef=1, pHp=1, pDex=1)
for index, grades in enumerate(("SAAA", "ASAS", "AASS", "AAAS"))]
duplicate_ids = {mon["id"] for mon in duplicates}
cases = [({}, False, {}), ({"900": 1, "901": 2, "902": 3, "903": 4, "904": 5}, False, {}),
({}, True, {}), ({}, False, {"901": 1})]
for feed_targets, manual_gifts, potential_targets in cases:
with self.subTest(feed_targets=feed_targets, manual_gifts=manual_gifts, potential_targets=potential_targets):
with workspace_temp() as folder:
value = raw(self.catalog)
value.update(monsters=copy.deepcopy([primary, *duplicates]),
items=[{"id": 600, "typeId": 30058, "num": 100},
{"id": 601, "typeId": 30005, "num": 10}])
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(enabled=True, dispatch=True, feed=True, manual_eggs=True,
fill=False, protect_star=4, protect_quality=5, keep_better_quality=False,
egg_rules={"1030010": {"enabled": True, "action": "feed", "keep_count": 1}},
feed_targets=feed_targets, breakthrough_targets=potential_targets,
gift_enabled=manual_gifts, gift_auto_representative=not manual_gifts,
gift_targets={str(mid): mid for mid in duplicate_ids | {900}},
gift_liked_only=False, gift_items={"30005": {"enabled": True}})
engine.planner.managed.update(duplicate_ids | {900})
engine.auto = True
_, plans, _ = engine.poll()
for path, payload in client.calls:
target = payload.get("targetId", payload.get("monsterId", payload.get("monId")))
self.assertNotIn(target, duplicate_ids, (path, payload))
self.assertNotIn(900, payload.get("foods", []) + payload.get("monsterIds", []))
for action in plans:
if action.kind in ("feed", "gift", "potential", "breakthrough"):
target = action.payload.get("targetId", action.payload.get("monsterId", action.payload.get("monId")))
self.assertNotIn(target, duplicate_ids, action)
self.assertIn(900, engine.snapshot.monsters)
def test_existing_enabled_duplicates_cleanup_without_managed_and_preserve_constraints(self):
for constraint in (None, "lock", "sysLock", "equip1", "team", "entangle", "inExploreTeam", "inBuild", "unknown_quality", "active_exploration_team", "active_exploration_team_csv", "stale_targets_high_rarity"):
with self.subTest(constraint=constraint):
with workspace_temp() as folder:
value = raw(self.catalog)
stale_targets = constraint == "stale_targets_high_rarity"
species = next(int(key) for key, row in self.catalog.monsters.items()
if row.get("star") == 5 and not row.get("npc")
and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex"))) if stale_targets else 1030010
rows = [species_monster(self.catalog, 900, "SASS", level=20, species=species)]
rows += [species_monster(self.catalog, mid, "CCCC", species=species) for mid in range(901, 905)]
rows += [species_monster(self.catalog, 950 + index, "CCCC", species=species)
for index, species in enumerate((1030012, 1030013, 1030014))]
value.update(monsters=rows, teams=[])
if constraint == "team":
value["teams"] = [{"monsters": [901]}]
elif constraint in ("active_exploration_team", "active_exploration_team_csv"):
value["exploreTeams"][0].update(status=1,
monsters="901" if constraint.endswith("_csv") else [901], endTime=9999999999999)
elif constraint == "unknown_quality":
rows[1]["gAtk"] = None
elif constraint and not stale_targets:
rows[1][constraint] = 1
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
keep_better_quality=False, gift_auto_representative=False,
egg_rules={str(species): {"enabled": True, "action": "sell", "keep_count": 0}},
feed_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
gift_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
breakthrough_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {})
self.assertEqual(engine.planner.managed, set())
engine.auto = True
for _ in range(5):
engine.poll()
expected = {900, 950, 951, 952} | ({901} if constraint and not stale_targets else set())
self.assertEqual(set(engine.snapshot.monsters), expected)
self.assertTrue(client.calls)
self.assertTrue(all(path == "monsterService/monsterSell" for path, _ in client.calls))
if constraint and not stale_targets:
self.assertTrue(engine.planner.statuses.get(901))
if constraint == "lock":
self.assertEqual(engine.snapshot.monsters[901]["lock"], 1)
if constraint in ("active_exploration_team", "active_exploration_team_csv"):
client.value["exploreTeams"][0]["status"] = 0
engine.poll()
self.assertEqual(set(engine.snapshot.monsters), {900, 950, 951, 952})
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [901]}))
def test_successive_quality_backups_replace_before_collect_and_new_mature_ties_dispatch(self):
with workspace_temp() as folder:
value = raw(self.catalog)
room_type = next(key for key, row in self.catalog.data["room_info"].items() if row.get("maxNum", 0) >= 2)
value.update(monsters=[species_monster(self.catalog, 900, "SASS", level=20, lock=1),
species_monster(self.catalog, 901, "SSSA"),
species_monster(self.catalog, 902, "SSSS", level=1, process=2, roomId=None)],
rooms=[{"id": 1, "typeId": int(room_type)}],
stacks=[{"id": 1, "position": 0, "monsterId": 902}])
row = self.catalog.monster(1030010)
for stat, scale in zip(("atk", "def", "hp", "dex"), (.95, .95, .95, .7)):
value["monsters"][1]["g" + stat.capitalize()] = row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
keep_better_quality=False, gift_auto_representative=False,
egg_rules={"1030010": {"enabled": True, "action": "sell", "keep_count": 4}})
engine.auto = True
with patch.dict(self.catalog.data["room_info"][room_type], {"maxNum": 2}):
engine.poll()
self.assertEqual(client.calls, [("monsterService/monsterSell", {"monsterIds": [901]})])
engine.poll()
self.assertEqual(client.calls[-1], ("stackService/stackTransferMonster",
{"datas": [{"monsterId": [902], "roomId": 1}]}))
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
client.value["monsters"].insert(0,
species_monster(self.catalog, 903, "SSSS", level=1, process=2, roomId=None))
client.value["stacks"][0]["monsterId"] = 903
engine.poll()
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [903]}))
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
engine.poll()
self.assertEqual(len(client.calls), 3)
def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
+63 -34
View File
@@ -27,47 +27,49 @@ class RanchRetentionTests(unittest.TestCase):
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,
values.setdefault("protect_quality", 5)
values.setdefault("keep_better_quality", False)
return Policy(manual_eggs=True, fill=False,
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):
def test_quality_uses_s_count_then_equal_weight_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")),
self.assertLess(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):
def test_legacy_quota_zero_one_two_always_reserves_one_primary(self):
for action in ("sell", "feed", "keep"):
for quota, disposed in ((0, 3), (1, 2), (2, 1)):
for quota in (0, 1, 2):
with self.subTest(action=action, quota=quota):
disposed = 2
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)
self.assertIn(1, self.planner.retained)
self.assertNotIn(2, self.planner.retained)
self.assertNotIn(3, self.planner.retained)
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):
def test_locked_ranch_duplicates_stay_locked_and_equal_mature_extras_dispatch(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]:
@@ -75,48 +77,67 @@ class RanchRetentionTests(unittest.TestCase):
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):
def test_incubator_batch_keeps_one_primary_and_same_id_after_collection(self):
for quota in (0, 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)
self.assertFalse(any(a.kind == "collect" for a in actions))
sold = {mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]}
self.assertEqual(sold, set(range(1, 4)) - collected)
self.assertEqual(sold, {2, 3})
self.assertEqual(self.planner.retained, {1})
rows = rows[:1]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
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, {1})
rows[0].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=quota))
self.assertEqual(self.planner.retained, collected)
self.assertFalse(actions)
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):
def test_ranch_primary_rejects_equal_incubator_extras_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})
self.assertEqual(collected, set())
self.assertEqual(self.planner.retained, {1})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
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])
self.assertEqual(self.planner.retained, {1})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
def test_initial_incubator_quota_prefers_best_quality_last_in_raw(self):
def test_initial_incubator_keeps_first_primary_and_best_quality_backup_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(collected, set())
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2])
self.assertEqual(self.planner.retained, {1, 3})
rows = [rows[0], rows[2]]
self.snapshot.raw["stacks"] = [self.snapshot.raw["stacks"][0], self.snapshot.raw["stacks"][2]]
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [1])
rows[0].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [3])
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][1]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.representatives["1001010"]["id"], 1)
self.assertEqual(self.planner.retained, {1, 3})
self.assertFalse(actions)
def test_incubator_quota_quality_prevents_equal_quality_extra_retention(self):
rows = [graded_monster(self.catalog, 1, "AASA")]
@@ -125,8 +146,16 @@ class RanchRetentionTests(unittest.TestCase):
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"]], [])
self.assertEqual(collected, [])
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3])
rows = rows[:2]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [2])
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertFalse(actions)
def test_zero_quota_still_protects_better_incubator_above_locked_ranch(self):
locked = graded_monster(self.catalog, 1, "AASA", lock=1)
@@ -159,7 +188,7 @@ class RanchRetentionTests(unittest.TestCase):
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"))))
self.assertFalse(any(a.kind == "feed" 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,
@@ -171,9 +200,9 @@ class RanchRetentionTests(unittest.TestCase):
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):
def test_unmanaged_other_species_primary_and_locked_monsters_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)
other = graded_monster(self.catalog, 2, "SSSA", species=1002010, 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]})
@@ -199,9 +228,9 @@ class RanchRetentionTests(unittest.TestCase):
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")
food = graded_monster(self.catalog, 2, "CCCC", level=1)
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)
target.update(tpLevel=0, tpExp=0, level=2, 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]})
@@ -41,7 +41,10 @@ class ManualRuleTests(unittest.TestCase):
self.planner.managed.add(food["id"])
primary = self.snapshot.monsters[900]
primary.update(potentialLevel=2, level=20)
secondary = dict(primary, id=901, level=9, potentialLevel=1)
row = self.catalog.monster(primary["typeId"])
for stat in ("atk", "def", "hp", "dex"):
primary["g" + stat.capitalize()] = row[stat + "_grow_min"] + .6 * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
secondary = dict(primary, id=901, typeId=1002010, 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", keep_count=0)}, feed_targets={"900": 1, "901": 2})
@@ -0,0 +1,479 @@
"""Offline regressions for primary-only cultivation and bounded species retention."""
import copy
from dataclasses import asdict
import unittest
from ranch_assistant.cultivation import quality_rank
from ranch_assistant.model import Action, Catalog, EggRule, Planner, Policy, Snapshot
SPECIES = 1030010
class SpeciesRetentionLimitsTests(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"] = 20
self.snapshot = Snapshot({"master": {"id": 1}, "monsters": [], "teams": [],
"stacks": [], "items": [], "rooms": [{"id": 1, "typeId": int(room_type)},
{"id": 2, "typeId": int(room_type)}]})
self.planner = Planner(self.catalog)
def mon(self, mid, grades="CCCC", *, species=SPECIES, **values):
info = self.catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2,
"level": 10, "feel": 0, "roomId": 1, "potentialLevel": 3,
"exp": 451, "tpLevel": 0, "tpExp": 0, "lock": 0}
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {
"C": .1, "B": .375, "A": .625, "S": .9}[grade]
return mon | values
def policy(self, *, action="sell", count=1, **values):
return Policy(**({"manual_eggs": True, "fill": False, "buy": False,
"protect_star": 6, "protect_quality": 5, "keep_better_quality": False,
"gift_auto_representative": True, "egg_rules": {str(SPECIES):
asdict(EggRule(enabled=True, action=action, keep_count=count))}} | values))
def plan(self, rows, policy=None, *, managed=()):
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(managed)
return self.planner.plan(self.snapshot, policy or self.policy())
@staticmethod
def sold(actions):
return {mid for action in actions if action.kind == "sell"
for mid in action.payload["monsterIds"]}
@staticmethod
def collected(actions):
return {mid for action in actions if action.kind == "collect"
for data in action.payload["datas"] for mid in data["monsterId"]}
def screenshot(self):
return [self.mon(910001, "SASS", level=20, potentialLevel=2,
tpLevel=4, tpExp=999, exp=self.catalog.data["monster_level"]["20"], lock=1),
self.mon(910002, "SASA"), self.mon(910003, "AASS"),
self.mon(910004, "SASA"), self.mon(910005, "ASAS", level=9)]
def test_screenshot_unmanaged_extras_are_trimmed_only_for_enabled_species(self):
rows = self.screenshot()
unrelated = self.mon(999, "SSSS", species=1030012)
actions = self.plan(rows + [unrelated])
self.assertEqual(self.sold(actions), {row["id"] for row in rows[1:]})
self.assertEqual(self.planner.retained, {910001})
self.assertFalse(any(action.kind == "feed" for action in actions))
self.assertFalse(self.planner.managed, "Planning must not invent recorded ownership")
def test_screenshot_tp_and_ordinary_caps_never_fall_back_to_duplicate(self):
rows = self.screenshot()
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(row["id"] for row in rows[1:])
target, _ = self.planner.same_species_feeding_target(rows[-1], self.snapshot,
self.policy(action="feed"))
self.assertIsNone(target)
self.assertFalse(any(action.kind == "feed" for action in
self.plan(rows, self.policy(action="feed"))))
def test_old_keep_flags_and_counts_do_not_expand_or_disable_fixed_slots(self):
for count in (0, 1, 2, 1000):
for keep_better in (False, True):
with self.subTest(count=count, keep_better=keep_better):
self.setUp()
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSAS"),
self.mon(3, "SSAS", roomId=2), self.mon(4, "AASA")]
policy = self.policy(count=count, keep_better_quality=keep_better)
before = copy.deepcopy(asdict(policy))
actions = self.plan(rows, policy)
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual(self.sold(actions), {3, 4})
self.assertEqual(asdict(policy), before)
def test_quality_protection_does_not_keep_unlimited_managed_four_s(self):
for threshold in (3, 6):
with self.subTest(threshold=threshold):
self.setUp()
rows = [self.mon(1, "SSSS", level=30)] + [
self.mon(mid, "SSSS") for mid in (2, 3, 4)]
actions = self.plan(rows, self.policy(count=1000, protect_quality=threshold),
managed=(1, 2, 3, 4))
self.assertEqual(self.planner.retained, {1})
self.assertEqual(self.sold(actions), {2, 3, 4})
def test_backup_requires_strict_improvement_over_primary(self):
rows = [self.mon(1, "SSAS", level=30), self.mon(2, "SSAS"), self.mon(3, "AASA")]
self.assertEqual(self.sold(self.plan(rows)), {2, 3})
self.assertEqual(self.planner.retained, {1})
def test_equal_four_s_newcomer_dispatches_instead_of_becoming_tp_food(self):
primary = self.mon(1, "SSSS", level=30, tpLevel=0, tpExp=0)
newcomer = self.mon(2, "SSSS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 2}]
policy = self.policy(action="feed")
actions = self.plan([primary, newcomer], policy)
self.assertEqual(self.sold(actions), {2})
self.assertEqual(self.collected(actions), set())
newcomer.update(process=3, roomId=1)
actions = self.plan([primary, newcomer], policy)
self.assertEqual(self.sold(actions), {2})
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_rejected_better_quality_candidate_dispatches_and_hard_locks_still_win(self):
for protected in (False, True):
with self.subTest(protected=protected):
self.setUp()
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSSS"),
self.mon(3, "SSAS", lock=int(protected))]
policy = self.policy(action="feed")
actions = self.plan(rows, policy, managed=(2, 3))
self.assertEqual(self.sold(actions), set() if protected else {3})
self.assertEqual(self.planner.disposition(rows[2], self.snapshot, policy),
"keep" if protected else "sell")
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_backup_ranks_s_count_before_equal_weight_normalized_growth(self):
rows = [self.mon(1, "CCCC", level=30), self.mon(2, "AAAC"),
self.mon(3, "BBAA"), self.mon(4, "SSAS"), self.mon(5, "AASA")]
self.assertGreater(quality_rank(self.catalog, rows[3]), quality_rank(self.catalog, rows[4]))
self.assertEqual(self.sold(self.plan(rows)), {2, 3, 5})
self.assertEqual(self.planner.retained, {1, 4})
def test_backup_breaks_grade_ties_by_equal_weight_normalized_growth(self):
primary = self.mon(1, level=30)
better_atk, better_hp = self.mon(2, "AAAA"), self.mon(3, "AAAA")
info = self.catalog.monster(SPECIES)
better_atk["gAtk"] += .05 * (info["atk_grow_max"] - info["atk_grow_min"])
better_hp["gHp"] += .10 * (info["hp_grow_max"] - info["hp_grow_min"])
self.assertEqual(self.sold(self.plan([primary, better_atk, better_hp])), {2})
self.assertEqual(self.planner.retained, {1, 3})
def test_equal_s_count_uses_growth_without_extra_a_or_b_count_priority(self):
rows = [self.mon(1, level=30), self.mon(2, "SACC"), self.mon(3, "SBBB")]
self.assertLess(quality_rank(self.catalog, rows[1]), quality_rank(self.catalog, rows[2]))
self.assertEqual(self.sold(self.plan(rows)), {2})
self.assertEqual(self.planner.retained, {1, 3})
def test_quality_tie_prefers_existing_ranch_backup_over_new_incubator(self):
primary, backup = self.mon(1, level=30), self.mon(20, "SSAS")
self.plan([primary, backup])
new = self.mon(10, "SSAS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 10}]
actions = self.plan([new, backup, primary])
self.assertEqual(self.planner.retained, {1, 20})
self.assertEqual(self.sold(actions), {10})
self.assertEqual(self.collected(actions), set())
def test_equal_ranch_backups_use_oldest_id_independent_of_row_order(self):
for order in ((30, 20, 10), (10, 30, 20)):
with self.subTest(order=order):
self.setUp()
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS") for mid in order]
self.assertEqual(self.sold(self.plan(rows)), {20, 30})
self.assertEqual(self.planner.retained, {1, 10})
def test_better_incubator_dispatches_obsolete_backup_before_collection(self):
primary, old = self.mon(1, level=30), self.mon(2, "SSAS")
self.plan([primary, old])
new = self.mon(3, "SSSS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
policy = self.policy(action="feed")
actions = self.plan([primary, old, new], policy, managed=(2, 3))
self.assertEqual(self.sold(actions), {2})
self.assertEqual(self.collected(actions), set())
self.assertFalse(any(action.kind == "feed" for action in actions))
actions = self.plan([primary, new], policy)
self.assertEqual(self.collected(actions), {3})
self.assertEqual(self.sold(actions), set())
def test_obsolete_backup_replacement_waits_when_dispatch_is_off(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS"),
self.mon(3, "SSSS", process=2, roomId=None)]
actions = self.plan(rows, self.policy(dispatch=False), managed=(2, 3))
self.assertEqual(actions, [])
self.assertIn("派遣", self.planner.statuses[2])
self.assertIn("关闭", self.planner.statuses[2])
def test_first_mature_incubator_is_collected_before_any_feeding(self):
rows = [self.mon(2, "SSSS", process=2, roomId=None),
self.mon(1, process=2, roomId=None)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1,
"monsterId": mid} for mid in (1, 2)]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), {1})
self.assertFalse(any(action.kind == "feed" for action in actions))
self.assertIn(1, self.planner.retained)
def test_primary_can_consume_only_nonprotected_lower_quality_excess(self):
rows = [self.mon(1, "AAAA", level=30, lock=1), self.mon(2, "SSSS"), self.mon(3)]
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 1, "foods": [3]}])
self.assertEqual(self.planner.retained, {1, 2})
def test_legacy_same_species_feed_does_not_require_target_quality_above_fodder(self):
rows = [self.mon(1, level=30, lock=1), self.mon(2, "SSAS")]
policy = Policy(strategy="experience", fill=False, protect_star=6, protect_quality=5)
actions = self.plan(rows, policy, managed=(2,))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 1, "foods": [2]}])
def test_backup_is_food_protected_but_never_a_target(self):
primary = self.mon(1, level=30, tpLevel=4, tpExp=999)
backup, food = self.mon(2, "SSSS"), self.mon(3, "SSAS")
self.snapshot.raw["monsters"] = [primary, backup, food]
self.planner.managed.update((2, 3))
policy = self.policy(action="feed")
self.assertTrue(self.planner.protected(backup, self.snapshot, policy))
target, reason = self.planner.same_species_feeding_target(food, self.snapshot, policy)
self.assertIsNone(target, reason)
self.assertNotIn(2, self.planner.tp_feed_targets)
def test_same_species_selection_uses_only_primary_even_if_priority_favors_backup(self):
primary, backup, food = self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")
self.snapshot.raw["monsters"] = [primary, backup, food]
self.planner.managed.update((2, 3))
policy = self.policy(action="feed", breakthrough_targets={"2": 1})
target, _ = self.planner.same_species_feeding_target(food, self.snapshot, policy)
self.assertIs(target, primary)
def test_unavailable_primary_does_not_fall_back_to_available_duplicate(self):
for unavailable in ({"inExploreTeam": True}, {"inBuild": True}):
with self.subTest(unavailable=unavailable):
self.setUp()
rows = [self.mon(1, level=30, **unavailable), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3))
policy = self.policy(action="feed", feed_targets={"1": 1, "2": 2})
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
self.assertIsNone(self.planner.same_species_feeding_target(rows[-1], self.snapshot, policy)[0])
def test_manual_backup_only_is_skipped_without_changing_selection(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
for values in ({"feed_targets": {"2": 1}}, {"feed_target": 2}):
with self.subTest(values=values):
self.snapshot.raw["monsters"] = rows
policy = self.policy(action="feed", **values)
before = copy.deepcopy(asdict(policy))
target, reason = self.planner.feeding_target(self.snapshot, policy)
self.assertIsNone(target)
self.assertIn("主培养", reason)
self.assertIn("#1", reason)
self.assertFalse(any(action.kind == "feed" for action in
self.plan(rows, policy, managed=(2, 3))))
self.assertEqual(asdict(policy), before)
def test_manual_capped_primary_skips_duplicate_and_may_use_other_species_primary(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, species=1002010)]
self.snapshot.raw["monsters"] = rows
policy = self.policy(feed_targets={"1": 1, "2": 2, "3": 3})
self.assertIs(self.planner.feeding_target(self.snapshot, policy)[0], rows[2])
del policy.feed_targets["3"]
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
def test_all_hard_protections_survive_species_limit(self):
flags = ({"lock": 1}, {"sysLock": 1}, {"equip1": 7}, {"entangle": 1},
{"inExploreTeam": 1}, {"inBuild": 1}, {"gAtk": None})
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS", **values)
for mid, values in enumerate(flags, 2)]
rows += [self.mon(20, "SSAS"), self.mon(21, "CCCC")]
self.snapshot.raw["teams"] = [{"id": 1, "monsters": [20]}]
before = copy.deepcopy(rows)
actions = self.plan(rows, managed=range(1, 22))
self.assertEqual(self.sold(actions), {21})
self.assertEqual(rows, before)
for row in rows[1:-1]:
self.assertIn("保护", self.planner.statuses[row["id"]])
def test_reserved_species_never_sells_or_feeds_extras(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS"), self.mon(3)]
actions = self.plan(rows, self.policy(reserved_types=[SPECIES]), managed=(2, 3))
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
self.assertIn("委托", self.planner.statuses[3])
def test_active_exploration_roster_protects_extras_without_individual_flags(self):
for members in ("910002", [910002], (910002,)):
with self.subTest(members=members):
self.setUp()
rows = self.screenshot()
# Status remains occupied until exploration rewards are claimed,
# including when its end time has already passed.
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
"monsters": members, "endTime": 1}]
actions = self.plan(rows, self.policy(action="feed"),
managed=tuple(row["id"] for row in rows))
self.assertEqual(self.sold(actions), {910003, 910004, 910005})
self.assertEqual(self.planner.retained, {910001, 910002})
self.assertIn("保护", self.planner.statuses[910002])
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_exploring_primary_without_individual_flag_is_never_feed_target(self):
rows = self.screenshot()
rows[0].update(level=19, exp=451, tpLevel=0, tpExp=0)
self.snapshot.raw["monsters"] = rows
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": "1",
"monsters": "910001"}]
self.planner.managed.update(row["id"] for row in rows[1:])
policy = self.policy(action="feed", feed_targets={"910001": 1})
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
self.assertIsNone(self.planner.same_species_feeding_target(rows[1], self.snapshot, policy)[0])
action = Action("feed", "busy primary", "monsterService/monsterIntensify",
{"targetId": 910001, "foods": [910002]})
self.assertEqual(self.planner.batch_actions([action], self.snapshot, policy), [])
def test_exploration_only_changes_invalidate_retention_cache(self):
rows = self.screenshot()
self.snapshot.raw["monsters"] = rows
policy = self.policy()
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
"monsters": [910002]}]
self.assertTrue(self.planner.protected(rows[1], self.snapshot, policy))
self.assertIn(910002, self.planner.retained)
self.snapshot.raw["exploreTeams"][0]["status"] = 0
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
self.assertNotIn(910002, self.planner.retained)
def test_dispatch_off_reports_unmanaged_extras_without_expanding_ownership(self):
rows = self.screenshot()
self.assertEqual(self.plan(rows, self.policy(dispatch=False)), [])
self.assertIn("关闭", self.planner.statuses[910002])
self.assertFalse(self.planner.managed)
def test_disabled_rules_and_disabled_automation_never_adopt_old_inventory(self):
rows = self.screenshot()
for policy in (self.policy(enabled=False), self.policy(egg_rules={str(SPECIES):
asdict(EggRule(enabled=False))})):
with self.subTest(policy=policy):
self.assertEqual(self.plan(rows, policy), [])
self.assertFalse(self.planner.managed)
def test_stale_nonprimary_targets_do_not_override_species_slots(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
policy = self.policy(action="feed", feed_targets={"3": 1}, breakthrough_targets={"4": 1})
actions = self.plan(rows, policy, managed=(2, 3, 4))
self.assertEqual(self.sold(actions), {3, 4})
self.assertFalse(any(a.kind == "feed" for a in actions))
self.assertFalse(self.planner.protected(rows[2], self.snapshot, policy))
self.assertFalse(self.planner.protected(rows[3], self.snapshot, policy))
def test_all_old_targets_and_star_threshold_are_soft_for_enabled_species(self):
rows = self.screenshot()
rows[2]["lock"] = 1
selected = {str(row["id"]): i for i, row in enumerate(rows, 1)}
policy = self.policy(action="feed", protect_star=1, feed_targets=selected.copy(),
gift_targets=selected.copy(), breakthrough_targets=selected.copy())
before = copy.deepcopy(asdict(policy))
actions = self.plan(rows, policy, managed=tuple(row["id"] for row in rows))
self.assertEqual(self.sold(actions), {910002, 910004, 910005})
self.assertEqual(self.planner.retained, {910001, 910003})
self.assertIn("保护", self.planner.statuses[910003])
self.assertEqual(asdict(policy), before)
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_batch_revalidates_primary_instead_of_trusting_supplied_feed_action(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3))
action = Action("feed", "stale duplicate target", "monsterService/monsterIntensify",
{"targetId": 2, "foods": [3]})
self.assertEqual(self.planner.batch_actions([action], self.snapshot,
self.policy(action="feed", feed_targets={"2": 1})), [])
def test_batch_never_consumes_primary_backup_unmanaged_or_locked_food(self):
rows = [self.mon(1, "AAAA", level=29), self.mon(2, "SSSS"), self.mon(3),
self.mon(4, lock=1), self.mon(5, species=1002010)]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3, 4))
policy = self.policy(action="feed", feed_targets={"1": 1})
actions = [Action("feed", "candidate", "monsterService/monsterIntensify",
{"targetId": 1, "foods": [mid]}) for mid in (1, 2, 3, 4, 5)]
self.assertEqual([a.payload for a in self.planner.batch_actions(actions, self.snapshot, policy)],
[{"targetId": 1, "foods": [3]}])
def test_normal_experience_cap_still_allows_same_species_tp_on_primary(self):
rows = [self.mon(1, "AAAA", level=30, tpLevel=2, tpExp=3), self.mon(2, "SSSS"), self.mon(3)]
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
self.assertEqual([a.payload for a in actions if a.kind == "feed"], [{"targetId": 1, "foods": [3]}])
def test_keep_action_cannot_bypass_the_two_species_slots(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
actions = self.plan(rows, self.policy(action="keep", count=1000))
self.assertEqual(self.sold(actions), {3, 4})
self.assertEqual(self.planner.retained, {1, 2})
def test_transient_food_collection_reserves_only_one_species_slot(self):
rows = [self.mon(1, "SSAS", level=30)] + [
self.mon(mid, process=2, roomId=None) for mid in (2, 3, 4, 5)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 2,
"monsterId": mid} for mid in (2, 3, 4, 5)]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.sold(actions), {3, 4, 5})
self.assertEqual(self.collected(actions), set())
rows = rows[:2]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(len(self.collected(actions)), 1)
self.assertEqual(self.collected(actions), {2})
self.assertTrue(all(action.kind != "feed" for action in actions))
# A refreshed snapshot sees one transient food, never four admitted at once.
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), set())
self.assertTrue(any(action.kind == "feed" and action.payload["targetId"] == 1 for action in actions))
def test_primary_and_backup_block_extra_food_collection(self):
rows = [self.mon(1, "AAAA", level=30), self.mon(2, "SSSS"),
self.mon(3, process=2, roomId=None)]
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), set())
self.assertEqual(self.sold(actions), {3})
def test_hard_protected_old_backup_blocks_replacement_at_two_ranch_members(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS", lock=1),
self.mon(3, "SSSS", process=2, roomId=None)]
actions = self.plan(rows, managed=(2, 3))
self.assertEqual(actions, [])
self.assertIn("保护", self.planner.statuses[2])
self.assertIn("两只", self.planner.statuses[3])
def test_unknown_primary_quality_pauses_cleanup_until_synchronized(self):
rows = [self.mon(1, level=30, gAtk=None), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
actions = self.plan(rows, managed=(1, 2, 3))
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
self.assertIn("同步", self.planner.statuses[3])
def test_saved_nonranch_primary_is_held_instead_of_promoting_backup(self):
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
self.plan([primary, backup])
primary.update(process=2, mode=1, roomId=None)
actions = self.plan([backup, primary], self.policy(action="feed"), managed=(10, 30))
self.assertEqual(self.planner.cultivation.select(self.snapshot), {})
self.assertIs(self.planner.representatives[str(SPECIES)], primary)
self.assertIn(30, self.planner.retained)
self.assertFalse(any(a.kind in ("feed", "sell", "collect") for a in actions))
self.assertIn("主培养", self.planner.statuses[10])
def test_confirmed_removed_primary_allows_selector_to_choose_new_primary(self):
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
self.plan([primary, backup])
self.assertEqual(self.plan([backup], self.policy(action="feed"), managed=(10,)), [])
self.assertIs(self.planner.representatives[str(SPECIES)], backup)
self.assertEqual(self.planner.retained, {10})
def test_ordinary_cross_species_feed_farming_and_priorities_still_work(self):
first = self.mon(1, "SSSS", level=30, species=1002010)
second = self.mon(2, "SSSS", level=20, potentialLevel=3, species=1003010)
foods = [self.mon(mid, species=1001010, level=1, exp=0) for mid in (3, 4, 5)]
policy = Policy(strategy="experience", protect_star=6, protect_quality=5,
fill=False, feed_targets={"1": 1, "2": 2})
actions = self.plan([first, second] + foods, policy, managed=(3, 4, 5))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 2, "foods": [3, 4, 5]}])
if __name__ == "__main__":
unittest.main()