From 43fe8c1e6255d2a2156afc88f55e7fa788a5ef30 Mon Sep 17 00:00:00 2001 From: spencergibb Date: Thu, 18 Mar 2021 18:19:49 -0400 Subject: [PATCH] Removes orphaned contract stubs/restdocs integration --- spring-cloud-netflix-eureka-server/pom.xml | 5 - .../doc/AbstractDocumentationTests.java | 187 --------- .../server/doc/AppRegistrationTests.java | 130 ------- .../eureka/server/doc/EurekaObjectMapper.java | 55 --- .../eureka/server/doc/EurekaServerTests.java | 46 --- .../server/doc/RequestVerifierFilter.java | 359 ------------------ 6 files changed, 782 deletions(-) delete mode 100644 spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java delete mode 100644 spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java delete mode 100644 spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java delete mode 100644 spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java delete mode 100644 spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java diff --git a/spring-cloud-netflix-eureka-server/pom.xml b/spring-cloud-netflix-eureka-server/pom.xml index 6fa4545b6..dbeb76465 100644 --- a/spring-cloud-netflix-eureka-server/pom.xml +++ b/spring-cloud-netflix-eureka-server/pom.xml @@ -86,11 +86,6 @@ spring-boot-autoconfigure-processor true - - org.springframework.restdocs - spring-restdocs-restassured - test - org.springframework.boot spring-boot-starter-test diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java deleted file mode 100644 index 3e9ca3d98..000000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AbstractDocumentationTests.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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.netflix.eureka.server.doc; - -import java.util.UUID; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.eureka.DefaultEurekaServerContext; -import com.netflix.eureka.EurekaServerConfig; -import com.netflix.eureka.EurekaServerContext; -import com.netflix.eureka.cluster.PeerEurekaNodes; -import com.netflix.eureka.registry.PeerAwareInstanceRegistry; -import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl; -import com.netflix.eureka.resources.ServerCodecs; -import io.restassured.RestAssured; -import io.restassured.builder.RequestSpecBuilder; -import io.restassured.filter.Filter; -import io.restassured.specification.RequestSpecification; -import org.junit.After; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean; -import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; -import org.springframework.cloud.netflix.eureka.server.doc.AbstractDocumentationTests.Application; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.restdocs.JUnitRestDocumentation; -import org.springframework.restdocs.restassured3.RestAssuredRestDocumentation; -import org.springframework.restdocs.restassured3.RestDocumentationFilter; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyUris; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessRequest; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; -import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT, - value = { "spring.jmx.enabled=false", "management.security.enabled=false" }) -@DirtiesContext -public abstract class AbstractDocumentationTests { - - @LocalServerPort - private int port = 0; - - @Autowired - private PeerAwareInstanceRegistryImpl registry; - - @Autowired - private EurekaInstanceConfigBean instanceConfig; - - @Autowired - private ApplicationInfoManager applicationInfoManager; - - @Rule - public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets"); - - @After - public void init() { - registry.clearRegistry(); - ReflectionTestUtils.setField(registry, "responseCache", null); - registry.initializedResponseCache(); - } - - protected InstanceInfo register(String name) { - return register(name, UUID.randomUUID().toString()); - } - - protected InstanceInfo register(String name, String id) { - registry.register(instance(name, id), false); - return instance(); - } - - protected InstanceInfo instance(String name) { - return instance(name, UUID.randomUUID().toString()); - } - - protected InstanceInfo instance(String name, String id) { - instanceConfig.setAppname(name); - instanceConfig.setInstanceId(id); - instanceConfig.setHostname("foo.example.com"); - applicationInfoManager.initComponent(instanceConfig); - return applicationInfoManager.getInfo(); - } - - protected InstanceInfo instance() { - return applicationInfoManager.getInfo(); - } - - private RestDocumentationFilter filter(String name) { - return RestAssuredRestDocumentation.document(name, - preprocessRequest(modifyUris().host("eureka.example.com").removePort(), prettyPrint()), - preprocessResponse(prettyPrint())); - } - - private RequestSpecification spec(Filter... filters) { - return spec(null, filters); - } - - private RequestSpecification spec(Object body, Filter... filters) { - RequestSpecBuilder builder = new RequestSpecBuilder() - .addFilter(documentationConfiguration(this.restDocumentation)); - for (Filter filter : filters) { - builder = builder.addFilter(filter); - } - RequestSpecification spec = builder.setPort(this.port).build(); - if (body != null) { - spec.contentType("application/json").body(body, new EurekaObjectMapper()); - } - return spec; - } - - protected RequestSpecification document() { - return document("{method-name}"); - } - - protected RequestSpecification document(Object body) { - RestDocumentationFilter filter = filter("{method-name}"); - RequestSpecification assured = RestAssured.given(spec(body, filter)); - return assured.filter(filter); - } - - protected RequestSpecification document(String name, Object body) { - RestDocumentationFilter filter = filter(name); - RequestSpecification assured = RestAssured.given(spec(body, filter)); - return assured.filter(filter); - } - - protected RequestSpecification document(String name) { - RestDocumentationFilter filter = filter(name); - return RestAssured.given(spec(filter)).filter(filter); - } - - @Configuration(proxyBeanMethods = false) - @EnableAutoConfiguration - @EnableEurekaServer - protected static class Application { - - private static final Logger logger = LoggerFactory.getLogger(DefaultEurekaServerContext.class); - - @Bean - public EurekaServerContext testEurekaServerContext(ServerCodecs serverCodecs, - PeerAwareInstanceRegistry registry, PeerEurekaNodes peerEurekaNodes, - ApplicationInfoManager applicationInfoManager, EurekaServerConfig eurekaServerConfig) { - return new DefaultEurekaServerContext(eurekaServerConfig, serverCodecs, registry, peerEurekaNodes, - applicationInfoManager) { - @Override - public void shutdown() { - logger.info("Shutting down (except ServoControl and EurekaMonitors).."); - registry.shutdown(); - peerEurekaNodes.shutdown(); - // ServoControl.shutdown(); - // EurekaMonitors.shutdown(); - logger.info("Shut down"); - } - }; - } - - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java deleted file mode 100644 index a9e55ea66..000000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/AppRegistrationTests.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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.netflix.eureka.server.doc; - -import java.util.UUID; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static com.github.tomakehurst.wiremock.client.WireMock.delete; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.matching; -import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.emptyIterable; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.cloud.netflix.eureka.server.doc.RequestVerifierFilter.verify; - -@RunWith(SpringJUnit4ClassRunner.class) -public class AppRegistrationTests extends AbstractDocumentationTests { - - @Test - public void startingApp() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps").then().assertThat() - .body("applications.application", hasSize(1), "applications.application[0].instance[0].status", - equalTo("STARTING")) - .statusCode(is(200)); - } - - @Test - public void addInstance() throws Exception { - document(instance("foo")) - .filter(verify("$.instance.app").json("$.instance.hostName").json("$.instance[?(@.status=='STARTING')]") - .json("$.instance.instanceId").json("$.instance.dataCenterInfo.name")) - .when().post("/eureka/apps/FOO").then().assertThat().statusCode(is(204)); - } - - @Test - public void setStatus() throws Exception { - String id = register("foo").getInstanceId(); - document() - .filter(verify( - put(urlPathMatching("/eureka/apps/FOO/.*/status")).withQueryParam("value", matching("UP")))) - .when().put("/eureka/apps/FOO/{id}/status?value={value}", id, "UP").then().assertThat() - .statusCode(is(200)); - } - - @Test - public void allApps() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps").then().assertThat() - .body("applications.application", hasSize(1)).statusCode(is(200)); - } - - @Test - public void delta() throws Exception { - register("foo"); - document().accept("application/json").when().get("/eureka/apps/delta").then().assertThat() - .body("applications.application", hasSize(1)).statusCode(is(200)); - } - - @Test - public void oneInstance() throws Exception { - String id = UUID.randomUUID().toString(); - register("foo", id); - document().filter(verify(get(urlPathMatching("/eureka/apps/FOO/.*")))).accept("application/json").when() - .get("/eureka/apps/FOO/{id}", id).then().assertThat().body("instance.app", equalTo("FOO")) - .statusCode(is(200)); - } - - @Test - public void lookupInstance() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(get(urlPathMatching("/eureka/instances/.*")))).accept("application/json").when() - .get("/eureka/instances/{id}", id).then().assertThat().body("instance.app", equalTo("FOO")) - .statusCode(is(200)); - } - - @Test - public void renew() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(put(urlPathMatching("/eureka/apps/FOO/.*")))).accept("application/json").when() - .put("/eureka/apps/FOO/{id}", id).then().assertThat().statusCode(is(200)); - } - - @Test - public void updateMetadata() throws Exception { - String id = register("foo").getInstanceId(); - document() - .filter(verify( - put(urlPathMatching("/eureka/apps/FOO/.*/metadata")).withQueryParam("key", matching(".*")))) - .accept("application/json").when().put("/eureka/apps/FOO/{id}/metadata?key=value", id).then() - .assertThat().statusCode(is(200)); - assertThat(instance().getMetadata()).containsEntry("key", "value"); - } - - @Test - public void deleteInstance() throws Exception { - String id = register("foo").getInstanceId(); - document().filter(verify(delete(urlPathMatching("/eureka/apps/FOO/.*")))).when() - .delete("/eureka/apps/FOO/{id}", id).then().assertThat().statusCode(is(200)); - } - - @Test - public void emptyApps() { - document().when().accept("application/json").get("/eureka/apps").then().assertThat() - .body("applications.application", emptyIterable()).statusCode(is(200)); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java deleted file mode 100644 index d3b347747..000000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaObjectMapper.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.netflix.eureka.server.doc; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import javax.ws.rs.core.MediaType; - -import com.netflix.discovery.converters.EntityBodyConverter; -import io.restassured.mapper.ObjectMapperDeserializationContext; -import io.restassured.mapper.ObjectMapperSerializationContext; - -final class EurekaObjectMapper implements io.restassured.mapper.ObjectMapper { - - private EntityBodyConverter converter = new EntityBodyConverter(); - - @Override - public Object serialize(ObjectMapperSerializationContext context) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - converter.write(context.getObjectToSerialize(), out, MediaType.APPLICATION_JSON_TYPE); - } - catch (IOException e) { - throw new IllegalStateException("Cannot serialize", e); - } - return out.toByteArray(); - } - - @Override - public Object deserialize(ObjectMapperDeserializationContext context) { - try { - return converter.read(context.getDataToDeserialize().asInputStream(), (Class) context.getType(), - MediaType.APPLICATION_JSON_TYPE); - } - catch (IOException e) { - throw new IllegalStateException("Cannot deserialize", e); - } - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java deleted file mode 100644 index c8f781eb4..000000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/EurekaServerTests.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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.netflix.eureka.server.doc; - -import java.util.UUID; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.notNullValue; - -@RunWith(SpringJUnit4ClassRunner.class) -// TODO: maybe this should be the default (the test fails without it because the JSON is -// invalid) -@TestPropertySource( - properties = { "eureka.server.minAvailableInstancesForPeerReplication=0", "spring.jmx.enabled=false" }) -public class EurekaServerTests extends AbstractDocumentationTests { - - @Test - public void serverStatus() throws Exception { - register("foo", UUID.randomUUID().toString()); - document() - .accept("application/json").when().get("/eureka/status").then().assertThat().body("generalStats", - notNullValue(), "applicationStats", notNullValue(), "instanceInfo", notNullValue()) - .statusCode(is(200)); - } - -} diff --git a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java b/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java deleted file mode 100644 index f949e3fd3..000000000 --- a/spring-cloud-netflix-eureka-server/src/test/java/org/springframework/cloud/netflix/eureka/server/doc/RequestVerifierFilter.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright 2016-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.netflix.eureka.server.doc; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.github.tomakehurst.wiremock.client.MappingBuilder; -import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; -import com.github.tomakehurst.wiremock.http.ContentTypeHeader; -import com.github.tomakehurst.wiremock.http.Cookie; -import com.github.tomakehurst.wiremock.http.HttpHeader; -import com.github.tomakehurst.wiremock.http.HttpHeaders; -import com.github.tomakehurst.wiremock.http.QueryParameter; -import com.github.tomakehurst.wiremock.http.Request; -import com.github.tomakehurst.wiremock.http.RequestMethod; -import com.github.tomakehurst.wiremock.matching.MatchResult; -import com.github.tomakehurst.wiremock.stubbing.StubMapping; -import com.jayway.jsonpath.JsonPath; -import io.restassured.filter.Filter; -import io.restassured.filter.FilterContext; -import io.restassured.http.Header; -import io.restassured.response.Response; -import io.restassured.specification.FilterableRequestSpecification; -import io.restassured.specification.FilterableResponseSpecification; -import wiremock.com.google.common.base.Optional; - -import org.springframework.util.Base64Utils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriComponentsBuilder; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Dave Syer - * - */ - -public class RequestVerifierFilter implements Filter { - - static final String CONTEXT_KEY_CONFIGURATION = "org.springframework.restdocs.configuration"; - - private Map jsonPaths = new LinkedHashMap<>(); - - private MappingBuilder builder; - - public static RequestVerifierFilter verify(String path) { - return new RequestVerifierFilter(path); - } - - public static RequestVerifierFilter verify(MappingBuilder builder) { - return new RequestVerifierFilter().wiremock(builder); - } - - private RequestVerifierFilter(String expression, Object... args) { - expression = String.format(expression, args); - this.jsonPaths.put(expression, JsonPath.compile(expression)); - } - - private RequestVerifierFilter() { - } - - public RequestVerifierFilter json(String expression, Object... args) { - expression = String.format(expression, args); - this.jsonPaths.put(expression, JsonPath.compile(expression)); - return this; - } - - public RequestVerifierFilter wiremock(MappingBuilder builder) { - this.builder = builder; - return this; - } - - @Override - public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, - FilterContext context) { - Map configuration = getConfiguration(requestSpec, context); - configuration.put("contract.jsonPaths", this.jsonPaths.keySet()); - Response response = context.next(requestSpec, responseSpec); - if (requestSpec.getBody() != null && !this.jsonPaths.isEmpty()) { - String actual = new String((byte[]) requestSpec.getBody()); - for (JsonPath jsonPath : this.jsonPaths.values()) { - new JsonPathValue(jsonPath, actual).assertHasValue(Object.class, "an object"); - } - } - if (this.builder != null) { - this.builder.willReturn(getResponseDefinition(response)); - StubMapping stubMapping = this.builder.build(); - MatchResult match = stubMapping.getRequest().match(new WireMockRestAssuredRequestAdapter(requestSpec)); - assertThat(match.isExactMatch()).as("wiremock did not match request").isTrue(); - configuration.put("contract.stubMapping", stubMapping); - } - return response; - } - - private ResponseDefinitionBuilder getResponseDefinition(Response response) { - ResponseDefinitionBuilder definition = ResponseDefinitionBuilder.responseDefinition() - .withBody(response.getBody().asString()).withStatus(response.getStatusCode()); - addResponseHeaders(definition, response); - return definition; - } - - private void addResponseHeaders(ResponseDefinitionBuilder definition, Response input) { - for (Header header : input.getHeaders().asList()) { - String name = header.getName(); - definition.withHeader(name, input.getHeader(name)); - } - } - - protected Map getConfiguration(FilterableRequestSpecification requestSpec, FilterContext context) { - Map configuration = context.>getValue(CONTEXT_KEY_CONFIGURATION); - return configuration; - } - -} - -class JsonPathValue { - - private final JsonPath jsonPath; - - private final String expression; - - private final CharSequence actual; - - JsonPathValue(JsonPath jsonPath, CharSequence actual) { - this.jsonPath = jsonPath; - this.actual = actual; - this.expression = jsonPath.getPath(); - } - - public void assertHasValue(Class type, String expectedDescription) { - Object value = getValue(true); - if (value == null || isIndefiniteAndEmpty()) { - throw new AssertionError(getNoValueMessage()); - } - if (type != null && !type.isInstance(value)) { - throw new AssertionError(getExpectedValueMessage(expectedDescription)); - } - } - - private boolean isIndefiniteAndEmpty() { - return !isDefinite() && isEmpty(); - } - - private boolean isDefinite() { - return this.jsonPath.isDefinite(); - } - - private boolean isEmpty() { - return ObjectUtils.isEmpty(getValue(false)); - } - - public Object getValue(boolean required) { - try { - CharSequence json = this.actual; - return this.jsonPath.read(json == null ? null : json.toString()); - } - catch (Exception ex) { - if (!required) { - return null; - } - throw new AssertionError(getNoValueMessage() + ". " + ex.getMessage()); - } - } - - private String getNoValueMessage() { - return "No value at JSON path \"" + this.expression + "\""; - } - - private String getExpectedValueMessage(String expectedDescription) { - return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression, - ObjectUtils.nullSafeToString(StringUtils.quoteIfString(getValue(false)))); - } - -} - -class WireMockRestAssuredRequestAdapter implements Request { - - private FilterableRequestSpecification request; - - WireMockRestAssuredRequestAdapter(FilterableRequestSpecification request) { - this.request = request; - } - - @Override - public Optional getOriginalRequest() { - return Optional.of(this); - } - - @Override - public String getScheme() { - return UriComponentsBuilder.fromUriString(request.getURI()).build().getScheme(); - } - - @Override - public String getHost() { - return UriComponentsBuilder.fromUriString(request.getURI()).build().getHost(); - } - - @Override - public int getPort() { - return request.getPort(); - } - - @Override - public String getUrl() { - return request.getDerivedPath(); - } - - @Override - public String getAbsoluteUrl() { - return request.getURI(); - } - - @Override - public RequestMethod getMethod() { - return RequestMethod.fromString(request.getMethod()); - } - - @Override - public String getClientIp() { - return "127.0.0.1"; - } - - @Override - public String getHeader(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return null; - } - return value; - } - - @Override - public HttpHeader header(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return null; - } - return new HttpHeader(key, value); - } - - @Override - public ContentTypeHeader contentTypeHeader() { - return new ContentTypeHeader(request.getContentType()); - } - - @Override - public HttpHeaders getHeaders() { - List headers = new ArrayList<>(); - for (Header header : request.getHeaders()) { - String value = header.getValue(); - if ("accept".equals(header.getName().toLowerCase()) && "*/*".equals(value)) { - continue; - } - headers.add(new HttpHeader(header.getName(), header.getValue())); - } - return new HttpHeaders(headers); - } - - @Override - public boolean containsHeader(String key) { - String value = request.getHeaders().getValue(key); - if ("accept".equals(key.toLowerCase()) && "*/*".equals(value)) { - return false; - } - return request.getHeaders().hasHeaderWithName(key); - } - - @Override - public Set getAllHeaderKeys() { - Set headers = new LinkedHashSet<>(); - for (Header header : request.getHeaders()) { - String value = header.getValue(); - if ("accept".equals(header.getName().toLowerCase()) && "*/*".equals(value)) { - continue; - } - headers.add(header.getName()); - } - return headers; - } - - @Override - public Map getCookies() { - Map map = new LinkedHashMap<>(); - for (io.restassured.http.Cookie cookie : request.getCookies()) { - Cookie value = new Cookie(cookie.getValue()); - map.put(cookie.getName(), value); - } - return map; - } - - @Override - public QueryParameter queryParameter(String key) { - Map params = request.getQueryParams(); - if (params.containsKey(key)) { - return new QueryParameter(key, Arrays.asList(params.get(key))); - } - return null; - } - - @Override - public byte[] getBody() { - return request.getBody(); - } - - @Override - public String getBodyAsString() { - return new String(getBody()); - } - - @Override - public String getBodyAsBase64() { - return Base64Utils.encodeToString(getBody()); - } - - @Override - public boolean isBrowserProxyRequest() { - return false; - } - - @Override - public boolean isMultipart() { - return false; - } - - @Override - public Collection getParts() { - return Collections.emptyList(); - } - - @Override - public Part getPart(String s) { - return null; - } - -}