Merge pull request #142 from Codearte/issues/regexps-and-jsonpaths-squashed

Regexps and jsonpaths
This commit is contained in:
Marcin Grzejszczak
2015-09-03 17:36:19 +02:00
43 changed files with 1172 additions and 895 deletions

View File

@@ -10,15 +10,15 @@ class DslToWireMockClientConverterSpec extends Specification {
def converter = new DslToWireMockClientConverter()
and:
String dslBody = """
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
url \$(client(~/\\/[0-9]{2}/), server('/12'))
}
response {
status 200
}
}
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method('PUT')
url \$(client(~/\\/[0-9]{2}/), server('/12'))
}
response {
status 200
}
}
"""
when:
String json = converter.convertContent(dslBody)
@@ -34,7 +34,7 @@ class DslToWireMockClientConverterSpec extends Specification {
def converter = new DslToWireMockClientConverter()
and:
String dslBody = """
io.codearte.accurest.dsl.GroovyDsl.make {
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method 'PUT'
url '/api/12'
@@ -84,57 +84,57 @@ class DslToWireMockClientConverterSpec extends Specification {
JSONAssert.assertEquals('''
{
"request" : {
"url" : "/api/12",
"method" : "PUT",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.995548)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.country == 'United States')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -77.119759)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.name == 'Washington')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box[?(@.type == 'Polygon')]"
}, {
"matchesJsonPath" : "$[*][?(@.id_str == '492967299297845248')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.country_code == 'US')]"
}, {
"matchesJsonPath" : "$[*][?(@.id == 492967299297845248)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -76.909393)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.791645)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.id == '01fbe706f872cb32')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.url == 'http://api.twitter.com/1/geo/id/01fbe706f872cb32.json')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -77.119759)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -76.909393)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.995548)]"
}, {
"matchesJsonPath" : "$[*][?(@.text == 'Gonna see you at Warsaw')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.place_type == 'city')]"
}, {
"matchesJsonPath" : "$[*][?(@.created_at == 'Sat Jul 26 09:38:57 +0000 2014')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.full_name == 'Washington, DC')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.791645)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.com.ofg.twitter-places-analyzer.v1+json"
}
}
"url" : "/api/12",
"method" : "PUT",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.995548)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.country == 'United States')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -77.119759)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.name == 'Washington')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box[?(@.type == 'Polygon')]"
}, {
"matchesJsonPath" : "$[*][?(@.id_str == '492967299297845248')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.country_code == 'US')]"
}, {
"matchesJsonPath" : "$[*][?(@.id == 492967299297845248)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -76.909393)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.791645)]"
}, {
"matchesJsonPath" : "$[*].place[?(@.id == '01fbe706f872cb32')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.url == 'http://api.twitter.com/1/geo/id/01fbe706f872cb32.json')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -77.119759)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == -76.909393)]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.995548)]"
}, {
"matchesJsonPath" : "$[*][?(@.text == 'Gonna see you at Warsaw')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.place_type == 'city')]"
}, {
"matchesJsonPath" : "$[*][?(@.created_at == 'Sat Jul 26 09:38:57 +0000 2014')]"
}, {
"matchesJsonPath" : "$[*].place[?(@.full_name == 'Washington, DC')]"
}, {
"matchesJsonPath" : "$[*].place.bounding_box.coordinates[*][*][?(@ == 38.791645)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.com.ofg.twitter-places-analyzer.v1+json"
}
}
},
"response" : {
"status" : 200
"status" : 200
}
}
''', json, false)

View File

@@ -68,8 +68,8 @@ class TestGenerator {
}
}
}
private String normalizePath(String path) {
return FilenameUtils.separatorsToUnix(path)
}
private String normalizePath(String path) {
return FilenameUtils.separatorsToUnix(path)
}
}

View File

@@ -10,86 +10,86 @@ import io.codearte.accurest.dsl.internal.QueryParameter
@TypeChecked
class JaxRsClientSpockMethodBodyBuilder extends SpockMethodBodyBuilder {
JaxRsClientSpockMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}
JaxRsClientSpockMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}
@Override
protected void givenBlock(BlockBuilder bb) {
}
@Override
protected void givenBlock(BlockBuilder bb) {
}
@Override
protected void when(BlockBuilder bb) {
bb.addLine("def response = webTarget")
bb.indent()
@Override
protected void when(BlockBuilder bb) {
bb.addLine("def response = webTarget")
bb.indent()
appendUrlPathAndQueryParameters(bb)
appendRequestWithRequiredResponseContentType(bb)
appendHeaders(bb)
appendMethodAndBody(bb)
appendUrlPathAndQueryParameters(bb)
appendRequestWithRequiredResponseContentType(bb)
appendHeaders(bb)
appendMethodAndBody(bb)
bb.unindent()
bb.unindent()
bb.addEmptyLine()
bb.addLine("String responseAsString = response.readEntity(String)")
}
bb.addEmptyLine()
bb.addLine("String responseAsString = response.readEntity(String)")
}
protected void appendRequestWithRequiredResponseContentType(BlockBuilder bb) {
String acceptHeader = getHeader("Accept")
if (acceptHeader) {
bb.addLine(".request('$acceptHeader')")
} else {
bb.addLine(".request()")
}
}
protected void appendRequestWithRequiredResponseContentType(BlockBuilder bb) {
String acceptHeader = getHeader("Accept")
if (acceptHeader) {
bb.addLine(".request('$acceptHeader')")
} else {
bb.addLine(".request()")
}
}
protected void appendUrlPathAndQueryParameters(BlockBuilder bb) {
if (request.url) {
bb.addLine(".path('$request.url.serverValue')")
} else if (request.urlPath) {
bb.addLine(".path('$request.urlPath.serverValue')")
request.urlPath.queryParameters?.parameters.findAll(this.&allowedQueryParameter).each { QueryParameter param ->
bb.addLine(".queryParam('$param.name', '${resolveParamValue(param).toString()}')")
}
}
}
protected void appendUrlPathAndQueryParameters(BlockBuilder bb) {
if (request.url) {
bb.addLine(".path('$request.url.serverValue')")
} else if (request.urlPath) {
bb.addLine(".path('$request.urlPath.serverValue')")
request.urlPath.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', entity('$bodyAsString', '$contentType'))")
} else {
bb.addLine(".method('$method')")
}
}
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', entity('$bodyAsString', '$contentType'))")
} else {
bb.addLine(".method('$method')")
}
}
protected appendHeaders(BlockBuilder bb) {
request.headers?.collect { Header header ->
if (header.name == 'Content-Type' || header.name == 'Accept') return // Particular headers are set via 'request' / 'entity' methods
bb.addLine(".header('${header.name}', '${header.serverValue}')")
}
}
protected appendHeaders(BlockBuilder bb) {
request.headers?.collect { Header header ->
if (header.name == 'Content-Type' || header.name == 'Accept') return // Particular headers are set via 'request' / 'entity' methods
bb.addLine(".header('${header.name}', '${header.serverValue}')")
}
}
protected String getHeader(String name) {
return request.headers?.entries.find { it.name == name }?.serverValue
}
protected String getHeader(String name) {
return request.headers?.entries.find { it.name == name }?.serverValue
}
@Override
protected void validateResponseCodeBlock(BlockBuilder bb) {
bb.addLine("response.status == $response.status.serverValue")
}
@Override
protected void validateResponseCodeBlock(BlockBuilder bb) {
bb.addLine("response.status == $response.status.serverValue")
}
@Override
protected void validateResponseHeadersBlock(BlockBuilder bb) {
response.headers?.collect { Header header ->
bb.addLine("response.getHeaderString('$header.name') == '$header.serverValue'")
}
}
@Override
protected void validateResponseHeadersBlock(BlockBuilder bb) {
response.headers?.collect { Header header ->
bb.addLine("response.getHeaderString('$header.name') == '$header.serverValue'")
}
}
@Override
protected String getResponseAsString() {
return 'responseAsString'
}
@Override
protected String getResponseAsString() {
return 'responseAsString'
}
}

View File

@@ -1,5 +1,4 @@
package io.codearte.accurest.builder
import groovy.transform.PackageScope
import groovy.transform.TypeChecked
import groovy.transform.TypeCheckingMode
@@ -15,73 +14,73 @@ import java.util.regex.Pattern
@TypeChecked
class MockMvcSpockMethodBodyBuilder extends SpockMethodBodyBuilder {
MockMvcSpockMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}
MockMvcSpockMethodBodyBuilder(GroovyDsl stubDefinition) {
super(stubDefinition)
}
protected void given(BlockBuilder bb) {
bb.addLine('def request = given()')
bb.indent()
request.headers?.collect { Header header ->
bb.addLine(".header('${header.name}', '${header.serverValue}')")
}
if (request.body) {
bb.addLine(".body('$bodyAsString')")
}
bb.unindent()
}
protected void given(BlockBuilder bb) {
bb.addLine('def request = given()')
bb.indent()
request.headers?.collect { Header header ->
bb.addLine(".header('${getTestSideValue(header.name)}', '${getTestSideValue(header.serverValue)}')")
}
if (request.body) {
bb.addLine(".body('$bodyAsString')")
}
bb.unindent()
}
protected void when(BlockBuilder bb) {
bb.addLine('def response = given().spec(request)')
bb.indent()
protected void when(BlockBuilder bb) {
bb.addLine('def response = given().spec(request)')
bb.indent()
String url = buildUrl(request)
String method = request.method.serverValue.toString().toLowerCase()
String url = buildUrl(request)
String method = request.method.serverValue.toString().toLowerCase()
bb.addLine(/.${method}("$url")/)
bb.unindent()
}
bb.addLine(/.${method}("$url")/)
bb.unindent()
}
protected void validateResponseCodeBlock(BlockBuilder bb) {
bb.addLine("response.statusCode == $response.status.serverValue")
}
protected void validateResponseCodeBlock(BlockBuilder bb) {
bb.addLine("response.statusCode == $response.status.serverValue")
}
protected void validateResponseHeadersBlock(BlockBuilder bb) {
response.headers?.collect { Header header ->
bb.addLine("response.header('$header.name') ${convertHeaderComparison(header.serverValue)}")
}
}
protected void validateResponseHeadersBlock(BlockBuilder bb) {
response.headers?.collect { Header header ->
bb.addLine("response.header('$header.name') ${convertHeaderComparison(header.serverValue)}")
}
}
private String convertHeaderComparison(Object headerValue) {
return " == '$headerValue'"
}
private String convertHeaderComparison(Object headerValue) {
return " == '$headerValue'"
}
private String convertHeaderComparison(Pattern headerValue) {
return "==~ java.util.regex.Pattern.compile('$headerValue')"
}
private String convertHeaderComparison(Pattern headerValue) {
return "==~ java.util.regex.Pattern.compile('$headerValue')"
}
@Override
protected String getResponseAsString() {
return 'response.body.asString()'
}
@Override
protected String getResponseAsString() {
return 'response.body.asString()'
}
protected String buildUrl(Request request) {
if (request.url)
return request.url.serverValue;
if (request.urlPath)
return buildUrlFromUrlPath(request.urlPath)
throw new IllegalStateException("URL is not set!")
}
protected String buildUrl(Request request) {
if (request.url)
return getTestSideValue(request.url.serverValue)
if (request.urlPath)
return getTestSideValue(buildUrlFromUrlPath(request.urlPath))
throw new IllegalStateException("URL is not set!")
}
@TypeChecked(TypeCheckingMode.SKIP)
protected String buildUrlFromUrlPath(UrlPath urlPath) {
String params = urlPath.queryParameters.parameters
.findAll(this.&allowedQueryParameter)
.inject([] as List<String>) { List<String> result, QueryParameter param ->
result << "${param.name}=${resolveParamValue(param).toString()}"
}
.join('&')
return "$urlPath.serverValue?$params"
}
@TypeChecked(TypeCheckingMode.SKIP)
protected String buildUrlFromUrlPath(UrlPath urlPath) {
String params = urlPath.queryParameters.parameters
.findAll(this.&allowedQueryParameter)
.inject([] as List<String>) { List<String> result, QueryParameter param ->
result << "${param.name}=${resolveParamValue(param).toString()}"
}
.join('&')
return "$urlPath.serverValue?$params"
}
}

View File

@@ -6,7 +6,7 @@ import io.codearte.accurest.dsl.GroovyDsl
import io.codearte.accurest.dsl.internal.*
import io.codearte.accurest.util.ContentType
import io.codearte.accurest.util.MapConverter
import io.codearte.accurest.util.JsonPathJsonConverter
import io.codearte.accurest.util.JsonToJsonPathsConverter
import io.codearte.accurest.util.JsonPaths
import static io.codearte.accurest.util.ContentUtils.*
@@ -17,6 +17,8 @@ import static io.codearte.accurest.util.ContentUtils.*
@TypeChecked
abstract class SpockMethodBodyBuilder {
private static final Boolean TEST_SIDE = false
protected final Request request
protected final Response response
@@ -86,7 +88,7 @@ abstract class SpockMethodBodyBuilder {
}
if (contentType == ContentType.JSON) {
appendJsonPath(bb, responseAsString)
JsonPaths jsonPaths = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(responseBody)
JsonPaths jsonPaths = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(responseBody)
jsonPaths.each {
it.buildJsonPathComparison('parsedJson').each {
bb.addLine(it)
@@ -200,4 +202,7 @@ abstract class SpockMethodBodyBuilder {
return contentType
}
protected String getTestSideValue(Object object) {
return MapConverter.getClientOrServerSideValues(object, TEST_SIDE).toString()
}
}

View File

@@ -6,6 +6,8 @@ import io.codearte.accurest.dsl.internal.DslProperty
import io.codearte.accurest.dsl.internal.Header
import io.codearte.accurest.dsl.internal.Headers
import io.codearte.accurest.util.ContentType
import io.codearte.accurest.util.ContentUtils
import io.codearte.accurest.util.MapConverter
import java.util.regex.Pattern
@@ -15,6 +17,12 @@ import static io.codearte.accurest.util.MapConverter.transformValues
@TypeChecked
abstract class BaseWireMockStubStrategy {
private static final Boolean STUB_SIDE = true
protected getStubSideValue(Object object) {
return MapConverter.getClientOrServerSideValues(object, STUB_SIDE)
}
private static Closure transform = {
it instanceof DslProperty ? transformValues(it.clientValue, transform) : it
}
@@ -58,7 +66,7 @@ abstract class BaseWireMockStubStrategy {
}
public String parseBody(Map map, ContentType contentType) {
def transformedMap = transformValues(map, transform)
def transformedMap = MapConverter.getClientOrServerSideValues(map, true)
return parseBody(toJson(transformedMap), contentType)
}
@@ -82,4 +90,14 @@ abstract class BaseWireMockStubStrategy {
return new JsonBuilder(value).toString()
}
protected ContentType tryToGetContentType(Object body, Headers headers) {
ContentType contentType = ContentUtils.recognizeContentTypeFromHeader(headers)
if (contentType == ContentType.UNKNOWN) {
if (!body) {
return ContentType.UNKNOWN
}
return ContentUtils.getClientContentType(body)
}
return contentType
}
}

View File

@@ -9,14 +9,14 @@ import groovy.transform.TypeCheckingMode
import io.codearte.accurest.dsl.internal.*
import io.codearte.accurest.util.ContentType
import io.codearte.accurest.util.ContentUtils
import io.codearte.accurest.util.JsonPathJsonConverter
import io.codearte.accurest.util.JsonToJsonPathsConverter
import io.codearte.accurest.util.JsonPaths
import io.codearte.accurest.util.MapConverter
import java.util.regex.Pattern
import static io.codearte.accurest.util.ContentUtils.*
import static io.codearte.accurest.util.RegexpBuilders.buildGStringRegexpMatch
import static io.codearte.accurest.util.RegexpBuilders.buildGStringRegexpForStubSide
import static io.codearte.accurest.util.RegexpBuilders.buildJSONRegexpMatch
@TypeChecked
@@ -51,9 +51,9 @@ class WireMockRequestStubStrategy extends BaseWireMockStubStrategy {
if (!request.body) {
return
}
ContentType contentType = tryToGetContentType()
ContentType contentType = tryToGetContentType(request.body.clientValue, request.headers)
if (contentType == ContentType.JSON) {
JsonPaths values = JsonPathJsonConverter.transformToJsonPathWithStubsSideValues(getMatchingStrategyFromBody(request.body)?.clientValue)
JsonPaths values = JsonToJsonPathsConverter.transformToJsonPathWithStubsSideValues(getMatchingStrategyFromBody(request.body)?.clientValue)
if (values.empty) {
requestPattern.bodyPatterns = [new ValuePattern(jsonCompareMode: org.skyscreamer.jsonassert.JSONCompareMode.LENIENT,
equalToJson: JsonOutput.toJson(getMatchingStrategy(request.body.clientValue).clientValue) ) ]
@@ -70,17 +70,6 @@ class WireMockRequestStubStrategy extends BaseWireMockStubStrategy {
}
}
private ContentType tryToGetContentType() {
ContentType contentType = recognizeContentTypeFromHeader(request.headers)
if (contentType == ContentType.UNKNOWN) {
if (!request.body.clientValue) {
return ContentType.UNKNOWN
}
return ContentUtils.getClientContentType(request.body.clientValue)
}
return contentType
}
private void appendHeaders(RequestPattern requestPattern) {
if(!request.headers) {
return
@@ -93,12 +82,12 @@ class WireMockRequestStubStrategy extends BaseWireMockStubStrategy {
private void appendUrl(RequestPattern requestPattern) {
Object urlPath = request?.urlPath?.clientValue
if (urlPath) {
requestPattern.setUrlPath(urlPath.toString())
requestPattern.setUrlPath(getStubSideValue(urlPath.toString()).toString())
}
if(!request.url) {
return
}
Object url = request?.url?.clientValue
Object url = getUrlIfGstring(request?.url?.clientValue)
if(url instanceof Pattern) {
requestPattern.setUrlPattern(url.pattern())
} else {
@@ -106,6 +95,17 @@ class WireMockRequestStubStrategy extends BaseWireMockStubStrategy {
}
}
private Object getUrlIfGstring(Object clientSide) {
if (clientSide instanceof GString) {
if (clientSide.values.any { getStubSideValue(it) instanceof Pattern }) {
return Pattern.compile(getStubSideValue(clientSide).toString())
} else {
return getStubSideValue(clientSide).toString()
}
}
return clientSide
}
private void appendQueryParameters(RequestPattern requestPattern) {
QueryParameters queryParameters = request?.urlPath?.queryParameters ?: request?.url?.queryParameters
queryParameters?.parameters?.each {
@@ -183,7 +183,7 @@ class WireMockRequestStubStrategy extends BaseWireMockStubStrategy {
case ContentType.JSON:
return new MatchingStrategy(buildJSONRegexpMatch(value), MatchingStrategy.Type.MATCHING)
case ContentType.UNKNOWN:
return new MatchingStrategy(buildGStringRegexpMatch(value), MatchingStrategy.Type.MATCHING)
return new MatchingStrategy(buildGStringRegexpForStubSide(value), MatchingStrategy.Type.MATCHING)
case ContentType.XML:
throw new IllegalStateException("XML pattern matching is not implemented yet")
}

View File

@@ -5,15 +5,15 @@ import groovy.transform.CompileStatic
@CompileStatic
class ExecutionProperty {
private static final String PLACEHOLDER_VALUE = '\\$it'
private static final String PLACEHOLDER_VALUE = '\\$it'
final String executionCommand
final String executionCommand
ExecutionProperty(String executionCommand) {
this.executionCommand = executionCommand
}
ExecutionProperty(String executionCommand) {
this.executionCommand = executionCommand
}
String insertValue(String valueToInsert) {
return executionCommand.replaceAll(PLACEHOLDER_VALUE, valueToInsert)
}
String insertValue(String valueToInsert) {
return executionCommand.replaceAll(PLACEHOLDER_VALUE, valueToInsert)
}
}

View File

@@ -8,16 +8,16 @@ import groovy.transform.ToString
@CompileStatic
class Header extends DslProperty {
String name
String name
Header(String name, DslProperty dslProperty) {
super(dslProperty.clientValue, dslProperty.serverValue)
this.name = name
}
Header(String name, DslProperty dslProperty) {
super(dslProperty.clientValue, dslProperty.serverValue)
this.name = name
}
Header(String name, Object value) {
super(value)
this.name = name
}
Header(String name, Object value) {
super(value)
this.name = name
}
}

View File

@@ -11,24 +11,24 @@ import static io.codearte.accurest.util.ValidateUtils.validateServerValueIsAvail
@CompileStatic
class QueryParameter extends DslProperty {
String name
String name
QueryParameter(String name, DslProperty dslProperty) {
super(dslProperty.clientValue, dslProperty.serverValue)
validateServerValueIsAvailable(dslProperty.serverValue, "Query parameter '$name'")
this.name = name
}
QueryParameter(String name, DslProperty dslProperty) {
super(dslProperty.clientValue, dslProperty.serverValue)
validateServerValueIsAvailable(dslProperty.serverValue, "Query parameter '$name'")
this.name = name
}
QueryParameter(String name, MatchingStrategy matchingStrategy) {
super(matchingStrategy)
validateServerValueIsAvailable(matchingStrategy, "Query parameter '$name'")
this.name = name
}
QueryParameter(String name, MatchingStrategy matchingStrategy) {
super(matchingStrategy)
validateServerValueIsAvailable(matchingStrategy, "Query parameter '$name'")
this.name = name
}
QueryParameter(String name, Object value) {
super(value)
validateServerValueIsAvailable(value, "Query parameter '$name'")
this.name = name
}
QueryParameter(String name, Object value) {
super(value)
validateServerValueIsAvailable(value, "Query parameter '$name'")
this.name = name
}
}

View File

@@ -9,15 +9,15 @@ import groovy.transform.TypeChecked
@TypeChecked
class QueryParameters {
List<QueryParameter> parameters = []
List<QueryParameter> parameters = []
void parameter(Map<String, Object> singleParameter) {
Map.Entry<String, Object> first = singleParameter.entrySet().first()
parameters << new QueryParameter(first?.key, first?.value)
}
void parameter(Map<String, Object> singleParameter) {
Map.Entry<String, Object> first = singleParameter.entrySet().first()
parameters << new QueryParameter(first?.key, first?.value)
}
void parameter(String parameterName, Object parameterValue) {
parameters << new QueryParameter(parameterName, parameterValue)
}
void parameter(String parameterName, Object parameterValue) {
parameters << new QueryParameter(parameterName, parameterValue)
}
}

View File

@@ -9,7 +9,7 @@ class RegexPatterns {
private static final Pattern IP_ADDRESS = Pattern.compile('([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])');
private static final Pattern HOSTNAME_PATTERN = Pattern.compile('((http[s]?|ftp):\\/)\\/?([^:\\/\\s]+)(:[0-9]{1,5})?');
private static final Pattern EMAIL = Pattern.compile('[_]*([a-z0-9]+(\\.|_*)?)+@([a-z][a-z0-9-]+(\\.|-*\\.))+[a-z]{2,6}');
private static final Pattern EMAIL = Pattern.compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}');
private static final Pattern URL = Pattern.compile('((www\\.|(http|https|ftp|news|file)+\\:\\/\\/)[_.a-z0-9-]+\\.[a-z0-9\\/_:@=.+?,##%&~-]*[^.|\\\'|\\# |!|\\(|?|,| |>|<|;|\\)])');
String ipAddress() {

View File

@@ -9,12 +9,12 @@ import groovy.transform.ToString;
@CompileStatic
class UrlPath extends Url {
UrlPath(String path) {
super(path)
}
UrlPath(String path) {
super(path)
}
UrlPath(DslProperty path) {
super(path)
}
UrlPath(DslProperty path) {
super(path)
}
}

View File

@@ -2,14 +2,14 @@ package io.codearte.accurest.util
enum ContentType {
JSON("application/json"),
XML("application/xml"),
UNKNOWN("application/octet-stream")
JSON("application/json"),
XML("application/xml"),
UNKNOWN("application/octet-stream")
final String mimeType
final String mimeType
ContentType(String mimeType) {
this.mimeType = mimeType
}
ContentType(String mimeType) {
this.mimeType = mimeType
}
}

View File

@@ -1,14 +1,13 @@
package io.codearte.accurest.util
import groovy.json.JsonSlurper
import io.codearte.accurest.dsl.internal.DslProperty
import io.codearte.accurest.dsl.internal.ExecutionProperty
import java.util.regex.Pattern
/**
* @author Marcin Grzejszczak
*/
class JsonPathJsonConverter {
class JsonToJsonPathsConverter {
private static final Boolean SERVER_SIDE = false
private static final Boolean CLIENT_SIDE = true
@@ -29,7 +28,7 @@ class JsonPathJsonConverter {
return new JsonPaths()
}
JsonPaths pathsAndValues = [] as Set
Object convertedJson = getClientOrServerSideValues(json, clientSide)
Object convertedJson = MapConverter.getClientOrServerSideValues(json, clientSide)
traverseRecursivelyForKey(convertedJson, ROOT_JSON_PATH_ELEMENT) { String key, Object value ->
if (value instanceof ExecutionProperty) {
return
@@ -40,18 +39,6 @@ class JsonPathJsonConverter {
return pathsAndValues
}
private static Object getClientOrServerSideValues(json, boolean clientSide) {
return MapConverter.transformValues(json) {
boolean dslProp = it instanceof DslProperty
if (dslProp) {
DslProperty dslProperty = ((DslProperty) it)
return clientSide ?
getClientOrServerSideValues(dslProperty.clientValue, clientSide) : getClientOrServerSideValues(dslProperty.serverValue, clientSide)
}
return it
}
}
protected static def traverseRecursively(Class parentType, String key, def value, Closure closure) {
if (value instanceof String && value) {
try {
@@ -142,6 +129,8 @@ class JsonPathJsonConverter {
protected static String compareWith(Object value) {
if (value instanceof Pattern) {
return """=~ /${(value as Pattern).pattern()}/"""
} else if (value instanceof GString) {
return """=~ /${RegexpBuilders.buildGStringRegexpForTestSide(value)}/"""
}
return """== ${potentiallyWrappedWithQuotesValue(value)}"""
}

View File

@@ -43,4 +43,22 @@ class MapConverter {
}
}
static Object getClientOrServerSideValues(json, boolean clientSide) {
return transformValues(json) {
if (it instanceof DslProperty) {
DslProperty dslProperty = ((DslProperty) it)
return clientSide ?
getClientOrServerSideValues(dslProperty.clientValue, clientSide) : getClientOrServerSideValues(dslProperty.serverValue, clientSide)
} else if (it instanceof GString) {
return ContentUtils.extractValue(it , null, {
if (it instanceof DslProperty) {
return clientSide ?
getClientOrServerSideValues((it as DslProperty).clientValue, clientSide) : getClientOrServerSideValues((it as DslProperty).serverValue, clientSide)
}
return it
})
}
return it
}
}
}

View File

@@ -10,29 +10,48 @@ import static org.apache.commons.lang3.StringEscapeUtils.escapeJson
public class RegexpBuilders {
public static String buildGStringRegexpMatch(GString gString) {
public static String buildGStringRegexpForStubSide(GString gString) {
new GStringImpl(
gString.values.collect(this.&buildGStringRegexpMatch) as Object[],
gString.values.collect(this.&buildGStringRegexpForStubSide) as Object[],
gString.strings.collect(this.&escapeSpecialRegexChars) as String[]
)
}
public static String buildGStringRegexpMatch(Pattern pattern) {
public static String buildGStringRegexpForStubSide(Pattern pattern) {
return pattern.pattern()
}
public static String buildGStringRegexpMatch(DslProperty dslProperty) {
return buildGStringRegexpMatch(dslProperty.clientValue)
public static String buildGStringRegexpForStubSide(DslProperty dslProperty) {
return buildGStringRegexpForStubSide(dslProperty.clientValue)
}
public static String buildGStringRegexpMatch(Object o) {
public static String buildGStringRegexpForStubSide(Object o) {
return escapeSpecialRegexChars(o.toString())
}
public static String buildGStringRegexpForTestSide(GString gString) {
new GStringImpl(
gString.values.collect(this.&buildGStringRegexpForTestSide) as Object[],
gString.strings.collect(this.&escapeSpecialRegexChars) as String[]
)
}
public static String buildGStringRegexpForTestSide(Pattern pattern) {
return pattern.pattern()
}
public static String buildGStringRegexpForTestSide(DslProperty dslProperty) {
return buildGStringRegexpForTestSide(dslProperty.clientValue)
}
public static String buildGStringRegexpForTestSide(Object o) {
return o.toString().replaceAll('\\\\', '\\\\\\\\')
}
private final static Pattern SPECIAL_REGEX_CHARS = Pattern.compile('[{}()\\[\\].+*?^$\\\\|]')
private static String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll('\\\\$0')
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll('\\\\\\\\$0')
}
private final static String WS = /\s*/

View File

@@ -12,35 +12,35 @@ import static io.codearte.accurest.dsl.internal.MatchingStrategy.Type.EQUAL_TO
@TypeChecked
class ValidateUtils {
static Object validateServerValueIsAvailable(Object value) {
validateServerValueIsAvailable(value, "Server value")
return value
}
static Object validateServerValueIsAvailable(Object value) {
validateServerValueIsAvailable(value, "Server value")
return value
}
static Object validateServerValueIsAvailable(Object value, String msg) {
validateServerValue(value, msg)
return value
}
static Object validateServerValueIsAvailable(Object value, String msg) {
validateServerValue(value, msg)
return value
}
static void validateServerValue(Pattern pattern, String msg) {
throw new IllegalStateException("$msg can't be a pattern for the server side")
}
static void validateServerValue(Pattern pattern, String msg) {
throw new IllegalStateException("$msg can't be a pattern for the server side")
}
static List ALLOWED_MATCHING_TYPES_ON_SERVER_SIDE = [EQUAL_TO, ABSENT]
static List ALLOWED_MATCHING_TYPES_ON_SERVER_SIDE = [EQUAL_TO, ABSENT]
static void validateServerValue(MatchingStrategy matchingStrategy, String msg) {
if (!ALLOWED_MATCHING_TYPES_ON_SERVER_SIDE.contains(matchingStrategy.type)) {
throw new IllegalStateException("$msg can't be of a matching type: $matchingStrategy.type for the server side")
}
validateServerValue(matchingStrategy.serverValue, msg)
}
static void validateServerValue(MatchingStrategy matchingStrategy, String msg) {
if (!ALLOWED_MATCHING_TYPES_ON_SERVER_SIDE.contains(matchingStrategy.type)) {
throw new IllegalStateException("$msg can't be of a matching type: $matchingStrategy.type for the server side")
}
validateServerValue(matchingStrategy.serverValue, msg)
}
static void validateServerValue(DslProperty value, String msg) {
validateServerValue(value.serverValue, msg)
}
static void validateServerValue(DslProperty value, String msg) {
validateServerValue(value.serverValue, msg)
}
static void validateServerValue(Object value, String msg) {
// OK
}
static void validateServerValue(Object value, String msg) {
// OK
}
}

View File

@@ -1,10 +1,12 @@
package io.codearte.accurest.builder
import io.codearte.accurest.dsl.GroovyDsl
import io.codearte.accurest.dsl.WireMockStubStrategy
import io.codearte.accurest.dsl.WireMockStubVerifier
import spock.lang.Issue
import spock.lang.Specification
class JaxRsClientSpockMethodBuilderSpec extends Specification {
class JaxRsClientSpockMethodBuilderSpec extends Specification implements WireMockStubVerifier {
def "should generate assertions for simple response body"() {
given:
@@ -16,8 +18,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
response {
status 200
body """{
"property1": "a",
"property2": "b"
"property1": "a",
"property2": "b"
}"""
}
}
@@ -28,6 +30,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$[?(@.property2 == 'b')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#79")
@@ -57,6 +61,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$.property2[*][?(@.a == 'sth')]")
blockBuilder.toString().contains("\$.property2[*][?(@.b == 'sthElse')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#82")
@@ -80,6 +86,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
builder.appendTo(blockBuilder)
then:
blockBuilder.toString().contains("entity('{\"items\":[\"HOP\"]}', 'application/json')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#88")
@@ -103,6 +111,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
builder.appendTo(blockBuilder)
then:
blockBuilder.toString().contains("entity('property1=VAL1', 'application/octet-stream')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for array in response body"() {
@@ -116,10 +126,10 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
status 200
body """[
{
"property1": "a"
"property1": "a"
},
{
"property2": "b"
"property2": "b"
}]"""
}
}
@@ -130,6 +140,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[*][?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$[*][?(@.property2 == 'b')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for array inside response body element"() {
@@ -142,10 +154,10 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
response {
status 200
body """{
"property1": [
{ "property2": "test1"},
{ "property3": "test2"}
]
"property1": [
{ "property2": "test1"},
{ "property3": "test2"}
]
}"""
}
}
@@ -156,6 +168,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$.property1[*][?(@.property3 == 'test2')]")
blockBuilder.toString().contains("\$.property1[*][?(@.property2 == 'test1')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for nested objects in response body"() {
@@ -169,8 +183,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
status 200
body '''\
{
"property1": "a",
"property2": {"property3": "b"}
"property1": "a",
"property2": {"property3": "b"}
}
'''
}
@@ -182,6 +196,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$.property2[?(@.property3 == 'b')]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate regex assertions for map objects in response body"() {
@@ -214,6 +230,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property2 =~ /[0-9]{3}/)]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate regex assertions for string objects in response body"() {
@@ -240,6 +258,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property2 =~ /[0-9]{3}/)]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should ignore 'Accept' header and use 'request' method"() {
@@ -262,6 +282,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
builder.appendTo(blockBuilder)
then:
blockBuilder.toString().contains("request('text/plain')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should ignore 'Content-Type' header and use 'entity' method"() {
@@ -288,7 +310,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
blockBuilder.toString().contains("entity('', 'text/plain')")
blockBuilder.toString().contains("header('Timer', '123')")
!blockBuilder.toString().contains("header('Content-Type'")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate a call with an url path and query parameters"() {
@@ -337,6 +360,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
spockTest.contains("queryParam('email', 'bob@email.com'")
spockTest.contains('$[?(@.property2 == \'b\')]')
spockTest.contains('$[?(@.property1 == \'a\')]')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate test for empty body"() {
@@ -358,6 +383,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
def spockTest = blockBuilder.toString()
then:
spockTest.contains("entity('', 'application/octet-stream')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate test for String in response body"() {
@@ -380,6 +407,8 @@ class JaxRsClientSpockMethodBuilderSpec extends Specification {
then:
spockTest.contains('def responseBody = (response.body.asString())')
spockTest.contains('responseBody == "test"')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
}

View File

@@ -1,13 +1,15 @@
package io.codearte.accurest.builder
import io.codearte.accurest.dsl.GroovyDsl
import io.codearte.accurest.dsl.WireMockStubStrategy
import io.codearte.accurest.dsl.WireMockStubVerifier
import spock.lang.Issue
import spock.lang.Specification
/**
* @author Jakub Kubrynski
*/
class MockMvcSpockMethodBuilderSpec extends Specification {
class MockMvcSpockMethodBuilderSpec extends Specification implements WireMockStubVerifier {
def "should generate assertions for simple response body"() {
given:
@@ -19,8 +21,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
response {
status 200
body """{
"property1": "a",
"property2": "b"
"property1": "a",
"property2": "b"
}"""
}
}
@@ -31,6 +33,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$[?(@.property2 == 'b')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#79")
@@ -60,6 +64,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$.property2[*][?(@.a == 'sth')]")
blockBuilder.toString().contains("\$.property2[*][?(@.b == 'sthElse')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#82")
@@ -83,6 +89,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
builder.appendTo(blockBuilder)
then:
blockBuilder.toString().contains(".body('{\"items\":[\"HOP\"]}')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue("#88")
@@ -106,6 +114,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
builder.appendTo(blockBuilder)
then:
blockBuilder.toString().contains(".body('property1=VAL1')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for array in response body"() {
@@ -119,10 +129,10 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
status 200
body """[
{
"property1": "a"
"property1": "a"
},
{
"property2": "b"
"property2": "b"
}]"""
}
}
@@ -133,6 +143,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[*][?(@.property1 == 'a')]")
blockBuilder.toString().contains("\$[*][?(@.property2 == 'b')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for array inside response body element"() {
@@ -145,10 +157,10 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
response {
status 200
body """{
"property1": [
{ "property2": "test1"},
{ "property3": "test2"}
]
"property1": [
{ "property2": "test1"},
{ "property3": "test2"}
]
}"""
}
}
@@ -159,6 +171,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$.property1[*][?(@.property3 == 'test2')]")
blockBuilder.toString().contains("\$.property1[*][?(@.property2 == 'test1')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate assertions for nested objects in response body"() {
@@ -172,8 +186,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
status 200
body '''\
{
"property1": "a",
"property2": {"property3": "b"}
"property1": "a",
"property2": {"property3": "b"}
}
'''
}
@@ -185,6 +199,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$.property2[?(@.property3 == 'b')]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate regex assertions for map objects in response body"() {
@@ -217,6 +233,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property2 =~ /[0-9]{3}/)]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate regex assertions for string objects in response body"() {
@@ -243,6 +261,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
blockBuilder.toString().contains("\$[?(@.property2 =~ /[0-9]{3}/)]")
blockBuilder.toString().contains("\$[?(@.property1 == 'a')]")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate a call with an url path and query parameters"() {
@@ -284,6 +304,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
spockTest.contains('get("/users?limit=10&offset=20&filter=email&sort=name&search=55&age=99&name=Denis.Stepanov&email=bob@email.com")')
spockTest.contains('$[?(@.property2 == \'b\')]')
spockTest.contains('$[?(@.property1 == \'a\')]')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate test for empty body"() {
@@ -305,6 +327,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
def spockTest = blockBuilder.toString()
then:
spockTest.contains(".body('')")
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should generate test for String in response body"() {
@@ -327,6 +351,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
spockTest.contains('def responseBody = (response.body.asString())')
spockTest.contains('responseBody == "test"')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue('113')
@@ -360,6 +386,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
def spockTest = blockBuilder.toString()
then:
spockTest.contains('''response.header('Location') ==~ java.util.regex.Pattern.compile('http://localhost/partners/[0-9]+/users/[0-9]+')''')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
@Issue('115')
@@ -393,6 +421,8 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
def spockTest = blockBuilder.toString()
then:
spockTest.contains('''response.header('Location') ==~ java.util.regex.Pattern.compile('^((http[s]?|ftp):\\/)\\/?([^:\\/\\s]+)(:[0-9]{1,5})?/partners/[0-9]+/users/[0-9]+')''')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should work with more complex stuff and jsonpaths"() {
@@ -428,5 +458,71 @@ class MockMvcSpockMethodBuilderSpec extends Specification {
then:
spockTest.contains('''$.errors[*][?(@.property == 'bank_account_number')]''')
spockTest.contains('''$.errors[*][?(@.message == 'incorrect_format')]''')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should work properly with GString url"() {
given:
GroovyDsl contractDsl = GroovyDsl.make {
request {
method 'PUT'
url "/partners/${value(client(regex('^[0-9]*$')), server('11'))}/agents/11/customers/09665703Z"
headers {
header 'Content-Type': 'application/json'
}
body(
first_name: 'Josef',
)
}
response {
status 422
}
}
MockMvcSpockMethodBodyBuilder builder = new MockMvcSpockMethodBodyBuilder(contractDsl)
BlockBuilder blockBuilder = new BlockBuilder(" ")
when:
builder.appendTo(blockBuilder)
def spockTest = blockBuilder.toString()
then:
spockTest.contains('''/partners/11/agents/11/customers/09665703Z''')
and:
stubMappingIsValidWireMockStub(new WireMockStubStrategy(contractDsl).toWireMockClientStub())
}
def "should resolve properties in GString with regular expression"() {
given:
GroovyDsl contractDsl = GroovyDsl.make {
priority 1
request {
method 'POST'
url '/users/password'
headers {
header 'Content-Type': 'application/json'
}
body(
email: $(client(regex(email())), server('not.existing@user.com')),
callback_url: $(client(regex(hostname())), server('http://partners.com'))
)
}
response {
status 404
headers {
header 'Content-Type': 'application/json'
}
body(
code: 4,
message: "User not found by email = [${value(server(regex(email())), client('not.existing@user.com'))}]"
)
}
}
MockMvcSpockMethodBodyBuilder builder = new MockMvcSpockMethodBodyBuilder(contractDsl)
BlockBuilder blockBuilder = new BlockBuilder(" ")
when:
builder.appendTo(blockBuilder)
def spockTest = blockBuilder.toString()
then:
spockTest.contains('''$[?(@.message =~ /User not found by email = \\\\[[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4}\\\\]/)]''')
}
}

View File

@@ -4,8 +4,9 @@ import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
import io.codearte.accurest.util.AssertionUtil
import spock.lang.Issue
import spock.lang.Specification
class WireMockGroovyDslSpec extends WireMockSpec {
class WireMockGroovyDslSpec extends Specification implements WireMockStubVerifier {
def 'should convert groovy dsl stub to wireMock stub for the client side'() {
given:
@@ -84,17 +85,17 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual('''
{
"request" : {
"url" : "/ingredients",
"method" : "GET",
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.pl.devoxx.aggregatr.v1+json"
}
}
"url" : "/ingredients",
"method" : "GET",
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.pl.devoxx.aggregatr.v1+json"
}
}
},
"response" : {
"status" : 200,
"body" : "{\\"ingredients\\":[{\\"type\\":\\"MALT\\",\\"quantity\\":100},{\\"type\\":\\"WATER\\",\\"quantity\\":200},{\\"type\\":\\"HOP\\",\\"quantity\\":300},{\\"type\\":\\"YIEST\\",\\"quantity\\":400}]}"
"status" : 200,
"body" : "{\\"ingredients\\":[{\\"type\\":\\"MALT\\",\\"quantity\\":100},{\\"type\\":\\"WATER\\",\\"quantity\\":200},{\\"type\\":\\"HOP\\",\\"quantity\\":300},{\\"type\\":\\"YIEST\\",\\"quantity\\":400}]}"
}
}
''', wireMockStub)
@@ -131,24 +132,24 @@ class WireMockGroovyDslSpec extends WireMockSpec {
then:
AssertionUtil.assertThatJsonsAreEqual('''
{
"request": {
"method": "POST",
"headers": {
"Content-Type": {
"equalTo": "application/x-www-form-urlencoded"
}
},
"url": "/ws/payments",
"bodyPatterns": [
{
"matches": "paymentType=INCOMING&transferType=BANK&amount=[0-9]{3}\\\\.[0-9]{2}&bookingDate=[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])"
}
]
},
"response": {
"status": 204,
"body": "{\\"paymentId\\":\\"4\\",\\"foundExistingPayment\\":false}"
}
"request": {
"method": "POST",
"headers": {
"Content-Type": {
"equalTo": "application/x-www-form-urlencoded"
}
},
"url": "/ws/payments",
"bodyPatterns": [
{
"matches": "paymentType=INCOMING&transferType=BANK&amount=[0-9]{3}\\\\.[0-9]{2}&bookingDate=[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])"
}
]
},
"response": {
"status": 204,
"body": "{\\"paymentId\\":\\"4\\",\\"foundExistingPayment\\":false}"
}
}
''', wireMockStub)
and:
@@ -165,13 +166,13 @@ class WireMockGroovyDslSpec extends WireMockSpec {
response {
status 200
body("""\
{
"id": "${value(client('123'), server('321'))}",
"surname": "${value(client('Kowalsky'), server('Lewandowski'))}",
"name": "Jan",
"created" : "${$(client('2014-02-02 12:23:43'), server('2999-09-09 01:23:45'))}"
}
"""
{
"id": "${value(client('123'), server('321'))}",
"surname": "${value(client('Kowalsky'), server('Lewandowski'))}",
"name": "Jan",
"created" : "${$(client('2014-02-02 12:23:43'), server('2999-09-09 01:23:45'))}"
}
"""
)
headers {
header 'Content-Type': 'text/plain'
@@ -184,15 +185,15 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"urlPattern" : "/[0-9]{2}",
"method" : "GET"
"urlPattern" : "/[0-9]{2}",
"method" : "GET"
},
"response" : {
"status" : 200,
"body" : "{\\"created\\":\\"2014-02-02 12:23:43\\",\\"id\\":\\"123\\",\\"name\\":\\"Jan\\",\\"surname\\":\\"Kowalsky\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
"status" : 200,
"body" : "{\\"created\\":\\"2014-02-02 12:23:43\\",\\"id\\":\\"123\\",\\"name\\":\\"Jan\\",\\"surname\\":\\"Kowalsky\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
}
}
'''), wireMockStub)
@@ -215,10 +216,10 @@ class WireMockGroovyDslSpec extends WireMockSpec {
response {
status 200
body("""\
{
"name": "Jan"
}
"""
{
"name": "Jan"
}
"""
)
headers {
header 'Content-Type': 'text/plain'
@@ -231,18 +232,18 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual('''
{
"request" : {
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
} ]
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
}
}
''', wireMockStub)
@@ -279,20 +280,20 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.created == '2014-02-02 12:23:43')]"
}, {
"matchesJsonPath" : "$[?(@.surname == 'Kowalsky')]"
}, {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
}, {
"matchesJsonPath" : "$[?(@.id == '123')]"
} ]
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.created == '2014-02-02 12:23:43')]"
}, {
"matchesJsonPath" : "$[?(@.surname == 'Kowalsky')]"
}, {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
}, {
"matchesJsonPath" : "$[?(@.id == '123')]"
} ]
},
"response" : {
"status" : 200
"status" : 200
}
}
'''), wireMockStub)
@@ -325,19 +326,19 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"url" : "/users",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "customtype/json"
}
}
"url" : "/users",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.name == 'Jan')]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "customtype/json"
}
}
},
"response" : {
"status" : 200
"status" : 200
}
}
'''), json)
@@ -547,10 +548,10 @@ class WireMockGroovyDslSpec extends WireMockSpec {
response {
status 200
body("""\
{
"name": "Jan"
}
"""
{
"name": "Jan"
}
"""
)
headers {
header 'Content-Type': 'text/plain'
@@ -563,18 +564,18 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.personalId =~ /^[0-9]{11}$/)]"
} ]
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.personalId =~ /^[0-9]{11}$/)]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
}
}
'''), wireMockStub)
@@ -589,11 +590,11 @@ class WireMockGroovyDslSpec extends WireMockSpec {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
@@ -618,25 +619,25 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"url" : "/fraudcheck",
"method" : "PUT",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.loanAmount == 123.123)]"
}, {
"matchesJsonPath" : "$[?(@.clientPesel =~ /[0-9]{10}/)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.fraud.v1+json"
}
}
"url" : "/fraudcheck",
"method" : "PUT",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.loanAmount == 123.123)]"
}, {
"matchesJsonPath" : "$[?(@.clientPesel =~ /[0-9]{10}/)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/vnd.fraud.v1+json"
}
}
},
"response" : {
"status" : 200,
"body" : "{\\"fraudCheckStatus\\":\\"OK\\",\\"rejectionReason\\":null}",
"headers" : {
"Content-Type" : "application/vnd.fraud.v1+json"
}
"status" : 200,
"body" : "{\\"fraudCheckStatus\\":\\"OK\\",\\"rejectionReason\\":null}",
"headers" : {
"Content-Type" : "application/vnd.fraud.v1+json"
}
}
}
'''), wireMockStub)
@@ -685,20 +686,20 @@ class WireMockGroovyDslSpec extends WireMockSpec {
"equalTo": "email"
},
"sort": {
"matches": "^[0-9]{10}$"
},
"search": {
"doesNotMatch": "^/[0-9]{2}$"
},
"age": {
"doesNotMatch": "^\\\\w*$"
},
"name": {
"matches": "Denis.*"
},
"credit": {
"absent": true
}
"matches": "^[0-9]{10}$"
},
"search": {
"doesNotMatch": "^/[0-9]{2}$"
},
"age": {
"doesNotMatch": "^\\\\w*$"
},
"name": {
"matches": "Denis.*"
},
"credit": {
"absent": true
}
}
},
"response": {
@@ -966,32 +967,32 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$.errors[*][?(@.propertyName =~ /[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.providerValue == 'Test')]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.providerValue == 'Test')]"
}, {
"matchesJsonPath" : "$[?(@.lastName =~ /.*/)]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.propertyName =~ /[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$[?(@.birthDate =~ /[0-9]{4}-[0-9]{2}-[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$[?(@.personalId =~ /[0-9]{11}/)]"
}, {
"matchesJsonPath" : "$[?(@.firstName =~ /.*/)]"
} ]
"urlPattern" : "/[0-9]{2}",
"method" : "GET",
"bodyPatterns" : [ {
"matchesJsonPath" : "$.errors[*][?(@.propertyName =~ /[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.providerValue == 'Test')]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.providerValue == 'Test')]"
}, {
"matchesJsonPath" : "$[?(@.lastName =~ /.*/)]"
}, {
"matchesJsonPath" : "$.errors[*][?(@.propertyName =~ /[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$[?(@.birthDate =~ /[0-9]{4}-[0-9]{2}-[0-9]{2}/)]"
}, {
"matchesJsonPath" : "$[?(@.personalId =~ /[0-9]{11}/)]"
}, {
"matchesJsonPath" : "$[?(@.firstName =~ /.*/)]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
"status" : 200,
"body" : "{\\"name\\":\\"Jan\\"}",
"headers" : {
"Content-Type" : "text/plain"
}
}
}
'''), wireMockStub)
@@ -1030,28 +1031,28 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"url" : "/reissue-payment-order",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.loanNumber == '999997001')]"
}, {
"matchesJsonPath" : "$[?(@.username =~ /.*/)]"
}, {
"matchesJsonPath" : "$[?(@.amount =~ /[0-9.]+/)]"
}, {
"matchesJsonPath" : "$[?(@.cardId == 1)]"
}, {
"matchesJsonPath" : "$[?(@.currency == 'DKK')]"
}, {
"matchesJsonPath" : "$[?(@.applicationName =~ /.*/)]"
} ]
"url" : "/reissue-payment-order",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.loanNumber == '999997001')]"
}, {
"matchesJsonPath" : "$[?(@.username =~ /.*/)]"
}, {
"matchesJsonPath" : "$[?(@.amount =~ /[0-9.]+/)]"
}, {
"matchesJsonPath" : "$[?(@.cardId == 1)]"
}, {
"matchesJsonPath" : "$[?(@.currency == 'DKK')]"
}, {
"matchesJsonPath" : "$[?(@.applicationName =~ /.*/)]"
} ]
},
"response" : {
"status" : 200,
"body" : "{\\"status\\":\\"OK\\"}",
"headers" : {
"Content-Type" : "application/json"
}
"status" : 200,
"body" : "{\\"status\\":\\"OK\\"}",
"headers" : {
"Content-Type" : "application/json"
}
}
}
'''), json)
@@ -1074,50 +1075,50 @@ class WireMockGroovyDslSpec extends WireMockSpec {
then:
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request": {
"method": "POST",
"url": "test",
"bodyPatterns": [
{
"equalTo": ""
}
]
},
"response": {
"status": 406
}
"request": {
"method": "POST",
"url": "test",
"bodyPatterns": [
{
"equalTo": ""
}
]
},
"response": {
"status": 406
}
}
'''), json)
}
def "should generate stub with priority"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
priority 9
request {
method('POST')
url("test")
}
response {
status 406
}
}
when:
def json = toWireMockClientJsonStub(groovyDsl)
then:
def "should generate stub with priority"() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
priority 9
request {
method('POST')
url("test")
}
response {
status 406
}
}
when:
def json = toWireMockClientJsonStub(groovyDsl)
then:
AssertionUtil.assertThatJsonsAreEqual(('''
{
"priority": 9,
"request": {
"method": "POST",
"url": "test"
},
"response": {
"status": 406
}
}
'''), json)
}
{
"priority": 9,
"request": {
"method": "POST",
"url": "test"
},
"response": {
"status": 406
}
}
'''), json)
}
@Issue("#127")
def 'should use "test" as an alias for "server"'() {
@@ -1139,16 +1140,16 @@ class WireMockGroovyDslSpec extends WireMockSpec {
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.property == 'value')]"
} ]
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.property == 'value')]"
} ]
},
"response" : {
"status" : 200
"status" : 200
}
}
'''), wireMockStub)
'''), wireMockStub)
and:
stubMappingIsValidWireMockStub(wireMockStub)
}
@@ -1189,6 +1190,109 @@ class WireMockGroovyDslSpec extends WireMockSpec {
stubMappingIsValidWireMockStub(wireMockStub)
}
def 'should generate stub properly resolving GString with regular expression'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
priority 1
request {
method 'POST'
url '/users/password'
headers {
header 'Content-Type': 'application/json'
}
body(
email: $(client(regex(email())), server('not.existing@user.com')),
callback_url: $(client(regex(hostname())), server('http://partners.com'))
)
}
response {
status 404
headers {
header 'Content-Type': 'application/json'
}
body(
code: 4,
message: "User not found by email = [${value(server(regex(email())), client('not.existing@user.com'))}]"
)
}
}
when:
String wireMockStub = new WireMockStubStrategy(groovyDsl).toWireMockClientStub()
then:
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"url" : "/users/password",
"method" : "POST",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.callback_url =~ /((http[s]?|ftp):\\\\/)\\\\/?([^:\\\\/\\\\s]+)(:[0-9]{1,5})?/)]"
}, {
"matchesJsonPath" : "$[?(@.email =~ /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,4}/)]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
}
},
"response" : {
"status" : 404,
"body" : "{\\"code\\":4,\\"message\\":\\"User not found by email = [not.existing@user.com]\\"}",
"headers" : {
"Content-Type" : "application/json"
}
},
"priority" : 1
}
'''), wireMockStub)
and:
stubMappingIsValidWireMockStub(wireMockStub)
}
def 'should generate stub properly resolving GString with regular expression in url'() {
given:
GroovyDsl groovyDsl = GroovyDsl.make {
request {
method 'PUT'
url "/partners/${value(client(regex('^[0-9]*$')), server('11'))}/agents/11/customers/09665703Z"
headers {
header 'Content-Type': 'application/json'
}
body(
first_name: 'Josef',
)
}
response {
status 422
}
}
when:
String wireMockStub = new WireMockStubStrategy(groovyDsl).toWireMockClientStub()
then:
AssertionUtil.assertThatJsonsAreEqual(('''
{
"request" : {
"urlPattern" : "/partners/^[0-9]*$/agents/11/customers/09665703Z",
"method" : "PUT",
"bodyPatterns" : [ {
"matchesJsonPath" : "$[?(@.first_name == 'Josef')]"
} ],
"headers" : {
"Content-Type" : {
"equalTo" : "application/json"
}
}
},
"response" : {
"status" : 422
}
}
'''), wireMockStub)
and:
stubMappingIsValidWireMockStub(wireMockStub)
}
String toJsonString(value) {
new JsonBuilder(value).toPrettyString()
}

View File

@@ -1,17 +0,0 @@
package io.codearte.accurest.dsl
import com.github.tomakehurst.wiremock.stubbing.StubMapping
import spock.lang.Specification
import java.util.regex.Pattern
abstract class WireMockSpec extends Specification {
void stubMappingIsValidWireMockStub(String mappingDefinition) {
StubMapping stubMapping = StubMapping.buildFrom(mappingDefinition)
stubMapping.request.bodyPatterns.findAll { it.matches }.every {
Pattern.compile(it.matches)
}
}
}

View File

@@ -0,0 +1,16 @@
package io.codearte.accurest.dsl
import com.github.tomakehurst.wiremock.stubbing.StubMapping
import java.util.regex.Pattern
trait WireMockStubVerifier {
void stubMappingIsValidWireMockStub(String mappingDefinition) {
StubMapping stubMapping = StubMapping.buildFrom(mappingDefinition)
stubMapping.request.bodyPatterns.findAll { it.matches }.every {
Pattern.compile(it.matches)
}
assert !mappingDefinition.contains('DslProperty')
}
}

View File

@@ -4,16 +4,16 @@ import spock.lang.Specification
class ExecutionPropertySpec extends Specification {
def 'should insert passed value in place of $it placeholder'() {
given:
String commandToExecute = 'commandToExecute($it)'
ExecutionProperty executionProperty = new ExecutionProperty(commandToExecute)
and:
String valueToInsert = 'someObject.itsValue'
when:
String commandWithInsertedValue = executionProperty.insertValue(valueToInsert)
then:
'commandToExecute(someObject.itsValue)' == commandWithInsertedValue
}
def 'should insert passed value in place of $it placeholder'() {
given:
String commandToExecute = 'commandToExecute($it)'
ExecutionProperty executionProperty = new ExecutionProperty(commandToExecute)
and:
String valueToInsert = 'someObject.itsValue'
when:
String commandWithInsertedValue = executionProperty.insertValue(valueToInsert)
then:
'commandToExecute(someObject.itsValue)' == commandWithInsertedValue
}
}

View File

@@ -11,12 +11,12 @@ import spock.lang.Unroll
import java.util.regex.Pattern
class JsonPathJsonConverterSpec extends Specification {
class JsonToJsonPathsConverterSpec extends Specification {
@Unroll
def 'should convert a json with list as root to a map of path to value'() {
when:
JsonPaths pathAndValues = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
JsonPaths pathAndValues = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
then:
pathAndValues['''$[*].some.nested[?(@.json == 'with value')]'''] == 'with value'
pathAndValues['''$[*].some.nested[?(@.anothervalue == 4)]'''] == 4
@@ -94,7 +94,7 @@ class JsonPathJsonConverterSpec extends Specification {
}
'''
when:
JsonPaths pathAndValues = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
JsonPaths pathAndValues = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
then:
pathAndValues['''$.some.nested[?(@.json == 'with value')]'''] == 'with value'
pathAndValues['''$.some.nested[?(@.anothervalue == 4)]'''] == 4
@@ -112,7 +112,7 @@ class JsonPathJsonConverterSpec extends Specification {
}
'''
when:
JsonPaths pathAndValues = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
JsonPaths pathAndValues = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
then:
pathAndValues['''$.items[?(@ == 'HOP')]'''] == 'HOP'
and:
@@ -131,7 +131,7 @@ class JsonPathJsonConverterSpec extends Specification {
}
'''
when:
JsonPaths pathAndValues = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
JsonPaths pathAndValues = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(new JsonSlurper().parseText(json))
then:
pathAndValues['''$.errors[*][?(@.property == 'email')]'''] == 'email'
pathAndValues['''$.errors[*][?(@.message == 'inconsistent value')]'''] == 'inconsistent value'
@@ -175,7 +175,7 @@ class JsonPathJsonConverterSpec extends Specification {
]
]
when:
JsonPaths pathAndValues = JsonPathJsonConverter.transformToJsonPathWithTestsSideValues(json)
JsonPaths pathAndValues = JsonToJsonPathsConverter.transformToJsonPathWithTestsSideValues(json)
then:
pathAndValues['''$[*].some.nested[?(@.json == 'with value')]'''] == 'with value'
pathAndValues['''$[*].some.nested[?(@.anothervalue == 4)]'''] == 4

View File

@@ -5,23 +5,23 @@ io.codearte.accurest.dsl.GroovyDsl.make {
header 'Content-Type': 'application/json'
}
body("""\
{
"name": "Jan",
"id": "${value(client('abc'), server('def'))}",
}
"""
{
"name": "Jan",
"id": "${value(client('abc'), server('def'))}",
}
"""
)
url $(client('/[0-9]{2}'), server('/12'))
}
response {
status 200
body("""\
{
"name": "Jan",
"id": "${value(client('123'), server('321'))}",
{
"name": "Jan",
"id": "${value(client('123'), server('321'))}",
"surname": "${value(client('Kowalsky'), server('$checkIfSurnameValid($value)'))}"
}
"""
}
"""
)
headers {
header 'Content-Type': 'text/plain'

View File

@@ -1,71 +1,71 @@
buildscript {
repositories {
mavenCentral()
}
repositories {
mavenCentral()
}
}
apply plugin: 'groovy'
apply plugin: 'accurest'
ext {
contractsDir = file("${project.rootDir}/repository/mappings/com/ofg/twitter-places-analyzer")
wireMockStubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
wireMockStubsOutputDir = new File(wireMockStubsOutputDirRoot, 'repository/mappings/')
contractsDir = file("${project.rootDir}/repository/mappings/com/ofg/twitter-places-analyzer")
wireMockStubsOutputDirRoot = file("${project.buildDir}/production/${project.name}-stubs/")
wireMockStubsOutputDir = new File(wireMockStubsOutputDirRoot, 'repository/mappings/')
}
configurations {
all {
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
// To prevent an accidental usage of groovy-all.jar and groovy.jar in different versions
// all modularized Groovy jars are replaced with groovy-all.jar by default.
if (details.requested.group == 'org.codehaus.groovy' && details.requested.name != "groovy-all") {
details.useTarget("org.codehaus.groovy:groovy-all:${details.requested.version}")
}
}
}
}
all {
resolutionStrategy {
eachDependency { DependencyResolveDetails details ->
// To prevent an accidental usage of groovy-all.jar and groovy.jar in different versions
// all modularized Groovy jars are replaced with groovy-all.jar by default.
if (details.requested.group == 'org.codehaus.groovy' && details.requested.name != "groovy-all") {
details.useTarget("org.codehaus.groovy:groovy-all:${details.requested.version}")
}
}
}
}
}
repositories {
mavenCentral()
mavenCentral()
}
dependencies {
compile "org.springframework:spring-web:$springVersion"
compile "org.springframework:spring-context-support:$springVersion"
compile "org.codehaus.groovy:groovy-all:2.4.1"
compile 'com.fasterxml.jackson.core:jackson-databind:2.4.4'
compile "org.codehaus.jackson:jackson-mapper-asl:$jacksonMapper"
compile "org.codehaus.jackson:jackson-core-asl:$jacksonMapper"
compile 'com.jayway.jsonpath:json-path-assert:1.2.0'
compile "org.springframework:spring-web:$springVersion"
compile "org.springframework:spring-context-support:$springVersion"
compile "org.codehaus.groovy:groovy-all:2.4.1"
compile 'com.fasterxml.jackson.core:jackson-databind:2.4.4'
compile "org.codehaus.jackson:jackson-mapper-asl:$jacksonMapper"
compile "org.codehaus.jackson:jackson-core-asl:$jacksonMapper"
compile 'com.jayway.jsonpath:json-path-assert:1.2.0'
testCompile('com.github.tomakehurst:wiremock:1.53') {
exclude group: 'org.mortbay.jetty', module: 'servlet-api'
}
testCompile "org.spockframework:spock-spring:0.7-groovy-2.0"
testCompile "com.jayway.restassured:rest-assured:$restAssuredVersion"
testCompile "com.jayway.restassured:spring-mock-mvc:$restAssuredVersion"
testCompile "javax.servlet:javax.servlet-api:3.0.1" //provided
testCompile "ch.qos.logback:logback-classic:1.1.2"
testCompile('com.github.tomakehurst:wiremock:1.53') {
exclude group: 'org.mortbay.jetty', module: 'servlet-api'
}
testCompile "org.spockframework:spock-spring:0.7-groovy-2.0"
testCompile "com.jayway.restassured:rest-assured:$restAssuredVersion"
testCompile "com.jayway.restassured:spring-mock-mvc:$restAssuredVersion"
testCompile "javax.servlet:javax.servlet-api:3.0.1" //provided
testCompile "ch.qos.logback:logback-classic:1.1.2"
}
accurest {
baseClassForTests = 'com.ofg.twitter.places.BaseMockMvcSpec'
basePackageForTests = 'accurest'
contractsDslDir = contractsDir
// generatedTestSourcesDir = file("${project.rootDir}/src/test/groovy/")
stubsOutputDir = wireMockStubsOutputDir
baseClassForTests = 'com.ofg.twitter.places.BaseMockMvcSpec'
basePackageForTests = 'accurest'
contractsDslDir = contractsDir
// generatedTestSourcesDir = file("${project.rootDir}/src/test/groovy/")
stubsOutputDir = wireMockStubsOutputDir
}
//TODO: Put it into the plugin
task createWireMockStubsOutputDir << {
wireMockStubsOutputDir.mkdirs()
wireMockStubsOutputDir.mkdirs()
}
generateWireMockClientStubs.dependsOn { createWireMockStubsOutputDir }
generateAccurest.dependsOn generateWireMockClientStubs
wrapper {
gradleVersion '2.2.1'
gradleVersion '2.2.1'
}

View File

@@ -1,18 +1,18 @@
io.codearte.accurest.dsl.GroovyDsl.make {
priority 2
request {
method 'PUT'
url '/api/12'
headers {
header 'Content-Type': 'application/json'
}
body '''\
[{
"text": "Gonna see you at Warsaw"
}]
request {
method 'PUT'
url '/api/12'
headers {
header 'Content-Type': 'application/json'
}
body '''\
[{
"text": "Gonna see you at Warsaw"
}]
'''
}
response {
status 200
}
}
response {
status 200
}
}

View File

@@ -1,21 +1,21 @@
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method 'PUT'
url $(client(regex('^/api/[0-9]{2}$')), server('/api/12'))
headers {
header 'Content-Type': 'application/json'
}
body '''\
[{
"text": "Gonna see you at Warsaw"
}]
request {
method 'PUT'
url $(client(regex('^/api/[0-9]{2}$')), server('/api/12'))
headers {
header 'Content-Type': 'application/json'
}
body '''\
[{
"text": "Gonna see you at Warsaw"
}]
'''
}
response {
body (
path: $(client('/api/12'), server(regex('^/api/[0-9]{2}$'))),
correlationId: $(client('1223456'), server(execute('isProperCorrelationId($it)')))
)
status 200
}
}
response {
body (
path: $(client('/api/12'), server(regex('^/api/[0-9]{2}$'))),
correlationId: $(client('1223456'), server(execute('isProperCorrelationId($it)')))
)
status 200
}
}

View File

@@ -16,21 +16,21 @@ import static org.springframework.web.bind.annotation.RequestMethod.PUT
@TypeChecked
class PairIdController {
@RequestMapping(
value = '{pairId}',
method = PUT,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
String getPlacesFromTweets(@PathVariable long pairId, @RequestBody List<com.ofg.twitter.place.Tweet> tweets) {
log.info("Inside PairIdController, doing very important logic")
if (tweets?.text != ["Gonna see you at Warsaw"]) {
throw new IllegalArgumentException("Wrong text in tweet: ${tweets?.text}")
}
return """
{
"path" : "/api/$pairId",
"correlationId" : 123456
}
"""
}
@RequestMapping(
value = '{pairId}',
method = PUT,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
String getPlacesFromTweets(@PathVariable long pairId, @RequestBody List<com.ofg.twitter.place.Tweet> tweets) {
log.info("Inside PairIdController, doing very important logic")
if (tweets?.text != ["Gonna see you at Warsaw"]) {
throw new IllegalArgumentException("Wrong text in tweet: ${tweets?.text}")
}
return """
{
"path" : "/api/$pairId",
"correlationId" : 123456
}
"""
}
}

View File

@@ -1,13 +1,13 @@
package com.ofg.twitter.place;
public class Tweet {
private String text;
private String text;
public String getText() {
return text;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@@ -11,13 +11,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
class AcceptanceSpec extends Specification {
def "should have controller up and running"() {
given:
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new PairIdController()).build()
expect:
mockMvc.perform(put("/api/${1}").
contentType(MediaType.APPLICATION_JSON).
content("""[{"text":"Gonna see you at Warsaw"}]""")).
andExpect(status().isOk())
}
def "should have controller up and running"() {
given:
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new PairIdController()).build()
expect:
mockMvc.perform(put("/api/${1}").
contentType(MediaType.APPLICATION_JSON).
content("""[{"text":"Gonna see you at Warsaw"}]""")).
andExpect(status().isOk())
}
}

View File

@@ -6,11 +6,11 @@ import spock.lang.Specification
abstract class BaseMockMvcSpec extends Specification {
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
}
def setup() {
RestAssuredMockMvc.standaloneSetup(new PairIdController())
}
void isProperCorrelationId(Integer correlationId) {
assert correlationId == 123456
}
void isProperCorrelationId(Integer correlationId) {
assert correlationId == 123456
}
}

View File

@@ -1,27 +1,27 @@
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method """PUT"""
url """/fraudcheck"""
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header("""Content-Type""", """application/vnd.fraud.v1+json""")
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(client('FRAUD'), server(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
request {
method """PUT"""
url """/fraudcheck"""
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header("""Content-Type""", """application/vnd.fraud.v1+json""")
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(client('FRAUD'), server(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
}""")
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
}

View File

@@ -1,28 +1,28 @@
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body(
fraudCheckStatus: "OK",
rejectionReason: $(client(null), server(execute('assertThatRejectionReasonIsNull($it)')))
)
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body(
fraudCheckStatus: "OK",
rejectionReason: $(client(null), server(execute('assertThatRejectionReasonIsNull($it)')))
)
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
}

View File

@@ -5,9 +5,9 @@ import java.util.Set;
public class FraudRestApplication extends javax.ws.rs.core.Application {
@Override
public Set<Class<?>> getClasses() {
return Collections.<Class<?>>singleton(FraudDetectionController.class);
}
@Override
public Set<Class<?>> getClasses() {
return Collections.<Class<?>>singleton(FraudDetectionController.class);
}
}

View File

@@ -1,23 +1,23 @@
{
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "\\s*\\{\\s*\"clientPesel\"\\s*:\\s*\"?[0-9]{10}\"?\\s*,\\s*\"loanAmount\"\\s*:\\s*\"?99999\"?\\s*\\}\\s*"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}"
}
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "\\s*\\{\\s*\"clientPesel\"\\s*:\\s*\"?[0-9]{10}\"?\\s*,\\s*\"loanAmount\"\\s*:\\s*\"?99999\"?\\s*\\}\\s*"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}"
}
}

View File

@@ -1,23 +1,23 @@
{
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "\\s*\\{\\s*\"clientPesel\"\\s*:\\s*\"?[0-9]{10}\"?\\s*,\\s*\"loanAmount\"\\s*:\\s*\"?123.123\"?\\s*\\}\\s*"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"OK\",\"rejectionReason\":null}"
}
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "\\s*\\{\\s*\"clientPesel\"\\s*:\\s*\"?[0-9]{10}\"?\\s*,\\s*\"loanAmount\"\\s*:\\s*\"?123.123\"?\\s*\\}\\s*"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"OK\",\"rejectionReason\":null}"
}
}

View File

@@ -1,27 +1,27 @@
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method """PUT"""
url """/fraudcheck"""
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header("""Content-Type""", """application/vnd.fraud.v1+json""")
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(client('FRAUD'), server(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
request {
method """PUT"""
url """/fraudcheck"""
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":99999}
"""
)
headers {
header("""Content-Type""", """application/vnd.fraud.v1+json""")
}
}
response {
status 200
body( """{
"fraudCheckStatus": "${value(client('FRAUD'), server(regex('[A-Z]{5}')))}",
"rejectionReason": "Amount too high"
}""")
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
}

View File

@@ -1,28 +1,28 @@
io.codearte.accurest.dsl.GroovyDsl.make {
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body(
fraudCheckStatus: "OK",
rejectionReason: $(client(null), server(execute('assertThatRejectionReasonIsNull($it)')))
)
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
request {
method 'PUT'
url '/fraudcheck'
body("""
{
"clientPesel":"${value(client(regex('[0-9]{10}')), server('1234567890'))}",
"loanAmount":123.123
}
"""
)
headers {
header('Content-Type', 'application/vnd.fraud.v1+json')
}
}
response {
status 200
body(
fraudCheckStatus: "OK",
rejectionReason: $(client(null), server(execute('assertThatRejectionReasonIsNull($it)')))
)
headers {
header('Content-Type': 'application/vnd.fraud.v1+json')
}
}
}

View File

@@ -1,23 +1,23 @@
{
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "{\"clientPesel\":\"[0-9]{10}\",\"loanAmount\":\"99999\"}"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}"
}
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "{\"clientPesel\":\"[0-9]{10}\",\"loanAmount\":\"99999\"}"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"FRAUD\",\"rejectionReason\":\"Amount too high\"}"
}
}

View File

@@ -1,23 +1,23 @@
{
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "{\"clientPesel\":\"[0-9]{10}\",\"loanAmount\":\"123.123\"}"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"OK\",\"rejectionReason\":null}"
}
"request": {
"method": "PUT",
"headers": {
"Content-Type": {
"equalTo": "application/vnd.fraud.v1+json"
}
},
"url": "/fraudcheck",
"bodyPatterns": [
{
"matches": "{\"clientPesel\":\"[0-9]{10}\",\"loanAmount\":\"123.123\"}"
}
]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/vnd.fraud.v1+json"
},
"body": "{\"fraudCheckStatus\":\"OK\",\"rejectionReason\":null}"
}
}

View File

@@ -37,3 +37,4 @@ modifyPom {
}
uploadArchives.dependsOn { check }