froblesmartin
froblesmartin

Reputation: 1891

How to handle unstable JUnit results in parallel stages in a scripted Jenkinsfile?

We are working on a scripted Jenkinsfile that runs a bunch of stages in parallel and sequentially.

We have the following code:

...
parallel {
    stage('test1') {
        try {
            githubNotify status: 'PENDING', context: 'test1', description: 'PENDING'
            test1 execution
            junit
            githubNotify status: 'SUCCESS', context: 'test1', description: 'SUCCESS'
        } catch (Exception e) {
            githubNotify status: 'FAILURE', context: 'test1, description: 'FAILURE'
        }
    }
    stage('test2') {
        try {
            githubNotify status: 'PENDING', context: 'test2', description: 'PENDING'
            test2 execution
            junit
            githubNotify status: 'SUCCESS', context: 'test2', description: 'SUCCESS'
        } catch (Exception e) {
            githubNotify status: 'FAILURE', context: 'test2', description: 'FAILURE'
        }
    }
}
...

The problem is that, whenever JUnit records the results and finds some failures, it sets the stage and the build as UNSTABLE, and does not throw an exception. How can we check the result of the stage or generally handle?

In a sequential case, this answer would be enough: https://stackoverflow.com/a/48991594/7653022. In our case, adding the finally block to the first try, would result as:

...
} finally {
    if (currentBuild.currentResult == 'UNSTABLE') {
        githubNotify status: 'FAILURE', context: 'test1', description: 'FAILURE'
    }
}

But as we are running stages in parallel and we want to still send correct notification in further stages if the tests pass, we can not use the currentBuild.currentResult, as once there is a stage UNSTABLE, all the following stages would enter the if block.

Thanks in advance!! :)

Upvotes: 2

Views: 438

Answers (1)

Damian229
Damian229

Reputation: 472

The jUnit plugin execution will return a TestResultSummary, where you could check the number of test failed. You could save the jUnit results, and if there are failures, you would rise the exception for being catch by the catch block:

try {
    githubNotify status: 'PENDING', context: 'test2', description: 'PENDING'
    test2 execution
    TestResultSummary summaryJUnit = junit
    if(summaryJUnit.getFailCount() > 0) {
        throw new Exception('Has tests failing')
    }
    githubNotify status: 'SUCCESS', context: 'test2', description: 'SUCCESS'
} catch (Exception e) {
    githubNotify status: 'FAILURE', context: 'test2', description: 'FAILURE'
}

You are not handling the stage status(UNSTABLE) but for you specific case with jUnit it will allow you to meet your requirements.

Upvotes: 1

Related Questions