当网络不稳定时,如何测试离线缓存与重发?

解读

面试官真正想考察的是“在不可控网络环境下,如何系统性地验证客户端的离线容错策略”。
国内项目普遍要求“弱网可用、断网可续、恢复即同步”,因此测试必须覆盖:

  1. 断网瞬间数据不丢;
  2. 缓存持久化格式正确;
  3. 网络恢复后自动重发且幂等;
  4. 重试策略符合产品文档(指数退避、最大次数、降级提示)。

Pytest 的优势在于可以用 fixtures 把“网络断/续”抽象为可复用的测试资源,用参数化一口气模拟 2G/3G/Wi-Fi 抖动、间歇性 DNS 劫持、502/503/429 混合场景,再结合 tmp_path、freezegun、time-machine 做持久化与重试时序断言,最后通过 pytest-xdist 并发压测重发幂等性。整套方案既轻量又能直接嵌入 GitLab CI / GitHub Actions,符合国内互联网“快迭代+高可用”节奏。

知识点

  1. pytest-httpserver / responses:本地零依赖 Mock 后端,可编程返回延迟、错误码、断链。
  2. pytest-socket:在测试层禁用真实 socket,强制走 Mock,杜绝误调用线上接口。
  3. fixtures 作用域:session 级启动 http server,function 级重置路由,保证用例隔离。
  4. tmp_path:官方内置,跨平台自动清理,用于验证缓存文件落地格式与完整性。
  5. pytest.mark.parametrize + 自定义 marker(slow、offline):一条用例覆盖 N 种弱网模型,CI 阶段可动态过滤。
  6. freezegun / time-machine:冻结时间,断言指数退避的间隔是否符合 1s、2s、4s 策略。
  7. pytest-xdist:并行跑 200 条重发用例,验证幂等性(订单号、uuid 去重)。
  8. pytest-rerunfailures:与重试逻辑区分,框架级 rerun 用于环境抖动,业务级重试是代码逻辑。
  9. allure-pytest:国内主流报告,附件里可上传抓包 har、缓存 db、日志,方便复现。
  10. 合规:若缓存含用户敏感字段,需用 pytest 钩子自动脱敏,避免泄露到测试报告。

答案

下面给出一套可直接落地的 pytest 方案,分为“环境搭建—断网模拟—缓存断言—重发验证—CI 集成”五步,全部代码均通过国内 Windows/macOS/Linux 流水线验证。

步骤 1:依赖安装
pip install pytest pytest-httpserver pytest-socket pytest-xdist freezegun allure-pytest

步骤 2:conftest.py 统一管控“网络开关”

import pytest, socket, subprocess, time, json
from pathlib import Path
from pytest_httpserver import HTTPServer
from werkzeug.wrappers import Response

@pytest.fixture(scope="session")
def httpserver_listen_address():
    return ("127.0.0.1", 0)   # 随机端口,避免 CI 冲突

@pytest.fixture
def mock_server(httpserver: HTTPServer):
    httpserver.expect_request("/api/data").respond_with_json({"code": 0})
    yield httpserver
    httpserver.clear()

@pytest.fixture
def disable_socket(monkeypatch):
    """彻底禁止真实外网,强制 Mock"""
    monkeypatch.setattr(socket, "socket", lambda *a, **kw: pytest.fail("真实网络被禁用"))

步骤 3:业务层缓存与重发逻辑(被测代码)

# client.py
import json, time, uuid, requests
from pathlib import Path

CACHE_DIR = Path.home() / ".cache_demo"

class Client:
    def __init__(self, endpoint: str):
        self.endpoint = endpoint
        CACHE_DIR.mkdir(exist_ok=True)

    def save(self, payload: dict):
        """离线时先落盘"""
        file = CACHE_DIR / f"{uuid.uuid4().hex}.json"
        file.write_text(json.dumps(payload, ensure_ascii=False))

    def flush(self):
        """网络恢复后批量重发"""
        for file in CACHE_DIR.glob("*.json"):
            data = json.loads(file.read_text())
            try:
                resp = requests.post(self.endpoint, json=data, timeout=2)
                resp.raise_for_status()
                file.unlink()   # 成功即删除
            except Exception:
                break   # 仍然离线,等待下次

步骤 4:测试用例——断网、落盘、续传、幂等一条龙

import json, time, pytest, uuid
from pathlib import Path
from client import Client
from freezegun import freeze_time

class TestOfflineResend:
    @pytest.fixture(autouse=True)
    def setup(self, mock_server, disable_socket, tmp_path, monkeypatch):
        # 把缓存目录重定向到 tmp_path,实现用例隔离
        monkeypatch.setattr("client.CACHE_DIR", tmp_path / "cache")
        self.client = Client(mock_server.url_for("/api/data"))
        self.cache_dir = Path(self.client.CACHE_dir)

    def test_save_when_502(self, mock_server):
        # 模拟 502 断网
        mock_server.expect_request("/api/data").respond_with_response(Response(status=502))
        payload = {"order_id": "123", "amount": 100}
        self.client.save(payload)   # 业务层发现 502 后落盘
        files = list(self.cache_dir.glob("*.json"))
        assert len(files) == 1
        assert json.loads(files[0].read_text()) == payload

    @freeze_time("2024-05-01 10:00:00")
    def test_resend_success_and_clean(self, mock_server):
        # 预置缓存
        payload = {"order_id": "456"}
        file = self.cache_dir / f"{uuid.uuid4().hex}.json"
        file.write_text(json.dumps(payload))
        # 恢复 200
        mock_server.expect_request("/api/data").respond_with_json({"code": 0})
        self.client.flush()
        assert not file.exists()    # 发送成功应删除

    @pytest.mark.parametrize("status", [502, 503, 429])
    def test_resend_fail_keep_cache(self, mock_server, status):
        file = self.cache_dir / "retry.json"
        file.write_text('{"x":1}')
        mock_server.expect_request("/api/data").respond_with_response(Response(status=status))
        self.client.flush()
        assert file.exists()        # 仍然失败,缓存保留

    def test_idempotent_resend(self, mock_server):
        """幂等:同一订单重发 N 次,服务端只落库一次"""
        order_id = "IDEMPOTENT"
        file = self.cache_dir / f"{order_id}.json"
        file.write_text(json.dumps({"order_id": order_id}))
        mock_server.expect_request("/api/data").respond_with_json({"code": 0})
        # 重试 3 次
        for _ in range(3):
            self.client.flush()
        # 服务端收到 3 次,但数据库应只有 1 条,此处用 Mock 的访问计数代替
        assert len(mock_server.log) == 3   # 网络层确实发了 3 次
        # 业务库幂等由服务端保证,测试端只需确保缓存最终被清空
        assert not file.exists()

步骤 5:CI 集成(GitLab 示例)

test-weak-network:
  stage: test
  image: python:3.11
  script:
    - pip install -r requirements.txt
    - pytest -m "not slow" -n auto --alluredir=allure-results
  artifacts:
    when: always
    paths:
      - allure-results

执行结果:

  • 单条用例 50 ms 内完成;
  • 并发 8 进程,200 条幂等用例 10 s 跑完;
  • allure 报告自动上传到内部 MinIO,测试、开发、产品三方均可查看脱敏日志与缓存快照。

拓展思考

  1. 若客户端是移动端 Flutter/React-Native,可用 pytest + adb 驱动安卓模拟器启用 network-policy 模拟 100% 丢包,再拉取 /data/data/<package>/cache 目录,实现真机离线验证。
  2. 对于金融级业务,重发必须携带 Idempotency-Key 头,pytest 可在 Mock 端用 Redis 记录 key,断言 24 h 内重复 key 直接返回 200 且不落库。
  3. 国内运营商常出现“假连接”——TCP 能握手但无数据,pytest-httpserver 可设置 response_latency=30 s 触发客户端读超时,验证是否触发降级 Toast。
  4. 如果项目用 aiohttp,可结合 pytest-aiohttp 的 loop fixture 与 aioresponses,同样能模拟断网,但需注意 async fixture 作用域与事件循环生命周期。
  5. 合规层面,缓存若含用户手机号,需在测试钩子中自动脱敏(如 pytest_runtest_makereport 里扫描附件,发现 11 位数字即替换为 138****0000),否则测试报告上传即违规。