Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions spring-cloud-contract-verifier/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@
<groupId>com.github.jknack</groupId>
<artifactId>handlebars</artifactId>
</dependency>
<!-- Leaving for backward-compatibility. We no longer rely on this library
and neither should you. For more information check
https://github.com/spring-cloud/spring-cloud-contract/issues/2129 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ else if (value instanceof DslProperty) {
return getResponseBodyPropertyComparisonString(singleContractMetadata, property,
((DslProperty) value).getServerValue());
}
else if (value instanceof EscapedString) {
return getResponseBodyPropertyComparisonString(property, (EscapedString) value);
}
return getResponseBodyPropertyComparisonString(property, value.toString());
}

Expand All @@ -94,6 +97,12 @@ private String getResponseBodyPropertyComparisonString(String property, String v
return this.comparisonBuilder.assertThatUnescaped("responseBody" + property, value);
}

private String getResponseBodyPropertyComparisonString(String property, EscapedString value) {
String quoted = this.comparisonBuilder.bodyParser().quotedEscapedShortText(value.value());
return this.comparisonBuilder.assertThat("responseBody" + property)
+ this.comparisonBuilder.isEqualToUnquoted(quoted);
}

/**
* Builds the code that for the given {@code property} will match it to the given
* regular expression {@code value}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,12 @@ else if (TEXT != contentType && FORM != contentType && DEFINED != contentType) {
}

default String escape(String text) {
return StringEscapeUtils.escapeJava(text);
String escaped = StringEscapeUtils.escapeJava(text);
return escaped.replace("\r", "\\r").replace("\n", "\\n");
}

default String escapeForSimpleTextAssertion(String text) {
return text;
return escape(text);
}

default String postProcessJsonPath(String jsonPath) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2013-present 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.verifier.builder;

final class EscapedString {

private final String value;

EscapedString(String value) {
this.value = value;
}

String value() {
return this.value;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ class GenericTextBodyThen implements Then {
public MethodVisitor<Then> apply(SingleContractMetadata metadata) {
Object convertedResponseBody = this.bodyParser.convertResponseBody(metadata);
if (convertedResponseBody instanceof String) {
convertedResponseBody = this.bodyParser.escapeForSimpleTextAssertion(convertedResponseBody.toString());
String escaped = this.bodyParser.escapeForSimpleTextAssertion(convertedResponseBody.toString());
convertedResponseBody = new EscapedString(escaped);
}
simpleTextResponseBodyCheck(metadata, convertedResponseBody);
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ default String postProcessJsonPath(String jsonPath) {

@Override
default String escape(String text) {
return text.replaceAll("\\n", "\\\\n");
String escaped = text.replace("\r", "\\r").replace("\n", "\\n");
return escaped.replaceAll("\\n", "\\\\n");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package org.springframework.cloud.contract.verifier.builder;

import java.math.BigDecimal;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand All @@ -26,8 +28,7 @@
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import groovy.json.JsonOutput;
import org.apache.commons.beanutils.PropertyUtilsBean;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.spec.ContractTemplate;
import org.springframework.cloud.contract.spec.internal.BodyMatcher;
Expand Down Expand Up @@ -298,7 +299,7 @@ private static Object retrieveObjectByPath(Object body, String path) {
+ contractTemplate.escapedClosingTemplate();
}
try {
Object result = new PropertyUtilsBean().getProperty(templateModel, justEntry);
Object result = resolveTemplateModelEntry(templateModel, justEntry);
// Path from the Test model is an object and we'd like to return its
// String representation
if (FROM_REQUEST_PATH.equals(justEntry)) {
Expand All @@ -314,6 +315,105 @@ private static Object retrieveObjectByPath(Object body, String path) {
};
}

private Object resolveTemplateModelEntry(TestSideRequestTemplateModel templateModel, String propertyPath) {
Object current = templateModel;
for (String token : tokenizePropertyPath(propertyPath)) {
current = resolveNextToken(current, token);
}
return current;
}

private Object resolveNextToken(Object current, String token) {
if (current == null) {
throw new IllegalStateException("Unable to resolve property for null value");
}
if (current instanceof Map) {
Map<?, ?> map = (Map<?, ?>) current;
String key = unquote(token);
if (!map.containsKey(key)) {
throw new IllegalStateException("Missing map key [" + key + "]");
}
return map.get(key);
}
if (current instanceof List) {
int index = parseIndex(token);
List<?> list = (List<?>) current;
if (index < 0 || index >= list.size()) {
throw new IllegalStateException("Index [" + index + "] out of bounds");
}
return list.get(index);
}
if (current.getClass().isArray()) {
int index = parseIndex(token);
int length = Array.getLength(current);
if (index < 0 || index >= length) {
throw new IllegalStateException("Index [" + index + "] out of bounds");
}
return Array.get(current, index);
}
BeanWrapperImpl wrapper = new BeanWrapperImpl(current);
if (!wrapper.isReadableProperty(token)) {
throw new IllegalStateException("No readable property [" + token + "]");
}
return wrapper.getPropertyValue(token);
}

private int parseIndex(String token) {
try {
return Integer.parseInt(token);
}
catch (NumberFormatException ex) {
throw new IllegalStateException("Invalid index token [" + token + "]", ex);
}
}

private List<String> tokenizePropertyPath(String propertyPath) {
List<String> tokens = new ArrayList<>();
String[] segments = propertyPath.split("\\.");
for (String segment : segments) {
addTokens(segment, tokens);
}
return tokens;
}

private void addTokens(String segment, List<String> tokens) {
int index = 0;
while (index < segment.length()) {
int bracketStart = segment.indexOf('[', index);
if (bracketStart == -1) {
String token = segment.substring(index);
if (!token.isEmpty()) {
tokens.add(token);
}
return;
}
String before = segment.substring(index, bracketStart);
if (!before.isEmpty()) {
tokens.add(before);
}
int bracketEnd = segment.indexOf(']', bracketStart);
if (bracketEnd == -1) {
String remainder = segment.substring(bracketStart + 1);
if (!remainder.isEmpty()) {
tokens.add(remainder);
}
return;
}
String inside = segment.substring(bracketStart + 1, bracketEnd);
if (!inside.isEmpty()) {
tokens.add(inside);
}
index = bracketEnd + 1;
}
}

private String unquote(String value) {
if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith("\"") && value.endsWith("\""))) {
return value.substring(1, value.length() - 1);
}
return value;
}

private static String minus(CharSequence self, Object target) {
String s = self.toString();
String text = target.toString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
import org.apache.commons.collections.MapUtils;
import org.yaml.snakeyaml.Yaml;

import org.springframework.cloud.contract.spec.Contract;
Expand Down Expand Up @@ -228,7 +227,7 @@ private void handleQueryParameters(YamlContract yamlContract, Url url) {

private void mapRequestHeaders(YamlContract.Request yamlContractRequest, Request dslContractRequest) {
Map<String, Object> yamlContractRequestHeaders = yamlContractRequest.headers;
if (MapUtils.isNotEmpty(yamlContractRequestHeaders)) {
if (yamlContractRequestHeaders != null && !yamlContractRequestHeaders.isEmpty()) {
dslContractRequest.headers((headers) -> yamlContractRequestHeaders.forEach((key, value) -> {
List<YamlContract.KeyValueMatcher> matchers = yamlContractRequest.matchers.headers.stream()
.filter((header) -> header.key.equals(key))
Expand All @@ -252,7 +251,7 @@ private void mapRequestHeaders(YamlContract.Request yamlContractRequest, Request

private void mapRequestCookies(YamlContract.Request yamlContractRequest, Request dslContractRequest) {
Map<String, Object> yamlContractRequestCookies = yamlContractRequest.cookies;
if (MapUtils.isNotEmpty(yamlContractRequestCookies)) {
if (yamlContractRequestCookies != null && !yamlContractRequestCookies.isEmpty()) {
dslContractRequest.cookies((cookies) -> yamlContractRequestCookies.forEach((key, value) -> {
YamlContract.KeyValueMatcher matcher = yamlContractRequest.matchers.cookies.stream()
.filter(cookie -> cookie.key.equals(key))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package org.springframework.cloud.contract.verifier.builder;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

import org.junit.Test;

import org.springframework.cloud.contract.spec.Contract;
import org.springframework.cloud.contract.spec.internal.BodyMatchers;
import org.springframework.cloud.contract.verifier.template.HandlebarsTemplateProcessor;

import static org.assertj.core.api.Assertions.assertThat;

class JsonBodyVerificationBuilderTest {

@Test
public void should_resolve_request_template_values_when_body_present() {
// given
Contract contract = contractWithRequest();
JsonBodyVerificationBuilder builder = jsonBuilder(contract);
Map<String, Object> responseBody = new HashMap<>();
responseBody.put("auth0", "{{{ request.headers.Authorization.0 }}}");
responseBody.put("auth1", "{{{ request.headers.Authorization.[1] }}}");
responseBody.put("param", "{{{ request.query.foo.1 }}}");
responseBody.put("path", "{{{ request.path.1 }}}");

// when
Object converted = builder.addJsonResponseBodyCheck(new BlockBuilder(" "), responseBody, new BodyMatchers(),
"\"{}\"", true);

// then
assertThat(converted).isInstanceOf(Map.class);
Map<?, ?> convertedMap = (Map<?, ?>) converted;
assertThat(convertedMap.get("auth0")).isEqualTo("alpha");
assertThat(convertedMap.get("auth1")).isEqualTo("beta");
assertThat(convertedMap.get("param")).isEqualTo("baz");
assertThat(convertedMap.get("path")).isEqualTo("12");
}

@Test
public void should_keep_template_entry_when_property_missing() {
// given
Contract contract = contractWithRequest();
JsonBodyVerificationBuilder builder = jsonBuilder(contract);
Map<String, Object> responseBody = new HashMap<>();
String templateEntry = "{{{ request.headers.Missing.0 }}}";
responseBody.put("missing", templateEntry);

// when
Object converted = builder.addJsonResponseBodyCheck(new BlockBuilder(" "), responseBody, new BodyMatchers(),
"\"{}\"", true);

// then
Map<?, ?> convertedMap = (Map<?, ?>) converted;
assertThat(convertedMap.get("missing")).isEqualTo(templateEntry);
}

private JsonBodyVerificationBuilder jsonBuilder(Contract contract) {
HandlebarsTemplateProcessor templateProcessor = new HandlebarsTemplateProcessor();
return new JsonBodyVerificationBuilder(false, templateProcessor, templateProcessor, contract, Optional.empty(),
Function.identity());
}

private Contract contractWithRequest() {
Contract contract = new Contract();
contract.request(request -> {
request.method("GET");
request.url("/users/12", url -> url.queryParameters(query -> {
query.parameter("foo", "bar");
query.parameter("foo", "baz");
}));
request.headers(headers -> {
headers.header("Authorization", "alpha");
headers.header("Authorization", "beta");
});
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("key", "value");
request.body(requestBody);
});
return contract;
}

}