【问题标题】:How to fail Gitlab pipeline if there are failed test in JUnit report如果 JUnit 报告中测试失败,如何使 Gitlab 管道失败
【发布时间】:2020-04-30 13:40:11
【问题描述】:
我的项目(移动应用程序)有 Gitlab 管道,带有用于运行基于 TestNG 和 maven 的 UI 测试 (Appium) 的阶段。带有万能插件。
我设置在管道结果中将 JUnit 报告显示为工件
工件:报告:junit:-surefire-reports/TEST-*.xml
并正确显示在管道页面上。
但是即使报告中有失败的测试,作业仍然标记为成功,并且管道是绿色的。
如果报告包含失败的测试,管道是否可能失败?
【问题讨论】:
标签:
junit
gitlab
maven-surefire-plugin
【解决方案1】:
如果测试过程以非零代码退出,Gitlab 似乎只会使管道失败,并且它不会解析 JUnit xml 文件以确定管道是否成功 (https://forum.gitlab.com/t/how-to-fail-job-and-pipeline-if-there-are-failed-tests-in-junit-report/37039/3)
这是我为解决这个问题所做的:
- 运行测试并将结果收集到一个文件中
# the echo command will only be run when the test process exits with a non zero code,
# and the entire step will still return 0 as the exit code
run_your_test_for_example_mvn_verify || echo "there is Maven test failure" >> failures.log
run_your_test_for_example_poetry_pytest || echo "there is pytest failure" >> failures.log
- 稍后测试此结果文件是否存在
# if the failures.log file exists,
# the command below will return false and will fail the pipeline
test ! -f failures.log
【解决方案3】:
在我看来,为某个正则表达式解析测试报告可能不是最佳解决方案。这是我解决它的方法-> 我正在使用 TestNG lib 运行我的 selenium UI 测试。 TestNG 生成多个测试结果 xml 文件,如 testng-passed.xml、testng-failed.xml、testng-skipped.xml 等。
只有在任何测试失败时才会创建失败的 xml,现在我们可以使用这个条件(存在 testng-failed.xml)来通过或失败管道。
------------ gitlab-ci.yml 代码 sn-p: ----------
variables:
TESTNG_FAILED_XML: jar/test-output/testng-failed.xml
script:
- #Your test-run command
- |
if [[ -f "$TESTNG_FAILED_XML" ]]; then
echo "Test failures observed as TestNG-Failed file exists."
exit 1
else
echo "All tests passed Successfully."
fi
注意:以上内容应该在您的脚本部分中,它不会在 after_script 部分中起作用。