如何为轻客户端验证写测试?

解读

“轻客户端”在国内通常指移动端 App、小程序、H5 或 IoT 固件里“薄”而“快”的 Python SDK/模块,它们往往只负责:

  1. 本地加签、加密、缓存
  2. 与云端网关做一次性 HTTPS 短连接
  3. 拿到结果后做极简校验即返回

因此测试重点不是服务端逻辑,而是“端侧行为”:证书校验、签名校验、本地缓存命中、降级策略、异常提示、性能指标(包大小、冷启动 ≤ 200 ms、内存峰值 ≤ 60 M)以及国内特有的“弱网/代理/根证书劫持”场景。面试官想确认你能否用 Pytest 把“端侧”验证做成可回归、可 CI、可并行、可数据驱动的套件,而不是简单调个接口。

知识点

  1. Pytest 自动发现规则:test_*.py 或 *test.py,测试函数以 test 开头
  2. fixture 依赖注入:scope 分级(session/module/class/function),配合 conftest.py 实现“轻客户端”对象复用与隔离
  3. 参数化:@pytest.mark.parametrize 覆盖国内三大运营商网络、不同 TLS 版本、国密/SM2 与国际 RSA 双通道
  4. mock & monkeypatch:替换 requests/urllib3 底层 socket,构造 “SSL 证书过期”“TCP 握手延迟 2 s”“代理返回 502” 等异常
  5. 断言内省:pytest 重写 assert,可直接对比 bytes、dict、protobuf 而不写 self.assertXXX
  6. 性能基准:pytest-benchmark 统计 CPU、内存峰值;pytest-memray 生成 native 层内存火焰图
  7. 覆盖率:pytest-cov + .coveragerc 排除 pycache、venv,确保“轻客户端”核心模块行覆盖 ≥ 95%,分支覆盖 ≥ 90%
  8. 并行与隔离:pytest-xdist -n auto 利用 8 核 CPU,3 min 跑完 1 k 条用例;同时用 pytest-shard 在 GitHub Actions 矩阵里拆 4 个 job,符合国内代码托管平台限速
  9. 合规与隐私:用 pytest 的 tmp_path 固件,测试结束后自动清理本地缓存、日志,避免《个人信息保护法》合规风险
  10. 自定义 marker:@pytest.mark.smoke @pytest.mark.low_end_device 让 CI 在 MR 阶段只跑冒烟,夜间全量,兼顾“轻客户端”硬件碎片化

答案

以下示例基于一个真实的“轻客户端”国密验签模块 gmclient.py,演示如何落地上述知识点。目录结构符合国内大厂规范:

tests/ ├── conftest.py ├── test_gmclient.py ├── test_cache.py └── benchmark/ └── test_bench_sign.py

conftest.py(节选)

import pytest, os, trustme
from pathlib import Path
from gmclient import GMClient

# 自签 CA,模拟国内私有 PKI
@pytest.fixture(scope="session")
def ca():
    return trustme.CA()

@pytest.fixture(scope="session")
def httpserver(ca):
    server = ca.issue_cert("gateway.example.com")
    return server

# 轻客户端单例,复用 session 级别减少冷启动
@pytest.fixture(scope="session")
def client(httpserver):
    c = GMClient(server_cert=httpserver.cert_pem.bytes(),
                 timeout=2.0,
                 cache_dir=Path(os.getenv("TMPDIR", "/tmp")) / "gm_cache")
    yield c
    c.close()  # 清理连接池

test_gmclient.py

import pytest, socket, ssl, time
from unittest import mock

@pytest.mark.parametrize("latency", [0, 100, 500, 2000])
def test_sign_verify_under_weak_network(client, latency, monkeypatch):
    # 模拟弱网延迟
    def slow_send(self, data, flags=0):
        time.sleep(latency / 1000)
        return self._real_send(data, flags)
    monkeypatch.setattr(socket.socket, "_real_send", socket.socket.send, raising=False)
    monkeypatch.setattr(socket.socket, "send", slow_send)

    payload = b"order_id=123456"
    sig = client.sign(payload)
    assert client.verify(payload, sig) is True

def test_raise_on_invalid_cert(client, monkeypatch):
    # 构造证书过期场景
    monkeypatch.setattr(client, "server_cert", b"invalid")
    with pytest.raises(ssl.SSLError):
        client.sign(b"test")

@pytest.mark.low_end_device
def test_memory_peak_within_budget(client, benchmark):
    # 低端机内存预算 60 MB
    def _run():
        for _ in range(1000):
            client.sign(b"x" * 1024)
    mem = benchmark.pedantic(_run, rounds=3, iterations=10)
    assert mem.mem_rss_peak < 60 * 1024 * 1024  # 单位 byte

test_cache.py

import pytest
from pathlib import Path

@pytest.mark.parametrize("ttl", [0, 60, 3600])
def test_local_cache_hit(client, ttl, tmp_path: Path):
    client.cache_dir = tmp_path
    key = "foo"
    client.cache_set(key, b"bar", ttl=ttl)
    if ttl == 0:
        assert client.cache_get(key) is None
    else:
        assert client.cache_get(key) == b"bar"

benchmark/test_bench_sign.py

import pytest

def test_sign_perf(benchmark, client):
    result = benchmark(client.sign, b"payload")
    assert benchmark.stats["mean"] <= 0.01  # 平均 10 ms 内

运行命令(符合国内 GitLab CI 模板)

pip install -r requirements-test.txt
pytest -n auto --dist=loadscope \
       --cov=gmclient --cov-branch --cov-report=term-missing \
       --cov-fail-under=95 \
       --benchmark-only --benchmark-json=bench.json \
       -m "not low_end_device"  # MR 阶段跳过低端机压力测试

输出示例

tests/test_gmclient.py ....
tests/test_cache.py ...
benchmark/test_bench_sign.py .
----------- coverage: platform linux, python 3.11 -----------
Name            Stmts   Miss Branch BrPart  Cover
-------------------------------------------------
gmclient.py       186      8     48      3    96%
-------------------------------------------------
TOTAL             186      8     48      3    96%
Required test coverage of 95% reached. Total coverage: 96%

拓展思考

  1. 国内 ROM 多样化:如何用 pytest-shard + docker-compose 在 CI 里并发跑 20 款安卓模拟器镜像,验证“轻客户端” so 库兼容性?
  2. 小程序环境:Pytest 本身跑在 PC,如何借助 pytest-playwright 把同一套 fixture 驱动到真机微信开发者工具,实现端到端截图比对?
  3. 法规审计:pytest 生成 JUnit XML 后,如何对接国内“数据出境安全评估”平台,自动把含敏感字段的用例标记为“禁止海外节点运行”?
  4. 性能基线漂移:利用 pytest-benchmark 的 --benchmark-compare-fail=mean:5% 在 MR 阶段拒绝性能回退,替代传统“人工拍脑袋”评估
  5. 插件自研:若公司采用国密双证书通道,可封装 pytest-gm 插件,把 CA 签发、证书吊销列表(CRL)校验封装为固件,供所有业务线复用,形成组织级测试资产