ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Playwright Python WebSocket 消息验证:4 个核心 API 与避坑清单

Playwright Python WebSocket 消息验证:4 个核心 API 与避坑清单 Playwright Python WebSocket 消息验证4 个核心 API 与避坑清单【免费下载链接】playwright-pythonPython version of the Playwright testing and automation library.项目地址: https://gitcode.com/GitHub_Trending/pl/playwright-python从人肉刷新看 Network到自动化断言你大概率遇到过这样的循环改完前端一条 WebSocket 逻辑打开页面、点连接按钮、盯着 Network 面板里的 WS 帧确认服务端推回来的是不是hello。改十遍重复十遍。断言全靠肉眼漏看一帧就是线上事故。用 Playwright Python 接管这个验证过程Playwright 是微软主导的跨浏览器自动化库playwright-python 是它的 Python 版本让 Python 代码直接驱动浏览器收发 WebSocket 帧并断言内容。page.expect_websocket()包住触发操作拿到WebSocket对象本身ws.on(framereceived)/ws.on(framesent)监听收到的帧 / 发出的帧payload 即文本或字节ws.send()测试侧主动发帧不等页面参与ws.wait_for_event()与ws.is_closed()等待指定事件、检查连接状态async with page.expect_websocket() as ws_info: await page.evaluate(new WebSocket(ws://...)) ws await ws_info.value最小可跑示例收一条 WS 帧并断言先搭环境。playwright install chromium下载浏览器内核只装 chromium 最快pip install playwright playwright install chromium示例需要一个能回帧的 WS 服务端。websockets是官方示例常用的库装好后在ws_server.py里写个回声服务收什么回什么便于验证收发对称pip install websocketsimport asyncio import websockets async def main(): async def echo(ws): # 首帧固定 hello模拟服务端的握手推送 await ws.send(hello) async for msg in ws: await ws.send(msg) async with websockets.serve(echo, localhost, 8765): await asyncio.Future() asyncio.run(main())在ws_client.py里驱动浏览器。要点把连接动作包进expect_websocket这样拿到的ws就是页面上真实建立的那条连接import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: browser await p.chromium.launch() page await browser.new_page() async with page.expect_websocket() as ws_info: # 让页面发起连接触发 websocket 事件 await page.evaluate( new WebSocket(ws://localhost:8765) ) ws await ws_info.value # 在连接上挂监听等首帧到达 async with ws.expect_event(framereceived) as frame: pass print(收到帧:, await frame.value) assert (await frame.value) hello await browser.close() asyncio.run(main())跑完之后服务端终端无报错、连接保持客户端终端打印收到帧: hello进程正常退出。若断言失败pytest 或裸跑都会在assert处抛错报错信息会给出实际帧内容。截图断言同理仓库的 golden 图就是这种像素级对答案下面这张来自 Chromium 下的区域截图测试注意中间被 mask 的那一格进阶用法场景验证客户端发 X、服务端回 Y的对称逻辑。 关键 APIws.onws.expect_event在open时直接ws.send再用expect_event等回帧def on_ws(ws): ws.on(open, lambda _: ws.send(ping)) ws.on(open, lambda _: asyncio.create_task(wait_reply(ws))) async def wait_reply(ws): async with ws.expect_event(framereceived) as f: pass assert await f.value ping page.on(websocket, on_ws)踩坑ws.send()是同步调用不保证服务端已处理。断言回帧要靠expect_event配对别拿send的返回值想太多。场景校验二进制帧如上传进度、图片分片。 关键 APIisinstance区分类型。framereceived的 payload 文本是str二进制是bytes两者混用时断言要先判类型ws.on(framereceived, lambda p: check(p)) def check(p): assert isinstance(p, bytes) # 二进制帧必须是 bytes assert len(p) 4踩坑用对比b...和...永远不相等先isinstance再比内容。场景连接意外断开时别让测试静默挂到超时。 关键 APIclose/socketerror事件挂上后记录状态并快速失败ws.on(close, lambda _: print(连接已关闭)) ws.on(socketerror, lambda e: print(错误:, e)) # 结束时兜底检查 assert not ws.is_closed() or expected_close踩坑socketerror回调参数是字符串而非异常对象打印前别当 Exception 处理。高频坑与对策现象expect_websocket超时抛错页面明明连上了。根因监听挂晚了——先evaluate再等事件事件已触发过。解法把连接动作写进expect_websocket的代码块内部。现象收到的帧和我发的对不上、顺序错乱。根因服务端有延迟推送或消息本身是异步到达。解法用expect_event按内容匹配不要按第几帧硬断言。现象断言比较结果莫名False。根因文本帧是str、二进制帧是bytes类型不同恒假。解法断言前先isinstance判定再比较内容。现象默认 30 秒超时报Timeout。根因服务端握手慢或断连时机晚于默认窗口。解法显式传timeout毫秒别依赖环境默认值。下一步Playwright Python 把实时消息验证从肉眼活变成了代码活帧级断言、事件监听、类型检查都能写进 CI。完整的帧收发、二进制、关闭事件测试见 tests/async/test_websocket.py 和内置服务端 tests/server.py。【免费下载链接】playwright-pythonPython version of the Playwright testing and automation library.项目地址: https://gitcode.com/GitHub_Trending/pl/playwright-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表