Use main-window menus, cache maps, and handle settled sweep events
This commit is contained in:
@@ -117,6 +117,82 @@ class AccountGuiTests(unittest.TestCase):
|
||||
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, role_id))))
|
||||
return client
|
||||
|
||||
def test_main_menu_routes_strategy_actions_to_selected_account_and_saves_immediately(self):
|
||||
with workspace_temp() as folder:
|
||||
hub = AccountsWindow(folder)
|
||||
hub.add_profile()
|
||||
windows = list(hub.windows.values())
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(windows)
|
||||
first, second = windows
|
||||
first.keep_money.setValue(1234)
|
||||
second.keep_money.setValue(5678)
|
||||
for window in windows:
|
||||
window.auto_save_timer.stop()
|
||||
for selected, other, expected in ((first, second, 1234), (second, first, 5678)):
|
||||
hub.tabs.setCurrentWidget(selected)
|
||||
with patch.object(selected, "import_policies") as imported, patch.object(other, "import_policies") as other_imported:
|
||||
hub.import_policy_action.trigger()
|
||||
imported.assert_called_once_with()
|
||||
other_imported.assert_not_called()
|
||||
with patch.object(selected, "export_policies") as exported, patch.object(other, "export_policies") as other_exported:
|
||||
hub.export_policy_action.trigger()
|
||||
exported.assert_called_once_with()
|
||||
other_exported.assert_not_called()
|
||||
with patch.object(other, "persist_settings") as other_saved:
|
||||
hub.save_policy_action.trigger()
|
||||
other_saved.assert_not_called()
|
||||
saved = json.loads((selected.state / "settings.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["policy"]["keep_money"], expected)
|
||||
self.assertEqual(selected.engine.policy.keep_money, expected)
|
||||
self.assertFalse(selected.execute.isChecked())
|
||||
finally:
|
||||
hub.close()
|
||||
|
||||
def test_only_main_window_has_menus_and_about_shows_versions(self):
|
||||
with workspace_temp() as folder:
|
||||
hub = AccountsWindow(folder)
|
||||
windows = list(hub.windows.values())
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(windows)
|
||||
self.assertEqual([action.text().split("(")[0] for action in hub.menuBar().actions()],
|
||||
["账号", "监控", "策略配置", "帮助"])
|
||||
for window in windows:
|
||||
self.assertIsNone(window.findChild(W.QMenuBar))
|
||||
labels = {button.text() for button in hub.findChildren(W.QPushButton)}
|
||||
for label in ("新增账号页签", "打开已保存账号", "恢复各页签的保存会话", "全部开始监控", "全部停止"):
|
||||
self.assertNotIn(label, labels)
|
||||
with patch.object(W.QMessageBox, "about") as about:
|
||||
hub.about_action.trigger()
|
||||
self.assertIn(gui.APP_VERSION, about.call_args.args[2])
|
||||
self.assertIn(gui.GAME_VERSION, about.call_args.args[2])
|
||||
finally:
|
||||
hub.close()
|
||||
|
||||
def test_strategy_menu_disables_when_no_account_is_open(self):
|
||||
with workspace_temp() as folder:
|
||||
hub = AccountsWindow(folder)
|
||||
windows = list(hub.windows.values())
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(windows)
|
||||
hub.close_profile(0)
|
||||
self.assertEqual(hub.tabs.count(), 0)
|
||||
self.assertTrue(all(not action.isEnabled() for action in hub.policy_actions))
|
||||
hub.add_profile()
|
||||
windows = list(hub.windows.values())
|
||||
for window in windows:
|
||||
window.timer.stop()
|
||||
self.wait(windows)
|
||||
self.assertTrue(all(action.isEnabled() for action in hub.policy_actions))
|
||||
finally:
|
||||
hub.close()
|
||||
|
||||
def test_closed_fresh_tab_does_not_start_queued_refresh_and_can_reopen(self):
|
||||
with workspace_temp() as folder:
|
||||
hub = AccountsWindow(folder)
|
||||
|
||||
@@ -112,6 +112,54 @@ class ActivityTests(unittest.TestCase):
|
||||
runner.run(client, self.snapshot, self.stage(), policy)
|
||||
self.assertTrue(SweepRunner(self.catalog, folder / "runs.json").state["pending"])
|
||||
|
||||
def test_reward_event_is_already_settled_and_does_not_block_next_sweep(self):
|
||||
runner = SweepRunner(self.catalog)
|
||||
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
|
||||
client = FakeClient(self.snapshot)
|
||||
response = {"resCode": 0, "triggerEvent": True, "stageEvent": {"resCode": 0,
|
||||
"typeId": "300007", "hideStageId": None, "costTi": 16,
|
||||
"result": {"money": 32, "exp": 64, "items": [], "monsters": [], "ti": 0, "ke": 0}}}
|
||||
def call(path, payload=None):
|
||||
client.calls.append((path, payload))
|
||||
if path == "stageService/stageStart":
|
||||
return response
|
||||
raise AssertionError("Reward events do not submit a battle result")
|
||||
client.call = call
|
||||
result = runner.run(client, self.snapshot, self.stage(), policy)
|
||||
self.assertIs(result, response)
|
||||
self.assertIsNone(runner.state["pending"])
|
||||
self.assertIsNotNone(runner.next(self.snapshot, policy))
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
|
||||
def test_legacy_event_block_recovers_only_from_role_matched_successful_reward_reply(self):
|
||||
with workspace_temp() as folder:
|
||||
trace = folder / "network_debug.jsonl"
|
||||
for role, hidden, http_status, recovered in ((123456, None, 200, False),
|
||||
(self.snapshot.raw["master"]["id"], "hidden", 200, False),
|
||||
(self.snapshot.raw["master"]["id"], None, 500, False),
|
||||
(self.snapshot.raw["master"]["id"], None, 200, True)):
|
||||
runner = SweepRunner(self.catalog)
|
||||
runner.state["pending"] = {"stage": "0101", "level": "3", "phase": "遇到事件或响应缺少事件状态,请在游戏内处理"}
|
||||
records = [{"kind": "response", "operation": "读取角色", "body": {"master": {"id": role}}},
|
||||
{"kind": "request", "operation": "stageService/stageStart", "request_id": "test-1",
|
||||
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
|
||||
{"kind": "response", "operation": "stageService/stageStart", "request_id": "test-1", "http_status": http_status,
|
||||
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": hidden, "result": {"money": 32}}}}]
|
||||
trace.write_text("\n".join(json.dumps(row) for row in records), encoding="utf-8")
|
||||
self.assertEqual(runner.recover_reward_event(self.snapshot, trace), recovered)
|
||||
self.assertEqual(runner.state["pending"] is None, recovered)
|
||||
|
||||
def test_hidden_stage_event_waits_for_real_battle_without_submitting_a_result(self):
|
||||
runner = SweepRunner(self.catalog)
|
||||
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
|
||||
client = FakeClient(self.snapshot)
|
||||
client.call = unittest.mock.Mock(return_value={"resCode": 0, "triggerEvent": True,
|
||||
"stageEvent": {"hideStageId": "hidden", "result": {"money": 1}}})
|
||||
with self.assertRaisesRegex(ValueError, "隐藏关卡"):
|
||||
runner.run(client, self.snapshot, self.stage(), policy)
|
||||
client.call.assert_called_once_with("stageService/stageStart", {"stageTypeId": "0101", "stageLevel": "3"})
|
||||
self.assertIsNone(runner.next(self.snapshot, policy))
|
||||
|
||||
def test_sweep_checks_team_stamina_and_active_story_before_writes(self):
|
||||
runner = SweepRunner(self.catalog)
|
||||
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}, keep_stamina=999)
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import json
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
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.engine import Engine
|
||||
from ranch_assistant.api import Session
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.stage_cache import StageCache
|
||||
from ranch_assistant.tests.test_activities import scenario, FakeClient
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
class MapCacheTests(unittest.TestCase):
|
||||
def test_snapshot_changes_and_restart_reuse_cache_until_explicit_refresh(self):
|
||||
catalog, snapshot = scenario()
|
||||
with workspace_temp() as folder:
|
||||
cache = StageCache(catalog, folder / "maps.json")
|
||||
original = cache.get(snapshot)
|
||||
original_json = (folder / "maps.json").read_text(encoding="utf-8")
|
||||
snapshot.raw["history"]["unlockStage"]["0102"] = ["1", "2", "3"]
|
||||
with patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("Unrequested refresh")):
|
||||
self.assertIs(cache.get(snapshot), original)
|
||||
restored = StageCache(catalog, folder / "maps.json")
|
||||
self.assertEqual([asdict(row) for row in restored.get(snapshot)], [asdict(row) for row in original])
|
||||
self.assertEqual((folder / "maps.json").read_text(encoding="utf-8"), original_json)
|
||||
refreshed = cache.get(snapshot, refresh=True)
|
||||
self.assertTrue(next(row for row in refreshed if row.stage_id == "0102" and row.level == "2").unlocked)
|
||||
|
||||
def test_cache_rejects_other_role_and_recovers_corrupt_local_file(self):
|
||||
catalog, snapshot = scenario()
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "maps.json"
|
||||
cache = StageCache(catalog, path)
|
||||
cache.get(snapshot)
|
||||
snapshot.raw["master"]["id"] += 1
|
||||
with patch("ranch_assistant.stage_cache.stages", wraps=__import__("ranch_assistant.maps", fromlist=["stages"]).stages) as build:
|
||||
cache.get(snapshot)
|
||||
self.assertEqual(build.call_count, 1)
|
||||
self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["owner"], str(snapshot.raw["master"]["id"]))
|
||||
path.write_text("[]", encoding="utf-8")
|
||||
self.assertTrue(StageCache(catalog, path).get(snapshot))
|
||||
|
||||
|
||||
class MapCacheGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, predicate):
|
||||
for _ in range(700):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if predicate():
|
||||
return
|
||||
self.fail("Qt worker did not finish")
|
||||
|
||||
def test_collapsed_maps_remain_cached_on_page_switch_and_poll_manual_refresh_updates(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)
|
||||
catalog, snapshot = scenario()
|
||||
client = FakeClient(snapshot)
|
||||
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
|
||||
client.persist_session = lambda: None
|
||||
client.close = lambda: None
|
||||
window.catalog = catalog
|
||||
window.engine = Engine(catalog, client, folder / "purchase.json")
|
||||
window.engine.snapshot = snapshot
|
||||
window.tabs.setCurrentWidget(window.map_page)
|
||||
self.wait(lambda: not window.map_render_timer.running)
|
||||
self.assertTrue(all(not window.maps_tree.topLevelItem(i).isExpanded() for i in range(window.maps_tree.topLevelItemCount())))
|
||||
original = window.engine.stage_cache.rows
|
||||
client.value["history"]["unlockStage"]["0102"] = ["1", "2", "3"]
|
||||
window.tabs.setCurrentWidget(window.slot_page)
|
||||
with patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("Page/poll refreshed cached maps")):
|
||||
window.refresh()
|
||||
self.wait(lambda: not window.busy)
|
||||
window.tabs.setCurrentWidget(window.map_page)
|
||||
self.wait(lambda: not window.map_render_timer.running)
|
||||
self.assertIs(window.engine.stage_cache.rows, original)
|
||||
self.assertTrue(window.engine.heartbeat_enabled)
|
||||
refresh = next(b for b in window.map_page.findChildren(W.QPushButton) if b.text() == "刷新关卡")
|
||||
refresh.click()
|
||||
self.wait(lambda: not window.busy and not window.map_render_timer.running)
|
||||
changed = next(row for row in window.engine.stage_cache.rows if row.stage_id == "0102" and row.level == "2")
|
||||
self.assertTrue(changed.unlocked)
|
||||
self.assertTrue((folder / "maps.json").exists())
|
||||
finally:
|
||||
window.close()
|
||||
@@ -0,0 +1,77 @@
|
||||
import os
|
||||
import unittest
|
||||
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
from ranch_assistant.gui import spin
|
||||
from ranch_assistant.native_widgets import IntegerInput
|
||||
|
||||
|
||||
class NumericWheelTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wheel(self, widget, delta=120):
|
||||
point = widget.rect().center()
|
||||
event = G.QWheelEvent(C.QPointF(point), C.QPointF(widget.mapToGlobal(point)),
|
||||
C.QPoint(), C.QPoint(0, delta), C.Qt.MouseButton.NoButton,
|
||||
C.Qt.KeyboardModifier.NoModifier, C.Qt.ScrollPhase.NoScrollPhase, False)
|
||||
self.app.sendEvent(widget, event)
|
||||
return event
|
||||
|
||||
def test_all_number_controls_require_focus_and_release_wheel_for_page_scrolling(self):
|
||||
host = W.QWidget()
|
||||
layout = W.QVBoxLayout(host)
|
||||
other = W.QLineEdit()
|
||||
layout.addWidget(other)
|
||||
widgets = [spin(0, 100, 10), spin(0, 100, 10, True), IntegerInput()]
|
||||
for widget in widgets:
|
||||
if isinstance(widget, IntegerInput):
|
||||
widget.setRange(0, 100)
|
||||
widget.setValue(10)
|
||||
layout.addWidget(widget)
|
||||
host.show()
|
||||
host.activateWindow()
|
||||
QTest.qWait(10)
|
||||
try:
|
||||
for widget in widgets:
|
||||
with self.subTest(type=type(widget).__name__):
|
||||
other.setFocus()
|
||||
self.app.processEvents()
|
||||
self.assertFalse(self.wheel(widget).isAccepted())
|
||||
self.assertEqual(widget.value(), 10)
|
||||
self.assertFalse(widget.hasFocus())
|
||||
QTest.mouseClick(widget, C.Qt.MouseButton.LeftButton)
|
||||
self.app.processEvents()
|
||||
self.assertTrue(widget.hasFocus())
|
||||
self.wheel(widget)
|
||||
self.assertEqual(widget.value(), 11)
|
||||
self.wheel(widget, -120)
|
||||
self.assertEqual(widget.value(), 10)
|
||||
other.setFocus()
|
||||
self.app.processEvents()
|
||||
self.wheel(widget)
|
||||
self.assertEqual(widget.value(), 10)
|
||||
finally:
|
||||
host.close()
|
||||
|
||||
def test_integer_wheel_clamps_and_accumulates_small_steps(self):
|
||||
widget = IntegerInput()
|
||||
widget.setRange(0, 2)
|
||||
widget.show()
|
||||
widget.activateWindow()
|
||||
widget.setFocus()
|
||||
QTest.qWait(10)
|
||||
try:
|
||||
self.wheel(widget, 60)
|
||||
self.assertEqual(widget.value(), 0)
|
||||
self.wheel(widget, 60)
|
||||
self.assertEqual(widget.value(), 1)
|
||||
self.wheel(widget, 1200)
|
||||
self.assertEqual(widget.value(), 2)
|
||||
self.wheel(widget, -1200)
|
||||
self.assertEqual(widget.value(), 0)
|
||||
finally:
|
||||
widget.close()
|
||||
Reference in New Issue
Block a user