如何为 WebSocket 测试做性能基准并生成 QPS 报告?

解读

面试官问的不是“会不会用 pytest”,而是“能不能把 pytest 当成一把瑞士军刀,在真实业务里把 WebSocket 压测做成可重复、可量化、可 CI 集成的质量门禁”。国内大厂(如字节、阿里、美团)的考核维度通常有三层:

  1. 协议理解:WebSocket 握手、帧格式、心跳、异常重连、子协议扩展。
  2. 压测设计:并发模型(协程/进程/多线程)、连接生命周期、消息回环 RT、资源上限(FD、内存、CPU)。
  3. 工程化:pytest 插件生态、自定义 metric 收集、Allure/Jenkins 可视化、阈值断言、失败自动重跑。

回答时必须给出“能直接跑在 GitLab CI 里的代码骨架”,并解释如何防止“本地一条龙、CI 一条虫”的常见坑(如 Docker 文件句柄限制、时区不一致导致报告时间戳错乱)。

知识点

  1. pytest-asyncio + pytest-xdist:用协程客户端打高并发,再用 xdist 多进程横向扩展,突破 Python GIL。
  2. pytest-benchmark 与自定义 fixture:benchmark 只能统计函数级 CPU 时间,WebSocket I/O 场景需要自定义“连接池级”指标,如 QPS、P99 延迟、失败率。
  3. pytest-html / pytest-allure-adaptor:国内面试时,Allure 报告是“加分项”,能下钻到每一次失败消息的 payload。
  4. 资源隔离:使用 pytest 的 tmp_path_factory 为每个 worker 生成独立 Unix socket,防止端口冲突;通过 pytest 的 hook(pytest_configure)动态修改 ulimit。
  5. 阈值断言:pytest-assertions 自定义 hook,在 teardown 阶段读取 prometheus_client 暴露的指标,一旦 QPS<预期值或 P99>200 ms,直接标记用例失败,阻断合并请求。

答案

下面给出“能直接落地”的最小可运行方案,依赖全部用国内 PyPI 镜像可拉取。

  1. 目录结构 websocket_perf/ ├── conftest.py ├── test_ws_qps.py ├── ws_client.py └── requirements.txt

  2. requirements.txt(锁定版本,防止 CI 漂移) pytest==7.4.3 pytest-asyncio==0.21.1 pytest-xdist==3.5.0 websockets==12.0 prometheus-client==0.19.0 allure-pytest==2.13.2

  3. ws_client.py(协程级连接池,支持异步发送-接收回环)

import asyncio, time, websockets, statistics
from prometheus_client import Counter, Histogram

SEND_CNT = Counter('ws_msg_sent', 'total sent')
RECV_CNT = Counter('ws_msg_recv', 'total recv')
LATENCY = Histogram('ws_latency_seconds', 'RTT latency')

class Pool:
    def __init__(self, uri, concurrency, duration):
        self.uri = uri
        self.concurrency = concurrency
        self.duration = duration
        self.latencies = []

    async def _one_connection(self):
        async with websockets.connect(self.uri) as ws:
            end = time.time() + self.duration
            while time.time() < end:
                t0 = time.perf_counter()
                await ws.send('ping')
                await ws.recv()
                delta = time.perf_counter() - t0
                LATENCY.observe(delta)
                SEND_CNT.inc()
                RECV_CNT.inc()
                self.latencies.append(delta)

    async def run(self):
        await asyncio.gather(*(self._one_connection() for _ in range(self.concurrency)))
        return {
            'qps': len(self.latencies) / self.duration,
            'p99': statistics.quantiles(self.latencies, n=100)[98] * 1000,  # ms
            'latencies': self.latencies
        }
  1. conftest.py(全局资源初始化与阈值校验)
import pytest, prometheus_client, os, resource

def pytest_configure(config):
    # CI 环境默认 ulimit 1024,直接改成 65535
    soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
    resource.setrlimit(resource.RLIMIT_NOFILE, (65535, hard))
    # 启动 prometheus exporter,端口 0 让系统自动分配,防止并行冲突
    prometheus_client.start_http_server(0)

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == 'call' and rep.outcome == 'passed':
        # 在 teardown 前校验 QPS 阈值
        qps = item.funcargs.get('qps_result', {}).get('qps', 0)
        if qps < 5000:  # 业务自定义
            rep.outcome = 'failed'
            rep.longrepr = f'QPS 不达标: {qps:.2f} < 5000'
  1. test_ws_qps.py(参数化并发度,生成 Allure 趋势图)
import pytest, asyncio, allure

@allure.feature('WebSocket 性能基线')
@pytest.mark.asyncio
@pytest.mark.parametrize('concurrency', [100, 500, 1000])
async def test_qps(benchmark, concurrency):
    from ws_client import Pool
    pool = Pool(uri='wss://echo.websocket.org/', concurrency=concurrency, duration=10)
    result = await pool.run()
    # 把关键指标写回 allure
    allure.attach(str(result['qps']), name='QPS', attachment_type=allure.attachment_type.TEXT)
    allure.attach(str(result['p99']), name='P99(ms)', attachment_type=allure.attachment_type.TEXT)
    # 通过 fixture 把结果回传给 conftest 做阈值断言
    pytest.qps_result = result
    assert result['qps'] >= 5000  # 最后一道保险
  1. 运行与报告

本地 4 核并行,生成 html 与 allure 双份报告

pytest -n 4 --html=report.html --self-contained-html --alluredir=allure_raw allure generate allure_raw -o allure_report --clean

  1. CI 集成(GitLab 片段)
variables:
  PYPI_MIRROR: https://pypi.tuna.tsinghua.edu.cn/simple
test_ws:
  stage: test
  image: python:3.11-slim
  before_script:
    - apt-get update && apt-get install -y allure-commandline
  script:
    - pip install -r requirements.txt -i $PYPI_MIRROR
    - pytest -n auto --alluredir=allure_raw
    - allure generate allure_raw -o public
  artifacts:
    reports:
      junit: junit.xml
    paths:
      - public
    expire_in: 7 days
    when: always

至此,每次合并请求都会拿到一张带 QPS、P99 趋势曲线的 Allure 报告,并在 QPS 低于 5000 或 P99 高于 200 ms 时自动打回。

拓展思考

  1. 如果业务消息体大于 8 KB,websockets 库默认 max_size=2^20,pytest 参数化时记得同步放大,防止压测提前异常断开。
  2. 国内很多网关(如阿里云 SLB、Kong)会默认 60 s 断链,测试脚本需加入心跳帧(ping/pong)并校验网关行为,避免“假 QPS”。
  3. 当并发超过 5 k 时,单台 CI runner 会成为瓶颈,可把 pytest-xdist 的 worker 改成 Kubernetes Pod,通过 pytest-kubernetes 插件动态扩缩容,实现“云原生压测”。
  4. 若需与现有 Prometheus 集群对接,可在 conftest 里把指标推到 pushgateway,并给每条测试用例打 label(branch、commit),方便在 Grafana 做版本对比。
  5. 面试反向提问:可问面试官“贵司 WebSocket 网关是否支持 HTTP/2 多路复用?若支持,是否考虑用 pytest + aiohttp 的 ws_connect 复用 TCP,进一步降低握手开销?”体现对协议细节的敏感度。