312 lines
15 KiB
Python
312 lines
15 KiB
Python
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 import presentation
|
|
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, "setItemWidget") 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_hidden_account_skips_worker_monster_preparation_and_prepares_on_show(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
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(500)]
|
|
window.set_presentation_active(False)
|
|
window.tabs.setCurrentWidget(window.monster_page)
|
|
window.engine.poll = lambda **kwargs: (snapshot, [], "fixture poll")
|
|
threads = []
|
|
build = presentation.monster_rows
|
|
def record_build(*args, **kwargs):
|
|
threads.append(threading.get_ident())
|
|
return build(*args, **kwargs)
|
|
with patch.object(presentation, "monster_rows", side_effect=record_build) as preparing, patch("ranch_assistant.gui.monster_rows", side_effect=AssertionError("GUI thread monster fallback")):
|
|
window.refresh()
|
|
self.wait(window)
|
|
self.assertEqual(preparing.call_count, 0, "hidden account formatted monster rows")
|
|
window.set_presentation_active(True)
|
|
for _ in range(600):
|
|
self.app.processEvents()
|
|
QTest.qWait(5)
|
|
if not window.busy and len(window.monsters.monster_items) == 500:
|
|
break
|
|
self.assertEqual(len(window.monsters.monster_items), 500)
|
|
self.assertTrue(threads)
|
|
self.assertTrue(all(tid != threading.get_ident() for tid in threads))
|
|
self.assertTrue(window.engine.presentation_active)
|
|
finally:
|
|
self.wait(window)
|
|
window.close()
|
|
|
|
def test_visible_other_page_skips_monster_preparation_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(presentation, "monster_rows", wraps=presentation.monster_rows) as preparing:
|
|
window.refresh()
|
|
self.wait(window)
|
|
self.assertEqual(preparing.call_count, 0, "another page formatted monster rows")
|
|
finally:
|
|
window.close()
|
|
|
|
def test_warm_monster_view_finishes_preparation_when_unchanged_after_show(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
self.wait(window)
|
|
window.tabs.setCurrentWidget(window.monster_page)
|
|
for _ in range(500):
|
|
self.app.processEvents()
|
|
QTest.qWait(2)
|
|
if not window.busy and not window.monster_render_timer.running:
|
|
break
|
|
original = dict(window.monsters.monster_items)
|
|
self.assertTrue(original)
|
|
window.set_presentation_active(False)
|
|
self.assertIsNone(window.prepared_views.monsters)
|
|
window.set_presentation_active(True)
|
|
for _ in range(500):
|
|
self.app.processEvents()
|
|
QTest.qWait(2)
|
|
if not window.busy and not window.monster_render_timer.running:
|
|
break
|
|
self.assertFalse(window.busy)
|
|
self.assertFalse(window.monster_render_timer.running)
|
|
self.assertEqual(window.monsters.monster_items, original)
|
|
finally:
|
|
self.wait(window)
|
|
window.close()
|
|
|
|
def test_prepare_views_default_stays_complete_and_opt_out_marks_monsters_dirty(self):
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
self.wait(window)
|
|
snapshot = window.engine.snapshot
|
|
with patch.object(presentation, "monster_rows", wraps=presentation.monster_rows) as preparing:
|
|
full = presentation.prepare_views(window.catalog, snapshot, set())
|
|
self.assertEqual(preparing.call_count, 1)
|
|
thin = presentation.prepare_views(window.catalog, snapshot, set(), include_monsters=False)
|
|
self.assertEqual(preparing.call_count, 1)
|
|
self.assertEqual(len(full.monsters), len(snapshot.raw["monsters"]))
|
|
self.assertEqual(full.monster_source, repr(snapshot.raw["monsters"]))
|
|
self.assertIsNone(thin.monsters)
|
|
self.assertIsNone(thin.monster_source)
|
|
self.assertIsInstance(full.maps, list)
|
|
self.assertIsInstance(thin.maps, list)
|
|
finally:
|
|
window.close()
|
|
|
|
def test_hidden_connection_sets_engine_visibility_before_first_plan(self):
|
|
from ranch_assistant.model import Snapshot
|
|
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
|
with workspace_temp() as folder:
|
|
window = Window(folder)
|
|
window.timer.stop()
|
|
try:
|
|
self.wait(window)
|
|
window.set_presentation_active(False)
|
|
previous = window.engine
|
|
session = Session("http://127.0.0.1/fixture/", "fixture-token", account_id="fixture", server_id=1, role_id=101)
|
|
client = fake_client(session, window.catalog, [])
|
|
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, 101))))
|
|
engine = window.engine
|
|
self.assertIsNot(engine, previous)
|
|
self.assertFalse(engine.presentation_active)
|
|
self.assertFalse(engine.progression_view_active)
|
|
observed = []
|
|
def plan():
|
|
observed.append((engine.presentation_active, threading.get_ident()))
|
|
return []
|
|
with patch.object(engine, "plans", side_effect=plan):
|
|
window.preview_cultivation()
|
|
self.wait(window)
|
|
self.assertEqual([active for active, _ in observed], [False])
|
|
self.assertTrue(all(tid != threading.get_ident() for _, tid in observed))
|
|
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(len(windows[1].monsters.monster_items), 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()
|