How can I perform cleanup after an operation is done, regardless of outcome?


(Ståle Undheim) #1

I have an integration test task, that performs integration test naturally. The flow is like this: 1. Create a new glassfish domain 2. Create a database in MS SQL 3. Deploy the jtds driver to glassfish 4. Start glassfish 5. Build an ear 6. Deploy the ear to glassfish 7. Run integration tests using jUnit 8. Stop glassfish and then delete the domain 9. Delete the database

I have done this by creating a test task:

task integrationTest(type: Test) {

dependsOn ear

dependsOn intTestClasses }

I then have several doFirst and doLast that do the setup off glassfish and the database, as well as a teardown. The problem is that doLast doesn’t seem to get run if the tests fails, so the cleanup isn’t done. This leaves the glassfish instance running, and the database remains.

I tried earlier to instead have try {} finally {} blocks, but there doesn’t seem to be a way of invoking tests without extending the Test type.


(René Groeschke) #2

Hello, the easiest solution might be to set the ignoreFailures flag to true:

test{
   ignoreFailures = true
}

For further information, the DSL reference has the details: http://gradle.org/docs/current/dsl/org.gradle.api.tasks.testing.Test.html#org.gradle.api.tasks.testing.Test:ignoreFailures

regards, René


(Ståle Undheim) #3

But I do want to fail the build still, I just want to make sure that failures does not prevent cleanup from happening.


(Joel Robotham) #4

One approach might be to put the cleanup code in a JVM shutdown hook, in groovy within your task you can just do something like:

task foo < {
  addShutdownHook {
    println("shutting down, stick some cleanup code here")
  }
}

I guess the caveat with this approach is that if you’re using the Gradle daemon (which I gather will soon be the default behaviour), then the shutdown hook won’t be executed until the daemon process is shut down…


(Luke Daley) #5

You can use a task listener for this: dsl:org.gradle.api.invocation.Gradle:addListener(java.lang.Object)

gradle.addListener(new TaskExecutionListener() {
  void beforeExecute(Task task) {}
  void afterExecute(Task task, TaskState state) {
    if (task.is foo) {
      // do cleanup
    }
  }
}

(Joel Robotham) #6

Much nicer!