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_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_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.execute.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(), first.monsters.rowCount(), first.rooms_table.rowCount()], [11, 4, 4, 1]) self.assertEqual(first.saved_sessions.count(), 1) first.start_monitor.setChecked(True) hub.tabs.setCurrentWidget(second) self.assertTrue(first.monitoring) hub.monitor_all() 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.execute.setChecked(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) first.farm.running = True first.farm.adb.serial = "phone-a" self.assertFalse(hub.allow_device(second, "phone-a")) self.assertTrue(hub.allow_device(second, "phone-b")) 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.execute.isChecked() and not window.monitoring for window in restarted)) finally: restored.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.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()