You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest单测通过批量运行失败:未认证WebSocket测试异常

问题分析与解决

1. 修正断言逻辑:混淆了Subprotocol与关闭码

你当前的测试断言subprotocol == 3000存在逻辑错误:WebsocketCommunicator.connect()返回的第二个值是协商的子协议字符串,并非WebSocket关闭码。关闭码需要通过communicator.close_code属性获取。

错误的断言在单独执行时可能因巧合通过,但批量测试时环境状态变化会直接导致断言失败。修改测试代码如下:

@pytest.mark.asyncio
async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator):
    connected, subprotocol = await unauthenticated_websocket_communicator.connect()
    assert connected is False
    assert unauthenticated_websocket_communicator.close_code == 3000  # 正确获取关闭码

2. 确保测试夹具的作用域隔离

如果unauthenticated_websocket_communicator这个测试夹具的作用域是module或session,批量测试时会复用同一个实例,可能被其他测试修改了scope["user"]的状态,导致当前测试中用户不再是匿名状态。

显式指定夹具的作用域为function,保证每个测试都拿到全新的实例:

@pytest.fixture(scope="function")  # 强制每个测试生成新的夹具实例
async def unauthenticated_websocket_communicator():
    # 你的夹具初始化逻辑,确保每次都创建新的communicator和匿名用户上下文
    communicator = WebsocketCommunicator(...)
    yield communicator
    await communicator.disconnect()

3. 重置异步事件循环(可选)

批量测试时,pytest-asyncio的事件循环可能残留之前测试的任务状态,导致WebSocket连接逻辑异常。可以在测试前重置事件循环:

@pytest.mark.asyncio
async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator, event_loop):
    event_loop.close()
    event_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(event_loop)
    
    connected, subprotocol = await unauthenticated_websocket_communicator.connect()
    assert connected is False
    assert unauthenticated_websocket_communicator.close_code == 3000

也可以在项目根目录的pytest.ini中配置全局规则,让每个测试使用独立事件循环:

[pytest]
asyncio_mode = auto

内容的提问来源于stack exchange,提问作者liam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 23:18:32