Showing posts with label junit. Show all posts
Showing posts with label junit. Show all posts

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)
}

}
}

Grails 1.3.5 webtests and JQuery trouble

recently I migrated my prototype code over to JQuery and promptly all my webtest's failed with a lot of error messages and exceptions.

Like:


"TypeError: Cannot find function createComment in
object [object]. (FunctionalTestCase.groovy#372)"


So during some googeling I found these reports:

old htmlunit version

replacing version

Which led to me reporting:

my approach

and the final solution was to put this into your 'BuildConfig.groovy'


plugin("webtest") {
test('net.sourceforge.htmlunit:htmlunit:2.8-SNAPSHOT') {
excludes 'xalan'
excludes 'xml-apis'
}
test('com.canoo.webtest:webtest:3.1-SNAPSHOT') {
excludes 'xalan'
excludes 'xml-apis'
}
test('xalan:xalan:2.7.0') {
excludes 'xml-apis'
}
}

Thursday, July 9, 2009

MockingSpring - Testing ServletFiltes

mocking spring,

well it's hot in davis and I have no AC, so what's better than to run into the nice and cold office and playing with some junit tests.

Basically how to junit test servlet filters. Like always somebody smart wrote some great tools for me to use.

An example of a simple servlet filter which forwads all access to a cutom report factory


package edu.ucdavis.genomics.metabolomics.binbase.filter;

import edu.ucdavis.genomics.metabolomics.util.status.Report;
import edu.ucdavis.genomics.metabolomics.util.status.ReportFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
* forwards all requests to the reporter which deals with it
*


* User: wohlgemuth
* Date: Jun 28, 2009
* Time: 3:33:00 PM
*/
public class IPLogger implements Filter {

/**
* forwards everything to the server
*/
private Report report;

/**
* logging nstances
*/
private Logger logger = Logger.getLogger(getClass().getName());

/**
* initialize the connection to the report method
*
* @param filterConfig
* @throws ServletException
*/
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("initialize filter");

//access the factory we need for the reporter
String factory = filterConfig.getInitParameter("factory");

if (factory == null) {
logger.info("no factory provided, so we use the default factory");

report = ReportFactory.newInstance().create(IPLogger.class.getSimpleName());
} else {
logger.info("using factory: " + factory);
report = ReportFactory.newInstance(factory).create(IPLogger.class.getSimpleName());
}
}

/**
* does the actual filtering
*
* @param servletRequest
* @param servletResponse
* @param filterChain
* @throws IOException
* @throws ServletException
*/
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
String host = servletRequest.getRemoteHost();
String address = servletRequest.getRemoteAddr();
int port = servletRequest.getRemotePort();

String uri = "unknown";
if (servletRequest instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) servletRequest;

uri = req.getRequestURI();
}

//send it out so that we can deal with these event in a different class or so
report.report(new IPRequest(host, uri, address, port), FilterReports.FITLER_URI_ACCESS, FilterReports.FILTER_REQUEST);
}

public void destroy() {
}
}



and the junit test to test it, without a web server or so.


public class IPLoggerTest {

private IPLogger filter;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain chain;

@Before
public void setUp() throws Exception {
filter = new IPLogger();
MockFilterConfig config = new MockFilterConfig();
config.addInitParameter("factory", TestFactory.class.getName());
filter.init(config);
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
chain = new MockFilterChain();
}

@After
public void tearDown() throws Exception {
}

@Test
public void testDoFilter() throws IOException, ServletException {
request.setRequestURI("http://127.0.0.1/test.html");
filter.doFilter(request, response, chain);


}
}



and our little factory which does the acutal testing of the received object


public class TestFactory extends ReportFactory{


private Logger logger = Logger.getLogger(getClass());
/**
* checks if all the result's fit the exspectations
*
* @param properties
* @param s
* @return
*/
public Report create(Properties properties, String s) {
return new Report() {
public void report(String s, Serializable serializable, ReportEvent reportEvent, ReportType reportType, String s1, Date date, Exception e) {
logger.info("received: " + serializable);
assertTrue(reportEvent.equals(FilterReports.FITLER_URI_ACCESS));
assertTrue(reportType.equals(FilterReports.FILTER_REQUEST));

assertTrue(serializable instanceof IPRequest);
IPRequest request = (IPRequest) serializable;

assertTrue(request.getHost().equals("localhost"));
assertTrue(request.getUri().equals("http://127.0.0.1/test.html"));
assertTrue(request.getAddress().equals("127.0.0.1"));
assertTrue(request.getPort() == 80);
}

public String getOwner() {

return IPLogger.class.getSimpleName();
}
};
}
}