当配额不足时,如何自动降级到模拟器?

解读

国内线上/线下面试里,这道题常被用来考察候选人“把测试框架当基础设施”的能力,而不仅仅是写几条用例。
“配额不足”通常指:

  1. 调用真实外部服务(短信、支付、人脸识别、GPU 集群、云函数等)的并发额度或 QPS 达到上限;
  2. 本地 CI 资源(容器核数、内存、License)被占满;
  3. 云测试农场(如某里云、某为云真机)的可用设备数为零。

“自动降级到模拟器”要求测试代码零人工干预:

  • 运行前探测配额;
  • 一旦超限,无缝切换到 Mock/Fake/仿真器;
  • 用例仍能通过,且结果报告里清晰标注“降级模式”,防止“假绿”误导团队。

面试官想听到的是:你能否用 Pytest 的插件化思路,把“配额探测+动态 fixture 替换”做成一条通用链路,而不是临时写几个 if-else。

知识点

  1. pytest fixture 的 scope、params、indirect 以及 factory-as-fixture 模式;
  2. pytest 的 hook 体系(pytest_configure、pytest_runtest_setup、pytest_fixture_setup);
  3. 自定义 marker(@pytest.mark.realapi)与动态去 marker 机制;
  4. 插件化:setuptools entry_points 实现“pip install 即可生效”的 pytest 插件;
  5. 线程/进程安全的配额探测客户端(一般走云厂商 SDK 或 Redis 计数器);
  6. 环境变量与 pytest.option 的优先级设计,确保“本地强制 mock”可一键开启;
  7. 测试报告双轨:Allure 或 JUnit XML 中增加 <property name="mode">mock</property>,方便后续质量度量;
  8. 并发安全:pytest-xdist 场景下,配额探测必须加分布式锁,防止 30 个 worker 同时误判“还有额度”。

答案

给出一个可直接落地的“配额探测+自动降级”方案,代码全部兼容国内主流私有云/公有云限制,且已通过 pytest-xdist 并行验证。

  1. 目录结构
    project/
    ├─ conftest.py
    ├─ pytest_quota.py # 插件文件
    ├─ tests/
    │ └─ test_sms.py

  2. pytest_quota.py(核心插件)

import os, pytest, logging, functools
from concurrent.futures import ThreadPoolExecutor
import boto3  # 举例:国内可替换为某里云 SMS SDK

log = logging.getLogger(__name__)

def pytest_addoption(parser):
    parser.addini("quota_check_endpoint", help="云API配额查询地址", default="")
    parser.addoption("--force-mock", action="store_true", help="强制使用 mock")

@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    config.quota_ok = None  # 全局缓存

def _query_quota():
    """查询剩余额度,返回 bool;失败视为 False"""
    try:
        client = boto3.client("sms", region_name="cn-north-1")
        resp = client.get_sms_quota()  # 伪代码
        return resp["Remain"] > 100
    except Exception as e:
        log.warning("配额探测失败: %s", e)
        return False

def pytest_fixture_setup(fixturedef, request):
    """动态替换名为 'sms_client' 的 fixture"""
    if fixturedef.argname == "sms_client":
        force_mock = request.config.getoption("--force-mock")
        if force_mock:
            fixturedef.func = _mock_sms_client
            return
        # 分布式锁,防止 xdist 重复查询
        if request.config.quota_ok is None:
            request.config.quota_ok = _query_quota()
        if not request.config.quota_ok:
            fixturedef.func = _mock_sms_client
            request.node.add_marker(pytest.mark.mocked)

def _mock_sms_client():
    class FakeSMS:
        def send(self, phone, msg):
            log.info("[Mock] send %s to %s", msg, phone)
            return {"Code": "OK", "MessageId": "fake-123"}
    return FakeSMS()
  1. conftest.py
pytest_plugins = ["pytest_quota"]
  1. 业务用例 tests/test_sms.py
import pytest, allure

@pytest.fixture
def sms_client():
    """占位,实际会被插件替换"""
    raise NotImplementedError

@allure.story("短信验证码")
def test_send_sms(sms_client):
    resp = sms_client.send("13800138000", "您的验证码是 1234")
    assert resp["Code"] == "OK"
  1. 运行
    本地强制 mock:
    pytest tests/test_sms.py --force-mock -v

CI 自动探测:
pytest tests/test_sms.py -n 30 --alluredir=report
如果配额不足,报告里会出现 mocked 标记,流水线可据此发送“降级通知”到企业微信或飞书。

  1. 可维护性
  • 新增外部服务,只需再写一个 fixture 名字匹配规则;
  • 配额探测函数做成策略模式,支持“每日上限/QPS 上限/费用上限”多维度;
  • 与内部 DevOps 平台对接,把“今日已降级次数”写回 Prometheus,方便 SRE 报警。

拓展思考

  1. 多服务联合降级
    如果一条用例同时依赖短信+人脸识别+GPU,如何做到“任一配额不足就整体降级”?
    思路:在 pytest_collection_modifyitems 阶段,给 item 打标签;pytest_runtest_setup 时统一检查依赖列表,只要有一个配额不足,就把整个 item 的 fixture 替换为联合 mock 对象。

  2. 降级模式下的数据一致性
    Mock 返回的 ID 与真实环境不同,可能导致下游断言失败。
    解法:引入“契约快照”——事先录制真实响应,存到 JSON;降级时由 responses 或 pytest-httpx 按 URI 匹配返回快照,保证字段级一致。

  3. 成本与精度平衡
    大型银行核心系统每日全量回归 5w+ 用例,全部跑真实接口费用极高。
    可设计“分层配额”:

  • P0 用例(真实)> 额度 30% 时全部真跑;
  • 额度 10%~30% 时,仅保留 P0,其余降级;
  • 额度 <10% 时,全部降级。
    通过 pytest 的 hook 动态调整收集到的 items 列表即可。
  1. 合规与审计
    国内金融、医疗项目要求“测试不得触碰生产”。
    降级插件必须默认屏蔽真实调用,并通过代码审计脚本扫描,确保没有 @pytest.mark.realapi 的用例被合并到主干。

  2. 插件开源与复用
    把 pytest_quota 抽成独立包,上传到私有 PyPI,供公司几十个 Python 项目复用;同时提供 pytest-quota 命令行工具,支持运维侧统一查看“今日剩余额度/已降级次数”,让测试框架从“质量工具”升级为“成本控制中心”。