How to distinguish failed tests from syntax error in jenkins pipeline - jenkins

I have this Jenkinsfile:
node{
stage ('Checkout')
{
checkout scm
}
stage ('Build')
{
try {
sh '''
mvn clean -B org.jacoco:jacoco-maven-plugin:prepare-agent install
'''
} catch (err) {
// do nothing
currentBuild.result = 'FAILED'
} finally {
//step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
step([$class: 'XUnitBuilder', testTimeMargin: '3000', thresholdMode: 1,
thresholds: [
[$class: 'FailedThreshold', unstableThreshold: '2'],
[$class: 'SkippedThreshold', unstableThreshold: '']],
tools: [
[$class: 'JUnitType', deleteOutputFiles: false, failIfNotNew: false, pattern: '**/target/surefire-reports/TEST-*.xml', skipNoTestFiles: true, stopProcessingIfError: false]]
])
}
}
}
I want to mark the build as UNSTABLE when : some tests are failed using threshold of xUnit plugin, and I want to mark it FAILED if there is any error in the code like syntax error.
The problem here is that catch is executed in both situations: code error and test failure. How can I configure the Jenkinsfile to make the difference ?
After running a build that has 3 test failures ( threshold is 2 ), I expected the build to be UNSTABLE but it turned to FAILED:
[xUnit] [INFO] - Starting to record.
[xUnit] [INFO] - Processing JUnit
[xUnit] [INFO] - [JUnit] - 1 test report file(s) were found with the pattern '**/target/surefire-reports/TEST-*.xml' relative to '/var/lib/jenkins/workspace/jenkins-failure_master-EHKMAGGDJWHA7FNGHQYY2VJNJHBX2RXI3XJY4NU5EB2PYT4ERTZQ' for the testing framework 'JUnit'.
[xUnit] [INFO] - Check 'Failed Tests' threshold.
[xUnit] [INFO] - The total number of tests for this category exceeds the specified 'unstable' threshold value.
[xUnit] [INFO] - Setting the build status to FAILURE
[xUnit] [INFO] - Stopping recording.
New case: I commented the line currentBuild.result = 'FAILED' and I added a syntax error in the test class. The build is successed even with the COMPILATION ERROR and it skipped the tests:
[xUnit] [INFO] - Starting to record.
[xUnit] [INFO] - Processing JUnit
[xUnit] [INFO] - [JUnit] - No test report file(s) were found with the pattern '**/target/surefire-reports/TEST-*.xml' relative to '/var/lib/jenkins/workspace/jenkins-failure_master-EHKMAGGDJWHA7FNGHQYY2VJNJHBX2RXI3XJY4NU5EB2PYT4ERTZQ' for the testing framework 'JUnit'. Did you enter a pattern relative to the correct directory? Did you generate the result report(s) for 'JUnit'?
[xUnit] [WARNING] - No test reports found for the metric 'JUnit' with the resolved pattern '**/target/surefire-reports/TEST-*.xml'.
[xUnit] [INFO] - Skipping the metric tool processing.
[xUnit] [INFO] - There are errors when processing test results.
[xUnit] [INFO] - Skipping tests recording.

From Reporting test results and storing artifacts (declarative pipeline):
pipeline {
agent { docker "java" }
stages {
stage("build") {
steps {
sh 'mvn clean install -Dmaven.test.failure.ignore=true'
}
}
}
post {
always {
archive "target/**/*"
junit 'target/surefire-reports/*.xml'
}
}
}
Use -Dmaven.test.failure.ignore=true to prevent failing the build on test failures. The junit step then collects the test results and marks the build as unstable.
This is also how it is done under the covers when using a non-pipeline Maven job, see JENKINS-24655.

Related

Fail build at 80% pass rate NUnit-Console + Jenkins

Could you tell me how to run tests in NUnit-Console so that they don't fail the build in Jenkins.
I want my build to fail at 80% pass rate. But under the current conditions, it fails if at least 1 test fails. Because the build returns an error code equal to the number of failed tests.
stage('Run tests') {
steps {
bat """nunit3-console.exe "Tests.dll" --skipnontestassemblies --result="TestResult.xml" """
}
}
I planned to fail the build using the Nunit plugin for Jenkins
post {
always {
step([$class: 'NUnitPublisher', testResultsPattern: """TestResult.xml""", healthScaleFactor: 1.0, keepJUnitReports: true, skipJUnitArchiver:false, failIfNoResults: true, failedTestsFailBuild: false ])
}
}

Unknown lifecycle phase "test-ci'"

I am trying to run my tests in jenkins pipelines.
but i got this error
Unknown lifecycle phase "test-ci'". You must specify a valid lifecycle
phase or a goal in the format : or
:[:]:.
Available lifecycle phases are: validate, initialize,
generate-sources, process-sources, generate-resources,
process-resources, compile, process-classes, generate-test-sources,
process-test-sources, generate-test-resources, process-test-resources,
test-compile, process-test-classes, test, prepare-package, package,
pre-integration-test, integration-test, post-integration-test, verify,
install, deploy, pre-clean, clean, post-clean, pre-site, site,
post-site, site-deploy. -> please how could i fix it ?
here is the full error:
C:\Users\ASUS\Documents\formation\jenkins\home\workspace\RDV>./mvnw -ntp com.github.eirslett:frontend-maven-plugin:npm -Dfrontend.npm.arguments='run test-ci'
[INFO] Scanning for projects...
[INFO]
[INFO] ----------------< ma.portnet.gestionrdvs:gestion-rd-vs >----------------
[INFO] Building Gestion RD Vs 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.543 s
[INFO] Finished at: 2022-04-11T00:04:08+02:00
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "test-ci'". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
Aucun fichier de rapport de test n'a été trouvé. Erreur de configuration?
here is my jenkins file
#!/usr/bin/env groovy
node {
stage('checkout') {
checkout scm
}
stage('check java') {
bat "java -version"
}
stage('clean') {
bat "./mvnw -ntp clean -P-webapp"
}
stage('nohttp') {
bat "./mvnw -ntp checkstyle:check"
}
stage('install tools') {
bat "./mvnw -ntp com.github.eirslett:frontend-maven-plugin:install-node-and-npm#install-node-and-npm"
}
stage('npm install') {
bat "./mvnw -ntp com.github.eirslett:frontend-maven-plugin:npm"
}
stage('backend tests') {
try {
bat "./mvnw -ntp verify -P-webapp"
} catch(err) {
throw err
} finally {
junit '**/target/surefire-reports/TEST-*.xml,**/target/failsafe-reports/TEST-*.xml'
}
}
stage('frontend tests') {
try {
bat "./mvnw -ntp com.github.eirslett:frontend-maven-plugin:npm -Dfrontend.npm.arguments='run test-ci'"
} catch(err) {
throw err
} finally {
junit '**/target/test-results/TESTS-results-jest.xml'
}
}
stage('packaging') {
bat "./mvnw -ntp verify -P-webapp -Pprod -DskipTests"
archiveArtifacts artifacts: '**/target/*.jar', fingerprint: true
}
}

Why do failing tests cause entire Jenkins build to be marked as "UNSTABLE" by Allure plugin?

I have set up Jenkins test jobs that will run Cucumber tests and want my jobs to always be successful up until a certain threshold (which I am controlling). The Allure plugin is always marking my builds as "UNSTABLE" when I have failed tests but I do not want my builds to be unstable. How can I change this behavior with allure?
I have tried setting
<testFailureIgnore>true</testFailureIgnore>
in pom.xml which is allowing the Maven Build to be successful. However, I am manually checking the Allure results in prometheusData.txt that is generated and failing/passing builds based off that result.
I want to be able to set Success/Failure status based off the 80% threshold. I am not aware of any thresholding that exists with Allure right now which is why I had to do it this way
Pipeline script
def testsInfo = readFile "${env.WORKSPACE}/allure-report/export/prometheusData.txt"
def passingTests = 0;
def totalTests = 0
def lineText = ''
def lineNum = 0
while(lineText != 'found'){
findText = testsInfo.split("\n")[lineNum]
if(findText.contains('launch_status_passed')){
passingTests = findText.split(' ')[1].toInteger()
}
if(findText.contains('launch_retries_run')){
totalTests = findText.split(' ')[1].toInteger()
lineText='found'
}
lineNum++
}
echo 'passing tests: ' + passingTests + ' total tests: ' + totalTests
percentSuccess = ((passingTests / totalTests) * 100).toString().split('\\.')[0]
echo 'Percent of tests that passed: ' + percentSuccess
if(build_ok && (percentSuccess.toInteger() > 80)) {
currentBuild.result = 'SUCCESS'
echo 'build OK'
} else {
currentBuild.result = 'FAILURE'
echo 'build bad'
}
Jenkins output
[INFO]
[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR] expected:<true> but was:<false>
[ERROR] expected:<[1].00> but was:<[2].00>
[ERROR] expected:<1.[0]0> but was:<1.[4]0>
[INFO]
[ERROR] Tests run: 90, Failures: 3, Errors: 0, Skipped: 0
[INFO]
[ERROR] There are test failures.
[INFO] -----------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -----------------------------------------------------------------
[INFO] Total time: 04:05 min
[INFO] Finished at: 2019-06-24T17:31:36Z
[INFO] Final Memory: 33M/1349M
[INFO] -----------------------------------------------------------------
Allure report was successfully generated.
Creating artifact for the build.
Artifact was added to the build.
[Pipeline] // stage
[Pipeline] readFile
[Pipeline] echo
passing tests: 96 total tests: 100
[Pipeline] echo
Percent of tests that passed: 96
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: UNSTABLE

xUnit fails on Jenkins even though js tests succeed

We have a CI pipeline on Jenkins. Under test is a REST api running in a Docker container. It is tested with frisby.js which also uses jasmine.
Test are successful
Finished in 0.168 seconds
1 test, 4 assertions, 0 failures, 0 skipped
but xUnit sets the build status to FAILURE:
[xUnit] [INFO] - Converting '/path/to/TEST-FrisbyTestMyApiTest.xml' .
[xUnit] [INFO] - Check 'Failed Tests' threshold.
[xUnit] [INFO] - Check 'Skipped Tests' threshold.
[xUnit] [INFO] - Setting the build status to FAILURE
Why is that? How can I get it to be SUCCESS?
The paths are validated and correct. The tests run successful. I'm running the Jenkins xUnit plugin with JUnit pattern. All xUnit thresholds are set to 0.

Casperjs export XML to Jenkins

I successfully setup a casperjs test exporting a "result.xml" file.
In Jenkins, I execute the following shell command:
casperjs /home/testing-radu/generated-test.js
This produces "results.xml" in my build's workspace.
In post-build actions I added "Publish XUnit test result report". I don't know how and where to setup the path to the .xml file.
When my build console I see the following:
[37;42;1mPASS 2 tests executed in 9.96s, 2 passed, 0 failed. [0m
[32;1mResult log stored in results.xml [0m
[xUnit] [INFO] - Starting to record.
ERROR: Publisher org.jenkinsci.plugins.xunit.XUnitPublisher aborted due to exception
/var/lib/jenkins/jobs/17live2/workspace/generatedJUnitFiles does not exist.
I added full rights to the workspace directory. I tried creating "generatedJUnitFiles" folder and here is what I'm getting:
[37;42;1mPASS 2 tests executed in 5.296s, 2 passed, 0 failed. [0m
[32;1mResult log stored in results.xml [0m
[xUnit] [INFO] - Starting to record.
[xUnit] [INFO] - Setting the build status to FAILURE
[xUnit] [INFO] - Stopping recording.
Build step 'Publish xUnit test result report' changed build result to FAILURE
Finished: FAILURE
Am I missing something?
Allright, here's the deal:
Under publish XUnit test results I chose JUnit (also setup the pattern to *.xml) and then
created a shell script to be executed by Jenkins:
# Auth tests
for f in auth/*.js ; do casperjs "$f"; done;
# Clean the old results and place the new ones
rm /var/lib/jenkins/jobs/17live2/workspace/*.xml
mv *.xml /var/lib/jenkins/jobs/17live2/workspace/
In Jenkins config I just do: ./run.sh
***You need read/write rights over your folders.

Resources