如何mock外部API并录制/回放HTTP交互?

解读

在国内 Django 面试中,这道题考察的是“如何在不依赖真实第三方接口的情况下,保证单元测试、CI 流水线、本地开发调试都能稳定运行”。
面试官想听到的不只是“用 mock”,而是:

  1. 选型:为什么选 VCR.py / responses / pytest-recording / httpx.MockTransport,而不是手动 monkey-patch;
  2. 落地:在 Django 项目里如何分层(settings、fixtures、conftest.py、基类 TestCase),让录制文件随代码入库、CI 可缓存;
  3. 安全:脱敏手机号、订单号、token,避免把生产密钥录进 Git;
  4. 性能: cassette 文件过大时如何按域名+日期分片、定期清理;
  5. 可维护性:当外部接口升级,如何“一键重录”并触发回归测试。
    回答时先给出最小闭环,再展开工程化细节,体现“可落地、可灰度、可回滚”的国内互联网交付思维。

知识点

  1. HTTP 拦截层:Python 主流库 urllib3、requests、httpx 的底层 hook 点(get_connection、send、event hooks)。
  2. 录制/回放协议:VCR.py 的 cassette(YAML/JSON)格式、match_on 规则(method、uri、body、headers)。
  3. Django 测试体系:pytest-django、unittest、LiveServerTestCase、override_settings、fixtures。
  4. 数据脱敏:自定义 VCR 的 before_record_request / before_record_response 回调,正则替换敏感字段。
  5. 持续集成:GitHub Actions / GitLab CI 缓存 ~/.vcr/cassettes,配合 Makefile 目标 make record-api / make test。
  6. 异常模拟:responses 的 ConnectionError、Timeout、status_code=500,覆盖重试与降级逻辑。
  7. 版本漂移:cassette 文件加 checksum,接口变更时 CI 失败提示“请执行 tox -e re-record”。
  8. 性能优化:VCR.py 的 record_mode=once / new_episodes,配合 pytest-xdist 并行执行无锁。
  9. 合规:国内《个人信息保护法》要求对身份证、手机号脱敏,录制文件需加密落盘或放私有仓库。
  10. 灰度方案:在预发布环境开启“旁路录制”,对比真实响应与 cassette 差异,差异率>5% 自动告警。

答案

最小可运行示例(Django 4.2 + pytest + VCR.py)

  1. 安装
    pip install pytest-django vcrpy

  2. 目录结构
    project/ ├── apps/ │ └── payment/ │ ├── client.py # 封装外部支付 API │ └── tests/ │ ├── conftest.py │ └── test_client.py ├── .vcr/ # cassette 统一目录,git 跟踪 └── pytest.ini

  3. 封装层 apps/payment/client.py
    import requests from django.conf import settings

class PayClient: def init(self): self.host = settings.PAY_API_HOST self.key = settings.PAY_API_KEY

def create_order(self, amount: int) -> dict:
    resp = requests.post(
        f"{self.host}/v1/orders",
        json={"amount": amount},
        headers={"Authorization": f"Bearer {self.key}"},
        timeout=3,
    )
    resp.raise_for_status()
    return resp.json()

4. conftest.py 全局配置
import os import vcr import pytest

脱敏回调

def scrub_sensitive(response): if "token" in response["body"]["string"].decode(): response["body"]["string"] = response["body"]["string"].replace( b"secret_token", b"***" ) return response

vcr.default_vcr = vcr.VCR( serializer="yaml", cassette_library_dir=os.path.join(os.path.dirname(file), "../../.vcr"), record_mode="once", # CI 用已录数据,本地可重录 match_on=["method", "uri", "body"], before_record_response=scrub_sensitive, filter_headers=["authorization"], )

@pytest.fixture(scope="module") def vcr_cassette(request): with vcr.default_vcr.use_cassette(f"{request.module.name}.yaml"): yield

  1. 测试用例 apps/payment/tests/test_client.py
    import pytest from apps.payment.client import PayClient

pytestmark = pytest.mark.usefixtures("vcr_cassette")

def test_create_order_success(db, settings): settings.PAY_API_HOST = "https://pay.example.com" settings.PAY_API_KEY = "fake_key" client = PayClient() data = client.create_order(100) assert data["order_id"] assert data["status"] == "PENDING"

  1. 录制与回放

第一次运行会自动录制

pytest apps/payment/tests/test_client.py::test_create_order_success

后续运行直接回放

pytest

接口变更时重录

pytest --vcr-record=new_episodes

  1. CI 缓存(GitHub Actions 片段)
  • name: Cache cassettes uses: actions/cache@v3 with: path: .vcr key: vcr-${{ hashFiles('**/test_*.py') }}
  1. 一键重录 Makefile
    record-api: rm -rf .vcr pytest --vcr-record=all

以上代码可直接放进简历项目,面试官追问“如何防止录到生产密钥”时,可答:
“通过 VCR 的 filter_headers 与 before_record_response 回调把 Authorization 与响应中的敏感字段统一替换成占位符,cassette 文件再经过 code review 才能合并到主干,合并前用 git diff 人工二次确认。”

拓展思考

  1. 多租户 SaaS 场景:不同租户访问不同子域名, cassette 文件按 {tenant_id}/{api_name}.yaml 分片,避免跨租户数据污染。
  2. 高并发压测:录制阶段只录一条“黄金请求”,压测时用 GoReplay 或 httpx.MockTransport 做并发回放,验证 Django 视图的连接池与缓存策略。
  3. GraphQL 外部网关:VCR 默认按 URI+body 匹配,GraphQL 同一 endpoint 不同 query,需自定义 match_on=graphql_query_hash。
  4. 合规审计:把 cassette 文件作为“电子证据”存到阿里云 OSS,开启版本管理,配合 DSC 敏感数据识别任务,每月出合规报告。
  5. 智能化更新:在预发布环境部署 Django 管理命令 python manage.py sync_cassette,定时对比真实响应字段与 cassette 的 JSONSchema,自动提交 PR 提示“接口已漂移”,实现无人值守的契约测试。