如何在 pytest 收集阶段自动扫描依赖并标记高危测试?

解读

国内一线互联网公司的测试工程化面试,常把“测试发现—分析—标记—隔离”作为一条完整链路来考察。
题目聚焦“收集阶段(collection)”而非“执行阶段”,意味着要利用 pytest 的钩子(hook)在内存里完成 AST/依赖扫描,并给 Item 打标签,后续可直接用 -m highrisk 或 --highrisk-only 快速隔离执行。
面试官想看到三点:

  1. 熟悉 pytest 的 collection 体系(Session → Package → Module → Item)。
  2. 能在不改动业务代码的前提下,用官方扩展点完成依赖扫描。
  3. 标记高危的规则可配置、可二次开发,且对并行收集(pytest-xdist)安全。

知识点

  1. pytest_collection_modifyitems(session, config, items):收集完成后、执行前的最后拦截点。
  2. ast + importlib 动态解析:将 Module.obj 的源码转成 AST,提取 import、call、decorator、fixture 使用链。
  3. 依赖风险规则:
    • 直接 import 了 os.system、subprocess、requests、celery_task 等“副作用”模块;
    • 使用了 scope=session 且 autouse=True 的 fixture;
    • 函数体出现 @pytest.mark.integration 或访问了数据库 fixture;
    • 代码调用链深度 >N 且包含外部 IO。
  4. 标记机制:item.add_marker(pytest.mark.highrisk(reason=…)),并同步写入 item.user_properties 供报表使用。
  5. 配置化:在 pytest.ini 新增 highrisk_patterns = os.system,subprocess,celery 支持 OPS 动态调整。
  6. 并发安全:解析结果缓存在 config.cache,key 带 nodeid 与 mtime,防止 xdist 重复 IO。

答案

  1. 实现插件 risk_marker.py
import ast, importlib, os, pytest, re
from pathlib import Path

def pytest_configure(config):
    # 读取用户配置
    patterns = config.getini("highrisk_patterns") or ""
    config._risk_patterns = [p.strip() for p in patterns.split(",") if p.strip()]

def pytest_collection_modifyitems(session, config, items):
    cache = config.cache
    patterns = config._risk_patterns
    for item in items:
        fspath, nodeid = item.fspath, item.nodeid
        # 用缓存避免重复解析
        cache_key = f"risk/v1/{nodeid}/{fspath.mtime()}"
        cached = cache.get(cache_key, None)
        if cached is None:
            cached = _scan_item(item, patterns)
            cache.set(cache_key, cached)
        if cached["highrisk"]:
            item.add_marker(pytest.mark.highrisk(reason=cached["reason"]))
            item.user_properties.append(("highrisk", True))

def _scan_item(item, patterns):
    """返回 dict: highrisk:bool, reason:str"""
    reason = []
    # 1. 扫描源码 import & call
    try:
        source = item.fspath.read_text(encoding="utf-8")
        tree = ast.parse(source)
    except Exception:
        return {"highrisk": False, "reason": ""}
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                if any(re.fullmatch(p, alias.name) for p in patterns):
                    reason.append(f"import {alias.name}")
        elif isinstance(node, ast.ImportFrom):
            if node.module and any(re.fullmatch(p, node.module) for p in patterns):
                reason.append(f"from {node.module} import")
    # 2. 扫描 fixture 使用链
    if hasattr(item, "fixturenames"):
        for fname in item.fixturenames:
            fix = item._fixtureinfo.name2fixturedefs.get(fname)
            if fix and any(f.autouse and f.scope == "session" for f in fix):
                reason.append(f"session-autouse fixture:{fname}")
    # 3. 扫描 marker
    if item.get_closest_marker("integration"):
        reason.append("marked integration")
    return {"highrisk": bool(reason), "reason": "|".join(reason)[:100]}
  1. 注册插件
    在 conftest.py 里 pytest_plugins = ["risk_marker"],或直接 pip install -e . 打包成 entry_points={"pytest11": ["risk_marker=risk_marker"]}。

  2. 配置 pytest.ini

[pytest]
highrisk_patterns = os\.system,subprocess,requests,celery
markers =
    highrisk: 可能引入外部依赖或副作用,建议单独执行
  1. 使用
pytest -m highrisk -v          # 只跑高危
pytest --highrisk-first -n4   # 先跑高危并并发
  1. 效果
    收集阶段控制台输出
collected 120 items / 8 deselected / 112 selected  
highrisk marker auto-applied: 12 items

拓展思考

  1. 精准度提升:结合静态分析工具 pycg 或 libcst 生成调用图,判断测试是否间接依赖网络/DB;对数据驱动测试,可进一步扫描 @pytest.mark.parametrize 里是否出现外部文件路径。
  2. 动态运行时补充:在 pytest_runtest_setup(item) 阶段再次检查环境变量 CI_HIGHRISK_MODE,若置位则把高危测试自动转投到 Docker 隔离容器,实现“静态度分析 + 运行时隔离”双保险。
  3. 平台化落地:在阿里、腾讯等内部 DevOps 平台,把高危标记结果回写至 TestHub,触发额外的 Review 流程;并与变更集(diff)联动,仅当高危测试关联的源码文件被修改才强制回归,节省 30%+ 的流水线时间。