198 lines
13 KiB
Python
198 lines
13 KiB
Python
"""Cross-PC setup tests: synthetic clients and databases, no real sending."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sqlite3
|
|
import tempfile
|
|
import time
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest import mock
|
|
import wecom_environment as env
|
|
import wxwork_db as db
|
|
import wxwork_protocol_probe as probe
|
|
from reply_database import LiveReplyDatabase
|
|
from reply_transport import protocol_ready
|
|
from wecom_native_sender import NativeUnavailable
|
|
|
|
|
|
def ready():
|
|
return dict(status='native_ready', nativeAdapter='wxwork-5.0.10.6023-x86', canSend=True,
|
|
loginVerified=True, adapterInstalled=True, sendVerified=True, receiptVerified=True,
|
|
databaseReady=True, checkedAt=time.time())
|
|
|
|
|
|
class ProbeTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.client=dict(pid=123,path=r'D:\应用目录\企业 微信\WXWork.exe',version='5.0.10.6023',architecture='x86')
|
|
self.live=dict(pid=123,accountId='100',clientVersion=self.client['version'])
|
|
self.running=self.enterContext(mock.patch.object(probe,'running_clients',return_value=[self.client]))
|
|
self.enterContext(mock.patch.object(probe,'inspect_binary',return_value={}))
|
|
self.enterContext(mock.patch.object(probe,'bundled_agent_info',return_value={'installed':False}))
|
|
self.discover=self.enterContext(mock.patch('wecom_native_sender.discover',return_value=self.live))
|
|
self.database=self.enterContext(mock.patch.object(env,'protocol_database_status',return_value={'ready':True,'status':'ready','label':'当前账号可读取'}))
|
|
|
|
def test_custom_install_path_needs_no_sdk(self):
|
|
with mock.patch('wecom_sdk_client.probe_sdk_runtime',side_effect=AssertionError('not needed')):
|
|
report=probe.probe_installed_client(initialize_database=True)
|
|
self.assertTrue(protocol_ready(report))
|
|
self.assertEqual(report['clientInstallPath'],self.client['path'])
|
|
self.assertFalse(report['targetSendVerified'])
|
|
self.database.assert_called_once_with('100',initialize=True)
|
|
self.assertEqual(self.discover.call_count,2)
|
|
|
|
def test_unsupported_version_or_architecture_does_not_access_sender(self):
|
|
for change,code in [({'version':'5.0.99.1'},'unsupported_client_version'),({'architecture':'x64'},'unsupported_client_architecture')]:
|
|
with self.subTest(change=change):
|
|
self.running.return_value=[{**self.client,**change}]
|
|
report=probe.probe_installed_client()
|
|
self.assertEqual(report['status'],code)
|
|
self.assertFalse(protocol_ready(report))
|
|
self.discover.assert_not_called();self.database.assert_not_called()
|
|
|
|
def test_real_failure_is_visible_instead_of_sdk_message(self):
|
|
for error,code in [('无法访问企业微信进程,请以相同权限运行','client_access_denied'),('当前企业微信文件未适配','client_build_mismatch'),('企业微信尚未登录','client_not_ready'),('多个企业微信账号同时运行,请保留一个主客户端','multiple_clients')]:
|
|
with self.subTest(code=code):
|
|
self.discover.side_effect=NativeUnavailable(error)
|
|
report=probe.probe_installed_client()
|
|
self.assertEqual(report['status'],code)
|
|
self.assertIn(error,report['message'])
|
|
self.assertNotIn('SDK',report['label'])
|
|
self.database.assert_not_called()
|
|
|
|
def test_database_failure_cannot_report_ready(self):
|
|
self.database.return_value=dict(ready=False,status='database_not_found',label='当前账号数据目录未找到',message='请选择聊天数据目录')
|
|
report=probe.probe_installed_client()
|
|
self.assertEqual(report['status'],'database_not_found')
|
|
self.assertFalse(protocol_ready(report));self.assertTrue(report['loginVerified'])
|
|
|
|
def test_account_change_and_exit_during_initialization_are_blocked(self):
|
|
for second in ({**self.live,'accountId':'101'},NativeUnavailable('企业微信已退出')):
|
|
with self.subTest(second=str(second)):
|
|
self.discover.side_effect=[self.live,second]
|
|
report=probe.probe_installed_client(initialize_database=True)
|
|
self.assertEqual(report['status'],'client_not_ready')
|
|
self.assertFalse(report['loginVerified']);self.assertFalse(protocol_ready(report))
|
|
|
|
def test_not_running_still_reports_custom_install(self):
|
|
self.running.return_value=[]
|
|
with mock.patch.object(env,'installed_executables',return_value=[Path(self.client['path'])]),mock.patch.object(probe,'inspect_binary',return_value={'path':self.client['path']}):
|
|
report=probe.probe_installed_client()
|
|
self.assertEqual(report['status'],'client_not_running')
|
|
self.assertEqual(report['clientInstallPath'],self.client['path'])
|
|
self.discover.assert_not_called()
|
|
|
|
def test_missing_database_flag_never_enables_sender(self):
|
|
for key in ('databaseReady','canSend','loginVerified','adapterInstalled','sendVerified','receiptVerified'):
|
|
report=ready();report.pop(key)
|
|
self.assertFalse(protocol_ready(report),key)
|
|
|
|
|
|
class StorageTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup)
|
|
self.root=Path(self.temp.name);self.appdata=self.root/'用户 甲'/'AppData'/'Local'/'ZhenYangTangRPA';self.appdata.mkdir(parents=True)
|
|
self.source=self.root/'另一个盘 中文 空格'/'WXWork';self.database=self.source/'100'/'Data'/'message.db';self.database.parent.mkdir(parents=True)
|
|
conn=sqlite3.connect(self.database)
|
|
conn.execute('CREATE TABLE message_table(sender_id TEXT,conversation_id TEXT,content_type INT,send_time INT,content TEXT)');conn.commit();conn.close()
|
|
self.enterContext(mock.patch.object(db,'_SCRIPT_DIR',str(self.appdata)))
|
|
self.enterContext(mock.patch.object(db,'KEYS_FILE',str(self.appdata/'wxwork_keys.json')))
|
|
self.enterContext(mock.patch.object(db,'_windows_documents_dirs',return_value=[]))
|
|
self.enterContext(mock.patch.object(env,'registry_locations',return_value={'data':[],'executables':[]}))
|
|
self.enterContext(mock.patch.dict(os.environ,{'WECOM_ARCHIVE_SOURCE_DIR':'','OneDrive':'','OneDriveCommercial':'','OneDriveConsumer':''}))
|
|
self.enterContext(mock.patch('reply_database.application_data_dir',return_value=self.appdata))
|
|
|
|
def test_root_account_data_and_file_paths_with_unicode_spaces(self):
|
|
for value in (self.source,self.database.parents[1],self.database.parent,self.database):
|
|
with self.subTest(path=str(value)):
|
|
self.assertEqual(db.detect_wxwork_dir([str(value)],account='100'),str(self.source))
|
|
|
|
def test_current_account_ignores_stale_saved_directory(self):
|
|
stale=self.root/'旧文档'/'WXWork'/'101'/'Data'/'message.db';stale.parent.mkdir(parents=True);stale.write_bytes(self.database.read_bytes())
|
|
(self.appdata/'wxwork_gui_config.json').write_text(json.dumps({'db_dir':str(stale.parents[2])}),encoding='utf-8')
|
|
with mock.patch.object(db,'_windows_documents_dirs',return_value=[str(self.source.parent)]):
|
|
self.assertEqual(db.detect_wxwork_dir(account='100'),str(self.source))
|
|
|
|
def test_registered_data_directory_takes_effect(self):
|
|
with mock.patch.object(env,'registry_locations',return_value={'data':[str(self.source)],'executables':[]}):
|
|
self.assertEqual(db.detect_wxwork_dir(account='100'),str(self.source))
|
|
|
|
def test_fresh_account_with_plain_db_needs_no_key_worker(self):
|
|
with mock.patch.dict(os.environ,{'WECOM_ARCHIVE_SOURCE_DIR':str(self.source)}),mock.patch('wxwork_local_setup.acquire_local_keys') as acquire:
|
|
report=env.protocol_database_status('100',initialize=True)
|
|
self.assertTrue(report['ready']);acquire.assert_not_called()
|
|
self.assertTrue((self.appdata/'wxwork_reply_cache/100/message.db').is_file())
|
|
|
|
def test_encrypted_first_install_initializes_only_current_machine_keys(self):
|
|
from test_crypto_roundtrip import PAGE, encrypt_page
|
|
import wxwork_local_setup as setup
|
|
key=bytes(range(1,17));raw=self.database.read_bytes()
|
|
encrypted=b"".join(encrypt_page(key,i//PAGE+1,raw[i:i+PAGE]) for i in range(0,len(raw),PAGE))
|
|
self.database.write_bytes(encrypted)
|
|
with mock.patch.dict(os.environ,{'WECOM_ARCHIVE_SOURCE_DIR':str(self.source)}), \
|
|
mock.patch.object(setup,'application_data_dir',return_value=self.appdata), \
|
|
mock.patch.object(setup,'acquire_local_keys',side_effect=lambda:setup._save_verified_keys({'local':key.hex()},str(self.source))) as acquire:
|
|
report=env.protocol_database_status('100',initialize=True)
|
|
self.assertTrue(report['ready']);acquire.assert_called_once()
|
|
self.assertEqual(self.database.read_bytes(),encrypted)
|
|
self.assertEqual(db.load_keys(),{'100':key.hex()})
|
|
|
|
def test_historical_account_and_empty_sqlite_cannot_prove_readiness(self):
|
|
database=db.WXWorkDB(str(self.source),{},str(self.appdata/'cache'))
|
|
try:
|
|
self.assertTrue(database.health_check());self.assertTrue(database.health_check(account='100'))
|
|
self.assertFalse(database.health_check(account='101'))
|
|
finally:database.close()
|
|
conn=sqlite3.connect(self.database);conn.execute('DROP TABLE message_table');conn.commit();conn.close()
|
|
empty=db.WXWorkDB(str(self.source),{},str(self.appdata/'empty-cache'))
|
|
try:self.assertFalse(empty.health_check(account='100'))
|
|
finally:empty.close()
|
|
with self.assertRaises(ValueError):db.detect_wxwork_dir(account='../100')
|
|
|
|
def test_passive_check_does_not_acquire_keys(self):
|
|
with mock.patch('reply_database.detect_wxwork_dir',return_value=str(self.source)),mock.patch('reply_database.WXWorkDB') as constructor,mock.patch('wxwork_local_setup.acquire_local_keys') as acquire:
|
|
constructor.return_value.health_check.return_value=False
|
|
with self.assertRaisesRegex(db.DatabaseReadError,'本机初始化'):LiveReplyDatabase._open_database(account='100',initialize=False)
|
|
acquire.assert_not_called();constructor.return_value.close.assert_called_once()
|
|
|
|
def test_registry_uses_both_views_and_ignores_numeric_data_flag(self):
|
|
import winreg
|
|
executable=self.root/'自选目录 空格'/'WXWork.exe';executable.parent.mkdir();executable.touch()
|
|
def value(key,name):return (str(executable),winreg.REG_SZ) if name=='Executable' else (0,winreg.REG_DWORD)
|
|
from importlib.util import spec_from_file_location,module_from_spec
|
|
spec=spec_from_file_location('environment_under_test',env.__file__);original=module_from_spec(spec);spec.loader.exec_module(original)
|
|
with mock.patch.object(winreg,'OpenKey') as openkey,mock.patch.object(winreg,'QueryValueEx',side_effect=value):values=original.registry_locations()
|
|
self.assertEqual(values,{'executables':[str(executable)],'data':[]});self.assertEqual(openkey.call_count,4)
|
|
with mock.patch.object(env,'registry_locations',return_value=values):self.assertIn(executable,env.installed_executables())
|
|
|
|
|
|
class GuiTests(unittest.TestCase):
|
|
def test_saved_protocol_gets_auto_probe_and_recent_report_is_reused(self):
|
|
from wechat_gui_qt import MainWindow
|
|
host=SimpleNamespace(runtime_settings={'reply_transport':'protocol'},_refresh_protocol_probe=mock.Mock())
|
|
MainWindow._maybe_refresh_protocol_probe(host);host._refresh_protocol_probe.assert_called_once()
|
|
host._protocol_report=ready();MainWindow._maybe_refresh_protocol_probe(host);host._refresh_protocol_probe.assert_called_once()
|
|
host._protocol_report={};host.runtime_settings['reply_transport']='visual';MainWindow._maybe_refresh_protocol_probe(host);host._refresh_protocol_probe.assert_called_once()
|
|
|
|
def test_start_waits_without_constructing_sender(self):
|
|
import wechat_gui_qt as qt
|
|
host=SimpleNamespace(_thread=None,save_runtime_settings=mock.Mock(return_value=True),runtime_settings={'reply_transport':'protocol'},append_log=mock.Mock(),_refresh_protocol_probe=mock.Mock())
|
|
with mock.patch.object(qt,'BotThread') as bot:qt.MainWindow.start_monitoring(host)
|
|
self.assertTrue(host._protocol_start_pending);bot.assert_not_called();host._refresh_protocol_probe.assert_called_once()
|
|
|
|
def test_stop_cancels_delayed_start(self):
|
|
from wechat_gui_qt import MainWindow
|
|
host=SimpleNamespace(_thread=None,_protocol_start_pending=True,_finish_thread=mock.Mock())
|
|
MainWindow.stop_monitoring(host);self.assertFalse(host._protocol_start_pending)
|
|
|
|
def test_only_success_resumes_pending_start(self):
|
|
import wechat_gui_qt as qt
|
|
for report in ({'status':'client_access_denied','message':'权限不一致'},ready()):
|
|
host=SimpleNamespace(_protocol_start_pending=True,runtime_settings={'reply_transport':'protocol'},append_log=mock.Mock(),_push_console_state=mock.Mock(),start_monitoring=mock.Mock())
|
|
with mock.patch.object(qt.QTimer,'singleShot') as timer:qt.MainWindow._protocol_probe_loaded(host,report)
|
|
self.assertFalse(host._protocol_start_pending)
|
|
if protocol_ready(report):timer.assert_called_once_with(0,host.start_monitoring)
|
|
else:timer.assert_not_called();self.assertEqual(host._protocol_probe['message'],'权限不一致')
|
|
|
|
if __name__=='__main__':unittest.main()
|