Settle player level and stamina; unify strategy configuration
This commit is contained in:
@@ -228,6 +228,11 @@ class ActivityGuiTests(unittest.TestCase):
|
||||
window.engine = Engine(catalog)
|
||||
window.engine.snapshot = snapshot
|
||||
window.render_maps()
|
||||
for _ in range(200):
|
||||
if not window.map_render_timer.running:
|
||||
break
|
||||
QTest.qWait(5)
|
||||
self.assertFalse(window.map_render_timer.running)
|
||||
window.render_daily()
|
||||
self.assertEqual(window.maps_tree.topLevelItem(0).text(0), "莉莉托斯")
|
||||
region = window.maps_tree.topLevelItem(0)
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import copy
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog, Snapshot
|
||||
|
||||
|
||||
NOW = 1800000000
|
||||
LEVEL = "masterService/masterLevelUpdate"
|
||||
STAMINA = "masterService/masterCheckTiAdd"
|
||||
|
||||
|
||||
class MasterClient:
|
||||
def __init__(self, catalog):
|
||||
self.raw = copy.deepcopy(demo_snapshot(catalog).raw)
|
||||
self.raw.update(monsters=[], items=[], stacks=[])
|
||||
self.raw["master"].update(level=1, exp=0, ti=5, timeTi=(NOW - 360) * 1000)
|
||||
self.calls = []
|
||||
self.responses = {LEVEL: {"level": 3}, STAMINA: {"ti": 6, "timeTi": NOW * 1000}}
|
||||
|
||||
def snapshot(self):
|
||||
return Snapshot(copy.deepcopy(self.raw))
|
||||
|
||||
def call(self, path, payload=None):
|
||||
self.calls.append((path, payload))
|
||||
return self.responses[path]
|
||||
|
||||
def persist_session(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
|
||||
class MasterSyncTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.clock = patch("ranch_assistant.model.time.time", return_value=NOW)
|
||||
self.now = self.clock.start()
|
||||
self.addCleanup(self.clock.stop)
|
||||
self.catalog = Catalog()
|
||||
self.catalog.data = self.catalog.data | {"game_setting": self.catalog.data["game_setting"] | {"tiCD": 360}}
|
||||
self.client = MasterClient(self.catalog)
|
||||
self.engine = Engine(self.catalog, self.client)
|
||||
|
||||
def test_monitor_settles_stamina_and_preserves_server_result_across_stale_read(self):
|
||||
snapshot, _, _ = self.engine.poll()
|
||||
self.assertEqual(snapshot.raw["master"]["ti"], 6)
|
||||
self.assertEqual(self.client.calls, [(STAMINA, {})])
|
||||
self.engine.poll()
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 6)
|
||||
self.assertEqual(len(self.client.calls), 1)
|
||||
|
||||
def test_experience_threshold_requests_server_level_without_starting_automation(self):
|
||||
self.client.raw["master"].update(exp=self.catalog.data["farm_level"]["4"], timeTi=NOW * 1000)
|
||||
snapshot, _, _ = self.engine.poll()
|
||||
self.assertEqual(snapshot.raw["master"]["level"], 3)
|
||||
self.assertEqual(self.client.calls, [(LEVEL, {})])
|
||||
self.assertFalse(self.engine.auto)
|
||||
|
||||
def test_before_recovery_boundary_and_level_threshold_no_request(self):
|
||||
self.client.raw["master"].update(exp=self.catalog.data["farm_level"]["2"] - 1,
|
||||
timeTi=(NOW - 359) * 1000)
|
||||
self.engine.poll()
|
||||
self.assertEqual(self.client.calls, [])
|
||||
self.assertFalse(self.engine.master_sync_due())
|
||||
self.now.return_value = NOW + 1
|
||||
self.assertTrue(self.engine.master_sync_due())
|
||||
self.engine.sync_master()
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 6)
|
||||
|
||||
def test_fresh_consumption_overrides_cached_stamina_and_levels_never_regress(self):
|
||||
self.client.raw["master"]["exp"] = self.catalog.data["farm_level"]["3"]
|
||||
self.engine.poll()
|
||||
self.client.raw["master"].update(ti=2, timeTi=NOW * 1000)
|
||||
self.engine.read_snapshot()
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 2)
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["level"], 3)
|
||||
self.assertIsNone(self.engine.master_sync.stamina)
|
||||
|
||||
def test_no_progress_and_failures_are_throttled_per_account(self):
|
||||
self.client.responses[STAMINA] = {"ti": 5, "timeTi": (NOW - 360) * 1000}
|
||||
with patch("ranch_assistant.master_sync.time.monotonic", return_value=100) as monotonic:
|
||||
self.engine.poll()
|
||||
self.engine.poll()
|
||||
self.assertEqual(len(self.client.calls), 1)
|
||||
other = Engine(self.catalog, MasterClient(self.catalog))
|
||||
other.poll()
|
||||
self.assertEqual(len(other.client.calls), 1)
|
||||
monotonic.return_value = 130
|
||||
self.assertTrue(self.engine.master_sync_due())
|
||||
self.client.call = unittest.mock.Mock(side_effect=RuntimeError("test failure"))
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.engine.sync_master()
|
||||
self.assertFalse(self.engine.master_sync_due())
|
||||
|
||||
def test_fast_hatching_never_settles_player_state(self):
|
||||
self.client.raw["master"]["exp"] = self.catalog.data["farm_level"]["3"]
|
||||
self.engine.poll(hatch_only=True)
|
||||
self.assertEqual(self.client.calls, [])
|
||||
|
||||
def test_full_stamina_uses_server_timestamp_without_repeated_requests(self):
|
||||
self.client.raw["master"]["ti"] = 600
|
||||
self.client.responses[STAMINA] = {"ti": 600, "timeTi": NOW * 1000}
|
||||
self.engine.poll()
|
||||
self.engine.poll()
|
||||
self.assertEqual(len(self.client.calls), 1)
|
||||
self.assertFalse(self.engine.master_sync_due())
|
||||
|
||||
def test_max_level_and_absent_timestamp_do_not_request(self):
|
||||
self.client.raw["master"].update(level=70, exp=10**9, timeTi=None)
|
||||
self.engine.poll()
|
||||
self.assertEqual(self.client.calls, [])
|
||||
|
||||
def test_incomplete_stamina_reply_never_fabricates_new_value(self):
|
||||
self.client.responses[STAMINA] = {"ti": 600}
|
||||
with self.assertRaisesRegex(ValueError, "ti / timeTi"):
|
||||
self.engine.poll()
|
||||
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 5)
|
||||
self.assertFalse(self.engine.master_sync_due())
|
||||
|
||||
|
||||
class MasterSyncGuiTests(unittest.TestCase):
|
||||
def test_recovery_deadline_uses_background_job_without_changing_poll_deadline(self):
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
from PySide6 import QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.api import Session
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
app = W.QApplication.instance() or W.QApplication([])
|
||||
with workspace_temp() as folder, patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
def wait():
|
||||
for _ in range(500):
|
||||
app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if not window.busy:
|
||||
return
|
||||
self.fail("Master sync worker did not finish")
|
||||
try:
|
||||
wait()
|
||||
client = MasterClient(window.catalog)
|
||||
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
|
||||
window.engine = Engine(window.catalog, client)
|
||||
window.engine.last_heartbeat = time.monotonic()
|
||||
window.engine.snapshot = client.snapshot()
|
||||
window.next_poll = float("inf")
|
||||
window.schedule()
|
||||
self.assertTrue(window.busy)
|
||||
wait()
|
||||
self.assertEqual(window.engine.snapshot.raw["master"]["ti"], 6)
|
||||
self.assertEqual(client.calls, [(STAMINA, {})])
|
||||
self.assertEqual(window.next_poll, float("inf"))
|
||||
self.assertFalse(window.execute.isChecked())
|
||||
self.assertFalse(window.monitoring)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
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.daily import DailyPolicy
|
||||
from ranch_assistant.engine import demo_snapshot
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.model import Catalog, Policy
|
||||
from ranch_assistant.policy_io import portable_config, import_config, portable_policy
|
||||
from ranch_assistant.quests import QuestPolicy
|
||||
from ranch_assistant.sweeping import SweepPolicy
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
class UnifiedPolicyTests(unittest.TestCase):
|
||||
def config(self):
|
||||
return {"policy": asdict(Policy(buy=True, gift_enabled=True, feed_target=900, room_id=999999,
|
||||
gift_targets={"900": 2}, gift_items={"30001": {"enabled": True, "reserve": 5}})),
|
||||
"quest_policy": asdict(QuestPolicy(enabled=True, max_money=100, item_reserves={"30001": 6})),
|
||||
"daily_policy": asdict(DailyPolicy(enabled=True, selected=["mail"])),
|
||||
"sweep_policy": asdict(SweepPolicy(enabled=True, rules={"0101": {"enabled": True, "level": 3, "limit": 5}}, keep_stamina=22)),
|
||||
"interval": 120, "overrides": {"1001010": {"sell_money": 151}}, "yield_stars": [1, 2],
|
||||
"token": "secret-test-only", "account": "private-test-only", "log_sizes": [600, 200]}
|
||||
|
||||
def test_all_strategies_round_trip_and_targets_match_other_account(self):
|
||||
snapshot = demo_snapshot(Catalog())
|
||||
exported = portable_config(self.config(), snapshot)
|
||||
text = json.dumps(exported)
|
||||
for secret in ("secret-test-only", "private-test-only", "999999", '"900"', "log_sizes"):
|
||||
self.assertNotIn(secret, text)
|
||||
snapshot.monsters[900]["id"] = 999
|
||||
config = import_config(exported, snapshot)
|
||||
self.assertEqual(config["policy"]["feed_targets"], {"999": 1})
|
||||
self.assertEqual(config["policy"]["gift_targets"], {"999": 2})
|
||||
self.assertEqual(config["policy"]["feed_target"], 0)
|
||||
self.assertEqual(config["policy"]["room_id"], 0)
|
||||
self.assertTrue(config["policy"]["gift_enabled"])
|
||||
for key in ("quest_policy", "daily_policy", "sweep_policy", "interval", "overrides", "yield_stars"):
|
||||
self.assertEqual(config[key], self.config()[key])
|
||||
|
||||
def test_old_files_import_without_replacing_other_strategy_sections(self):
|
||||
config = import_config(portable_policy(Policy(protect_quality=6)))
|
||||
self.assertEqual(list(config), ["policy"])
|
||||
self.assertEqual(config["policy"]["protect_quality"], 6)
|
||||
self.assertFalse(config["policy"]["enabled"])
|
||||
|
||||
def test_invalid_bundle_rejected_before_applying(self):
|
||||
exported = portable_config(self.config())
|
||||
for value in (exported | {"schema": 100}, exported | {"interval": 0},
|
||||
exported | {"daily_policy": []}, exported | {"yield_stars": [None]},
|
||||
exported | {"policy": exported["policy"] | {"target_level": "bad"}},
|
||||
exported | {"sweep_policy": exported["sweep_policy"] | {"rules": {"0101": None}}}):
|
||||
with self.assertRaises((ValueError, TypeError)):
|
||||
import_config(value)
|
||||
|
||||
|
||||
class StrategyGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window):
|
||||
for _ in range(500):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if not window.busy:
|
||||
return
|
||||
self.fail("Offline task did not finish")
|
||||
|
||||
def test_separate_pages_and_unified_import_apply_without_starting_execution(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
self.assertEqual([window.automation_tabs.tabText(i) for i in range(3)],
|
||||
["孵蛋策略", "牧场策略", "喂养策略"])
|
||||
self.assertEqual(window.tabs.tabText(window.tabs.indexOf(window.gift_page)), "自动赠礼")
|
||||
self.assertTrue(window.gift_page.isAncestorOf(window.gift_enabled))
|
||||
self.assertTrue(window.feed_scroll.isAncestorOf(window.feed))
|
||||
value = portable_config(UnifiedPolicyTests().config(), window.engine.snapshot)
|
||||
path = folder / "portable.json"
|
||||
path.write_text(json.dumps(value), encoding="utf-8")
|
||||
with patch("ranch_assistant.gui.W.QFileDialog.getOpenFileName", return_value=(str(path), "")):
|
||||
window.import_policies()
|
||||
self.assertFalse(window.execute.isChecked())
|
||||
self.assertFalse(window.engine.auto)
|
||||
self.assertTrue(window.engine.policy.gift_enabled)
|
||||
self.assertEqual(window.engine.quest_policy.max_money, 100)
|
||||
self.assertEqual(window.engine.sweep_policy.keep_stamina, 22)
|
||||
self.assertEqual(window.engine.daily_policy.selected, ["mail"])
|
||||
self.assertEqual(window.interval.currentData(), 120)
|
||||
window.quest_money.setValue(42)
|
||||
window.gift_liked_only.setChecked(False)
|
||||
QTest.qWait(400)
|
||||
self.assertEqual(window.engine.quest_policy.max_money, 42)
|
||||
self.assertFalse(window.engine.policy.gift_liked_only)
|
||||
with patch("ranch_assistant.gui.W.QFileDialog.getSaveFileName", return_value=(str(path), "")):
|
||||
window.export_policies()
|
||||
exported = json.loads(path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(import_config(exported, window.engine.snapshot)["quest_policy"]["max_money"], 42)
|
||||
self.assertFalse(any("保存规则" in b.text() for b in window.findChildren(W.QPushButton)))
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_gift_only_workflow_does_not_require_hatch_rules(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.ranch_enabled.setChecked(False)
|
||||
window.gift_enabled.setChecked(True)
|
||||
with patch.object(window, "refresh"):
|
||||
window.start_workflow()
|
||||
self.assertTrue(window.execute.isChecked())
|
||||
finally:
|
||||
window.close()
|
||||
Reference in New Issue
Block a user