249 lines
14 KiB
Python
249 lines
14 KiB
Python
import copy
|
|
from dataclasses import asdict
|
|
import json
|
|
import os
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
|
from PySide6 import QtWidgets as W
|
|
from PySide6.QtTest import QTest
|
|
|
|
from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
|
|
from ranch_assistant.engine import Engine, demo_snapshot
|
|
from ranch_assistant.gifts import GiftPlanner
|
|
from ranch_assistant.gui import Window
|
|
from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
|
|
from ranch_assistant.policy_io import import_config, portable_config
|
|
from ranch_assistant.tests.test_core import workspace_temp
|
|
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
|
from ranch_assistant.api import Session
|
|
|
|
|
|
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3, **values):
|
|
row = catalog.monster(species)
|
|
return {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
|
|
"feel": feel, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0,
|
|
**{"g" + stat.capitalize(): row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
|
|
for stat in ("atk", "def", "hp", "dex")}, **values}
|
|
|
|
|
|
def graded_monster(catalog, mid, grades, **values):
|
|
mon = monster(catalog, mid, **values)
|
|
row = catalog.monster(mon["typeId"])
|
|
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
|
|
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
|
|
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
|
|
return mon
|
|
|
|
|
|
class CultivationTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.catalog = Catalog()
|
|
self.snapshot = demo_snapshot(self.catalog)
|
|
self.snapshot.raw.update(monsters=[], teams=[], stacks=[])
|
|
|
|
def test_representative_prefers_level_then_feel_then_growth(self):
|
|
rows = [monster(self.catalog, 1, level=11, feel=0, scale=.1),
|
|
monster(self.catalog, 2, level=10, feel=99, scale=1),
|
|
monster(self.catalog, 3, level=11, feel=1, scale=.1),
|
|
monster(self.catalog, 4, level=11, feel=1, scale=.8),
|
|
monster(self.catalog, 5, level=99, feel=200, scale=1, process=2)]
|
|
self.snapshot.raw["monsters"] = rows
|
|
selector = CultivationSelector(self.catalog)
|
|
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 4)
|
|
rows[1]["level"] = 12
|
|
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
|
|
|
|
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"
|
|
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
|
|
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)]
|
|
selector = CultivationSelector(self.catalog)
|
|
selector.select(self.snapshot)
|
|
updated = Snapshot(copy.deepcopy(self.snapshot.raw))
|
|
updated.raw["monsters"][0].update(giftTime=123456789, entangleLevel=2)
|
|
chosen = selector.select(updated)["1001010"]
|
|
self.assertIs(chosen, updated.raw["monsters"][0])
|
|
self.assertEqual((chosen["giftTime"], chosen["entangleLevel"]), (123456789, 2))
|
|
|
|
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(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
|
|
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")
|
|
|
|
def test_missing_species_or_unknown_reference_is_conservatively_retained(self):
|
|
hatched = monster(self.catalog, 2, process=2)
|
|
self.snapshot.raw["monsters"] = [hatched]
|
|
policy = Policy(protect_star=6, protect_quality=5, keep_better_quality=True)
|
|
planner = Planner(self.catalog)
|
|
self.assertIn("首次", planner.protection_reason(hatched, self.snapshot, policy))
|
|
reference = monster(self.catalog, 1, level=50)
|
|
reference["gAtk"] = None
|
|
self.snapshot.raw["monsters"].append(reference)
|
|
self.assertIn("尚未同步", planner.protection_reason(hatched, self.snapshot, policy))
|
|
|
|
def test_gifts_target_only_the_representative_and_do_not_move_to_duplicates_at_cap(self):
|
|
best = monster(self.catalog, 1, level=30)
|
|
duplicate = monster(self.catalog, 2, level=29, feel=50, scale=1)
|
|
self.snapshot.raw["monsters"] = [best, duplicate]
|
|
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30005, "num": 20}]
|
|
policy = Policy(gift_enabled=True, gift_auto_representative=True, gift_liked_only=False,
|
|
gift_targets={"2": 1}, gift_items={"30005": {"enabled": True, "reserve": 2}})
|
|
planner = GiftPlanner(self.catalog)
|
|
self.assertEqual(planner.plan(self.snapshot, policy)[0].payload["monsterId"], 1)
|
|
best["feel"] = self.catalog.max_feel(best)
|
|
self.assertEqual(planner.plan(self.snapshot, policy), [])
|
|
best["feel"] = 0
|
|
best["giftTime"] = self.snapshot.now * 1000
|
|
self.assertEqual(planner.plan(self.snapshot, policy), [])
|
|
|
|
def test_cooldown_or_unavailable_food_skips_to_other_species_without_wasting_on_duplicates(self):
|
|
self.snapshot.raw["monsters"] = [monster(self.catalog, 1, level=50), monster(self.catalog, 2, level=40),
|
|
monster(self.catalog, 3, level=20, species=1002010)]
|
|
self.snapshot.raw["monsters"][0]["giftTime"] = self.snapshot.now * 1000
|
|
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30005, "num": 3}]
|
|
policy = Policy(gift_enabled=True, gift_auto_representative=True, gift_liked_only=False,
|
|
gift_items={"30005": {"enabled": True, "reserve": 2}})
|
|
planner = GiftPlanner(self.catalog)
|
|
self.assertEqual(planner.plan(self.snapshot, policy)[0].payload["monsterId"], 3)
|
|
self.snapshot.raw["items"][0]["num"] = 2
|
|
self.assertEqual(planner.plan(self.snapshot, policy), [])
|
|
|
|
def test_auto_gift_representative_is_also_protected_from_hatch_disposal(self):
|
|
representative = monster(self.catalog, 1, level=20)
|
|
self.snapshot.raw["monsters"] = [representative, monster(self.catalog, 2, level=1)]
|
|
policy = Policy(strategy="gold", protect_star=6, protect_quality=5, gift_auto_representative=True)
|
|
planner = Planner(self.catalog)
|
|
self.assertTrue(planner.protected(representative, self.snapshot, policy))
|
|
self.assertFalse(planner.protected(self.snapshot.monsters[2], self.snapshot, policy))
|
|
|
|
def test_growth_score_normalizes_health_and_attack_to_their_own_ranges(self):
|
|
mon = monster(self.catalog, 1, scale=.5)
|
|
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):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.app = W.QApplication.instance() or W.QApplication([])
|
|
|
|
def wait(self, predicate):
|
|
for _ in range(800):
|
|
self.app.processEvents()
|
|
QTest.qWait(2)
|
|
if predicate():
|
|
return
|
|
self.fail("Cultivation preview did not finish")
|
|
|
|
def test_rule_flags_autosave_and_portable_settings_and_representative_preview(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
|
window.keep_better_quality.setChecked(True)
|
|
window.gift_auto_representative.setChecked(True)
|
|
self.wait(lambda: not window.auto_save_timer.isActive())
|
|
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
|
|
self.assertTrue(saved["policy"]["keep_better_quality"])
|
|
self.assertTrue(window.engine.policy.gift_auto_representative)
|
|
imported = import_config(portable_config(window.config_value(), window.engine.snapshot), window.engine.snapshot)
|
|
self.assertTrue(imported["policy"]["keep_better_quality"])
|
|
self.assertTrue(imported["policy"]["gift_auto_representative"])
|
|
window.engine.plans()
|
|
window.tabs.setCurrentWidget(window.gift_page)
|
|
self.assertGreater(window.gift_representatives.rowCount(), 0)
|
|
self.assertFalse(window.strategy_toggle.isChecked())
|
|
window.load_config()
|
|
self.assertTrue(window.keep_better_quality.isChecked())
|
|
self.assertTrue(window.gift_auto_representative.isChecked())
|
|
finally:
|
|
window.close()
|
|
|
|
def test_selecting_representatives_replans_locally_without_an_api_request(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
calls = []
|
|
try:
|
|
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
|
session = Session("http://127.0.0.1/", "synthetic-token", account_id="fixture", server_id=1, role_id=101)
|
|
client = fake_client(session, window.catalog, calls)
|
|
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, 101))))
|
|
window.gift_auto_representative.setChecked(True)
|
|
self.wait(lambda: not window.auto_save_timer.isActive() and not window.busy and bool(window.engine.cultivation.selected))
|
|
self.assertEqual(calls, [])
|
|
self.assertTrue(window.monitoring)
|
|
self.assertFalse(window.strategy_toggle.isChecked())
|
|
finally:
|
|
window.close()
|
|
|
|
def test_local_selection_failure_is_recorded_as_local_and_keeps_monitoring(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
|
window.monitoring = True
|
|
with patch.object(window.engine.cultivation, "select", side_effect=ValueError("fixture-selection-failure")):
|
|
window.gift_auto_representative.setChecked(True)
|
|
self.wait(lambda: any("fixture-selection-failure" in e.get("message", "") for e in window.trace.events))
|
|
self.wait(lambda: not window.busy)
|
|
event = next(e for e in window.trace.events if "fixture-selection-failure" in e.get("message", ""))
|
|
self.assertEqual(event["scope"], "local")
|
|
self.assertEqual(event["kind"], "error")
|
|
self.assertTrue(window.monitoring)
|
|
self.assertFalse(window.strategy_toggle.isChecked())
|
|
finally:
|
|
window.close()
|