101 lines
5.5 KiB
Python
101 lines
5.5 KiB
Python
"""Exercise search in the real console HTML using isolated, local-only WebEngine."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
|
os.environ.setdefault('QTWEBENGINE_CHROMIUM_FLAGS', '--disable-gpu')
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT))
|
|
from tools.test_proactive_console import LocalOnly, Page
|
|
from PySide6.QtCore import QEventLoop, QTimer, QUrl
|
|
from PySide6.QtWidgets import QApplication
|
|
from PySide6.QtWebEngineCore import QWebEngineProfile
|
|
from PySide6.QtWebEngineWidgets import QWebEngineView
|
|
from PySide6.QtTest import QTest
|
|
|
|
|
|
def main():
|
|
app = QApplication.instance() or QApplication([])
|
|
view = QWebEngineView()
|
|
profile = QWebEngineProfile(view)
|
|
interceptor = LocalOnly(profile)
|
|
profile.setUrlRequestInterceptor(interceptor)
|
|
page = Page(profile, view)
|
|
view.setPage(page)
|
|
view.resize(1440, 1000)
|
|
view.show()
|
|
loop = QEventLoop()
|
|
loaded = []
|
|
page.loadFinished.connect(lambda ok: (loaded.append(ok), loop.quit()))
|
|
page.load(QUrl.fromLocalFile(str(ROOT / 'assets/ui/zhenyang-ai-console.html')))
|
|
QTimer.singleShot(15000, loop.quit)
|
|
loop.exec()
|
|
assert loaded == [True]
|
|
|
|
def js(script):
|
|
results = []
|
|
wait = QEventLoop()
|
|
page.runJavaScript('(() => { try {' + script + '} catch(e){return {error:String(e)};} })()',
|
|
lambda value: (results.append(value), wait.quit()))
|
|
QTimer.singleShot(10000, wait.quit)
|
|
wait.exec()
|
|
assert results and not (isinstance(results[0], dict) and results[0].get('error')), results
|
|
return results[0]
|
|
|
|
rows = [dict(id=f'M:{n}', name=f'测试客户{n}', kind='微信客户', messageCount=100,
|
|
lastTime='2026-10-31', preview='最近消息', lastDirection='收到') for n in range(50)]
|
|
fixture = dict(loading=False, query='', selectedAccount='1', selectedConversation='M:0',
|
|
accounts=[dict(id='1', name='测试账号')], accountCount=1, conversations=rows,
|
|
conversationDetails=rows[0], conversationTotal=50, conversationLimit=50,
|
|
messageTotal=80, messageLimit=80, messageLoadDirection='newest',
|
|
messages=[dict(id=str(n), sender='测试客户0', direction='inbound', time='12:00',
|
|
type='文字', content=f'测试消息 {n}') for n in range(80)])
|
|
js('window.commands=[]; window.qtBridge={navigate:()=>{},setWeChatDatabaseQuery:q=>commands.push(q),'
|
|
'selectWeChatConversation:q=>commands.push("select:"+q)};window.applyState(' +
|
|
json.dumps(dict(view='wechatdb', demo=False, wechatDb=fixture), ensure_ascii=False) + '); return true;')
|
|
QTest.qWait(100)
|
|
js('window.savedChat=document.querySelector(".db-chat"); window.savedMessage=savedChat.querySelector(".db-message");'
|
|
'window.savedInput=document.getElementById("wechat-db-search"); savedChat.scrollTop=180;'
|
|
'savedInput.focus(); savedInput.value="客户1"; savedInput.setSelectionRange(2,2); return true;')
|
|
for searching in (True, False):
|
|
patch = dict(query='客户1', searching=searching, conversations=[rows[1]], conversationTotal=1)
|
|
js('window.applyState({view:"wechatdb",wechatDb:{...STATE.wechatDb,...' + json.dumps(patch, ensure_ascii=False) + '}}); return true;')
|
|
QTest.qWait(60)
|
|
assert js('return document.querySelector(".db-chat")===savedChat && document.querySelector(".db-message")===savedMessage;')
|
|
assert js('return document.activeElement===savedInput && savedInput.selectionStart===2;')
|
|
assert js('return Math.abs(savedChat.scrollTop-180)<2;')
|
|
assert js('return document.querySelector("[data-db-region=messages] h2").textContent;') == '测试客户0'
|
|
assert js('return document.querySelector("[data-db-search-status]").textContent.includes("找到 1 个会话");')
|
|
|
|
# Fast typing is debounced and does not trigger chat navigation.
|
|
js('for (const value of ["a","ab","abc"]){savedInput.value=value;savedInput.dispatchEvent(new Event("input",{bubbles:true}));}return true;')
|
|
QTest.qWait(400)
|
|
assert js('return JSON.stringify(commands);') == '["abc"]'
|
|
# Chinese IME should never send an incomplete composition.
|
|
js('commands=[];savedInput.dispatchEvent(new CompositionEvent("compositionstart",{bubbles:true}));'
|
|
'savedInput.value="高";savedInput.dispatchEvent(new Event("input",{bubbles:true}));return true;')
|
|
QTest.qWait(400)
|
|
assert js('return commands.length;') == 0
|
|
js('savedInput.value="高瑞";savedInput.dispatchEvent(new CompositionEvent("compositionend",{bubbles:true}));return true;')
|
|
QTest.qWait(400)
|
|
assert js('return JSON.stringify(commands);') == '["高瑞"]'
|
|
|
|
# Selecting a result can update the chat; background list updates cannot.
|
|
js('document.querySelector(".db-conversation").click();return true;')
|
|
assert js('return commands.at(-1);') == 'select:M:1'
|
|
js('savedInput.blur();window.applyState({view:"wechatdb",wechatDb:{...STATE.wechatDb,selectedConversation:"M:1",'
|
|
'conversationDetails:STATE.wechatDb.conversations[0],messages:[{id:"new",content:"新会话消息"}]}});return true;')
|
|
assert js('return document.querySelector("[data-db-region=messages] h2").textContent;') == '测试客户1'
|
|
assert js('return document.querySelector(".db-chat").textContent.includes("新会话消息");')
|
|
assert not page.errors, page.errors
|
|
print('WebEngine search passed: stable chat/input/scroll, debounce, Chinese IME, result selection.')
|
|
view.close()
|
|
view.deleteLater()
|
|
QTest.qWait(30)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|