Files
myrzx_bot/ranch_assistant/tests/test_master_sync.py
T

166 lines
7.0 KiB
Python

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()