Using Groovy to Generate Code

I was banging out a few cursory webtests and found myself tired of repeating the same boiler plate over an over. I could have abstracted out to a library. However, the nature of how these tests will be expanded in the future pointed more toward code generation. Initially, I tried to use Netbeans code templates. However, I ran into problems because it did not support groovy templates. So, I just decided to do it the old fashion way.

It took about 20 min to code this up and I thought I would share it in case it is useful to anyone. I used a combination of a data file, a groovy template, and a groovy script.

The data file looked like:

entshipinquiry:Enterprise Shipping Inquiry:Enterprise Shipping Inquiry
FlexCycleCount:Flex Cycle Count:Cycle Count Activation
flexengineering/Index.jsp?view=ProductionRunSheet&appid=660141&masloc=CSC&ccn=403500:Flex Engineering:flexengineering
FoamEngineering/faces/BlendPalette.jsp?clear=true&appid=557935&user=99900&masloc=CSC&ccn=403500:Foam Engineering:Blend Palette
...
...

There were MANY more. :) “:” delimited the data elements.

The groovy template looked like:

import com.canoo.webtest.WebtestCase
import org.junit.Test

/**
The same tests as in googleWebTest.xml and googleWebTestSteps.xml but expressed as Groovy code
*/
public class ${testname}Test extends WebtestCase
{

    void test${testname}Appears()
    {
        webtest("Checks that the ${desc} Page Exists")
        {
                        config useInsecureSSL:true
            invoke url: "https://apache01.barnhardt.local/${address}", description: "Go to ${desc}"
            verifyTitle "${title}"
        }
    }

}

The groovy script looked like:

import groovy.text.*

//template
def f = new File('/blah/testtemplate')
engine = new GStringTemplateEngine()

new File("/blah/testfile").eachLine{line->
    def tokens = line.split(':');
    //println tokens
    def t = tokens[1].replaceAll(" ", "")
    def binding = ["testname":t, "desc":tokens[1], "address":tokens[0], "title":tokens[2]]

    template = engine.createTemplate(f).make(binding)
    def filename = "/blah/project/functional/tests/${t}Test.groovy"
    File wf= new File(filename)
    wf.write( template.toString() )

}

Essentially, the script reads in the data, tokenizes it, and then applies the template. The result is a canoo webtest file that I can run as a part of my test suite. Hoep this helps someone.

Related Posts with Thumbnails
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • DZone
  • Facebook
  • Furl
  • Google Bookmarks
  • YahooBuzz
  • YahooMyWeb

About this entry