Merge branch '3.0.x' into 3.1.x

This commit is contained in:
Marcin Grzejszczak
2022-06-20 17:00:02 +02:00
13 changed files with 447 additions and 75 deletions

View File

@@ -1134,4 +1134,64 @@ class DslToWireMockClientConverterSpec extends Specification {
return stubMapping
}
@Issue("1656")
def "should convert DSL file to WireMock JSON with array"() {
given:
def converter = new DslToWireMockClientConverter()
and:
File file = tmpFolder.newFile("dsl1656.groovy")
file.write('''
org.springframework.cloud.contract.spec.Contract.make {
request {
method "GET"
url "/api/foo/61923376"
headers {
accept 'application/json'
}
}
response {
status OK()
headers {
contentType(applicationJson())
}
//language=JSON
body(
"""
[
813146,
814952,
813102,
813282
]
"""
)
}
}
''')
when:
String json = converter.convertContents("Test", new ContractMetadata(file.toPath(), false, 0, null,
ContractVerifierDslConverter.convertAsCollection(new File("/"), file))).values().first()
then:
JSONAssert.assertEquals('''
{
"request" : {
"url" : "/api/foo/61923376",
"method" : "GET",
"headers" : {
"Accept" : {
"matches" : "application/json.*"
}
}
},
"response" : {
"status" : 200,
"body" : "[813146,814952,813102,813282]",
"headers" : {
"Content-Type" : "application/json"
},
"transformers" : [ "response-template", "spring-cloud-contract" ]
}
}''', json, false)
}
}

View File

@@ -43,7 +43,9 @@ class RestAssuredGiven implements Given, BodyMethodVisitor, RestAssuredAcceptor
.addAll(Arrays.asList(new MockMvcHeadersGiven(blockBuilder), new MockMvcCookiesGiven(blockBuilder),
new MockMvcBodyGiven(blockBuilder, generatedClassMetaData, bodyParser),
new JavaMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
new SpockMockMvcMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser)));
new SpockMockMvcMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
new SpockExplicitMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser),
new SpockWebTestClientMultipartGiven(blockBuilder, generatedClassMetaData, bodyParser)));
}
@Override

View File

@@ -0,0 +1,68 @@
package org.springframework.cloud.contract.verifier.builder;
import java.util.Map;
import org.springframework.cloud.contract.spec.internal.NamedProperty;
import org.springframework.cloud.contract.spec.internal.Request;
import org.springframework.cloud.contract.verifier.config.TestFramework;
import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;
import org.springframework.cloud.contract.verifier.util.ContentUtils;
import org.springframework.cloud.contract.verifier.util.MapConverter;
class SpockExplicitMultipartGiven implements Given, ExplicitAcceptor {
private final BlockBuilder blockBuilder;
private final GeneratedClassMetaData generatedClassMetaData;
private final BodyReader bodyReader;
private final BodyParser bodyParser;
SpockExplicitMultipartGiven(BlockBuilder blockBuilder, GeneratedClassMetaData generatedClassMetaData,
BodyParser bodyParser) {
this.blockBuilder = blockBuilder;
this.bodyReader = new BodyReader(generatedClassMetaData);
this.bodyParser = bodyParser;
this.generatedClassMetaData = generatedClassMetaData;
}
@Override
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
getMultipartParameters(metadata).entrySet()
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
return this;
}
private String getMultipartParameterLine(SingleContractMetadata metadata, Map.Entry<String, Object> parameter) {
if (parameter.getValue() instanceof NamedProperty) {
return ".multiPart(" + getMultipartFileParameterContent(metadata, parameter.getKey(),
(NamedProperty) parameter.getValue()) + ")";
}
return getParameterString(parameter);
}
@SuppressWarnings("unchecked")
private Map<String, Object> getMultipartParameters(SingleContractMetadata metadata) {
return (Map<String, Object>) metadata.getContract().getRequest().getMultipart().getServerValue();
}
private String getMultipartFileParameterContent(SingleContractMetadata metadata, String propertyName,
NamedProperty propertyValue) {
return ContentUtils.getGroovyMultipartFileParameterContent(propertyName, propertyValue,
fileProp -> this.bodyReader.readBytesFromFileString(metadata, fileProp, CommunicationType.REQUEST));
}
private String getParameterString(Map.Entry<String, Object> parameter) {
return ".param(" + this.bodyParser.quotedShortText(parameter.getKey()) + ", "
+ this.bodyParser.quotedShortText(MapConverter.getTestSideValuesForNonBody(parameter.getValue())) + ")";
}
@Override
public boolean accept(SingleContractMetadata metadata) {
Request request = metadata.getContract().getRequest();
return request != null && request.getMultipart() != null && acceptType(this.generatedClassMetaData)
&& this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.SPOCK;
}
}

View File

@@ -0,0 +1,68 @@
package org.springframework.cloud.contract.verifier.builder;
import java.util.Map;
import org.springframework.cloud.contract.spec.internal.NamedProperty;
import org.springframework.cloud.contract.spec.internal.Request;
import org.springframework.cloud.contract.verifier.config.TestFramework;
import org.springframework.cloud.contract.verifier.file.SingleContractMetadata;
import org.springframework.cloud.contract.verifier.util.ContentUtils;
import org.springframework.cloud.contract.verifier.util.MapConverter;
public class SpockWebTestClientMultipartGiven implements Given, WebTestClientAcceptor {
private final BlockBuilder blockBuilder;
private final GeneratedClassMetaData generatedClassMetaData;
private final BodyReader bodyReader;
private final BodyParser bodyParser;
SpockWebTestClientMultipartGiven(BlockBuilder blockBuilder, GeneratedClassMetaData generatedClassMetaData,
BodyParser bodyParser) {
this.blockBuilder = blockBuilder;
this.bodyReader = new BodyReader(generatedClassMetaData);
this.bodyParser = bodyParser;
this.generatedClassMetaData = generatedClassMetaData;
}
@Override
public MethodVisitor<Given> apply(SingleContractMetadata metadata) {
getMultipartParameters(metadata).entrySet()
.forEach(entry -> this.blockBuilder.addLine(getMultipartParameterLine(metadata, entry)));
return this;
}
private String getMultipartParameterLine(SingleContractMetadata metadata, Map.Entry<String, Object> parameter) {
if (parameter.getValue() instanceof NamedProperty) {
return ".multiPart(" + getMultipartFileParameterContent(metadata, parameter.getKey(),
(NamedProperty) parameter.getValue()) + ")";
}
return getParameterString(parameter);
}
@SuppressWarnings("unchecked")
private Map<String, Object> getMultipartParameters(SingleContractMetadata metadata) {
return (Map<String, Object>) metadata.getContract().getRequest().getMultipart().getServerValue();
}
private String getMultipartFileParameterContent(SingleContractMetadata metadata, String propertyName,
NamedProperty propertyValue) {
return ContentUtils.getGroovyMultipartFileParameterContent(propertyName, propertyValue,
fileProp -> this.bodyReader.readBytesFromFileString(metadata, fileProp, CommunicationType.REQUEST));
}
private String getParameterString(Map.Entry<String, Object> parameter) {
return ".param(" + this.bodyParser.quotedShortText(parameter.getKey()) + ", "
+ this.bodyParser.quotedShortText(MapConverter.getTestSideValuesForNonBody(parameter.getValue())) + ")";
}
@Override
public boolean accept(SingleContractMetadata metadata) {
Request request = metadata.getContract().getRequest();
return request != null && request.getMultipart() != null && acceptType(this.generatedClassMetaData)
&& this.generatedClassMetaData.configProperties.getTestFramework() == TestFramework.SPOCK;
}
}

View File

@@ -95,8 +95,15 @@ abstract class BaseWireMockStubStrategy {
/**
* For the given {@link ContentType} returns the Boolean version of the body.
*/
String parseBody(Boolean value, ContentType contentType) {
return value.toString();
Boolean parseBody(Boolean value, ContentType contentType) {
return value;
}
/**
* For the given {@link ContentType} returns the Number version of the body.
*/
Number parseBody(Number value, ContentType contentType) {
return value;
}
/**
@@ -156,6 +163,15 @@ abstract class BaseWireMockStubStrategy {
else if (l instanceof List) {
result.add(parseBody((List<?>) l, contentType));
}
else if (l instanceof Boolean) {
result.add(parseBody((Boolean) l, contentType));
}
else if (l instanceof Number) {
result.add(parseBody((Number) l, contentType));
}
else if (l == null) {
result.add(null);
}
else {
result.add(parseBody(l, contentType));
}

View File

@@ -1659,7 +1659,7 @@ World.'''"""
}
@Issue('180')
@Issue(['180', '1667'])
def 'should generate proper test code when having multipart parameters with named as map with #methodBuilderName'() {
given:
org.springframework.cloud.contract.spec.Contract contractDsl = org.springframework.cloud.contract.spec.Contract.make {
@@ -1699,6 +1699,15 @@ World.'''"""
"testng" | { configProperties.testFramework = TestFramework.TESTNG }
"mockmvc" | { configProperties.testMode = TestMode.MOCKMVC }
"webclient" | { configProperties.testMode = TestMode.WEBTESTCLIENT }
"spock-mockmvc" | {
configProperties.testFramework = TestFramework.SPOCK; configProperties.testMode = TestMode.MOCKMVC
}
"spock-explicit" | {
configProperties.testFramework = TestFramework.SPOCK; configProperties.testMode = TestMode.EXPLICIT
}
"spock-webclient" | {
configProperties.testFramework = TestFramework.SPOCK; configProperties.testMode = TestMode.WEBTESTCLIENT
}
}
@Issue('#216')

View File

@@ -32,68 +32,109 @@ class WireMockResponseStubStrategySpec extends Specification {
def "should not quote floating point numbers"() {
given:
def irrelevantStatus = 200
def contract = Contract.make {
request {
method GET()
url "/foo"
}
response {
status irrelevantStatus
body([
value: 1.5
])
}
def irrelevantStatus = 200
def contract = Contract.make {
request {
method GET()
url "/foo"
}
response {
status irrelevantStatus
body([
value: 1.5
])
}
}
when:
SingleContractMetadata metadata = Stub()
metadata.evaluatedOutputStubContentType >> ContentType.JSON
def subject = new WireMockResponseStubStrategy(contract, metadata) {
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
SingleContractMetadata metadata = Stub()
metadata.evaluatedOutputStubContentType >> ContentType.JSON
def subject = new WireMockResponseStubStrategy(contract, metadata) {
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
def content = subject.buildClientResponseContent()
}
def content = subject.buildClientResponseContent()
then:
'{"value":1.5}' == content.body
'{"value":1.5}' == content.body
}
@Issue("#468")
def "should not quote generated numbers"() {
given:
def irrelevantStatus = 200
def contract = Contract.make {
request {
method GET()
url "/foo"
}
response {
status irrelevantStatus
body([
number : anyNumber(),
integer : anyInteger(),
positiveInt: anyPositiveInt(),
double : anyDouble(),
])
}
def irrelevantStatus = 200
def contract = Contract.make {
request {
method GET()
url "/foo"
}
response {
status irrelevantStatus
body([
number : anyNumber(),
integer : anyInteger(),
positiveInt: anyPositiveInt(),
double : anyDouble(),
])
}
}
when:
SingleContractMetadata metadata = Stub()
metadata.evaluatedOutputStubContentType >> ContentType.JSON
def subject = new WireMockResponseStubStrategy(contract, metadata) {
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
SingleContractMetadata metadata = Stub()
metadata.evaluatedOutputStubContentType >> ContentType.JSON
def subject = new WireMockResponseStubStrategy(contract, metadata) {
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
def content = subject.buildClientResponseContent()
}
def content = subject.buildClientResponseContent()
then:
Map body = new JsonSlurper().parseText(content.body) as Map
assert body.get("number") instanceof Number
assert body.get("integer") instanceof Integer
assert body.get("positiveInt") instanceof Integer
assert body.get("double") instanceof BigDecimal
Map body = new JsonSlurper().parseText(content.body) as Map
assert body.get("number") instanceof Number
assert body.get("integer") instanceof Integer
assert body.get("positiveInt") instanceof Integer
assert body.get("double") instanceof BigDecimal
}
@Issue("#1656")
def "should not quote numbers, booleans, and null inside arrays"() {
given:
def irrelevantStatus = 200
def contract = Contract.make {
request {
method GET()
url "/foo"
}
response {
status irrelevantStatus
body([
anyPositiveInt(),
anyInteger(),
true,
anyNumber(),
null,
"value"
])
}
}
when:
SingleContractMetadata metadata = Stub()
metadata.evaluatedOutputStubContentType >> ContentType.JSON
def subject = new WireMockResponseStubStrategy(contract, metadata) {
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
}
def content = subject.buildClientResponseContent()
then:
List body = new JsonSlurper().parseText(content.body) as List
assert body.getAt(0) instanceof Integer
assert body.getAt(1) instanceof Integer
assert body.getAt(2) instanceof Boolean
assert body.getAt(3) instanceof Number
assert body.getAt(4) == null
assert body.getAt(5) instanceof String
}
@Shared def patternsContract = Contract.make {
@@ -246,29 +287,29 @@ class WireMockResponseStubStrategySpec extends Specification {
def "should convert patterns to proper value"() {
when:
def subject = new WireMockRequestStubStrategy(patternsContract, null) {
@Override
protected ContentType contentType(SingleContractMetadata singleContractMetadata) {
return ContentType.JSON
}
def subject = new WireMockRequestStubStrategy(patternsContract, null) {
@Override
protected ContentType contentType(SingleContractMetadata singleContractMetadata) {
return ContentType.JSON
}
subject.buildClientRequestContent()
}
subject.buildClientRequestContent()
then:
noExceptionThrown()
noExceptionThrown()
when:
def response = new WireMockResponseStubStrategy(patternsContract, null) {
@Override
protected ContentType contentType(SingleContractMetadata singleContractMetadata) {
return ContentType.JSON
}
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
def response = new WireMockResponseStubStrategy(patternsContract, null) {
@Override
protected ContentType contentType(SingleContractMetadata singleContractMetadata) {
return ContentType.JSON
}
response.buildClientResponseContent()
@Override
Function parsingClosureForContentType() {
return MapConverter.JSON_PARSING_FUNCTION
}
}
response.buildClientResponseContent()
then:
noExceptionThrown()
noExceptionThrown()
}
}

View File

@@ -38,6 +38,7 @@ import static java.util.Arrays.asList;
/**
* @author Dave Syer
* @author Pei-Tang Huang
* @author Hunhee Jung
*/
public class ResourcesFileSource implements FileSource {
@@ -111,7 +112,10 @@ public class ResourcesFileSource implements FileSource {
try {
UrlResource uri = new UrlResource(resource.getUri());
if (uri.exists()) {
return resource.getBinaryFileNamed(name);
Resource relativeResource = uri.createRelative(name);
if (relativeResource.exists()) {
return resource.getBinaryFileNamed(name);
}
}
}
catch (IOException e) {
@@ -147,8 +151,9 @@ public class ResourcesFileSource implements FileSource {
for (FileSource resource : this.sources) {
try {
UrlResource uri = new UrlResource(resource.child(subDirectoryName).getUri());
if (uri.createRelative(subDirectoryName).exists()) {
childSources.add(resource.child(subDirectoryName));
if (uri.exists()) {
FileSource child = resource.child(subDirectoryName);
childSources.add(child);
}
}
catch (IOException e) {

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.contract.wiremock.file;
import com.github.tomakehurst.wiremock.common.FileSource;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import static org.assertj.core.api.Assertions.assertThat;
class ResourcesFileSourceTest {
@DisplayName("find all files in the multiple files directories.")
@Test
void child() {
//given
Resource resource1 = new ClassPathResource("src/test/resources/files_banner");
Resource resource2 = new ClassPathResource("src/test/resources/files_notice");
ResourcesFileSource resourcesFileSource = new ResourcesFileSource(resource1, resource2);
//when
String filesDirName = "__files";
FileSource fileSource = resourcesFileSource.child(filesDirName);
//then
assertThat(fileSource).isInstanceOf(ResourcesFileSource.class);
assertThat(fileSource.listFilesRecursively()).hasSize(4);
}
@DisplayName("find a mapped response file in multiple directories.")
@Test
void getBinaryFileNamed() {
//given
Resource resource1 = new ClassPathResource("src/test/resources/files_banner/__files");
Resource resource2 = new ClassPathResource("src/test/resources/files_notice/__files");
ResourcesFileSource resourcesFileSource = new ResourcesFileSource(resource1, resource2);
//when & then
assertThat(resourcesFileSource.getBinaryFileNamed("response-bannerList-success.json").getStream()).isNotEmpty();
assertThat(resourcesFileSource.getBinaryFileNamed("response-noticeList-success.json").getStream()).isNotEmpty();
}
}

View File

@@ -0,0 +1,5 @@
{
"successful": false,
"message": "INVALID_PARAMETER",
"result": null
}

View File

@@ -0,0 +1,17 @@
{
"results": [
{
"seq": 1,
"title": "1111111111111111111111111",
"content": "1111111111111111111111111111111",
"regDate": "2022/06/17"
},
{
"seq": 2,
"title": "22222222222222222222222222",
"content": "2222222222222222222222222222222",
"regDate": "2022/06/18"
}
]
}

View File

@@ -0,0 +1,5 @@
{
"successful": false,
"message": "INVALID_PARAMETER",
"result": null
}

View File

@@ -0,0 +1,17 @@
{
"results": [
{
"seq": 1,
"title": "[AAA] BBBBBBBBBBBBBBB",
"content": "CCCCCCCCCCCCCCCCCCCCCCCCC",
"regDate": "2022/06/17"
},
{
"seq": 2,
"title": "[BBB] CCCCCCCCCCCCCCCCCCCCCCC",
"content": "DDDDDDDDDDDDDDDDDDD",
"regDate": "2022/06/18"
}
]
}