当门禁未通过时,如何让 Pytest 以非零码退出并附带 SonarQube 链接?

解读

国内大厂普遍把“门禁”做成一条 CI 流水线:单元测试 → 覆盖率扫描 → SonarQube 质量阈 → 合并请求。
面试官想知道你能否把“测试失败”与“质量阈失败”统一成一次 Pytest 调用,并给出可追踪的退出码与日志,方便 Jenkins/GitLab CI 精准卡点。
核心难点有三点:

  1. Pytest 正常失败只会返回 1,无法区分“测试失败”还是“质量阈失败”。
  2. SonarQube 扫描是异步任务,Pytest 运行结束时质量报告可能还没生成。
  3. 链接必须随日志一次性透出,避免研发二次翻找。

知识点

  • pytest.exit(code) 与 sys.exit(code) 的差异:pytest.exit 会立即触发内部 shutdown,保证所有 finalizer 执行完再退出。
  • pytest-custom_exit_code 插件:可把“测试失败”映射成任意退出码,但无法感知外部系统状态。
  • subprocess + polling:在 Pytest 的 pytest_sessionfinish 钩子中同步等待 SonarQube 的 ceTask 状态,实现“测试结束但门禁未过”场景下的阻塞。
  • 国内私有 SonarQube 的 token 鉴权方式:/api/ce/task?id=xxx&additionalField=scannerContext,需带 Authorization: Bearer xxxx。
  • CI 环境变量:MR_ID、GIT_COMMIT、SONAR_HOST,用于拼出可直接点击的链接。
  • pytest.Stash 机制(7.0+):可在钩子间线程安全地传递自定义状态,替代全局变量。

答案

  1. 写一个本地插件 gate.py,注册 pytest_sessionfinish 钩子:
    a. 先判断当前 session 的 testfailed + testerror 数量,如果 >0,直接 pytest.exit(101)。
    b. 若用例全部通过,调用 subprocess 触发 sonar-scanner,拿到 ceTaskId。
    c. 轮询 /api/ce/task 接口,直到 status=SUCCESS 或 FAILED;若 qualityGate 状态为 ERROR,则 stash["gate_failed"]=True。
    d. 在 pytest_terminal_summary 中打印:
    print(f"::error file=qualitygate::门禁未通过,详见 {SONAR_HOST}/dashboard?id={PROJECT_KEY}&pullRequest={MR_ID}")
    e. 再次 pytest.exit(102),确保 CI 阶段失败。

  2. 在 pyproject.toml 中配置:
    [tool.pytest.ini_options]
    addopts = "-p gate --tb=short"

  3. Jenkinsfile 片段:
    stage('测试+门禁') {
    steps {
    sh 'python -m pytest'
    }
    }
    post {
    failure {
    // 退出码 101 代表用例失败,102 代表质量阈失败
    script {
    if (currentBuild.result == 'FAILURE') {
    def log = readFile 'pytest.log'
    if (log.contains('门禁未通过')) {
    pullRequest.comment("❌ SonarQube 质量阈未通过,请查看报告后修复")
    }
    }
    }
    }
    }

这样,无论用例失败还是质量阈失败,Pytest 都会给出非零退出码,并在控制台高亮 SonarQube 链接,CI 精准卡点,研发一键直达问题。

拓展思考

  1. 如果 SonarQube 扫描耗时过长,可把轮询逻辑拆成独立 stage,用 pytest-stash 把“用例通过”标志写到文件,第二个 stage 读到标志后再做质量阈判断,实现测试与扫描并行,缩短流水线时间。
  2. 对于多模块 monorepo,可在 gate.py 里根据 pytest.Item.nodeid 前缀动态拼接 PROJECT_KEY,实现“一个仓库多个 Sonar 项目”的精细化门禁。
  3. 结合 pytest-xdist,让 gate 钩子只在 master 节点执行,避免重复触发扫描;退出码用 stash 广播到 worker,保证分布式场景下也能正确返回 102。