我已经在jenkins脚本部分定义了If-Else。但它根本没有被执行。你知道怎么了吗?
script {
unit_test_result = sh (
script: ''' #!/bin/bash
mvn clean test | grep 'Tests run:' | grep -v 'Time elapsed'
if [[ $? == 1 ]];
then echo "No Unit tests to run!";
fi
''',
returnStdout: true
).trim()
}
但是if部分根本没有运行…
[Pipeline] script
[Pipeline]
[Pipeline]
+ grep Tests run:
+ mvn clean test
+ grep -v Time elapsed
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
Failed in branch Unit Tests
grep -v 'Time elapsed'
仅在每个输入行不包含Time elapsed
时以状态码1
退出,但这永远不会发生,因为mvn
似乎总是打印摘要。
根据这个网站,如果有测试,mvn clean test
的输出如下所示
-------------------------------------------------------
T E S T S
-------------------------------------------------------
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.547 sec
[...]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.018 sec
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
,根据这个问题,如果没有测试
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
在这两种情况下,grep 'Tests run:'
将至少打印最后一行的摘要。摘要中从不包含Time elapsed
。因此grep -v 'Time elapsed'
总是以状态码0
退出。
试试下面的脚本:
#!/bin/bash
if ! mvn clean test | grep -q '^Tests run: [^0]'; then
echo "No Unit tests to run!";
fi
对于这个问题中显示的输出,我们可以使用if mvn clean test | grep -Fxq 'There are no tests to run.'
代替。但我发现其他示例输出mvn
没有打印字符串;有时甚至没有总结。第一个脚本也处理所有这些情况。