320 lines
18 KiB
Python
320 lines
18 KiB
Python
"""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()
|