如何用 pytest 运行 bandit 并将结果转为 JUnit XML?

解读

面试官抛出这道题,并不是单纯问“一条命令怎么敲”,而是想验证三件事:

  1. 你是否真的把 pytest 当成“测试执行引擎”来用,而不是只会写 assert;
  2. 你是否理解国内企业对安全门禁的硬性要求——GitLab CI、禅道、Jenkins 都要消费 JUnit XML;
  3. 你是否能把“非功能测试(安全扫描)”无缝接入既有 pytest 生态,而不是让运维再写一套独立流程。

因此,回答时必须给出“pytest 驱动 → 扫描 → 结果标准化 → 产物归档”的完整闭环,并体现对国内 CI 场景(如 Jenkins 中文插件、禅道解析器)的兼容性考虑。

知识点

  1. bandit 原生只输出 txt、json、csv、xml(非标准 JUnit 格式)。
  2. pytest 通过自定义 session-scoped fixture + subprocess 或 bandit Python API 完成扫描,再把结果转 JUnit XML。
  3. pytest 自带 junitxml 选项,但只能转 pytest 自身用例;要让 bandit 缺陷也变成“用例”,需要动态构造 TestReport 对象。
  4. 国内 Jenkins 对 JUnit XML 的 classname 与 name 字段有隐式约定:必须满足 包名.类名#方法名 形式,否则趋势图会乱码。
  5. 企业合规要求:blocker 级漏洞必须让 CI 失败,因此要在 pytest 退出码上做文章(--maxfail 或 pytest.exit(msg, returncode=2))。

答案

步骤如下,全部在源码树内完成,不依赖额外脚本,方便 GitLab-CI/Jenkins 直接调用。

  1. 安装依赖(国内源加速)
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pytest bandit pytest-junit-xml
  1. 在项目根目录新建 tests/test_bandit.py,内容如下:
import subprocess
import json
import os
import pytest
from pathlib import Path

# 让 Jenkins 能识别的高危等级映射
LEVEL_MAP = {"HIGH": "failure", "MEDIUM": "error", "LOW": "skipped"}

def run_bandit():
    """调用 bandit 并返回 json 报告"""
    cmd = [
        "bandit", "-r", str(Path(__file__).resolve().parent.parent / "src"),
        "-f", "json", "-q"
    ]
    proc = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8")
    if proc.returncode not in (0, 1):   # 1 表示发现漏洞,仍可继续
        pytest.fail(f"bandit 异常退出: {proc.stderr}")
    return json.loads(proc.stdout) if proc.stdout else {}

def id_func(item):
    """生成 Jenkins 友好的用例名"""
    return f"bandit.{item['filename'].replace('/', '.')}.{item['line_number']}"

def pytest_generate_tests(metafunc):
    """动态参数化:每个漏洞变成一条测试用例"""
    if "bandit_item" in metafunc.fixturenames:
        results = run_bandit()
        items = results.get("results", [])
        metafunc.parametrize(
            "bandit_item",
            items,
            ids=[id_func(it) for it in items]
        )

def test_bandit_vulnerability(bandit_item):
    """用例:只要出现 HIGH 级别就让 CI 失败"""
    severity = bandit_item["issue_severity"]
    msg = f"{bandit_item['issue_text']} @ {bandit_item['filename']}:{bandit_item['line_number']}"
    if severity == "HIGH":
        pytest.fail(f"[BLOCK] {msg}")
    elif severity == "MEDIUM":
        pytest.fail(f"[ERROR] {msg}")
    else:
        pytest.skip(f"[LOW] {msg}")
  1. 运行并生成国内 Jenkins 可识别的 JUnit XML
pytest tests/test_bandit.py --junit-xml=bandit-junit.xml -o junit_family=xunit1 -v

说明:

  • junit_family=xunit1 保证 XML 格式兼容老版 Jenkins 中文插件;
  • 每条漏洞作为 <testcase> 输出,HIGH/MEDIUM 对应 <failure>/<error>,LOW 对应 <skipped>;
  • pytest 退出码:只要出现 HIGH 漏洞,exit code=1,CI 阶段自动失败,满足国内安全红线要求。
  1. 在 Jenkinsfile(或 .gitlab-ci.yml)中归档
junit 'bandit-junit.xml'
archiveArtifacts artifacts: 'bandit-junit.xml', fingerprint: true

禅道用户可额外调用 zentao.py 脚本把 XML 解析后推送到测试单,实现缺陷闭环。

拓展思考

  1. 如果仓库很大,bandit 全量扫描耗时 3~5 分钟,可把 run_bandit() 改成增量扫描:通过 git diff origin/master --name-only --diff-filter=d 拿到增量 .py 文件,再传给 bandit -f json 参数,既满足门禁又节省 CI 时间。
  2. 对于多模块项目,可在 conftest.py 里注册 pytest_configure 钩子,把 bandit 结果写入 session 级 stash,再统一输出到一份聚合 JUnit XML,避免 Jenkins 侧出现“几千个用例”导致页面卡顿。
  3. 国内部分金融客户要求“漏洞责任人归属”,可在 test_bandit_vulnerability 里通过 git blame 拿到行级作者邮箱,再写入 <testcase> 的 file 属性,方便后续自动创建 Jira 缺陷并 @ 责任人。
  4. 如果团队已接入 Allure 报告,可放弃 JUnit XML,改用 pytest-allure-adaptor 把 bandit 缺陷作为 severity=critical 的 Step 展示,领导层更直观。
  5. 未来 bandit 官方可能直接支持 JUnit 格式,但企业内网 PyPI 源同步滞后,因此“pytest 驱动 + 动态用例”方案依旧是最稳妥、最可维护的落地路径。