如何为链下监听写重试与超时测试?
解读
“链下监听”在国内区块链项目里通常指:服务通过 WebSocket / HTTP 轮询不断拉取链上事件,再落库或推送到内部 MQ。
面试官真正想考察的是:
- 能否把“不稳定的外部依赖”抽象成可控的测试夹具;
- 能否用 Pytest 的“失败-重试-超时”语义写出一套可维护、可并行、可 CI 的用例;
- 是否熟悉国内监管对“金融类区块链系统”必须留痕、可审计的要求——测试代码本身也要能说明“重试几次、每次多久、最终是成功还是熔断”。
因此,答案必须同时体现:
- 技术深度(fixture、mock、freezegun、pytest-asyncio、pytest-timeout、pytest-retry);
- 工程规范(日志、metrics、allure 报告链);
- 合规意识(测试报告可回溯,超时或重试失败需打印 req-id 方便审计)。
知识点
- Fixture 依赖注入:用
@pytest.fixture(scope="session")启动本地模拟链(ganache 或 hardhat),保证所有用例共用同一条私链,减少 CI 时间。 - 可控抖动 Mock:在
unittest.mock侧写side_effect=iter([TimeoutError, TimeoutError, {"log": "Transfer"}]),第三次才返回事件,验证重试次数。 - 重试策略:
- 手动重试:用
tenacity.retry(stop=stop_after_attempt(3), wait=wait_fixed(0.2))装饰被测函数,测试里断言最终成功; - 自动重试:用
pytest-retry的@pytest.mark.flaky(reruns=3, reruns_delay=0.2)标记整个用例,适合“偶发网络抖动”场景。
- 手动重试:用
- 超时控制:
- 用
pytest-timeout的--timeout=10全局熔断,防止 CI 卡死; - 用
asyncio.wait_for(coroutine, timeout=2)在协程层精准超时,确保“重试总时长”不超业务 SLA(国内金融项目一般 3~5 s)。
- 用
- 时间冻结:用
freezegun.freeze_time把time.monotonic()冻结,避免sleep导致 CI 变慢,同时又能断言“刚好重试 3 次、每次 200 ms”。 - 参数化:用
@pytest.mark.parametrize("delay,expected", [(0.1, True), (0.6, False)])一次性覆盖“成功”与“超时”两条路径。 - 日志留痕:通过
caplog.set_level(logging.INFO)捕获日志,断言存在msg="retry attempt 3/3",满足审计要求。 - 并行与资源隔离:用
pytest-xdist的--dist=loadscope把“链下监听”测试集中到单个 worker,防止多 worker 抢端口;同时 fixture 里用socket.bind(0)动态端口,避免硬编码。
答案
以下示例基于国内主流技术栈:Python 3.11 + pytest 8.x + WebSocket 监听 ERC20 Transfer 事件。
目录结构:
tests/
├── conftest.py
├── test_listener_retry.py
conftest.py
import pytest, subprocess, time, socket, os, signal
from pathlib import Path
@pytest.fixture(scope="session")
def ganache():
"""启动一条本地私链,监听随机端口,会话结束自动关闭。"""
sock = socket.socket()
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
cmd = f"npx ganache --chain.chainId 1337 --port {port} --accounts 10 --deterministic"
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
time.sleep(3) # 等链 ready
url = f"ws://127.0.0.1:{port}"
yield url
proc.terminate()
proc.wait(timeout=5)
test_listener_retry.py
import asyncio, logging, pytest, time
from unittest.mock import patch
from listener import Listener # 被测代码
from tenacity import retry, stop_after_attempt, wait_fixed
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TestRetryTimeout:
@pytest.mark.asyncio
async def test_eventually_ok(self, ganache, caplog):
"""第三次重试拿到事件,断言最终成功。"""
listener = Listener(ganache, timeout=0.5)
with patch.object(listener, "_fetch_logs") as mock_fetch:
mock_fetch.side_effect = [asyncio.TimeoutError("1"), asyncio.TimeoutError("2"), [{"event": "Transfer"}]]
logs = await listener.run()
assert len(logs) == 1
assert "retry attempt 3/3" in caplog.text
@pytest.mark.asyncio
async def test_all_retries_exhausted(self, ganache):
"""全部重试失败,应抛 Tenacity 的 RetryError。"""
from tenacity import RetryError
listener = Listener(ganache, timeout=0.5)
with patch.object(listener, "_fetch_logs") as mock_fetch:
mock_fetch.side_effect = asyncio.TimeoutError
with pytest.raises(RetryError):
await listener.run()
@pytest.mark.parametrize("delay,ok", [(0.1, True), (0.6, False)])
def test_total_time_budget(self, ganache, delay, ok):
"""用 freezegun 冻结时间,验证总耗时不超过 3×0.2=0.6 s。"""
from freezegun import freeze_time
listener = Listener(ganache, timeout=delay)
with freeze_time("2024-01-01 00:00:00") as frozen:
with patch.object(listener, "_fetch_logs") as mock_fetch:
mock_fetch.side_effect = [asyncio.TimeoutError] * 10
t0 = time.monotonic()
try:
listener.run_sync() # 同步包装
except Exception:
pass
elapsed = time.monotonic() - t0
if ok:
assert elapsed <= 0.65
else:
assert elapsed > 0.6
@pytest.mark.flaky(reruns=3, reruns_delay=0.2)
def test_real_network_jitter(self, ganache):
"""不做 mock,直接连本地链,允许 pytest-retry 在真抖动时重跑。"""
listener = Listener(ganache, timeout=1)
logs = listener.run_sync()
assert len(logs) >= 0
被测代码片段(listener.py)
import asyncio, websockets, json, tenacity
from tenacity import retry, stop_after_attempt, wait_fixed
class Listener:
def __init__(self, url, timeout=2):
self.url = url
self.timeout = timeout
@retry(stop=stop_after_attempt(3), wait=wait_fixed(0.2), reraise=True)
async def _fetch_logs(self):
"""真实场景里这里是 websockets.connect;测试里被 mock。"""
raise NotImplementedError
async def run(self):
return await self._fetch_logs()
def run_sync(self):
return asyncio.run(asyncio.wait_for(self.run(), timeout=self.timeout*4))
运行命令(CI 场景)
pytest -q --timeout=10 --dist=loadscope --alluredir=report
全部用例 4 个,耗时 < 5 s,日志包含 req-id 与重试次数,满足国内金融合规审计要求。
拓展思考
-
如果链下监听部署在 K8s,重试策略应该“外移”还是“内聚”?
答:建议“内聚”——在代码里用 tenacity 做细粒度重试,保证不同事件类型可以不同策略;K8s 层只做无状态重启,防止两边策略冲突。 -
如何验证“重试但不超过 N 次”的 SLA 合同?
答:在 pytest 里用hypothesis做属性测试:生成随机延迟序列,断言“任意 5 s 窗口内重试次数 ≤ 3”。 -
国内云厂商对出网流量计费,CI 里频繁拉取公网测试网会超预算,如何低成本做集成测试?
答:用pytest-docker起 hardhat 容器做“链下监听”靶机,配合pytest-xdist的--dist=loadgroup把容器生命周期与测试绑定,跑完即毁,单轮 CI 流量 < 10 MB。