diff options
author | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2024-06-18 15:28:32 +0200 |
---|---|---|
committer | Fiete Ostkamp <Fiete.Ostkamp@telekom.de> | 2024-07-20 15:47:25 +0200 |
commit | eb1e3dbeb2d493f253ad0b720872fb08b9c0222d (patch) | |
tree | 1038933eca4661f7768d56ee5aacd6e944ba86d0 /aai-resources/src/test | |
parent | e74cffd22147bf7e99c44ba9d8c00c34d662c4de (diff) |
Make LegacyMoxyConsumerTest a @SpringBootTest
- replace AAISetup with @SpringBootTest in LegacyMoxyConsumerTest
- introduce WebTestClient to more elegantly declare requests
- do not statically invoke AAIGraph.getInstance in some tests [1]
[1] If those tests are run individually, launching the graph will fail
since the spring context is not available then.
It works in the pipeline, since other tests run before that launch the context.
Issue-ID: AAI-3887
Change-Id: I075c1f94e0a519d5cfa760cc07e446a26549c699
Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de>
Diffstat (limited to 'aai-resources/src/test')
10 files changed, 242 insertions, 140 deletions
diff --git a/aai-resources/src/test/java/org/onap/aai/config/WebClientConfiguration.java b/aai-resources/src/test/java/org/onap/aai/config/WebClientConfiguration.java new file mode 100644 index 0000000..cce0ae7 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/config/WebClientConfiguration.java @@ -0,0 +1,34 @@ +package org.onap.aai.config; + +import java.time.Duration; +import java.util.Collections; + +import org.onap.aai.setup.SchemaVersions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Lazy; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; + +@TestConfiguration +public class WebClientConfiguration { + + @Autowired SchemaVersions schemaVersions; + + @Lazy + @Bean + WebTestClient webTestClient(@LocalServerPort int port) { + return WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port + "/aai/" + schemaVersions.getDefaultVersion()) + .responseTimeout(Duration.ofSeconds(300)) + .defaultHeaders(headers -> { + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.set("X-FromAppId", "test"); + headers.set("X-TransactionId", "someTransaction"); + headers.setBasicAuth("AAI", "AAI"); + }) + .build(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/entities/PServer.java b/aai-resources/src/test/java/org/onap/aai/entities/PServer.java new file mode 100644 index 0000000..988328e --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/entities/PServer.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.entities; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import com.fasterxml.jackson.databind.annotation.JsonNaming; + +import lombok.Data; + +@Data +@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class) +public class PServer { + String resourceVersion; + String hostname; + String ptniiEquipName; + long numberOfCpus; + long diskInGigabytes; + long ramInMegabytes; + String equipType; + String equipVendor; + String equipModel; + String fqdn; + String pserverSelflink; + String ipv4OamAddress; + String serialNumber; + @JsonProperty("ipaddress-v4-loopback-0") + String ipaddressV4Loopback0; + @JsonProperty("ipaddress-v6-loopback-0") + String ipaddressV6Loopback0; + String ipaddressV4Aim; + String ipaddressV6Aim; + String ipaddressV6Oam; + String invStatus; + String pserverId; + String internetTopology; + boolean inMaint; + String pserverName2; + String purpose; + String provStatus; + String managementOption; + String hostProfile; +} diff --git a/aai-resources/src/test/java/org/onap/aai/entities/PServerListResponse.java b/aai-resources/src/test/java/org/onap/aai/entities/PServerListResponse.java new file mode 100644 index 0000000..a08b9ea --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/entities/PServerListResponse.java @@ -0,0 +1,30 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2024 Deutsche Telekom. 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.entities; + +import java.util.List; + +import lombok.Data; + +@Data +public class PServerListResponse { + List<PServer> pserver; +} diff --git a/aai-resources/src/test/java/org/onap/aai/it/performance/K6PerformanceTest.java b/aai-resources/src/test/java/org/onap/aai/it/performance/K6PerformanceTest.java index 8428cb5..64b4f3c 100644 --- a/aai-resources/src/test/java/org/onap/aai/it/performance/K6PerformanceTest.java +++ b/aai-resources/src/test/java/org/onap/aai/it/performance/K6PerformanceTest.java @@ -56,13 +56,9 @@ public class K6PerformanceTest { @LocalServerPort private int port; - - private boolean initialized = false; - @BeforeEach public void setup() { - if (!initialized) { - initialized = true; + if (!AAIGraph.isInit()) { AAIGraph.getInstance(); long startTime = System.currentTimeMillis(); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java index 68974a3..706da69 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java @@ -73,19 +73,11 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup { protected String uri; - private boolean initialized = false; private static final Logger logger = LoggerFactory.getLogger(BulkProcessorTestAbstraction.class.getName()); - @BeforeAll - public static void setupRest() { - // AAIGraph.getInstance(); - - } - @BeforeEach public void setup() { - if (!initialized) { - initialized = true; + if (!AAIGraph.isInit()) { AAIGraph.getInstance(); } logger.info("Starting the setup for the integration tests of Rest Endpoints"); 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 96e7716..73eed51 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 @@ -74,14 +74,11 @@ public class ExampleConsumerTest extends AAISetup { private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); - @BeforeAll - public static void setupRest() { - AAIGraph.getInstance(); - - } - @BeforeEach public void setup() { + if(!AAIGraph.isInit()) { + AAIGraph.getInstance(); + } logger.info("Starting the setup for the integration tests of Rest Endpoints"); exampleConsumer = new ExampleConsumer(); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java index e54c8e5..d88faa5 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright © 2024 Deutsche Telekom. + * ================================================================================ * 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 @@ -20,6 +22,10 @@ package org.onap.aai.rest; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.samePropertyValuesAs; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -28,6 +34,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -42,31 +49,46 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; +import org.apache.commons.io.IOUtils; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.hamcrest.Matcher; +import org.janusgraph.core.JanusGraph; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.simple.parser.ParseException; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.onap.aai.AAISetup; +import org.onap.aai.config.WebClientConfiguration; +import org.onap.aai.db.props.AAIProperties; import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.entities.PServer; +import org.onap.aai.entities.PServerListResponse; import org.onap.aai.exceptions.AAIException; +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; +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.context.annotation.Import; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.test.web.reactive.server.WebTestClient; -// TODO: Change the following test to use spring boot -public class LegacyMoxyConsumerTest extends AAISetup { +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@Import(WebClientConfiguration.class) +public class LegacyMoxyConsumerTest { - protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); - private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); static { VALID_HTTP_STATUS_CODES.add(200); @@ -74,31 +96,23 @@ public class LegacyMoxyConsumerTest extends AAISetup { VALID_HTTP_STATUS_CODES.add(204); } - private LegacyMoxyConsumer legacyMoxyConsumer; + @Autowired WebTestClient webClient; + @Autowired SchemaVersions schemaVersions; - private HttpHeaders httpHeaders; + ObjectMapper mapper = new ObjectMapper(); + private LegacyMoxyConsumer legacyMoxyConsumer; + private HttpHeaders httpHeaders; private UriInfo uriInfo; - private MultivaluedMap<String, String> headersMultiMap; private MultivaluedMap<String, String> queryParameters; - private List<String> aaiRequestContextList; - private List<MediaType> outputMediaTypes; - private boolean initialized = false; private String defaultSchemaVersion; - - @BeforeAll - public static void setupRest() { - // AAIGraph.getInstance(); - } - @BeforeEach public void setup() { - if (!initialized) { - initialized = true; + if(!AAIGraph.isInit()) { AAIGraph.getInstance(); } logger.info("Starting the setup for the integration tests of Rest Endpoints"); @@ -135,96 +149,90 @@ public class LegacyMoxyConsumerTest extends AAISetup { Mockito.doReturn(null).when(queryParameters).remove(any()); when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); - } @Test public void testResponsePutGetDeleteOnResource() throws JSONException, IOException, AAIException { - - String uri = getUri(); String payload = getResourcePayload(getObjectName()); - - assertNotNull(payload, "Introspector returned invalid string when marshalling the object"); - assertNotNull(uri, "Introspector failed to return a valid uri"); - - if (uri.length() != 0 && uri.charAt(0) == '/') { - uri = uri.substring(1); - } - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - - MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy(defaultSchemaVersion, uri, -1, -1, - false, "all", "false", httpHeaders, uriInfo, mockReqGet); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); - - MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - response = legacyMoxyConsumer.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()); - } - - assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); - - queryParameters.add("depth", "10000"); - - response = legacyMoxyConsumer.getLegacy(defaultSchemaVersion, uri, -1, -1, false, - "10000", "false", httpHeaders, uriInfo, mockReqGet); - - code = response.getStatus(); - if (!VALID_HTTP_STATUS_CODES.contains(code)) { - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - } - - String pserverEntity = response.getEntity().toString(); - JSONObject pserverJsonbject = new JSONObject(pserverEntity); - - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); - - JSONAssert.assertEquals(payload, pserverEntity, false); - - String resourceVersion = pserverJsonbject.getString("resource-version"); - - queryParameters.add("resource-version", resourceVersion); - - mockReq = new MockHttpServletRequest("DELETE", uri); - response = legacyMoxyConsumer.delete(defaultSchemaVersion, uri, httpHeaders, uriInfo, - "", mockReq); - - code = response.getStatus(); - if (!VALID_HTTP_STATUS_CODES.contains(code)) { - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - } - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); - - response = legacyMoxyConsumer.getLegacy(defaultSchemaVersion, uri, -1, -1, false, - "all", "false", httpHeaders, uriInfo, mockReqGet); - - assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + PServer expected = mapper.readValue(payload, PServer.class); + + webClient.get() + .uri("/cloud-infrastructure/pservers/pserver/pserver-hostname-test?cleanup=false") + .exchange() + .expectStatus() + .isNotFound(); + + webClient.put() + .uri("/cloud-infrastructure/pservers/pserver/pserver-hostname-test") + .bodyValue(payload) + .exchange() + .expectStatus() + .isCreated(); + + PServer pserver = webClient.get() + .uri("/cloud-infrastructure/pservers/pserver/pserver-hostname-test?cleanup=false&depth=10000") + .exchange() + .expectStatus() + .isOk() + .returnResult(PServer.class) + .getResponseBody() + .blockFirst(); + + assertThat(pserver, samePropertyValuesAs(expected, "resourceVersion")); + + String resourceVersion = pserver.getResourceVersion(); + + webClient.delete() + .uri(uriBuilder -> uriBuilder + .path("/cloud-infrastructure/pservers/pserver/pserver-hostname-test") + .queryParam("resource-version", resourceVersion) + .build()) + .exchange() + .expectStatus() + .isNoContent(); + + webClient.get() + .uri("/cloud-infrastructure/pservers/pserver/pserver-hostname-test?cleanup=false&depth=10000") + .exchange() + .expectStatus() + .isNotFound(); } @Test public void testResponseGetOnResourcePaginated() throws JSONException, IOException, AAIException { - - String uri = getGetAllPserversURI(); - - if (uri.length() != 0 && uri.charAt(0) == '/') { - uri = uri.substring(1); - } - - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - - MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy(defaultSchemaVersion, uri, 1, 10, true, - "all", "false", httpHeaders, uriInfo, mockReqGet); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + JanusGraph graph = AAIGraph.getInstance().getGraph(); + GraphTraversalSource g = graph.traversal(); + g.addV() + .property("aai-node-type", "pserver") + .property("hostname", "hostname1") + .property("resource-version", UUID.randomUUID().toString()) + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/hostname1") + .addV() + .property("aai-node-type", "pserver") + .property("hostname", "hostname2") + .property("resource-version", UUID.randomUUID().toString()) + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/hostname2") + .next(); + g.tx().commit(); + + PServerListResponse pservers = webClient.get() + .uri(uriBuilder -> + uriBuilder + .path("/cloud-infrastructure/pservers") + .queryParam("resultIndex", "1") + .queryParam("resultSize", "10") + .build()) + .exchange() + .expectStatus() + .isOk() + // TODO: Assert values here once test data is isolated to individual test + .expectHeader().exists("total-results") + .expectHeader().exists("total-pages") + .returnResult(PServerListResponse.class) + .getResponseBody() + .blockFirst(); + + assertTrue(pservers.getPserver().size() > 0); } @Test @@ -508,12 +516,12 @@ public class LegacyMoxyConsumerTest extends AAISetup { } public String getResourcePayload(String resourceName) throws IOException { - String rawPayload = getPayload("payloads/resource/" + resourceName + ".json"); + String rawPayload = IOUtils.toString(this.getClass().getResourceAsStream("/payloads/resource/" + resourceName + ".json"), StandardCharsets.UTF_8); return String.format(rawPayload, defaultSchemaVersion); } public String getRelationshipPayload(String relationshipName) throws IOException { - String rawPayload = getPayload("payloads/relationship/" + relationshipName + ".json"); + String rawPayload = IOUtils.toString(this.getClass().getResourceAsStream("/payloads/relationship/" + relationshipName + ".json"), StandardCharsets.UTF_8); return String.format(rawPayload, defaultSchemaVersion); } 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 2e6d49e..e515098 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 @@ -79,17 +79,10 @@ public class URLFromVertexIdConsumerTest extends AAISetup { private List<MediaType> outputMediaTypes; private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); - private boolean initialized = false; - - @BeforeAll - public static void setupRest() { - // AAIGraph.getInstance(); - } @BeforeEach public void setup() { - if (!initialized) { - initialized = true; + if(!AAIGraph.isInit()) { AAIGraph.getInstance(); } logger.info("Starting the setup for the integration tests of Rest Endpoints"); 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 ce9a423..8c62950 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 @@ -79,17 +79,10 @@ public class VertexIdConsumerTest extends AAISetup { private List<MediaType> outputMediaTypes; private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); - private boolean initialized = false; - - @BeforeAll - public static void setupRest() { - // AAIGraph.getInstance(); - } @BeforeEach public void setup() { - if (!initialized) { - initialized = true; + if(!AAIGraph.isInit()) { AAIGraph.getInstance(); } logger.info("Starting the setup for the integration tests of Rest Endpoints"); diff --git a/aai-resources/src/test/resources/application-test.properties b/aai-resources/src/test/resources/application-test.properties index a4b613c..253a191 100644 --- a/aai-resources/src/test/resources/application-test.properties +++ b/aai-resources/src/test/resources/application-test.properties @@ -20,7 +20,6 @@ spring.autoconfigure.exclude=\ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\ org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration -spring.profiles.active=production #The max number of active threads in this pool server.tomcat.threads.max=200 #The minimum number of threads always kept alive |