Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle task that depends on a failure

Tags:

gradle

Can a gradle task depend on the failure of another task?

For example, I have an auxillary task that opens the test report in a browser. I want the report to only appear when the task "test" fails, not when all tests pass as it does now.

task viewTestReport(dependsOn: 'test') << {
    def testReport = project.testReportDir.toString() + "/index.html"
    "powershell ii \"$testReport\"".execute()
}
like image 554
cheezsteak Avatar asked Oct 19 '22 23:10

cheezsteak


1 Answers

You can try to set task's finilizedBy property, like:

task taskX << {
    throw new GradleException('This task fails!');
}

task taskY << {
    if (taskX.state.failure != null) {
        //here is what shoud be executed if taskX fails
        println 'taskX was failed!'
    }
}

taskX.finalizedBy taskY

You can find the explanation gradle's user guide in chapter 14.11 "Finalizer tasks". Shortly, due to docs:

Finalizer tasks will be executed even if the finalized task fails.

So, you just have to check the state of the finilized task with TaskState and if it was failed, do what you wanted.

Update: Unfortunately, because configuration is always executed for all tasks, seems not possible to create some custom task to set the flag to show report within script. On execution phase it is not possible too, because the task will not be called if previewsly runned task has failed. But you can do, what you wanted, providing the build script arguments, like:

task viewTestReport << {
    if (project.hasProperty("showReport") && test.state.failure != null) {
        //here is what shoud be executed on taskX fail
        println 'test was failed!'
    }
}
test.finalizedBy(viewTestReport)

In that case, you have to provide -PshowReport arguments, while you call any gradle task, if ou want to get the report in test task fail. For example, if you call:

gradle test -PshowReport

then report will be shown if test task fails, but if you call it:

gradle test

no report will be shown in any case.

like image 83
Stanislav Avatar answered Oct 24 '22 11:10

Stanislav