Files
myrzx_bot/ranch_assistant/tests/test_cultivation.py
T
AttilaNet 3b5da7ebcb Fix gift item instance IDs and per-monster cooldown scheduling
Use bag instance IDs required by the client protocol. Apply confirmed feel and giftDate values across stale queries, skip cooling targets, and schedule ready gifts independently of random polling. Replan cultivation locally and retain local strategy errors in diagnostics.
2026-11-08 13:08:12 +08:00

216 lines
12 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
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.gifts import GiftPlanner
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
from ranch_assistant.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):
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")}}
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_are_chosen_once_persisted_and_do_not_leak_to_other_role(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)
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)
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_growth_is_kept_independently_of_four_s_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.keep_better_quality = False
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "sell")
policy.keep_better_quality = True
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)
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()