当 MongoDB 版本低于 4.0 时,如何优雅地跳过多文档事务测试?
解读
国内互联网公司的 Python 后端项目普遍用 MongoDB 做热数据存储,而事务特性是 4.0 之后才支持的。面试时,面试官想确认三件事:
- 你是否能在测试层感知运行环境,而不是让用例裸奔报错;
- 你是否熟悉 Pytest 的“跳过”机制,并且能写出可维护、可复用的代码;
- 你是否能把“版本判断”做成 fixture,让后续所有事务相关用例一键复用,而不是每个测试函数里写一遍 if。
一句话:不是简单加个 @pytest.mark.skip,而是“判断—标记—复用”全链路优雅。
知识点
- Pytest 的跳过 API:
pytest.skip(reason)只能在测试执行体内调用;pytest.mark.skipif(condition, reason)在收集阶段就生效,更符合“版本不足直接跳过”的语义。 - fixture 可以返回任意对象,也可以只做副作用(如跳过测试),并且支持
scope复用。 pymongo.MongoClient().server_info()["versionArray"]能拿到三元组(major, minor, patch),比字符串比较更可靠。- 自定义 marker(
pytest.ini里注册)可以把“事务测试”语义化,方便在 CI 阶段加过滤标签,例如pytest -m "not mongo_txn"。 - 国内 CI 常用镜像源,MongoDB 版本可能滞后,必须保证本地、测试、预发、生产四个环境都能自动识别,而不是写死 IP。
答案
- 在顶层 conftest.py 里写一个自动触发的 fixture:
# conftest.py
import pytest
from pymongo import MongoClient
def pytest_configure(config):
config.addinivalue_line(
"markers", "mongo_txn: 多文档事务测试,仅在 MongoDB>=4.0 时运行"
)
@pytest.fixture(scope="session", autouse=True)
def check_mongo_version(request):
"""会话级 fixture,发现版本低于 4.0 就给所有 mongo_txn 用例打 skipif"""
client = MongoClient(host=request.config.getoption("--mongo-host") or "localhost")
version_array = client.server_info()["versionArray"] # 如 [3, 6, 0, 0]
client.close()
if version_array < [4, 0, 0]:
# 动态添加 skipif 标记
for item in request.node.items:
if item.get_closest_marker("mongo_txn"):
item.add_marker(
pytest.mark.skipif(
True, reason=f"MongoDB {'.'.join(map(str, version_array))} 不支持多文档事务"
)
)
- 在测试模块里用声明式 marker:
# test_order.py
import pytest
from pymongo import MongoClient
@pytest.mark.mongo_txn
def test_create_order_with_transaction():
client = MongoClient()
with client.start_session() as s:
with s.start_transaction():
client.db.order.insert_one({"_id": 1}, session=s)
client.db.stock.update_one({"sku": "A"}, {"$inc": {"qty": -1}}, session=s)
- 运行:
本地 MongoDB 3.6 时,收集阶段即跳过,控制台输出:
test_order.py::test_create_order_with_transaction SKIPPED (MongoDB 3.6.0 不支持多文档事务)
- 如果 CI 里临时想强制跑,也可以命令行覆盖:
pytest test_order.py -m mongo_txn --mongo-host=4.4-mongo-service
拓展思考
- 如果项目同时支持 MySQL、MongoDB 两套存储,可以用复合 marker
@pytest.mark.mongo_txn+@pytest.mark.mysql_txn,在 CI 矩阵里按存储类型分 Job,避免“全量跑”浪费时间。 - 版本判断逻辑可以下沉到单独模块
mongo_compat.py,提供is_transaction_supported(),既给测试用,也给业务代码做运行时降级,实现“测试—生产”同一份逻辑。 - 当 MongoDB 以副本集形式运行在 Docker Compose 时,启动顺序可能慢于 Pytest 收集阶段,可以在 fixture 里加
tenacity.retry等待server_info()可连通,再判断版本,防止“误跳”。 - 国内部分金融场景用 MongoDB 4.0 但关闭了
featureCompatibilityVersion,需要额外检查client.admin.command("getParameter", 1, featureCompatibilityVersion=1),把兼容性也纳入跳过条件,避免“版本号够但功能关”的坑。