Files
myrzx_bot/ranch_assistant/tests/test_accounts.py
T

444 lines
22 KiB
Python

import copy
import json
import os
import time
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import requests
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant import gui
from ranch_assistant.accounts_gui import AccountsWindow
from ranch_assistant.api import ApiError, Client, Session, decode, encode
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog, Snapshot
from ranch_assistant.sessions import SessionStore, identity
from ranch_assistant.tests.test_core import workspace_temp
def role_snapshot(catalog, role_id):
raw = demo_snapshot(catalog).raw
raw["master"].update(id=role_id, roleName=f"测试角色 {role_id}")
raw["activityHistory"]["vipInfo"] = None
raw["stacks"] = raw["stacks"][:4]
for slot in raw["stacks"]:
slot["monsterId"] = 0
raw["monsters"] = raw["monsters"][:4]
for mon in raw["monsters"]:
mon.update(process=3, mode=2, roomId=1)
raw["items"] = raw["items"][:4]
return raw
def fake_client(session, catalog, calls):
client = Client(session)
def post(url, data, **kwargs):
body = decode(data, session.key)
calls.append((session.account_id, url, body))
raw = role_snapshot(catalog, session.role_id)
return SimpleNamespace(status_code=200, content=encode(raw | {"resCode": 0}, session.key), headers={})
client.http.post = post
return client
class SessionTests(unittest.TestCase):
def test_encrypted_sessions_are_isolated_by_owner_region_and_role(self):
with workspace_temp() as folder:
store = SessionStore(folder)
first = Session("http://127.0.0.1/a/", "private-token-a", account_id="account-a", server_id=1, role_id=101, reqid=5, reqsid=7)
second = Session("http://127.0.0.1/b/", "private-token-b", account_id="account-b", server_id=1, role_id=202)
other_region = copy.deepcopy(first)
other_region.server_id, other_region.role_id = 2, 303
keys = [store.save(s, "测试会话") for s in (first, second, other_region)]
self.assertEqual(len(set(keys)), 3)
self.assertEqual(store.load(keys[0]), first)
first.reqid = 9
store.save(first, "测试会话")
self.assertEqual(len(store.entries()), 3)
self.assertEqual(store.load(keys[0]).reqid, 9)
for path in store.folder.glob("*.json"):
text = path.read_text(encoding="utf-8")
self.assertNotIn("private-token", text)
self.assertNotIn(first.key, text)
with self.assertRaises(ValueError):
store.load("../credentials")
def test_failed_request_persists_advanced_counters_without_retry(self):
with workspace_temp() as folder:
store = SessionStore(folder)
session = Session("http://127.0.0.1/", "private-token", account_id="account-a", server_id=1, role_id=101)
client = Client(session, on_session_change=lambda current: store.save(current, "测试会话"))
try:
with patch.object(client.http, "post", side_effect=requests.Timeout()) as post:
with self.assertRaises(ApiError):
client.call("masterService/masterQueryDetail")
self.assertEqual(post.call_count, 1)
restored = store.load(identity(session))
self.assertEqual((restored.reqid, restored.reqsid), (1, 1))
finally:
client.close()
def test_resume_rejects_another_role_before_any_strategy_runs(self):
catalog = Catalog()
session = Session("http://127.0.0.1/", "private-token", role_id=101)
client = Client(session)
response = SimpleNamespace(status_code=200, content=encode(role_snapshot(catalog, 202) | {"resCode": 0}, session.key), headers={})
try:
with patch.object(client.http, "post", return_value=response):
with self.assertRaisesRegex(ApiError, "其他角色"):
client.snapshot()
self.assertEqual(session.role_id, 101)
finally:
client.close()
class AccountGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, windows):
for _ in range(300):
self.app.processEvents()
QTest.qWait(5)
if all(not window.busy and window.slots.rowCount() for window in windows):
return
self.fail("Account workers did not complete")
def connect(self, window, owner, region, role_id, calls):
window.account.setText(owner)
session = Session("http://127.0.0.1/game/", f"test-token-{owner}", account_id=owner,
account_name=owner, server_id=region, role_id=role_id)
client = fake_client(session, window.catalog, calls)
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.strategy_toggle.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])
self.assertNotIn("开发中", 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)
hub.add_profile()
profile = hub.profiles[-1]
try:
hub.close_profile(hub.tabs.count() - 1)
self.wait(list(hub.windows.values()))
self.assertEqual(hub.tabs.count(), 1)
hub.open_profile(profile)
self.wait(list(hub.windows.values()))
self.assertEqual(hub.tabs.count(), 2)
finally:
hub.close()
def test_closed_tab_stays_closed_after_restart_and_can_be_opened_manually(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
for window in hub.windows.values():
window.timer.stop()
self.wait(list(hub.windows.values()))
closed = hub.profiles[-1]
hub.close_profile(hub.tabs.count() - 1)
hub.close()
restarted = AccountsWindow(folder)
for window in restarted.windows.values():
window.timer.stop()
try:
self.wait(list(restarted.windows.values()))
self.assertNotIn(closed["id"], restarted.windows)
self.assertTrue(any(p["id"] == closed["id"] for p in restarted.profiles))
restarted.open_profile(next(p for p in restarted.profiles if p["id"] == closed["id"]))
for window in restarted.windows.values():
window.timer.stop()
self.wait(list(restarted.windows.values()))
self.assertIn(closed["id"], restarted.windows)
finally:
restarted.close()
def test_failed_resume_saves_counters_before_response_and_keeps_execution_off(self):
with workspace_temp() as folder:
window = gui.Window(folder)
window.timer.stop()
try:
self.wait([window])
session = Session("http://127.0.0.1/", "private-resume-token", account_id="account-a", server_id=1, role_id=101)
key = window.session_store.save(session, "测试账号 / 区服 1 / 测试角色")
window.reload_saved_sessions()
def failing_client(current, **kwargs):
client = Client(current, **kwargs)
client.http.post = lambda *args, **kwargs: (_ for _ in ()).throw(requests.Timeout())
return client
with patch.object(gui, "Client", side_effect=failing_client):
window.resume_session()
self.wait([window])
self.assertEqual(window.session_store.load(key).reqid, 1)
self.assertFalse(window.strategy_toggle.isChecked())
self.assertTrue(window.engine.demo)
finally:
window.close()
def test_two_accounts_run_independently_restore_and_right_click_read_only(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
windows = list(hub.windows.values())
for window in windows:
window.timer.stop()
calls = []
try:
self.wait(windows)
first, second = windows
self.connect(first, "account-a", 1, 101, calls)
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(), len(first.monsters.monster_items)], [11, 4, 4])
self.assertFalse(first.monsters.group_items)
self.assertTrue(all(item.parent() is None for item in first.monsters.monster_items.values()))
self.assertEqual(first.saved_sessions.count(), 1)
first.monitoring = True
hub.tabs.setCurrentWidget(second)
self.assertTrue(first.monitoring)
self.assertTrue(all(window.monitoring for window in windows))
for window in windows:
window.engine.last_heartbeat = time.monotonic()
window.next_poll = 0
window.schedule()
self.wait(windows)
self.assertEqual({owner for owner, _, _ in calls}, {"account-a", "account-b"})
self.assertEqual(first.engine.client.session.token, "test-token-account-a")
self.assertEqual(second.engine.client.session.token, "test-token-account-b")
self.assertEqual(first.engine.snapshot.raw["master"]["id"], 101)
self.assertEqual(second.engine.snapshot.raw["master"]["id"], 202)
first.set_strategy_checked(True)
before = len(calls)
hub.tabs.setCurrentWidget(first)
first.tabs.setCurrentWidget(first.egg_page)
point = C.QPoint(3, 3)
event = G.QContextMenuEvent(G.QContextMenuEvent.Reason.Mouse, point, first.eggs.viewport().mapToGlobal(point))
self.app.sendEvent(first.eggs.viewport(), event)
self.app.processEvents()
self.assertEqual(first.refresh_menu.actions()[0].text(), "刷新本页")
first.refresh_menu.actions()[0].trigger()
first.refresh_menu.close()
self.wait(windows)
self.assertGreater(len(calls), before)
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls[before:]))
self.assertFalse(first.engine.auto)
self.assertIs(first.tabs.currentWidget(), first.egg_page)
self.assertFalse(hub.allow_login(second, "account-a"))
self.assertFalse(hub.allow_connection(second, first.engine.client.session))
finally:
hub.close()
restored = AccountsWindow(folder)
restarted = list(restored.windows.values())
for window in restarted:
window.timer.stop()
try:
self.wait(restarted)
self.assertEqual(len(restarted), 2)
self.assertTrue(all(window.saved_sessions.count() == 1 for window in restarted))
with patch.object(gui, "Client", side_effect=lambda session, **kwargs: fake_client(session, restarted[0].catalog, calls)):
restored.resume_all()
self.wait(restarted)
self.assertEqual({window.engine.snapshot.raw["master"]["id"] for window in restarted}, {101, 202},
"\n".join(window.log.toPlainText() for window in restarted))
self.assertTrue(all(not window.engine.demo and not window.strategy_toggle.isChecked() and window.monitoring for window in restarted))
finally:
restored.close()
def test_login_refreshes_automatically_and_strategy_menu_only_controls_execution(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
windows = list(hub.windows.values())
calls = []
for window in windows:
window.timer.stop()
try:
self.wait(windows)
for number, window in enumerate(windows, 1):
self.connect(window, f"account-{number}", number, number, calls)
self.assertTrue(window.monitoring)
self.assertFalse(window.strategy_toggle.isChecked())
window.engine.last_heartbeat = time.monotonic()
window.schedule()
self.wait(windows)
self.assertTrue(calls)
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls))
for window in windows:
window.ranch_enabled.setChecked(False)
window.daily_enabled.setChecked(True)
# Exercise real Qt menu actions with synthetic worker results.
observed = []
from contextlib import ExitStack
with ExitStack() as stack:
for window in windows:
def poll(current=window, **kwargs):
observed.append((current, current.engine.auto))
return current.engine.snapshot, [], "synthetic refresh"
stack.enter_context(patch.object(window.engine, "poll", side_effect=poll))
menu = next(action.menu() for action in hub.menuBar().actions() if action.text() == "策略(&R)")
menu.actions()[0].trigger()
self.wait(windows)
self.assertEqual(len(observed), 2)
self.assertTrue(all(enabled for _, enabled in observed))
self.assertTrue(all(w.strategy_toggle.text() == "停止" for w in windows))
# A manual refresh never executes, even with strategies on.
windows[0].refresh()
self.wait(windows)
self.assertFalse(observed[-1][1])
menu.actions()[1].trigger()
self.assertTrue(all(w.monitoring and not w.strategy_toggle.isChecked() for w in windows))
observed.clear()
for window in windows:
window.next_poll = 0
window.schedule()
self.wait(windows)
self.assertEqual(len(observed), 2)
self.assertFalse(any(enabled for _, enabled in observed))
windows[0].demo()
self.wait(windows)
self.assertFalse(windows[0].monitoring)
self.assertTrue(windows[1].monitoring)
finally:
hub.close()
def test_incomplete_policy_keeps_logged_in_account_refreshing_without_actions(self):
with workspace_temp() as folder:
window = gui.Window(folder)
window.timer.stop()
calls = []
try:
self.wait([window])
self.connect(window, "account-a", 1, 101, calls)
window.reserved_types.setText("incomplete-input")
window.strategy_toggle.click()
self.assertFalse(window.strategy_toggle.isChecked())
self.assertTrue(window.monitoring)
window.engine.last_heartbeat = time.monotonic()
window.next_poll = 0
window.schedule()
self.wait([window])
self.assertTrue(window.monitoring)
self.assertFalse(window.engine.auto)
self.assertTrue(calls)
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls))
finally:
window.close()
def test_role_switch_restores_own_strategy_and_heartbeat_uses_normal_api(self):
with workspace_temp() as folder:
window = gui.Window(folder)
window.timer.stop()
calls = []
try:
self.wait([window])
self.connect(window, "account-a", 1, 101, calls)
first_state = window.state
window.strategy.setCurrentIndex(window.strategy.findData("gold"))
self.connect(window, "account-a", 2, 202, calls)
self.assertNotEqual(window.state, first_state)
self.assertEqual(window.strategy.currentData(), "wiki")
self.connect(window, "account-a", 1, 101, calls)
self.assertEqual(window.state, first_state)
self.assertEqual(window.strategy.currentData(), "gold")
self.assertEqual(window.saved_sessions.count(), 2)
window.engine.last_heartbeat = 0
window.next_poll = float("inf")
window.schedule()
self.wait([window])
self.assertTrue(calls[-1][1].endswith("heartBeatService/keepAlive"))
count = len(calls)
window.schedule()
self.app.processEvents()
self.assertEqual(len(calls), count)
finally:
window.close()
if __name__ == "__main__":
unittest.main()