Files
xieyi-weixin-/test_protocol_features.py
T
2026-09-21 10:56:48 +08:00

385 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Protocol preparation regressions; no test connects to or sends to a real contact."""
import json
from contextlib import closing
import os
import queue
import sqlite3
import struct
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
import wxwork_protocol_probe as probe
from gui_runtime import BotThread
from reply_database import LiveReplyDatabase
from reply_transport import normalize_reply_transport, transport_start_blocker
from wxwork_db import DatabaseReadError, WXWorkDB
class ProtocolProbeTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
trial_path = mock.patch("wecom_native_protocol.trial_path", return_value=self.root / "native-trial.json")
trial_path.start(); self.addCleanup(trial_path.stop)
def binary(self, machine=0x14c):
path = self.root / "WXWork.exe"
data = bytearray(160)
data[:2] = b"MZ"
struct.pack_into("<I", data, 0x3c, 64)
data[64:68] = b"PE\0\0"
struct.pack_into("<HHIIIHH", data, 68, machine, 3, 0, 0, 0, 0, 2)
path.write_bytes(data)
return path
def test_pe_architecture_and_corrupt_header(self):
path = self.binary()
self.assertEqual(probe.pe_header(path)["architecture"], "x86")
self.assertEqual(probe.pe_header(self.binary(0x8664))["architecture"], "x64")
path.write_bytes(b"not a binary")
with self.assertRaises(ValueError):
probe.pe_header(path)
def test_installed_client_and_bundled_sdk_never_imply_send_or_login(self):
path = self.binary()
version = "5.0.10.6023"
sdk = self.root / version / "WeComAgent" / "python" / "3.10" / "site-packages" / "wecomagent"
sdk.mkdir(parents=True)
# This text must only be read, never imported/executed by detection.
(sdk / "_rpc.py").write_text(
'raise RuntimeError("must not execute")\n# wecom.exec WECOMAGENT_RPC_HOST WECOMAGENT_RPC_PORT WECOMAGENT_RPC_TOKEN',
encoding="utf8")
(self.root / version / "WeComAgent" / "wecom-agent.exe").touch()
clients = [{"pid": 123, "path": str(path), "version": version, "architecture": "x86"}]
with mock.patch.object(probe, "running_clients", return_value=clients), mock.patch.object(probe, "file_version", return_value=version), mock.patch("wecom_native_sender.discover", side_effect=OSError("unreadable test client")):
result = probe.probe_installed_client()
self.assertEqual(result["status"], "native_unavailable")
self.assertEqual(result["clientVersion"], version)
self.assertTrue(result["bundledAgents"][0]["requiresRuntimeAuthorization"])
for key in ("canSend", "loginVerified", "adapterInstalled", "sendVerified", "receiptVerified"):
self.assertFalse(result[key], key)
def test_no_client_and_inaccessible_client(self):
with mock.patch.object(probe, "running_clients", return_value=[]):
self.assertEqual(probe.probe_installed_client()["status"], "client_not_running")
with mock.patch.object(probe, "running_clients", return_value=[{"pid": 123, "path": ""}]):
result = probe.probe_installed_client()
self.assertEqual(result["status"], "probe_failed")
self.assertFalse(result["canSend"])
def test_atomic_export_does_not_destroy_existing_report_on_failure(self):
path = self.root / "report.json"
path.write_text("original", encoding="utf8")
with mock.patch.object(probe.os, "replace", side_effect=OSError("disk")):
with self.assertRaises(OSError):
probe.export_probe_report({"status": "probe_failed"}, path)
self.assertEqual(path.read_text(encoding="utf8"), "original")
self.assertEqual(list(self.root.glob(".protocol-report-*")), [])
probe.export_probe_report({"label": "协议待适配", "canSend": False}, path)
self.assertEqual(json.loads(path.read_text(encoding="utf8"))["label"], "协议待适配")
class ProtocolRoutingTest(unittest.TestCase):
def test_invalid_explicit_transport_never_defaults_to_visual(self):
for value in (None, "", False, 1, "http", {}, "visual-protocol"):
self.assertEqual(normalize_reply_transport(value), "invalid")
self.assertFalse(transport_start_blocker(value)["canSend"])
self.assertIsNone(transport_start_blocker("visual"))
self.assertEqual(normalize_reply_transport(" PROTOCOL "), "protocol")
def test_protocol_start_never_constructs_visual_sender_even_with_true_flag(self):
events = queue.Queue()
report = {"status": "adapter_unverified", "canSend": True, "message": "未完成实际适配"}
with mock.patch.object(probe, "probe_installed_client", return_value=report), mock.patch("wechat_bot.WeChatBot") as visual:
thread = BotThread(events, "测试文本", 2, reply_transport="protocol")
thread.run()
visual.assert_not_called()
self.assertIsNone(thread.bot)
self.assertIn(("status", "error"), list(events.queue))
self.assertNotIn(("status", "stopped"), list(events.queue))
def test_database_failure_is_propagated_and_request_identity_includes_limit(self):
db = LiveReplyDatabase()
with mock.patch.object(db, "_request", side_effect=DatabaseReadError("offline")) as request:
with self.assertRaises(DatabaseReadError):
db.get_conversation_context_by_id("100", "M:200")
self.assertEqual(request.call_args.args[0], ("context_by_id", "100", "M:200", 100))
with mock.patch.object(db, "_request", return_value=None) as request:
db.get_conversation_context_by_id("100", "M:200", limit=2)
self.assertEqual(request.call_args.args[0][-1], 2)
with self.assertRaises(ValueError):
db.get_conversation_context_by_id("", "M:200")
db.close()
class ProtocolIdContextTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
root = Path(self.tmp.name)
source = root / "WXWork"
for account in ("100", "101"):
data = source / account / "Data"
data.mkdir(parents=True)
with closing(sqlite3.connect(data / "user.db")) as conn, conn:
conn.execute("CREATE TABLE user_table(id TEXT,name TEXT,real_name TEXT,account TEXT)")
conn.executemany("INSERT INTO user_table VALUES(?,?,'','')", [
("200", "同名客户"), ("201", "同名客户")])
with closing(sqlite3.connect(data / "message.db")) as conn, conn:
conn.execute("CREATE TABLE message_table(sender_id TEXT,conversation_id TEXT,content_type INT,send_time INTEGER,content TEXT,server_id TEXT)")
for cid in ("200", "201"):
conn.execute("INSERT INTO message_table VALUES(?,?,2,100,?,'5')",
(cid, "M:" + cid, account + "/" + cid))
conn.execute("INSERT INTO message_table VALUES(?,?,2,101,?,'6')",
(account, "M:" + cid, account + "/reply/" + cid))
self.db = WXWorkDB(str(source), {}, str(root / "cache"))
self.addCleanup(self.db.close)
def test_duplicate_names_and_server_ids_remain_isolated_by_exact_account_conversation(self):
self.assertIsNone(self.db.get_conversation_context("同名客户", account="100", conv_id="M:200"))
for account in ("100", "101"):
for cid in ("200", "201"):
context = self.db.get_conversation_context_by_id(account, "M:" + cid)
self.assertEqual(context["account"], account)
self.assertEqual(context["conv_id"], "M:" + cid)
self.assertEqual([m["content"] for m in context["messages"]],
[account + "/" + cid, account + "/reply/" + cid])
self.assertTrue(context["last_message"]["is_self"])
self.assertEqual(len(self.db.get_conversation_context_by_id(account, "M:" + cid, limit=1)["messages"]), 1)
def test_missing_account_unknown_conversation_and_group_never_guess(self):
for account, conv in (("999", "M:200"), ("100", "M:999"), ("100", "R:200")):
self.assertIsNone(self.db.get_conversation_context_by_id(account, conv))
for account, conv in (("", "M:200"), ("100", ""), (None, "M:200")):
with self.assertRaises(ValueError):
self.db.get_conversation_context_by_id(account, conv)
class ProtocolGuiTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
from PySide6.QtWidgets import QApplication
cls.app = QApplication.instance() or QApplication([])
def test_actual_web_page_protocol_state_buttons_and_visual_return(self):
from PySide6.QtCore import QEventLoop, QTimer
from PySide6.QtWidgets import QMainWindow
from wechat_gui_qt import ConsoleShell
host = QMainWindow()
host._push_console_state = mock.Mock()
shell = ConsoleShell(host)
shell.resize(1630, 965)
shell.show()
try:
if not shell.page_ready:
loop = QEventLoop()
loaded = []
def finished(ok):
loaded.append(ok)
loop.quit()
shell.loadFinished.connect(finished)
QTimer.singleShot(10000, loop.quit)
loop.exec()
shell.loadFinished.disconnect(finished)
self.assertEqual(loaded, [True])
def js(source):
values = []
loop = QEventLoop()
def done(value):
values.append(value)
loop.quit()
shell.page().runJavaScript(source, done)
QTimer.singleShot(5000, loop.quit)
loop.exec()
self.assertEqual(len(values), 1)
return values[0]
payload = {
"view": "automation", "ready": True, "demo": False,
"listening": False, "people": [], "archives": [], "queue": [],
"automation": {"transport": "protocol", "protocol": {
"status": "adapter_unverified", "label": "协议发送待适配",
"message": "已检测到客户端,发送入口与回执尚未验证。",
"clientVersion": "5.0.10.6023", "architecture": "x86",
"checkedAt": 1789380000, "bundledAgentDetected": True,
"exportable": True,
}},
}
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("""document.querySelector('#main').textContent.includes('协议模式尚未就绪')
&& !document.querySelector('[data-action="export-protocol"]').disabled
&& !document.querySelector('.automation-top')
&& !document.querySelector('#main').textContent.includes('undefined')"""))
payload["automation"]["protocol"]["nativeTrial"] = {
"checkedAt": 1789434960, "clientVersion": "5.0.10.6023", "sameClientVersion": True,
"transportVerified": True, "toolsListVerified": True, "businessStatus": "not_enabled",
}
payload["automation"]["protocol"].update(
label="最近实测:业务接口未开放",
message="原生 MCP 握手成功;身份和会话列表查询返回 -90020005(user not in gray)。原账号发送和回执未验证。")
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("""document.querySelector('#main').textContent.includes('原生 MCP 上次实测:握手成功')
&& document.querySelector('#main').textContent.includes('user not in gray')
&& document.querySelector('#main').textContent.includes('此记录不代表当前连接')
&& !document.querySelector('#main').textContent.includes('undefined')"""))
payload["automation"]["protocol"].update(
status="native_ready", canSend=True, nativeAdapter="wxwork-5.0.10.6023-x86",
label="原账号协议已就绪", message="本版本真实发送及回执已验证",
nativeAccount="100", loginVerified=True, sendVerified=True, receiptVerified=True, databaseReady=True)
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("""document.querySelector('#main').textContent.includes('协议自动回复已就绪')
&& !!document.querySelector('#auto-poll') && !!document.querySelector('#auto-delay')
&& !!document.querySelector('[data-action="send-mode"][data-key="review"]')
&& !document.querySelector('#main').textContent.includes('user not in gray')
&& !document.querySelector('#main').textContent.includes('undefined')"""))
payload["automation"]["protocol"].update(status="database_not_found", canSend=False, databaseReady=False,
label="当前账号数据目录未找到", message="请选择本机数据目录", clientInstallPath="D:/应用 目录/WXWork.exe",
database={"ready": False, "label": "当前账号数据目录未找到"})
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("""!!document.querySelector('[data-action="wechat-db-directory"]')
&& document.querySelector('#main').textContent.includes('D:/应用 目录/WXWork.exe')
&& document.querySelector('#main').textContent.includes('需处理')
&& !document.querySelector('#main').textContent.includes('SDK 运行时')"""))
payload["automation"]["protocol"].update(status="native_validation_required", needsSendValidation=True, databaseReady=True, clientVersion="5.0.11.6018")
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("!!document.querySelector('[data-action=\"verify-protocol-send\"]') && !document.querySelector('[data-action=\"verify-protocol-send\"]').disabled"))
js("""window.__protocolActions=[];
window.qtBridge={
setReplyTransport: (value, callback)=>{window.__protocolActions.push(value);callback('{"ok":true,"message":"saved"}');},
probeProtocol: ()=>window.__protocolActions.push('probe'),
validateProtocolSend: ()=>window.__protocolActions.push('verify'),
exportProtocolReport: ()=>window.__protocolActions.push('export')
};
document.querySelector('[data-action="verify-protocol-send"]').click();
document.querySelector('[data-action="probe-protocol"]').click();
document.querySelector('[data-action="export-protocol"]').click();
document.querySelector('[data-action="reply-transport"][data-key="visual"]').click();""")
self.assertEqual(json.loads(js("JSON.stringify(window.__protocolActions)")), ["verify", "probe", "export", "visual"])
payload["automation"]["transport"] = "visual"
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("!!document.querySelector('.automation-top') && !!document.querySelector('#auto-batch')"))
payload["automation"]["protocol"] = {"status": "checking", "label": "正在检测"}
js("window.applyState(" + json.dumps(payload, ensure_ascii=False) + ");")
self.assertTrue(js("""document.querySelector('[data-action="probe-protocol"]').disabled
&& document.querySelector('[data-action="export-protocol"]').disabled"""))
finally:
shell.close()
shell.deleteLater()
host.deleteLater()
self.app.processEvents()
def test_qt_persists_transport_and_restores_memory_after_disk_failure(self):
import wechat_gui_qt as qt
host = SimpleNamespace(
_runtime_defaults=qt.MainWindow._runtime_defaults,
runtime_settings={"reply_transport": "visual", "send_mode": "review"},
settings_page=SimpleNamespace(values=lambda: {}),
_thread=None, _broadcast_save_result=mock.Mock(), append_log=mock.Mock(),
)
with tempfile.TemporaryDirectory() as directory:
target = Path(directory) / "settings.json"
with mock.patch.object(qt, "APP_SETTINGS_FILE", target):
self.assertTrue(qt.MainWindow.save_runtime_settings(host, {"reply_transport": "protocol"}))
self.assertEqual(qt.MainWindow._load_runtime_settings(host)["reply_transport"], "protocol")
self.assertEqual(host.runtime_settings["send_mode"], "review")
with mock.patch.object(qt.os, "replace", side_effect=OSError("disk failure")):
self.assertFalse(qt.MainWindow.save_runtime_settings(host, {"reply_transport": "visual"}))
self.assertEqual(host.runtime_settings["reply_transport"], "protocol")
self.assertEqual(json.loads(target.read_text(encoding="utf8"))["reply_transport"], "protocol")
def test_probe_worker_coalesces_clicks_and_delivers_failures(self):
import wechat_gui_qt as qt
host = SimpleNamespace(_push_console_state=mock.Mock(), protocolProbeLoaded=mock.Mock())
with mock.patch.object(qt.threading, "Thread") as thread:
qt.MainWindow._refresh_protocol_probe(host)
qt.MainWindow._refresh_protocol_probe(host)
thread.assert_called_once()
thread.return_value.start.assert_called_once()
worker = thread.call_args.kwargs["target"]
self.assertEqual(host._protocol_probe["status"], "checking")
with mock.patch.object(probe, "probe_installed_client", side_effect=OSError("unreadable")):
worker()
report = host.protocolProbeLoaded.emit.call_args.args[0]
self.assertEqual(report["status"], "probe_failed")
self.assertFalse(report["canSend"])
host.append_log = mock.Mock()
qt.MainWindow._protocol_probe_loaded(host, report)
self.assertFalse(host._protocol_probe_running)
def test_qt_and_classic_keep_protocol_even_when_other_settings_are_corrupt(self):
import wechat_gui as tk
import wechat_gui_qt as qt
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "app_settings.json"
for transport in ("protocol", "broken", None):
path.write_text(json.dumps({"reply_transport": transport, "poll_interval": "bad"}), encoding="utf8")
with mock.patch.object(tk, "APP_SETTINGS_FILE", str(path)):
result = tk.App._load_runtime_settings(SimpleNamespace(_runtime_defaults=tk.App._runtime_defaults))
with mock.patch.object(qt, "APP_SETTINGS_FILE", path):
result_qt = qt.MainWindow._load_runtime_settings(SimpleNamespace(_runtime_defaults=qt.MainWindow._runtime_defaults))
expected = "protocol" if transport == "protocol" else "invalid"
self.assertEqual(result["reply_transport"], expected)
self.assertEqual(result_qt["reply_transport"], expected)
def test_transport_change_is_saved_and_rejected_while_running(self):
from PySide6.QtWidgets import QMainWindow
from wechat_gui_qt import ConsoleBridge
host = QMainWindow()
self.addCleanup(host.deleteLater)
host._thread = SimpleNamespace(is_alive=lambda: False)
host.save_runtime_settings = mock.Mock(return_value=True)
host._refresh_protocol_probe = mock.Mock()
host._push_console_state = mock.Mock()
bridge = ConsoleBridge(host)
self.addCleanup(bridge.deleteLater)
self.assertTrue(json.loads(bridge.setReplyTransport("protocol"))["ok"])
host.save_runtime_settings.assert_called_once_with({"reply_transport": "protocol"})
host._refresh_protocol_probe.assert_called_once()
host._thread = SimpleNamespace(is_alive=lambda: True)
self.assertFalse(json.loads(bridge.setReplyTransport("visual"))["ok"])
self.assertFalse(json.loads(bridge.setReplyTransport("arbitrary"))["ok"])
self.assertEqual(host.save_runtime_settings.call_count, 1)
def test_qt_protocol_start_passes_transport_to_background_thread(self):
from wechat_gui_qt import MainWindow
defaults = MainWindow._runtime_defaults()
defaults["reply_transport"] = "protocol"
host = SimpleNamespace(
_thread=None, runtime_settings=defaults, _queue=queue.Queue(),
save_runtime_settings=mock.Mock(return_value=True),
append_log=mock.Mock(), _refresh_protocol_probe=mock.Mock(),
set_status=mock.Mock(), enter_capsule_mode=mock.Mock(),
persona_page=SimpleNamespace(save_config=mock.Mock()),
)
host._protocol_report = dict(status="native_ready", nativeAdapter="wxwork-5.0.10.6023-x86",
canSend=True, loginVerified=True, adapterInstalled=True, sendVerified=True,
receiptVerified=True, databaseReady=True, checkedAt=__import__("time").time())
with mock.patch("wechat_gui_qt.BotThread") as bot, mock.patch("wechat_gui_qt.LogQueue"), \
mock.patch("wechat_gui_qt.QTimer.singleShot"), mock.patch("wechat_gui_qt.sys.stdout"):
MainWindow.start_monitoring(host)
self.assertEqual(bot.call_args.kwargs["reply_transport"], "protocol")
bot.return_value.start.assert_called_once()
host.persona_page.save_config.assert_called_once()
def test_detection_state_keeps_binary_paths_out_of_web_payload(self):
from wechat_gui_qt import MainWindow
host = SimpleNamespace(append_log=mock.Mock(), _push_console_state=mock.Mock())
report = {"status": "adapter_unverified", "message": "检测完成",
"clients": [{"path": "local-program-path"}], "binaries": [{"sha256": "x"}],
"bundledAgents": [{"installed": True}]}
MainWindow._protocol_probe_loaded(host, report)
self.assertTrue(host._protocol_probe["exportable"])
self.assertTrue(host._protocol_probe["bundledAgentDetected"])
self.assertFalse(host._protocol_probe["canSend"])
self.assertNotIn("clients", host._protocol_probe)
self.assertEqual(host._protocol_report, report)
if __name__ == "__main__":
unittest.main()