如何将 pytest-cov 的 XML 报告上传至 SonarQube 并显示单元测试数?
解读
国内绝大多数公司把 SonarQube 作为“代码质量门禁”,面试时问“单测数怎么在 SonarQube 里看到”并不是考你会不会敲命令,而是考你对“测试→度量→门禁”整条流水线的闭环理解。
很多候选人只答“加 --cov-report=xml 就行”,结果扫描后 SonarQube 页面“单元测试数”永远是 0,原因有三:
- pytest-cov 只生成覆盖率 XML,不含“测试数量”信息;
- SonarQube 要的是“测试执行报告”,不是“覆盖率报告”;
- 没有通过 sonar-project.properties 把两份报告同时喂给 SonarQube。
面试官想听的是:你怎么让 SonarQube 既看到覆盖率,又看到“跑了多少条用例、成功多少、失败多少”。
知识点
- pytest-cov 原生只出 coverage.xml,属于“覆盖率”维度,不含 test count。
- SonarQube 解析测试数的官方格式是 Generic Test Execution,即 generic.xml,格式由 sonar-generic-test-schema 定义。
- pytest-sonarqube-generic 插件(或自建钩子)可把 pytest 的 result.log 转成 generic.xml。
- sonar-project.properties 里
sonar.python.coverage.reportPaths=coverage.xml
sonar.testExecutionReportPaths=generic.xml
二者缺一不可。 - 社区版 SonarQube 对 Python 测试数只“展示”,不“门禁”;开发版才能配指标“单测数环比减少即失败”。
- 在 GitLab-CI / Jenkins 流水线里,必须先
pytest --cov=src --cov-report=xml --junitxml=junit.xml,再二次转换 junit.xml → generic.xml,最后执行sonar-scanner。 - 如果项目用 src-layout,必须显式声明
sonar.tests=tests,否则 SonarQube 会误判目录,导致解析为空。 - 国内私有部署的 SonarQube 往往装在子路径,需加
sonar.host.url=https://sonar.xxx.com/sonar,并配置 Project Key 与 Git 分支一致,否则 MR 装饰器不生效。
答案
步骤一:安装依赖
pip install pytest pytest-cov pytest-sonarqube-generic(或 pytest-junitxml 亦可)
步骤二:运行测试并产出双报告
pytest tests/ \
--cov=src \
--cov-report=xml:coverage.xml \
--junitxml=junit.xml
步骤三:把 junit.xml 转成 SonarQube 能识别的 generic.xml
python -m pytest_sonarqube_generic.junit_to_generic junit.xml generic.xml
(若用 pytest-sonarqube-generic 0.3+,可直接加 --sonarqube-generic=generic.xml 一步生成)
步骤四:在项目根目录新建 sonar-project.properties
sonar.projectKey=com.xxx:project
sonar.sources=src
sonar.tests=tests
sonar.python.coverage.reportPaths=coverage.xml
sonar.testExecutionReportPaths=generic.xml
步骤五:执行扫描
sonar-scanner -Dsonar.host.url=https://sonar.xxx.com -Dsonar.login=${SONAR_TOKEN}
步骤六:在 SonarQube 项目首页→“Measures”→“Coverage” 可见覆盖率;再切到“Tests”标签即可看到“Tests=xxx,Failures=xx,Skipped=xx”。
至此,单元测试数量成功上报。
拓展思考
- 多模块 monorepo 场景:每个子目录都有 tests,需要写通配符
sonar.testExecutionReportPaths=**/generic.xml,并在顶层聚合。 - 并行执行:pytest-xdist 会把 junit.xml 拆成多份,需用 junitparser 合并后再转 generic.xml,否则 SonarQube 只会读第一份。
- 增量扫描:在 PR 阶段只想看“新增代码的单测数”,可结合
sonar.pullrequest.key与sonar.python.coverage.newCode, 并在 CI 里加--cov-branch生成分支覆盖,再写自定义 Quality Gate:新增代码行覆盖≥80% 且新增单测数>0。 - 失败用例阻断:GitLab-CI 里把
allow_failure: false放在 pytest job,但 SonarQube 侧只“展示”失败,不会自动把 MR 标红;需要再调 Web API 把“test failures > 0”作为外部检查回写给 GitLab。 - 替代方案:若公司禁用 sonar-scanner 镜像,可在 Python 侧用官方包
sonar-python-api直接 POST generic.xml,实现“零 sonar-scanner”上传,满足内网安全扫描要求。