You need to enable JavaScript to run this app. Docker多阶段构建场景下Jenkins测试失败时如何获取Test Reports
优惠活动
大模型
产品
解决方案
定价
更多

Docker多阶段构建场景下Jenkins测试失败时如何获取Test Reports

解决方案

核心问题本质是Dockerfile的RUN指令只要返回非0状态码就会直接终止整个构建流程,pytest测试用例执行失败时会返回非0状态码,因此构建提前终止,测试镜像还未生成完成,后续自然无法提取测试报告。

1. 调整Dockerfile测试执行逻辑

修改测试步骤的命令,捕获pytest的退出状态码存入文件,保证RUN指令最终返回0,不会中断Docker构建,测试报告也能正常生成:

# 替换原有 RUN pytest --junit=test-reports/junit.xml
RUN set -o pipefail && pytest --junit=test-reports/junit.xml; echo $? > /app/test_exit_code

2. 调整Jenkinsfile执行逻辑

先把测试报告和退出码文件复制到Jenkins工作区,优先执行junit报告解析,再根据之前存储的退出码判断是否标记构建失败:

def app = docker.build("app:${BUILD_NUMBER}", "--target test .")
app.inside {
  sh "cp -r /app/test-reports test-reports"
  sh "cp /app/test_exit_code test_exit_code"
}
// 优先解析测试报告,无论测试是否通过都能展示结果
junit 'test-reports/junit.xml'
// 读取测试退出码,非0则主动标记构建失败
sh "exit \$(cat test_exit_code)"

可选替代方案

如果不想修改Dockerfile逻辑,可以直接把测试执行环节移到Jenkins的容器运行阶段:

// Dockerfile中删除pytest相关的RUN指令
def app = docker.build("app:${BUILD_NUMBER}", "--target test .")
app.inside {
  // 执行测试同时存储退出码
  sh "pytest --junit=test-reports/junit.xml; echo \$? > /app/test_exit_code"
  sh "cp -r /app/test-reports test-reports"
  sh "cp /app/test_exit_code test_exit_code"
}
junit 'test-reports/junit.xml'
sh "exit \$(cat test_exit_code)"

内容的提问来源于stack exchange,提问作者timbmg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 10:06:04