Thursday, December 16, 2010

Grails 1.3.5 webtests - custom steps to reset the database

once in a while I have the trouble that I want to reset the complete database during webtests or to make a snapshot of the current database while running the test.

So we use the great dbunit plugin to dump the database in one step:


import javax.sql.DataSource
import grails.plugin.remotecontrol.RemoteControl
import org.dbunit.database.DatabaseConnection
import org.dbunit.dataset.IDataSet
import org.dbunit.database.IDatabaseConnection
import org.dbunit.dataset.xml.FlatXmlDataSet
/**
* Created by IntelliJ IDEA.
* User: wohlgemuth
* Date: Nov 24, 2010
* Time: 3:46:47 PM
* To change this template use File | Settings | File Templates.
*/
class DumpDatabaseStep extends com.canoo.webtest.steps.Step {

String fileName = "result.xml"
/**
* resets the database
*/
void doExecute() {

RemoteControl remote = new RemoteControl()
try {

def outputFile = fileName
remote {
File file = new File("target/test-reports/data")
file.mkdirs()

DataSource dataSource = ctx.dataSource

IDatabaseConnection connection = new DatabaseConnection(dataSource.connection)

IDataSet fullDataSet = connection.createDataSet()

File out = new File(file, outputFile)

int counter = 1;

boolean run = out.exists()
while (run) {
out = new File(file, "${counter}-${outputFile}")

run = out.exists()
if (counter == 100) {
println "killed after 100 runs.."
run = false
}
counter++
}

FlatXmlDataSet.write(fullDataSet, new FileOutputStream(out))

null
}
}
catch (Exception e) {
e.printStackTrace()

throw e
}

}
}


and also to reset the complete database in another step


import grails.plugin.remotecontrol.RemoteControl
import javax.sql.DataSource
import groovy.sql.Sql

/**
* simple step which resets the complete database
*/
class ResetDatabaseStep extends com.canoo.webtest.steps.Step {

/**
* resets the database
*/
void doExecute() {

try {
DbUnitOperator.create()


RemoteControl remote = new RemoteControl()

remote.exec {
try {
DataSource dataSource = ctx.dataSource
Sql sql = Sql.newInstance(dataSource)

sql.execute("DROP SEQUENCE MINIX_ID")
sql.execute("CREATE SEQUENCE MINIX_ID START WITH 1000 INCREMENT BY 1")
}
catch (Exception e) {
e.printStackTrace()
throw e
}
}


}
catch (Exception e) {
println "error: ${e.getMessage()}"
e.printStackTrace()
throw new RuntimeException(e)
}

}
}

No comments:

Post a Comment