如果 JUnit 报告中的测试失败,如何使 Gitlab 管道失败



我的项目(移动应用程序)有Gitlab管道,带有基于TestNG和maven运行UI测试(Appium)的阶段。 我设置在管道结果中将 JUnit 报告显示为工件 工件:报告:JUNIT: - 万无一失的报告/测试-*.xml 并且它正确显示在管道页面上。 但是,即使报告中有失败的测试,作业仍标记为成功,并且管道为绿色。 如果报告包含失败的测试,管道是否可能失败?

似乎 Gitlab 只有在测试进程以非零代码退出时才会使管道失败,并且它不会解析 JUnit xml 文件来确定管道的成功(https://forum.gitlab.com/t/how-to-fail-job-and-pipeline-if-there-are-failed-tests-in-junit-report/37039/3)

以下是我为解决此问题所做的工作:

  1. 运行测试并将结果收集到文件中
# 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 
  1. 稍后测试此结果文件是否存在
# if the failures.log file exists, 
# the command below will return false and will fail the pipeline
test ! -f failures.log

刚才有同样的问题!

看来 GitLab 并没有因为测试失败而使管道失败。GitLab 似乎是一个奇怪的选择,但它就是这样。

我是这样解决的(.gitlab-ci文件被压缩为仅重要部分):

lint-job:
stage: build
script:
# Your build steps that create the JUnit XML
- ./do_build.sh
# Horrible way of parsing XML
- test -f lint.xml && grep -L "<failure" lint.xml

似乎没有任何"祝福"的工具可用于解析JUnit XML文件。同时使用testgrep绝对是一种黑客攻击,但希望它不会中断。

GitLab 论坛参考,确认测试 XML 文件中的失败/错误/警告不会使管道失败。

在我看来,解析某个正则表达式的测试报告可能不是最佳解决方案。这是我解决它的方法 ->我正在使用TestNG lib来运行我的Selenium UI测试。TestNG生成多个测试结果xml文件,如testng-passed.xml testng-failed.xml testng-skipped.xml等。 仅当有任何测试失败时,才会创建失败的 xml,现在我们可以使用此条件(存在 testng-failed.xml)来通过或失败管道。

------------gitlab-ci.yml代码片段:----------

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部分中工作。

最新更新