Skip to content

Instantly share code, notes, and snippets.

@mariogarcia
Created May 26, 2015 09:40
Show Gist options
  • Save mariogarcia/8de43c8efc32675cca57 to your computer and use it in GitHub Desktop.
Save mariogarcia/8de43c8efc32675cca57 to your computer and use it in GitHub Desktop.
POF about a rest-testing-autodoc-framework in Groovy/Java
import org.codehaus.groovy.control.CompilationUnit
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.ast.expr.*
import org.codehaus.groovy.ast.stmt.*
String code = '''
class PersonSpec {
static final String ENDPOINT = '/users/'
void 'list users'() {
when: 'sending a GET request'
GET()
and: 'optionally using pagination params'
params.max = 10
params.offset = 0
expect: 'a success http response'
status == 200
and: 'a specific response payload'
}
void 'create user'() {
when: 'trying to create a new user'
POST()
and: 'sending a proper payload'
payload('req_full.json')
expect: 'a created http status'
status == 201
and: 'a json with the created user back'
and: 'it will contain the saved user id'
response.json('id')
}
}
'''
GroovyClassLoader groovyClassLoader = new GroovyClassLoader()
CompilerConfiguration conf = new CompilerConfiguration()
CompilationUnit compilationUnit = new CompilationUnit(conf, null, groovyClassLoader)
compilationUnit.addSource('Person', code)
compilationUnit.compile()
def ast = compilationUnit.ast
def spec = ast.classes.first()
def endpoint = spec.fields.find { it.name == 'ENDPOINT' }.initialExpression.value
def tests = spec.methods.findAll { !it.isSynthetic() }
println "== ${spec.name} API\n"
tests.each { method ->
def methodStatement = method.code.statements.find { it.statementLabel == 'when'}
def description = method.code.statements.inject('') { acc, val ->
acc +
((val instanceof ExpressionStatement &&
val.expression instanceof ConstantExpression) ?
(val.statementLabel + ' ' + val.expression.value + ' ') :
'')
}
def next = method.code.statements - methodStatement
def http = next.findAll {it instanceof ExpressionStatement && it.expression instanceof MethodCallExpression}.collect {it?.expression?.method?.value}?:[null]
println "=== ${method.name.capitalize()}\n"
println "*${http.first()} ${endpoint}* \n"
println "${description}\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment