Keep multi-account refresh responsive and batch monster feeding
This commit is contained in:
@@ -169,6 +169,9 @@ class AccountGuiTests(unittest.TestCase):
|
||||
self.connect(second, "account-b", 2, 202, calls)
|
||||
self.assertNotEqual(first.state, second.state)
|
||||
self.assertIsNot(first.pool, second.pool)
|
||||
hub.tabs.setCurrentWidget(first)
|
||||
for page in (first.egg_page, first.monster_page, first.room_page):
|
||||
first.tabs.setCurrentWidget(page)
|
||||
self.assertEqual([first.slots.rowCount(), first.eggs.rowCount(), first.monsters.rowCount(), first.rooms_table.rowCount()], [11, 4, 4, 1])
|
||||
self.assertEqual(first.saved_sessions.count(), 1)
|
||||
first.start_monitor.setChecked(True)
|
||||
|
||||
@@ -396,9 +396,11 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
snapshot.raw["currentTasks"] = [{"id": 88, "typeId": key, "curStep": 1}]
|
||||
snapshot.monsters[900].update(level=20, potentialLevel=2)
|
||||
window.render(snapshot, [])
|
||||
window.refresh_target_choices(snapshot)
|
||||
window.target.setCurrentIndex(window.target.findData(900))
|
||||
self.assertIn("上限 20", window.target_status.text())
|
||||
reward = window.catalog.data["task_info"][key]["reward"]
|
||||
window.tabs.setCurrentWidget(window.quests_table.parentWidget())
|
||||
self.assertEqual(int(window.quests_table.item(0, 4).text()), reward["ke"])
|
||||
self.assertIn("氪金", window.summary.text())
|
||||
finally:
|
||||
@@ -415,6 +417,7 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
window.start_monitor.setChecked(True)
|
||||
before = len(window.engine.snapshot.raw["monsters"])
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if int(window.monsters.item(i, 0).text()) == mid)
|
||||
window.monsters.selectRow(row)
|
||||
select(101)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import copy
|
||||
import unittest
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.model import Catalog, Planner, Policy
|
||||
|
||||
|
||||
class BatchFeedingTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
self.snapshot = demo_snapshot(self.catalog)
|
||||
template = self.snapshot.raw["monsters"][0]
|
||||
foods = [copy.deepcopy(template) | {"id": 101 + i, "process": 3, "mode": 2, "roomId": 1} for i in range(4)]
|
||||
self.snapshot.raw["monsters"] = foods + [self.snapshot.monsters[900]]
|
||||
self.snapshot.raw["stacks"] = []
|
||||
self.planner = Planner(self.catalog)
|
||||
self.planner.managed.update(m["id"] for m in foods)
|
||||
self.policy = Policy(strategy="experience", protect_star=6, protect_quality=5, feed_target=900, fill=False)
|
||||
|
||||
def test_all_eligible_foods_use_one_request_and_log_names_and_ids(self):
|
||||
actions = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(len(actions), 1)
|
||||
self.assertEqual(actions[0].payload, {"targetId": 900, "foods": [101, 102, 103, 104]})
|
||||
for mid in (900, 101, 102, 103, 104):
|
||||
self.assertIn(self.catalog.monster_label(self.snapshot.monsters[mid]), actions[0].description)
|
||||
|
||||
def test_locked_team_and_unmanaged_foods_are_excluded(self):
|
||||
self.snapshot.monsters[102]["lock"] = 1
|
||||
self.snapshot.raw["teams"][0]["monsters"].append(103)
|
||||
self.planner.managed.discard(104)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["foods"], [101])
|
||||
|
||||
def test_remaining_experience_bounds_batch_at_current_breakthrough_cap(self):
|
||||
target = self.snapshot.monsters[900]
|
||||
target.update(level=19, potentialLevel=2, exp=self.catalog.data["monster_level"]["20"] - 1)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["foods"], [101])
|
||||
target["level"] = 20
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
|
||||
|
||||
def test_full_first_target_advances_to_next_priority(self):
|
||||
first = self.snapshot.monsters[900]
|
||||
first.update(level=20, potentialLevel=2)
|
||||
self.snapshot.raw["monsters"].append(copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0})
|
||||
self.policy.feed_targets = {"900": 1, "901": 2}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 901)
|
||||
|
||||
def test_collect_then_feed_all_in_two_batches(self):
|
||||
for mid in (101, 102, 103, 104):
|
||||
self.snapshot.monsters[mid].update(process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": i + 1, "position": i, "monsterId": 101 + i} for i in range(4)]
|
||||
engine = Engine(self.catalog)
|
||||
engine.snapshot, engine.policy, engine.auto = self.snapshot, self.policy, True
|
||||
_, actions, _ = engine.poll()
|
||||
self.assertTrue(all(self.snapshot.monsters[mid]["process"] == 3 for mid in (101, 102, 103, 104)))
|
||||
self.assertEqual(actions[0].payload["foods"], [101, 102, 103, 104])
|
||||
engine.poll()
|
||||
self.assertEqual(set(self.snapshot.monsters), {900})
|
||||
|
||||
def test_collection_reserves_room_space_for_entire_batch(self):
|
||||
for mid in (101, 102, 103, 104):
|
||||
self.snapshot.monsters[mid].update(process=2, roomId=None)
|
||||
room_type = str(self.snapshot.raw["rooms"][0]["typeId"])
|
||||
self.catalog.data["room_info"][room_type]["maxNum"] = 3
|
||||
actions = self.planner.plan(self.snapshot, self.policy)
|
||||
self.assertEqual(sum(len(d["monsterId"]) for d in actions[0].payload["datas"]), 2)
|
||||
@@ -73,8 +73,8 @@ class CoreTests(unittest.TestCase):
|
||||
mon.update(process=3, roomId=1)
|
||||
snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
plans = planner.plan(snapshot, policy)
|
||||
self.assertEqual(plans[0].kind, "feed")
|
||||
self.assertEqual(plans[0].payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
feeding = next(a for a in plans if a.kind == "feed")
|
||||
self.assertEqual(feeding.payload, {"targetId": 900, "foods": [mon["id"]]})
|
||||
snapshot.monsters[900]["level"] = policy.target_level
|
||||
self.assertFalse(any(a.kind == "feed" for a in planner.plan(snapshot, policy)))
|
||||
|
||||
|
||||
@@ -199,6 +199,7 @@ class GrowthGuiTests(unittest.TestCase):
|
||||
window.engine.policy = window.read_policy()
|
||||
window.engine.snapshot = client.snapshot()
|
||||
window.render(window.engine.snapshot, window.engine.plans())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.slots.rowCount()) if window.slots.item(i, 1).text() == "1")
|
||||
self.assertIn("待同步", window.slots.item(row, 5).text())
|
||||
self.assertIn("待成熟", window.slots.item(row, 7).text())
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.engine import demo_snapshot
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.api import Client, Session, encode
|
||||
from ranch_assistant.tests.test_activities import scenario
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
class ResponsivenessTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window):
|
||||
for _ in range(400):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if not window.busy:
|
||||
return
|
||||
self.fail("Background operation did not complete")
|
||||
|
||||
def test_hidden_maps_are_not_rebuilt_on_poll(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.tabs.setCurrentIndex(0)
|
||||
with patch.object(window, "render_maps") as maps:
|
||||
window.render(window.engine.snapshot, [])
|
||||
maps.assert_not_called()
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_account_does_not_rebuild_large_monster_table(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.presentation_active = False
|
||||
snapshot = demo_snapshot(window.catalog)
|
||||
template = snapshot.raw["monsters"][-1]
|
||||
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(500)]
|
||||
with patch.object(window.monsters, "setCellWidget") as cells:
|
||||
window.engine.snapshot = snapshot
|
||||
window.render(snapshot, [])
|
||||
self.assertEqual(cells.call_count, 0)
|
||||
self.assertIn("魔物 500", window.data_summary.text())
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_unchanged_maps_reuse_controls_and_keep_edits(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
catalog, snapshot = scenario()
|
||||
window.catalog = catalog
|
||||
window.engine.catalog = catalog
|
||||
window.engine.snapshot = snapshot
|
||||
window.render_maps()
|
||||
original = window.maps_tree.topLevelItem(0).child(0)
|
||||
edit = window.maps_tree.itemWidget(original, 8)
|
||||
edit.setText("12")
|
||||
window.render_maps()
|
||||
self.assertIs(window.maps_tree.topLevelItem(0).child(0), original)
|
||||
self.assertIs(window.maps_tree.itemWidget(original, 8), edit)
|
||||
self.assertEqual(edit.text(), "12")
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_debug_does_not_format_large_json(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
event = {"time": "2026-11-07T23:30:00+08:00", "kind": "response", "operation": "test", "body": {"rows": ["value"] * 1000}}
|
||||
with patch.object(window.debug_window, "selected_text", wraps=window.debug_window.selected_text) as formatting:
|
||||
window.on_network_event(event)
|
||||
formatting.assert_not_called()
|
||||
self.assertEqual(window.debug_window.rows.rowCount(), 1)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_slow_network_jobs_leave_ui_timer_responsive_and_accounts_parallel(self):
|
||||
with workspace_temp() as folder:
|
||||
windows = [Window(folder / str(i)) for i in range(2)]
|
||||
release = threading.Event()
|
||||
started = [threading.Event(), threading.Event()]
|
||||
beats, worker_threads = [], []
|
||||
timer = C.QTimer()
|
||||
timer.setInterval(5)
|
||||
timer.timeout.connect(lambda: beats.append(True))
|
||||
try:
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
self.wait(window)
|
||||
def work(index):
|
||||
worker_threads.append(threading.get_ident())
|
||||
started[index].set()
|
||||
release.wait(2)
|
||||
return "done"
|
||||
timer.start()
|
||||
for i, window in enumerate(windows):
|
||||
window.submit("test", lambda i=i: work(i))
|
||||
for _ in range(20):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
self.assertTrue(all(event.is_set() for event in started))
|
||||
self.assertGreater(len(beats), 3)
|
||||
self.assertTrue(all(tid != threading.get_ident() for tid in worker_threads))
|
||||
self.assertTrue(all(w.busy for w in windows))
|
||||
finally:
|
||||
release.set()
|
||||
timer.stop()
|
||||
for window in windows:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_large_two_account_replies_and_inventory_batches_keep_ui_responsive(self):
|
||||
with workspace_temp() as folder:
|
||||
windows = [Window(folder / str(i)) for i in range(2)]
|
||||
clients, beats = [], []
|
||||
timer = C.QTimer()
|
||||
timer.setInterval(5)
|
||||
timer.timeout.connect(lambda: beats.append(time.perf_counter()))
|
||||
try:
|
||||
for index, window in enumerate(windows):
|
||||
window.timer.stop()
|
||||
self.wait(window)
|
||||
snapshot = demo_snapshot(window.catalog)
|
||||
template = snapshot.raw["monsters"][-1]
|
||||
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(80 if index == 0 else 500)]
|
||||
types = [int(k) for k in window.catalog.monsters if window.catalog.total_time(k) > 0][:200]
|
||||
snapshot.raw["items"] = [{"id": 2000 + i, "typeId": key, "num": 20} for i, key in enumerate(types)]
|
||||
client = Client(Session("http://127.0.0.1/test/", "synthetic-token"), trace=window.trace)
|
||||
data = encode(snapshot.raw | {"resCode": 0}, client.session.key)
|
||||
def post(*args, response_data=data, **kwargs):
|
||||
time.sleep(.7) # emulate the user's network latency
|
||||
return SimpleNamespace(status_code=200, content=response_data, headers={})
|
||||
client.http.post = post
|
||||
clients.append(client)
|
||||
window.engine = Engine(window.catalog, client)
|
||||
windows[1].set_presentation_active(False)
|
||||
windows[0].tabs.setCurrentWidget(windows[0].egg_page)
|
||||
windows[0].show()
|
||||
self.app.processEvents()
|
||||
timer.start()
|
||||
for window in windows:
|
||||
window.refresh()
|
||||
for _ in range(800):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
batch = getattr(windows[0].eggs, "row_batch", None)
|
||||
if not any(w.busy for w in windows) and (not batch or not batch.running):
|
||||
break
|
||||
self.assertFalse(any(w.busy for w in windows))
|
||||
self.assertEqual(windows[0].eggs.rowCount(), 200)
|
||||
self.assertEqual(windows[1].monsters.rowCount(), 0)
|
||||
self.assertGreater(len(beats), 10)
|
||||
self.assertLess(max(b - a for a, b in zip(beats, beats[1:])), .25)
|
||||
self.assertTrue(any(e["operation"] == "刷新耗时" for e in windows[0].trace.events))
|
||||
finally:
|
||||
timer.stop()
|
||||
for window in windows:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
@@ -180,6 +180,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(window)
|
||||
self.assertEqual(window.tabs.tabText(0), "登录")
|
||||
window.tabs.setCurrentWidget(window.egg_page)
|
||||
key = window.eggs.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
|
||||
window.eggs.cellWidget(0, 3).setChecked(True)
|
||||
window.eggs.cellWidget(0, 4).setValue(1)
|
||||
@@ -192,6 +193,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
row = next(i for i in range(window.eggs.rowCount()) if window.eggs.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == key)
|
||||
self.assertEqual(window.eggs.item(row, 2).text(), "0")
|
||||
self.assertTrue(window.eggs.cellWidget(row, 3).isChecked())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == "900")
|
||||
window.monsters.cellWidget(row, 8).setChecked(True)
|
||||
window.monsters.cellWidget(row, 9).setValue(1)
|
||||
@@ -273,6 +275,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(window)
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == str(mid))
|
||||
window.monsters.selectRow(row)
|
||||
select(101)
|
||||
|
||||
Reference in New Issue
Block a user