Skip to content

Commit

Permalink
Merge pull request #198 from Codearte/feature/#16-real-support-for-JU…
Browse files Browse the repository at this point in the history
…nit-new

Feature/#16 real support for junit new
  • Loading branch information
OlgaMaciaszek committed Feb 23, 2016
2 parents 61f92d7 + ca39338 commit dbc0129
Show file tree
Hide file tree
Showing 35 changed files with 2,670 additions and 1,763 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import static io.codearte.accurest.util.NamesUtil.capitalize
@Slf4j
class SingleTestGenerator {

private static final String JSON_ASSERT_STATIC_IMPORT = 'com.blogspot.toomuchcoding.jsonassert.JsonAssertion.assertThat'
private static final String JSON_ASSERT_STATIC_IMPORT = 'com.blogspot.toomuchcoding.jsonassert.JsonAssertion.assertThatJson'
private static final String JSON_ASSERT_CLASS = 'com.blogspot.toomuchcoding.jsonassert.JsonAssertion'

private final AccurestConfigProperties configProperties
Expand Down Expand Up @@ -51,16 +51,22 @@ class SingleTestGenerator {

if (configProperties.testMode == TestMode.JAXRSCLIENT) {
clazz.addStaticImport('javax.ws.rs.client.Entity.*')
if (configProperties.targetFramework == TestFramework.JUNIT) {
clazz.addImport('javax.ws.rs.core.Response')
}
} else if (configProperties.testMode == TestMode.MOCKMVC) {
clazz.addStaticImport('com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.*')
} else {
clazz.addStaticImport('com.jayway.restassured.RestAssured.*')
}

if (configProperties.targetFramework == TestFramework.JUNIT) {
if (configProperties.testMode == TestMode.MOCKMVC) {
clazz.addImport('com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification')
clazz.addImport('com.jayway.restassured.response.ResponseOptions')
}
clazz.addImport('org.junit.Test')
} else {
clazz.addImport('groovy.json.JsonSlurper')
clazz.addStaticImport('org.assertj.core.api.Assertions.assertThat')
}

if (configProperties.ruleClassForTests) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,17 @@ class BlockBuilder {
return this
}

BlockBuilder addAtTheEnd(String toAdd) {
if (builder.charAt(builder.length() - 1) as String == '\n') {
builder.replace(builder.length() - 1, builder.length(), toAdd)
builder << '\n'
} else {
builder << toAdd
}
return this
}


@Override
String toString() {
return builder.toString()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,116 @@
package io.codearte.accurest.builder

import groovy.json.StringEscapeUtils
import groovy.transform.PackageScope
import groovy.transform.TypeChecked
import io.codearte.accurest.dsl.GroovyDsl
import io.codearte.accurest.dsl.internal.ExecutionProperty
import io.codearte.accurest.dsl.internal.Header
import io.codearte.accurest.dsl.internal.NamedProperty
import io.codearte.accurest.dsl.internal.Request

import static groovy.json.StringEscapeUtils.escapeJava
import static io.codearte.accurest.config.TestFramework.JUNIT
import static io.codearte.accurest.util.ContentUtils.getJavaMultipartFileParameterContent

/**
* @author Jakub Kubrynski
* @author Olga Maciaszek-Sharma
*/
class JUnitMethodBodyBuilder {
/*
given()
.contentType("application/json")
.header("Accept", "application/json")
.body("{'name': 'MyApp', 'description' : 'awesome app'}".replaceAll("'", "\"")).
expect()
.statusCode(200).body("id", is(not(nullValue()))).
when()
.post(root.toString() + "rest/applications").asString();*/
@TypeChecked
@PackageScope
abstract class JUnitMethodBodyBuilder extends MethodBodyBuilder {

JUnitMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}

@Override
protected String getResponseAsString() {
return "response.getBody().asString()"
}

@Override
protected String addCommentSignIfRequired(String baseString) {
return "// $baseString"
}

@Override
protected BlockBuilder addColonIfRequired(BlockBuilder blockBuilder) {
blockBuilder.addAtTheEnd(JUNIT.lineSuffix)
return blockBuilder
}

@Override
protected String getResponseBodyPropertyComparisonString(String property, String value) {
return "assertThat(responseBody${property}).isEqualTo(\"${value}\")"
}

@Override
protected void processBodyElement(BlockBuilder blockBuilder, String property, ExecutionProperty exec) {
blockBuilder.addLine("${exec.insertValue("parsedJson.read(\"\\\$$property\")")};")
}

@Override
protected String getPropertyInListString(String property, Integer listIndex) {
return "${property}.get($listIndex)" ?: ''
}

@Override
protected String convertUnicodeEscapesIfRequired(String json) {
String unescapedJson = StringEscapeUtils.unescapeJavaScript(json)
return escapeJava(unescapedJson)
}

@Override
protected void processBodyElement(BlockBuilder blockBuilder, String property, Map.Entry entry) {
processBodyElement(blockBuilder, property + getMapKeyReferenceString(entry), entry.value)
}

private String getMapKeyReferenceString(Map.Entry entry) {
if (entry.value instanceof ExecutionProperty) {
return "." + entry.key
}
return """.get(\\\"$entry.key\\\")"""
}

@Override
protected String getParsedXmlResponseBodyString(String responseString) {
return "Object responseBody = new XmlSlurper().parseText($responseString);"
}

@Override
protected String getSimpleResponseBodyString(String responseString) {
return "Object responseBody = ($responseString);"
}

@Override
protected String getResponseString(Request request) {
return 'ResponseOptions response = given().spec(request)'
}

@Override
protected String getRequestString() {
return 'MockMvcRequestSpecification request = given()'
}

@Override
protected String getHeaderString(Header header) {
return ".header(\"${getTestSideValue(header.name)}\", \"${getTestSideValue(header.serverValue)}\")"
}

@Override
protected String getBodyString(String bodyAsString) {
return ".body(\"$bodyAsString\")"
}

@Override
protected String getMultipartFileParameterContent(String propertyName, NamedProperty propertyValue) {
return getJavaMultipartFileParameterContent(propertyName, propertyValue)
}

@Override
protected String getParameterString(Map.Entry<String, Object> parameter) {
return """.param("${escapeJava(parameter.key)}", "${escapeJava(parameter.value as String)}")"""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package io.codearte.accurest.builder

import io.codearte.accurest.dsl.GroovyDsl
import io.codearte.accurest.dsl.internal.Header
import io.codearte.accurest.dsl.internal.QueryParameter
import io.codearte.accurest.dsl.internal.QueryParameters

import static io.codearte.accurest.config.TestFramework.JUNIT

/**
* @author Olga Maciaszek-Sharma
@since 21.02.16
*/
class JaxRsClientJUnitMethodBodyBuilder extends JUnitMethodBodyBuilder {

JaxRsClientJUnitMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}

@Override
protected void given(BlockBuilder bb) {}

@Override
protected void givenBlock(BlockBuilder bb) {
}

@Override
protected void when(BlockBuilder bb) {
bb.addLine("Response response = webTarget")
bb.indent()

appendUrlPathAndQueryParameters(bb)
appendRequestWithRequiredResponseContentType(bb)
appendHeaders(bb)
appendMethodAndBody(bb)
bb.addAtTheEnd(JUNIT.lineSuffix)

bb.unindent()

bb.addEmptyLine()
bb.addLine("String responseAsString = response.readEntity(String.class);")
}

protected void appendUrlPathAndQueryParameters(BlockBuilder bb) {
if (request.url) {
bb.addLine(".path(\"$request.url.serverValue\")")
appendQueryParams(request.url.queryParameters, bb)
} else if (request.urlPath) {
bb.addLine(".path(\"$request.urlPath.serverValue\")")
appendQueryParams(request.urlPath.queryParameters, bb)
}
}

private void appendQueryParams(QueryParameters queryParameters, BlockBuilder bb) {
if (!queryParameters?.parameters) {
return
}
queryParameters.parameters.findAll(this.&allowedQueryParameter).each { QueryParameter param ->
bb.addLine(".queryParam(\"$param.name\", \"${resolveParamValue(param).toString()}\")")
}
}

protected void appendMethodAndBody(BlockBuilder bb) {
String method = request.method.serverValue.toString().toLowerCase()
if (request.body) {
String contentType = getHeader('Content-Type') ?: getRequestContentType().mimeType
bb.addLine(".method(\"${method.toUpperCase()}\", entity(\"$bodyAsString\", \"$contentType\"))")
} else {
bb.addLine(".method(\"${method.toUpperCase()}\")")
}
}

protected appendHeaders(BlockBuilder bb) {
request.headers?.collect { Header header ->
if (header.name == 'Content-Type' || header.name == 'Accept') return
bb.addLine(".header(\"${header.name}\", \"${header.serverValue}\")")
}
}

protected void appendRequestWithRequiredResponseContentType(BlockBuilder bb) {
String acceptHeader = getHeader("Accept")
if (acceptHeader) {
bb.addLine(".request(\"$acceptHeader\")")
} else {
bb.addLine(".request()")
}
}

@Override
protected void validateResponseCodeBlock(BlockBuilder bb) {
bb.addLine("assertThat(response.getStatus()).isEqualTo($response.status.serverValue);")
}

@Override
protected void validateResponseHeadersBlock(BlockBuilder bb) {
response.headers?.collect { Header header ->
bb.addLine("assertThat(response.getHeaderString(\"$header.name\")).isEqualTo(\"$header.serverValue\");")
}
}

protected String getHeader(String name) {
return request.headers?.entries.find { it.name == name }?.serverValue
}

@Override
protected String getResponseAsString() {
return 'responseAsString'
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package io.codearte.accurest.builder

import groovy.transform.PackageScope
import groovy.transform.TypeChecked
import io.codearte.accurest.dsl.GroovyDsl
Expand All @@ -14,6 +15,9 @@ class JaxRsClientSpockMethodBodyBuilder extends SpockMethodBodyBuilder {
super(stubDefinition)
}

@Override
protected void given(BlockBuilder bb) {}

@Override
protected void givenBlock(BlockBuilder bb) {
}
Expand Down
Loading

0 comments on commit dbc0129

Please sign in to comment.