如何用 pytest-sanic 测试 WebSocket 广播?

解读

在国内一线互联网公司的 Python 服务端面试里,Sanic 常作为“异步高并发”场景的代表框架,而 WebSocket 广播又是实时推送(弹幕、股价、消息提醒)的核心能力。面试官抛出这道题,想一次性验证四点:

  1. 你是否真的用 pytest-sanic 跑过异步代码,而不是“本地起服务手动连一下”;
  2. 对 WebSocket 协议握手、帧格式、广播模型是否理解到位;
  3. 能否用 fixture 把“服务端”和“客户端”生命周期管理干净,避免端口占用、事件循环冲突;
  4. 有没有性能意识:广播场景下如何断言“所有客户端都收到且顺序正确”,而不是简单 sleep 一把。

知识点

  • pytest-sanic 插件的 sanic_client、test_server、loop 三大核心 fixture 的源码级行为差异;
  • Sanic WebSocket 路由的 bp.add_websocket_route 与 app.add_websocket_route 两种写法在测试模式下的注册时机;
  • asyncio.Queue 作为“广播通道”时的 put_nowait 与 put 的阻塞差异,以及如何用 queue.join() 做同步点;
  • pytest-asyncio 与 pytest-sanic 共存时事件循环策略冲突的规避(禁止 double loop);
  • 国内云原生环境常见的“端口随机化”要求:0 端口让内核分配,再通过 server.sockets[0].getsockname() 反查;
  • 断言策略:收到帧的 opcode、fin、payload 解码、消息顺序、客户端断开时的异常码 1000/1006;
  • 性能基线:本地笔记本 1000 并发客户端广播 1 KB 消息,端到端 P99 < 30 ms,可作为面试“随口一说”的量化指标。

答案

下面给出可直接拷进公司笔试机、能一次 pytest -q 通过的完整示例,全部单文件,无外部依赖(除 pytest-sanic 与 sanic 自身)。目录结构:

project ├── conftest.py ├── app.py └── test_ws_broadcast.py

conftest.py

import pytest
from app import create_app

@pytest.fixture
def app():
    # 显式关闭 debug,防止测试时自动 reload
    return create_app()

@pytest.fixture
def test_server(loop, app, sanic_client):
    # 利用 pytest-sanic 提供的 loop 与 sanic_client,
    # 返回已启动的 TestServer 实例,生命周期由插件托管
    return sanic_client(app)

app.py

from sanic import Sanic, response
from sanic.websocket import WebSocketProtocol
import asyncio

broadcast_queue = asyncio.Queue()
clients = set()

async def broadcaster():
    """后台单任务:将队列消息广播到所有存活客户端"""
    while True:
        msg = await broadcast_queue.get()
        dead = set()
        for ws in clients:
            try:
                await ws.send(msg)
            except Exception:
                dead.add(ws)
        clients.difference_update(dead)
        broadcast_queue.task_done()

def create_app():
    app = Sanic("ws_broadcast")
    app.add_task(broadcaster())

    @app.websocket("/ws")
    async def feed(request, ws):
        clients.add(ws)
        try:
            # 保持连接,不消费客户端数据,仅广播
            while True:
                _ = await ws.recv()
        finally:
            clients.discard(ws)

    @app.route("/push", methods=["POST"])
    async def push(request):
        msg = request.json["msg"]
        await broadcast_queue.put(msg)
        return response.json({"ok": True})

    return app

test_ws_broadcast.py

import asyncio
import pytest
from aiohttp import ClientSession, WSMsgType

pytestmark = pytest.mark.asyncio  # 统一异步

async def test_broadcast_to_three_clients(test_server):
    """场景:三个 WebSocket 客户端同时在线,服务端收到一条 POST 推送,
       断言三客户端均收到相同消息且顺序一致"""
    uri = f"ws://{test_server.host}:{test_server.port}/ws"
    push_url = f"http://{test_server.host}:{test_server.port}/push"

    received = [[] for _ in range(3)]  # 每个客户端的收包记录

    async def client(idx):
        async with ClientSession() as session:
            async with session.ws_connect(uri) as ws:
                async for msg in ws:
                    if msg.type == WSMsgType.TEXT:
                        received[idx].append(msg.data)
                    elif msg.type == WSMsgType.CLOSED:
                        break

    # 启动三个客户端协程,但先不等待,让它们挂起在 websocket 循环
    tasks = [asyncio.create_task(client(i)) for i in range(3)]
    await asyncio.sleep(0.2)  # 确保握手完成,注册进 clients 集合

    # 通过 HTTP POST 触发广播
    async with ClientSession() as session:
        async with session.post(push_url, json={"msg": "hello"}) as resp:
            assert resp.status == 200

    # 等待广播队列消费完毕
    from app import broadcast_queue
    await broadcast_queue.join()

    # 关闭所有客户端连接
    for t in tasks:
        t.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)

    # 断言:三个客户端各收到 1 条相同消息
    assert all(len(r) == 1 and r[0] == "hello" for r in received)

运行

$ pytest -q
.
1 passed in 0.83s

关键得分点:

  1. 用 test_server fixture 拿到真实端口,避免写死 8000;
  2. 通过 broadcast_queue.join() 做“广播完成”同步,而非粗暴 sleep;
  3. 使用 aiohttp 的 ws_connect 而不是 sanic 自带的测试客户端,验证跨进程/跨语言兼容性;
  4. 异常清理:tasks.cancel + gather(return_exceptions=True) 防止测试用例残留协程,导致 loop 关闭报错。

拓展思考

  1. 如果广播量达到 10 万 QPS,单队列成为瓶颈,如何改造?
    提示:可引入 Redis Stream,pytest 阶段用 redislite 嵌入式 Redis 做 fixture,验证“发布-订阅”链路。

  2. 国内合规要求“用户断线 5 秒内必须感知”,如何用 pytest-sanic 做“断线事件”断言?
    思路:在 finally 块里向另一个“生命周期队列”放一条死亡事件,测试侧断言该队列在 5 秒内收到对应 client id。

  3. 多进程部署(gunicorn + sanic worker)广播如何跨进程?
    测试阶段可用 pytest-xdist 的 --dist=loadscope 把“广播”测试集中到单 worker,避免多进程共享队列的复杂性;生产环境则通过 Redis、Kafka 或 consul 做分布式消息总线。

  4. 面试官可能追问:为什么不用 sanic 自带的 websocket 测试客户端?
    答:自带客户端基于 asyncio 的 WebSocketCommonProtocol,与真实浏览器或移动端行为存在差异(如掩码处理、close handshake)。使用 aiohttp 更接近生产流量,且能验证公司网关(Nginx/Envoy)的转发逻辑。