pytest 进行 websocket 协议测试的核心做法是结合 pytest 的 fixture 机制与第三方库(如 websockets 或 websocket-client)来建立连接、发送消息并验证响应。具体实现时,通常定义一个自动使用的 fixture 来管理连接的创建与销毁,确保每个测试用例都能获得干净的会话环境,并在测试结束后正确关闭连接以释放资源。

pytest Fixture 如何管理 WebSocket 生命周期
通过自定义 @pytest.fixture(autouse=True) 可以自动化处理 WebSocket 连接的建立和断开。在 fixture 中实例化客户端对象,使用 yield 关键字将连接对象传递给测试函数,并在 finally 块中调用关闭方法,从而保证无论测试成功与否,连接都会被清理。

import pytest
import websockets
@pytest.fixture
def ws_connection():
# 假设服务器地址为 ws://localhost:8765
uri = "ws://localhost:8765"
async def connect():
return await websockets.connect(uri)
# 在同步测试中使用 asyncio.run 运行异步连接
conn = asyncio.run(connect())
yield conn
try:
await conn.close()
except Exception:
pass
def test_send_message(ws_connection):
import asyncio
asyncio.run(ws_connection.send("hello"))
response = asyncio.run(ws_connection.recv())
assert response == "hello received"
如何验证 WebSocket 的消息收发逻辑
验证消息逻辑主要依赖对发送和接收行为的断言。可以使用 asyncio.run() 在同步测试中执行异步操作,或者直接使用 pytest-asyncio 插件支持异步测试函数。重点在于检查返回数据的格式、内容以及特定状态码下的行为。

import pytest
import asyncio
import websockets
# 使用 pytest-asyncio 插件
@pytest.mark.asyncio
async def test_binary_message_handling():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
# 发送二进制数据
await websocket.send(b"\x00\x01")
# 接收响应
data = await websocket.recv()
assert isinstance(data, bytes)
assert len(data) > 0
@pytest.mark.asyncio
async def test_error_handling_on_invalid_input():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
await websocket.send("invalid_json")
with pytest.raises(websockets.exceptions.ConnectionClosedError):
await websocket.recv()
当服务器主动关闭连接时客户端如何处理异常
当服务器主动关闭连接或网络中断时,客户端尝试接收数据会抛出 ConnectionClosed 异常。在测试中,应捕获此类异常并验证程序是否按预期处理了断连情况,例如记录日志或触发重连逻辑。这有助于确保系统的健壮性。


















