diff options
author | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2024-11-06 15:49:13 +0100 |
---|---|---|
committer | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2024-11-19 08:32:06 +0100 |
commit | 6ecf6370d5bc38b6313f869d321dd2294563d4b0 (patch) | |
tree | 35879c3b697ec9fe4a1f85c3eede2e979cfdab9c | |
parent | fd112727637454135c8ec80a8455ed0b6db3e948 (diff) |
Use WebTestClient in tests - part 31.15.2
- make ResourcesControllerTest full integration test
- this later on allows declaring all supported api query params explicitly,
that are implicitly supported currently
- add new ResourcesControllerMockTest that asserts exception handling for internal server errors
- remove body arg from @GET annotated controller methods
Issue-ID: AAI-4039
Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de>
Change-Id: I4f2f31bbea4e5f0f19cb98ebc040472616e9eee0
-rw-r--r-- | aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java | 5 | ||||
-rw-r--r-- | aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java | 3 | ||||
-rw-r--r-- | aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java | 2 | ||||
-rw-r--r-- | aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java | 6 | ||||
-rw-r--r-- | aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java | 4 | ||||
-rw-r--r-- | aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerMockTest.java | 134 | ||||
-rw-r--r-- | aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerTest.java (renamed from aai-resources/src/test/java/org/onap/aai/rest/ResourcesControllerTest.java) | 301 | ||||
-rw-r--r-- | aai-resources/src/test/resources/junit-platform.properties | 5 |
8 files changed, 214 insertions, 246 deletions
diff --git a/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java index bf29fd0..d64e862 100644 --- a/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java +++ b/aai-resources/src/main/java/org/onap/aai/rest/URLFromVertexIdConsumer.java @@ -47,8 +47,8 @@ import org.onap.aai.setup.SchemaVersion; /** * The Class URLFromVertexIdConsumer. */ -@Path("{version: v[1-9][0-9]*|latest}/generateurl") @Timed +@Path("{version: v[1-9][0-9]*|latest}/generateurl") public class URLFromVertexIdConsumer extends RESTAPI { private ModelType introspectorFactoryType = ModelType.MOXY; @@ -57,7 +57,6 @@ public class URLFromVertexIdConsumer extends RESTAPI { /** * Generate url from vertex id. * - * @param content the content * @param versionParam the version param * @param vertexid the vertexid * @param headers the headers @@ -68,7 +67,7 @@ public class URLFromVertexIdConsumer extends RESTAPI { @GET @Path(ID_ENDPOINT) @Produces({MediaType.WILDCARD}) - public Response generateUrlFromVertexId(String content, @PathParam("version") String versionParam, + public Response generateUrlFromVertexId(@PathParam("version") String versionParam, @PathParam("vertexid") long vertexid, @Context HttpHeaders headers, @Context UriInfo info, @Context HttpServletRequest req) { diff --git a/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java b/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java index a7b353e..f0a3c3e 100644 --- a/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java +++ b/aai-resources/src/main/java/org/onap/aai/rest/VertexIdConsumer.java @@ -64,7 +64,6 @@ public class VertexIdConsumer extends RESTAPI { /** * Gets the by vertex id. * - * @param content the content * @param versionParam the version param * @param vertexid the vertexid * @param depthParam the depth param @@ -76,7 +75,7 @@ public class VertexIdConsumer extends RESTAPI { @GET @Path(ID_ENDPOINT) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) - public Response getByVertexId(String content, @PathParam("version") String versionParam, + public Response getByVertexId(@PathParam("version") String versionParam, @PathParam("vertexid") long vertexid, @DefaultValue("all") @QueryParam("depth") String depthParam, @Context HttpHeaders headers, @Context UriInfo info, @Context HttpServletRequest req) { diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java index fbdfd5b..e3b923f 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java @@ -71,7 +71,7 @@ public class ExampleConsumerTest extends AAISetup { private List<MediaType> outputMediaTypes; - private static final Logger logger = LoggerFactory.getLogger(ResourcesControllerTest.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ExampleConsumerTest.class); @BeforeEach public void setup() { diff --git a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java index c29a186..37304fe 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java @@ -78,7 +78,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup { private List<MediaType> outputMediaTypes; - private static final Logger logger = LoggerFactory.getLogger(ResourcesControllerTest.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(URLFromVertexIdConsumerTest.class.getName()); @BeforeEach public void setup() { @@ -153,7 +153,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup { assertTrue(responseHeaders.containsKey("vertex-id"), "Response doesn't contain the key vertexId"); String vertexId = responseHeaders.get("vertex-id").get(0).toString(); - response = urlFromVertexIdConsumer.generateUrlFromVertexId("", schemaVersions.getDefaultVersion().toString(), + response = urlFromVertexIdConsumer.generateUrlFromVertexId(schemaVersions.getDefaultVersion().toString(), Long.valueOf(vertexId).longValue(), httpHeaders, uriInfo, mockReqGet); assertNotNull(response); @@ -171,7 +171,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup { String vertexId = "384584"; MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = - urlFromVertexIdConsumer.generateUrlFromVertexId("", schemaVersions.getDefaultVersion().toString(), + urlFromVertexIdConsumer.generateUrlFromVertexId(schemaVersions.getDefaultVersion().toString(), Long.valueOf(vertexId).longValue(), httpHeaders, uriInfo, mockReqGet); assertNotNull(response, "Check if the response is not null"); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java index c7a9bdd..137ffc6 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java @@ -78,7 +78,7 @@ public class VertexIdConsumerTest extends AAISetup { private List<MediaType> outputMediaTypes; - private static final Logger logger = LoggerFactory.getLogger(ResourcesControllerTest.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(VertexIdConsumerTest.class.getName()); @BeforeEach public void setup() { @@ -155,7 +155,7 @@ public class VertexIdConsumerTest extends AAISetup { String vertexId = responseHeaders.get("vertex-id").get(0).toString(); - response = vertexIdConsumer.getByVertexId("", schemaVersions.getDefaultVersion().toString(), + response = vertexIdConsumer.getByVertexId(schemaVersions.getDefaultVersion().toString(), Long.valueOf(vertexId).longValue(), "10000", httpHeaders, uriInfo, mockReqGet); assertNotNull(response); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerMockTest.java b/aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerMockTest.java new file mode 100644 index 0000000..8fc0754 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerMockTest.java @@ -0,0 +1,134 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom AG Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.rest.resources; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertIterableEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphTransaction; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.onap.aai.config.WebClientConfiguration; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.entities.AAIErrorResponse; +import org.onap.aai.entities.ServiceException; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.rest.db.HttpEntry; +import org.onap.aai.setup.SchemaVersions; +import org.onap.aai.util.AAIConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.Import; + +import org.springframework.http.HttpMethod; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.web.reactive.server.WebTestClient; + +@DirtiesContext +// This currently has to be executed last, since the @MockBean is dirtying the context. +// Restarting the context leads to other test failures that would need to be investigated. +@Order(Integer.MAX_VALUE) +@Import(WebClientConfiguration.class) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +public class ResourcesControllerMockTest { + + @MockBean(name = "traversalUriHttpEntry") + HttpEntry mockHttpEntry; + + @Autowired + WebTestClient webClient; + + @Autowired + SchemaVersions schemaVersions; + + @ParameterizedTest + @CsvSource({ + "GET, /cloud-infrastructure/pservers/pserver/someHostname", + "PUT, /cloud-infrastructure/pservers/pserver/someHostname", + "PUT, /cloud-infrastructure/pservers/pserver/someHostname/relationship-list/relationship", + "DELETE, /cloud-infrastructure/pservers/pserver/someHostname", + "DELETE, /cloud-infrastructure/pservers/pserver/someHostname/relationship-list/relationship", + }) + public void thatInternalServerErrorsAreMappedToAAIErrorResponse(HttpMethod method, String uri) { + // assure that any exception is mapped to an AAIErrorResponse + when(mockHttpEntry.setHttpEntryProperties(any())).thenThrow(new IllegalArgumentException()); + when(mockHttpEntry.setHttpEntryProperties(any(), anyString())).thenThrow(new IllegalArgumentException()); + + AAIErrorResponse errorResponse = webClient + .method(method) + .uri(uri) + .bodyValue("{}") + .exchange() + .expectStatus().isEqualTo(500) + .returnResult(AAIErrorResponse.class) + .getResponseBody() + .blockFirst(); + + ServiceException serviceException = errorResponse.getRequestError().getServiceException(); + assertEquals("SVC3002", serviceException.getMessageId()); + assertEquals("Error writing output performing %1 on %2 (msg=%3) (ec=%4)", serviceException.getText()); + List<String> expected = List.of( + method.toString(), + schemaVersions.getDefaultVersion() + uri, + "Internal Error:java.lang.IllegalArgumentException", + "ERR.5.4.4000"); + assertIterableEquals(expected, serviceException.getVariables()); + } + + @BeforeEach + public void setup() throws AAIException { + if(!AAIGraph.isInit()) { + AAIConfig.init(); + AAIGraph.getInstance(); + } + } + + @AfterEach + public void tearDown() { + JanusGraph janusGraph = AAIGraph.getInstance().getGraph(); + JanusGraphTransaction transaction = janusGraph.newTransaction(); + boolean success = true; + try { + GraphTraversalSource g = transaction.traversal(); + g.V().drop().iterate(); + } catch (Exception ex) { + success = false; + } finally { + if (success) { + transaction.commit(); + } else { + transaction.rollback(); + } + } + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ResourcesControllerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerTest.java index 57907ee..a724b51 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/ResourcesControllerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/resources/ResourcesControllerTest.java @@ -20,7 +20,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.aai.rest; +package org.onap.aai.rest.resources; import static org.hamcrest.MatcherAssert.assertThat; @@ -58,8 +58,10 @@ import org.json.JSONObject; import org.json.simple.parser.ParseException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.Mockito; import org.onap.aai.config.WebClientConfiguration; import org.onap.aai.db.props.AAIProperties; @@ -70,10 +72,10 @@ import org.onap.aai.entities.PServerListResponse; import org.onap.aai.entities.PolicyException; import org.onap.aai.entities.ServiceException; import org.onap.aai.exceptions.AAIException; +import org.onap.aai.rest.ResourcesController; import org.onap.aai.service.ResourcesService; import org.onap.aai.setup.SchemaVersions; import org.onap.aai.util.AAIConfig; -import org.onap.aai.util.AAIConstants; import org.skyscreamer.jsonassert.JSONAssert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,12 +85,15 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.web.reactive.server.WebTestClient; import com.fasterxml.jackson.databind.ObjectMapper; import reactor.core.publisher.Mono; +// @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @Import(WebClientConfiguration.class) public class ResourcesControllerTest { @@ -118,8 +123,9 @@ public class ResourcesControllerTest { private String defaultSchemaVersion; @BeforeEach - public void setup() { + public void setup() throws AAIException { if(!AAIGraph.isInit()) { + AAIConfig.init(); AAIGraph.getInstance(); } logger.info("Starting the setup for the integration tests of Rest Endpoints"); @@ -307,10 +313,12 @@ public class ResourcesControllerTest { doSetupResource(pserverUri, payload); } - @Test - public void thatUnknownPathReturnsBadRequest() throws JSONException { + @ParameterizedTest + @EnumSource(value = HttpMethod.class, names = {"GET", "PUT", "DELETE"}) + public void thatUnknownPathReturnsBadRequest(HttpMethod method) throws JSONException { String uri = "/fake-infrastructure/pservers/pserver/fajsidj"; - AAIErrorResponse errorResponse = webClient.put() + AAIErrorResponse errorResponse = webClient + .method(method) .uri(uri) .bodyValue("{}") .exchange() @@ -323,68 +331,14 @@ public class ResourcesControllerTest { assertEquals("SVC3000", serviceException.getMessageId()); assertEquals("Invalid input performing %1 on %2 (msg=%3) (ec=%4)", serviceException.getText()); List<String> expected = List.of( - "PUT", - "v29/fake-infrastructure/pservers/pserver/fajsidj", + method.toString(), + schemaVersions.getDefaultVersion() + uri, "Invalid input performing %1 on %2:Unrecognized AAI object fake-infrastructure", "ERR.5.2.3000"); assertIterableEquals(expected, serviceException.getVariables()); } @Test - public void testInvalidUriThrowRandomException() throws JSONException { - - String payload = "{}"; - String uri = "fake-infrastructure/pservers/pserver/fajsidj"; - - // webClient.put() - // .uri(uri) - // .bodyValue(payload) - // .exchange() - // .expectStatus().isEqualTo(500) - // .expectBody(AAIErrorResponse.class) - // .value(responseBody -> { - // assertNotNull(responseBody, "Response body should not be null"); - // assertEquals("SVC3002", responseBody.getRequestError().getServiceException().getMessageId()); - // }); - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenThrow(new IllegalArgumentException()); - MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = resourcesController.update(payload, defaultSchemaVersion, uri, - httpHeaders, uriInfo, mockReq); - - int code = response.getStatus(); - assertNotNull(response, "Response from the legacy moxy consumer returned null"); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - - response = resourcesController.updateRelationship(payload, defaultSchemaVersion, uri, - httpHeaders, uriInfo, mockReq); - - code = response.getStatus(); - assertNotNull(response, "Response from the legacy moxy consumer returned null"); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - mockReq = new MockHttpServletRequest("GET", uri); - response = resourcesController.getLegacy(defaultSchemaVersion, uri, -1, -1, false, - "all", "false", httpHeaders, uriInfo, mockReq); - - assertNotNull(response, "Response from the legacy moxy consumer returned null"); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - mockReq = new MockHttpServletRequest("DELETE", uri); - response = resourcesController.delete(defaultSchemaVersion, uri, httpHeaders, uriInfo, - "", mockReq); - - code = response.getStatus(); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - - response = resourcesController.deleteRelationship(payload, defaultSchemaVersion, uri, - httpHeaders, uriInfo, mockReq); - code = response.getStatus(); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - } - - @Test public void testInvalidUriContainingRelatedToShouldThrowAAIException() throws JSONException { String payload = "{}"; @@ -428,63 +382,44 @@ public class ResourcesControllerTest { "ERR.5.6.3010"); assertIterableEquals(expected, serviceException.getVariables()); + // Not sure if this is really the response that should be given + uri = "/cloud-infrastructure/pservers/pserver/hostname/related-to/fsdf/relationship-list/relationship"; + errorResponse = webClient + .method(HttpMethod.DELETE) + .uri(uri) + .bodyValue(payload) + .exchange() + .expectStatus().isBadRequest() + .returnResult(AAIErrorResponse.class) + .getResponseBody() + .blockFirst(); - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response; - int code; - mockReq = new MockHttpServletRequest("GET", uri); - response = resourcesController.getLegacy(defaultSchemaVersion, uri, -1, -1, false, - "all", "false", httpHeaders, uriInfo, mockReq); - code = response.getStatus(); - assertNotNull(response, "Response from the legacy moxy consumer returned null"); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); - - mockReq = new MockHttpServletRequest("DELETE", uri); - queryParameters.add("resource-version", "3434394839483"); - response = resourcesController.delete(defaultSchemaVersion, uri, httpHeaders, uriInfo, - "", mockReq); - - code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); - - response = resourcesController.deleteRelationship(payload, defaultSchemaVersion, uri, - httpHeaders, uriInfo, mockReq); - code = response.getStatus(); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); + serviceException = errorResponse.getRequestError().getServiceException(); + expected = List.of( + "DELETE", + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hostname/related-to/fsdf/relationship-list/relationship", + "Cannot write via this URL", + "ERR.5.6.3010"); + assertIterableEquals(expected, serviceException.getVariables()); } @Test - @Disabled("Unable to test this method due to WRITE_BIGDECIMAL_AS_PLAIN error") public void testPatchWithValidData() throws IOException { String payload = getResourcePayload("pserver-patch-test"); - String uri = getUri("pserver-patch-test"); - - if (uri.length() != 0 && uri.charAt(0) == '/') { - uri = uri.substring(1); - } - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - - MockHttpServletRequest mockReq = new MockHttpServletRequest("GET", uri); - Response response = resourcesController.getLegacy(defaultSchemaVersion, uri, -1, -1, - false, "all", "false", httpHeaders, uriInfo, mockReq); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); - mockReq = new MockHttpServletRequest("PUT", uri); - response = resourcesController.update(payload, defaultSchemaVersion, uri, httpHeaders, - uriInfo, mockReq); - - int code = response.getStatus(); - if (!VALID_HTTP_STATUS_CODES.contains(code)) { - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - } + String uri = "/cloud-infrastructure/pservers/pserver/pserver-patch-test"; + webClient.get() + .uri(uri) + .exchange() + .expectStatus() + .isNotFound(); - assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + webClient.put() + .uri(uri) + .bodyValue(payload) + .exchange() + .expectStatus() + .isCreated(); String patchData = "{\"in-maint\": false}"; @@ -493,15 +428,13 @@ public class ResourcesControllerTest { outputMediaTypes.remove(APPLICATION_JSON); outputMediaTypes.add(MediaType.valueOf("application/merge-patch+json")); - mockReq = new MockHttpServletRequest("PATCH", uri); - response = resourcesController.patch(patchData, defaultSchemaVersion, uri, httpHeaders, - uriInfo, mockReq); - - code = response.getStatus(); - assertNotNull(response, "Response from the patch returned null"); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - assertEquals(Response.Status.OK.getStatusCode(), code); - + webClient.patch() + .uri(uri) + .header("Content-Type", "application/merge-patch+json") + .bodyValue(patchData) + .exchange() + .expectStatus() + .isOk(); } protected void doSetupResource(String uri, String payload) throws JSONException { @@ -584,85 +517,13 @@ public class ResourcesControllerTest { } @Test - public void checkTimeoutEnabled() throws Exception { - boolean isTimeoutEnabled = resourcesController.isTimeoutEnabled("JUNITTESTAPP1", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(true, isTimeoutEnabled); - } - - @Test - public void checkTimeoutEnabledOverride() throws Exception { - boolean isTimeoutEnabled = resourcesController.isTimeoutEnabled("JUNITTESTAPP2", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(false, isTimeoutEnabled); - } - - @Test - public void checkTimeoutEnabledDefaultLimit() throws Exception { - boolean isTimeoutEnabled = resourcesController.isTimeoutEnabled("JUNITTESTAPP3", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(true, isTimeoutEnabled); - int timeout = resourcesController.getTimeoutLimit("JUNITTESTAPP3", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(100000, timeout); - } - - @Test - public void getTimeout() throws Exception { - int timeout = resourcesController.getTimeoutLimit("JUNITTESTAPP1", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(1, timeout); - } - - @Test - public void getTimeoutOverride() throws Exception { - int timeout = resourcesController.getTimeoutLimit("JUNITTESTAPP2", - AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); - assertEquals(-1, timeout); - } - - @Disabled("Time sensitive test only times out if the response takes longer than 1 second") - @Test - public void testTimeoutGetCall() throws Exception { - String uri = getUri(); - - if (uri.length() != 0 && uri.charAt(0) == '/') { - uri = uri.substring(1); - } - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - headersMultiMap.putSingle("X-FromAppId", "JUNITTESTAPP1"); - when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); - - MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = resourcesController.getLegacy(defaultSchemaVersion, uri, -1, -1, - false, "all", "false", httpHeaders, uriInfo, mockReqGet); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); - } - - @Test public void testBypassTimeoutGetCall() throws Exception { - String uri = getUri(); - - if (uri.length() != 0 && uri.charAt(0) == '/') { - uri = uri.substring(1); - } - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - headersMultiMap.putSingle("X-FromAppId", "JUNITTESTAPP2"); - when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); - - MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = resourcesController.getLegacy(defaultSchemaVersion, uri, -1, -1, - false, "all", "false", httpHeaders, uriInfo, mockReqGet); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + String uri = "/cloud-infrastructure/pservers/pserver/pserver-hostname-test"; + webClient.get() + .uri(uri) + .exchange() + .expectStatus() + .isNotFound(); } @Test @@ -1076,42 +937,12 @@ public class ResourcesControllerTest { } private void putResourceWithQueryParam(String uri, String payload) { - - String[] uriSplit = uri.split("\\?"); - if (uriSplit[1] != null && !uriSplit[1].isEmpty()) { - String[] params; - if (!uriSplit[1].contains("&")) { - String param = uriSplit[1]; - params = new String[] {param}; - } else { - params = uriSplit[1].split("&"); - } - for (String param : params) { - String[] splitParam = param.split("="); - String key = splitParam[0]; - String value = splitParam[1]; - uriInfo.getQueryParameters().add(key, value); - } - } - uri = uriSplit[0]; - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - - MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = resourcesController.update(payload, defaultSchemaVersion, uri, - httpHeaders, uriInfo, mockReq); - - assertNotNull(response, "Response from the legacy moxy consumer returned null"); - int code = response.getStatus(); - if (!VALID_HTTP_STATUS_CODES.contains(code)) { - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - } - - assertEquals(Response.Status.CREATED.getStatusCode(), - response.getStatus(), - "Expected to return status created from the response"); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + webClient.put() + .uri(uri) + .bodyValue(payload) + .exchange() + .expectStatus() + .isCreated(); } private String getResponse(String uri) { diff --git a/aai-resources/src/test/resources/junit-platform.properties b/aai-resources/src/test/resources/junit-platform.properties new file mode 100644 index 0000000..aa50ae3 --- /dev/null +++ b/aai-resources/src/test/resources/junit-platform.properties @@ -0,0 +1,5 @@ +# junit.jupiter.testclass.order.default=org.junit.jupiter.api.ClassOrderer$ClassName + + +junit.jupiter.testclass.order.default = \ + org.junit.jupiter.api.ClassOrderer$OrderAnnotation |