From f61e8a4b2581165ae6c0c4663bf52e841c5be39e Mon Sep 17 00:00:00 2001 From: Fiete Ostkamp Date: Wed, 26 Oct 2022 14:15:46 +0000 Subject: Run the formatter for the resources service - reduces the format violations from ~7000 to ~400 Issue-ID: AAI-3567 Signed-off-by: Fiete Ostkamp Change-Id: I570805692bfbd3f80a43c0813831adcdb98016d4 --- .../src/test/java/org/onap/aai/AAISetup.java | 68 +- .../src/test/java/org/onap/aai/HttpTestUtil.java | 123 ++-- .../java/org/onap/aai/IncreaseNodesToolTest.java | 19 +- .../src/test/java/org/onap/aai/PayloadUtil.java | 25 +- .../org/onap/aai/ResourcesTestConfiguration.java | 45 +- .../it/multitenancy/KeycloakTestConfiguration.java | 23 +- .../it/multitenancy/KeycloakTestProperties.java | 1 + .../onap/aai/it/multitenancy/MultiTenancyIT.java | 32 +- .../org/onap/aai/it/multitenancy/RoleHandler.java | 19 +- .../org/onap/aai/rest/AbstractSpringRestTest.java | 27 +- .../org/onap/aai/rest/BulkAddConsumerTest.java | 51 +- .../org/onap/aai/rest/BulkProcessConsumerTest.java | 184 +++-- .../aai/rest/BulkProcessorTestAbstraction.java | 51 +- .../java/org/onap/aai/rest/CloudRegionTest.java | 16 +- .../java/org/onap/aai/rest/ConfigurationTest.java | 106 ++- .../onap/aai/rest/CustomerFilterSearchTest.java | 15 +- .../org/onap/aai/rest/ExampleConsumerTest.java | 38 +- .../org/onap/aai/rest/ExceptionHandlerTest.java | 48 +- .../java/org/onap/aai/rest/InvalidURITest.java | 11 +- .../org/onap/aai/rest/LegacyMoxyConsumerTest.java | 817 ++++++++------------- .../org/onap/aai/rest/PserverGenerateUrlTest.java | 19 +- .../java/org/onap/aai/rest/PserverMissingTest.java | 16 +- .../org/onap/aai/rest/PserverRelationshipTest.java | 24 +- .../test/java/org/onap/aai/rest/PserverTest.java | 16 +- .../org/onap/aai/rest/PserverWrongHeaderTest.java | 16 +- .../onap/aai/rest/URLFromVertexIdConsumerTest.java | 76 +- .../org/onap/aai/rest/VertexIdConsumerTest.java | 74 +- .../bulk/BulkSingleTransactionConsumerTest.java | 743 +++++++++---------- .../rest/retired/RetiredConsumerSpringTest.java | 30 +- .../org/onap/aai/rest/util/LogFormatToolsTest.java | 7 +- .../onap/aai/rest/util/ValidateEncodingTest.java | 166 ++--- 31 files changed, 1265 insertions(+), 1641 deletions(-) (limited to 'aai-resources/src/test/java/org') diff --git a/aai-resources/src/test/java/org/onap/aai/AAISetup.java b/aai-resources/src/test/java/org/onap/aai/AAISetup.java index dac7b60..8227d37 100644 --- a/aai-resources/src/test/java/org/onap/aai/AAISetup.java +++ b/aai-resources/src/test/java/org/onap/aai/AAISetup.java @@ -20,6 +20,12 @@ package org.onap.aai; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; + import org.apache.commons.io.IOUtils; import org.junit.BeforeClass; import org.junit.ClassRule; @@ -40,46 +46,32 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; +@ContextConfiguration( + classes = {ConfigConfiguration.class, AAIConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class, + EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class, + XmlFormatTransformerConfiguration.class, RestBeanConfig.class}) +@TestPropertySource( + properties = {"schema.uri.base.path = /aai", + "schema.ingest.file = src/test/resources/application-test.properties"}) +public abstract class AAISetup { -import static org.junit.Assert.assertNotNull; + @Autowired + protected NodeIngestor nodeIngestor; -@ContextConfiguration(classes = { - ConfigConfiguration.class, - AAIConfigTranslator.class, - NodeIngestor.class, - EdgeIngestor.class, - EdgeSerializer.class, - SpringContextAware.class, - IntrospectionConfig.class, - XmlFormatTransformerConfiguration.class, - RestBeanConfig.class -}) -@TestPropertySource(properties = { - "schema.uri.base.path = /aai" , - "schema.ingest.file = src/test/resources/application-test.properties" -}) -public abstract class AAISetup { + @Autowired + protected LoaderFactory loaderFactory; + + @Autowired + protected Map moxyLoaderInstance; - @Autowired - protected NodeIngestor nodeIngestor; + @Autowired + protected HttpEntry traversalHttpEntry; - @Autowired - protected LoaderFactory loaderFactory; - - @Autowired - protected Map moxyLoaderInstance; - - @Autowired - protected HttpEntry traversalHttpEntry; - - @Autowired - protected HttpEntry traversalUriHttpEntry; + @Autowired + protected HttpEntry traversalUriHttpEntry; - @Autowired - protected SchemaVersions schemaVersions; + @Autowired + protected SchemaVersions schemaVersions; @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @@ -92,12 +84,10 @@ public abstract class AAISetup { System.setProperty("AJSC_HOME", "./"); System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/"); } - + public String getPayload(String filename) throws IOException { - InputStream inputStream = getClass() - .getClassLoader() - .getResourceAsStream(filename); + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename); String message = String.format("Unable to find the %s in src/test/resources", filename); assertNotNull(message, inputStream); diff --git a/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java index cc021bc..9235109 100644 --- a/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java +++ b/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai; import static org.mockito.ArgumentMatchers.anyObject; @@ -73,13 +74,13 @@ public class HttpTestUtil extends RESTAPI { protected List outputMediaTypes; protected SchemaVersions schemaVersions; - public void init(){ + public void init() { - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -118,26 +119,26 @@ public class HttpTestUtil extends RESTAPI { uri = uri.replaceAll("/aai/", ""); logger.info("Starting the put request for the uri {} with payload {}", uri, payload); - String [] arr = uri.split("/"); + String[] arr = uri.split("/"); SchemaVersion version = null; - if(arr.length > 1){ - if(arr[0].matches("^v\\d+")){ + if (arr.length > 1) { + if (arr[0].matches("^v\\d+")) { version = new SchemaVersion(arr[0]); uri = uri.replaceAll("^v\\d+", ""); } } - if(version == null){ + if (version == null) { version = schemaVersions.getDefaultVersion(); } Mockito.when(uriInfo.getPath()).thenReturn(uri); HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class); resourceHttpEntry.setHttpEntryProperties(version); - Loader loader = resourceHttpEntry.getLoader(); - dbEngine = resourceHttpEntry.getDbEngine(); + Loader loader = resourceHttpEntry.getLoader(); + dbEngine = resourceHttpEntry.getDbEngine(); URI uriObject = UriBuilder.fromPath(uri).build(); URIToObject uriToObject = new URIToObject(loader, uriObject); @@ -145,13 +146,13 @@ public class HttpTestUtil extends RESTAPI { String objType = uriToObject.getEntityName(); QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject); - logger.info("Unmarshalling the payload to this {}", objType); Introspector obj; HttpMethod httpMethod; - if(uri.contains("/relationship-list/relationship")){ - obj = loader.unmarshal("relationship", payload, org.onap.aai.restcore.MediaType.getEnum("application/json")); + if (uri.contains("/relationship-list/relationship")) { + obj = loader.unmarshal("relationship", payload, + org.onap.aai.restcore.MediaType.getEnum("application/json")); httpMethod = HttpMethod.PUT_EDGE; } else { obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json")); @@ -159,36 +160,35 @@ public class HttpTestUtil extends RESTAPI { this.validateIntrospector(obj, loader, uriObject, httpMethod); } - - DBRequest dbRequest = - new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION") - .rawRequestContent(payload).build(); + DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, + "JUNIT-TRANSACTION").rawRequestContent(payload).build(); List dbRequestList = new ArrayList<>(); dbRequestList.add(dbRequest); - Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); + Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); response = responsesTuple.getValue1().get(0).getValue1(); } catch (AAIException e) { - response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e); - success = false; - } catch(Exception e){ + response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e); + success = false; + } catch (Exception e) { AAIException ex = new AAIException("AAI_4000", e); response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex); success = false; } finally { - if(success){ - if(response != null){ - if((response.getStatus() / 100) == 2){ - logger.info("Successfully completed the PUT request with status {} and committing it to DB", response.getStatus()); + if (success) { + if (response != null) { + if ((response.getStatus() / 100) == 2) { + logger.info("Successfully completed the PUT request with status {} and committing it to DB", + response.getStatus()); } else { logFailure(HttpMethod.PUT, response); } } dbEngine.commit(); } else { - if(response != null) { + if (response != null) { logFailure(HttpMethod.PUT, response); } dbEngine.rollback(); @@ -210,25 +210,25 @@ public class HttpTestUtil extends RESTAPI { uri = uri.replaceAll("/aai/", ""); logger.info("Starting the GET request for the uri {} with depth {}", uri, "all"); - String [] arr = uri.split("/"); + String[] arr = uri.split("/"); SchemaVersion version = null; - if(arr.length > 1){ - if(arr[0].matches("^v\\d+")){ + if (arr.length > 1) { + if (arr[0].matches("^v\\d+")) { version = new SchemaVersion(arr[0]); uri = uri.replaceAll("^v\\d+", ""); } } - if(version == null){ + if (version == null) { version = schemaVersions.getDefaultVersion(); } HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class); resourceHttpEntry.setHttpEntryProperties(version); - Loader loader = resourceHttpEntry.getLoader(); - dbEngine = resourceHttpEntry.getDbEngine(); + Loader loader = resourceHttpEntry.getLoader(); + dbEngine = resourceHttpEntry.getDbEngine(); URI uriObject = UriBuilder.fromPath(uri).build(); URIToObject uriToObject = new URIToObject(loader, uriObject); @@ -243,28 +243,28 @@ public class HttpTestUtil extends RESTAPI { Introspector obj = loader.introspectorFromName(objType); - DBRequest dbRequest = - new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION") - .build(); + DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo, + "JUNIT-TRANSACTION").build(); List dbRequestList = new ArrayList<>(); dbRequestList.add(dbRequest); - Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); + Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); response = responsesTuple.getValue1().get(0).getValue1(); } catch (AAIException e) { response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e); success = false; - } catch(Exception e){ + } catch (Exception e) { AAIException ex = new AAIException("AAI_4000", e); response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex); success = false; } finally { - if(success){ - if(response != null){ - if((response.getStatus() / 100) == 2){ - logger.info("Successfully completed the GET request with status {} and committing it to DB", response.getStatus()); + if (success) { + if (response != null) { + if ((response.getStatus() / 100) == 2) { + logger.info("Successfully completed the GET request with status {} and committing it to DB", + response.getStatus()); } else { logFailure(HttpMethod.GET, response); } @@ -291,28 +291,28 @@ public class HttpTestUtil extends RESTAPI { uri = uri.replaceAll("/aai/", ""); logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion); - String [] arr = uri.split("/"); + String[] arr = uri.split("/"); SchemaVersion version = null; - if(arr.length > 1){ - if(arr[0].matches("^v\\d+")){ + if (arr.length > 1) { + if (arr[0].matches("^v\\d+")) { version = new SchemaVersion(arr[0]); - if(!uri.contains("relationship-list/relationship")){ + if (!uri.contains("relationship-list/relationship")) { uri = uri.replaceAll("^v\\d+", ""); } } } - if(version == null){ + if (version == null) { version = schemaVersions.getDefaultVersion(); } Mockito.when(uriInfo.getPath()).thenReturn(uri); HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class); resourceHttpEntry.setHttpEntryProperties(version); - Loader loader = resourceHttpEntry.getLoader(); - dbEngine = resourceHttpEntry.getDbEngine(); + Loader loader = resourceHttpEntry.getLoader(); + dbEngine = resourceHttpEntry.getDbEngine(); URI uriObject = UriBuilder.fromPath(uri).build(); URIToObject uriToObject = new URIToObject(loader, uriObject); @@ -325,7 +325,7 @@ public class HttpTestUtil extends RESTAPI { Introspector obj; HttpMethod httpMethod; - if(uri.contains("/relationship-list/relationship")){ + if (uri.contains("/relationship-list/relationship")) { obj = loader.introspectorFromName("relationship"); httpMethod = HttpMethod.DELETE_EDGE; } else { @@ -333,28 +333,28 @@ public class HttpTestUtil extends RESTAPI { httpMethod = HttpMethod.DELETE; } - DBRequest dbRequest = - new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION") - .build(); + DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, + "JUNIT-TRANSACTION").build(); List dbRequestList = new ArrayList<>(); dbRequestList.add(dbRequest); - Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); + Pair>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT"); response = responsesTuple.getValue1().get(0).getValue1(); } catch (AAIException e) { response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e); success = false; - } catch(Exception e){ + } catch (Exception e) { AAIException ex = new AAIException("AAI_4000", e); response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex); success = false; } finally { - if(success){ - if(response != null){ - if((response.getStatus() / 100) == 2){ - logger.info("Successfully completed the DELETE request with status {} and committing it to DB", response.getStatus()); + if (success) { + if (response != null) { + if ((response.getStatus() / 100) == 2) { + logger.info("Successfully completed the DELETE request with status {} and committing it to DB", + response.getStatus()); } else { logFailure(HttpMethod.DELETE, response); } @@ -369,8 +369,9 @@ public class HttpTestUtil extends RESTAPI { return response; } - public static void logFailure(HttpMethod httpMethod, Response response){ - logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(), response.getStatus()); + public static void logFailure(HttpMethod httpMethod, Response response) { + logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(), + response.getStatus()); logger.info("Response body of failed request {}", response.getEntity()); } diff --git a/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java b/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java index 47dfdbe..328e611 100644 --- a/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java +++ b/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java @@ -17,8 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -31,9 +35,6 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.when; - public class IncreaseNodesToolTest extends AAISetup { @Mock @@ -54,10 +55,11 @@ public class IncreaseNodesToolTest extends AAISetup { @Mock GraphTraversal graphTraversalVertex; private IncreaseNodesTool increaseNodesTool; - String [] args = {"-numberOfNodes", "5" ,"-nodeType", "pserver", "-uri", "/cloud-infrastructure/pservers/pserver/", "-child", "false"}; + String[] args = {"-numberOfNodes", "5", "-nodeType", "pserver", "-uri", "/cloud-infrastructure/pservers/pserver/", + "-child", "false"}; @Before - public void setup(){ + public void setup() { increaseNodesTool = new IncreaseNodesTool(loaderFactory, schemaVersions); } @@ -68,11 +70,11 @@ public class IncreaseNodesToolTest extends AAISetup { when(janusGraphtransaction.traversal()).thenReturn(graphTraversalSource); when(graphTraversalSource.addV(nodeTypeCapture.capture())).thenReturn(graphTraversalVertex); when(graphTraversalVertex.next()).thenReturn(mockVertex); - increaseNodesTool.run(janusGraph,args); + increaseNodesTool.run(janusGraph, args); Mockito.verify(janusGraph).newTransaction(); - Mockito.verify(graphTraversalSource,times(5)).addV(nodeTypeCapture.capture()); + Mockito.verify(graphTraversalSource, times(5)).addV(nodeTypeCapture.capture()); } @Test @@ -81,10 +83,9 @@ public class IncreaseNodesToolTest extends AAISetup { when(janusGraph.newTransaction()).thenReturn(janusGraphtransaction); when(janusGraphtransaction.traversal()).thenThrow(new RuntimeException()); - increaseNodesTool.run(janusGraph,args); + increaseNodesTool.run(janusGraph, args); Mockito.verify(janusGraphtransaction).rollback(); } } - diff --git a/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java b/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java index 9c99163..3197c69 100644 --- a/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java +++ b/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai; -import org.apache.commons.io.IOUtils; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.io.InputStream; @@ -28,7 +29,7 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.junit.Assert.assertNotNull; +import org.apache.commons.io.IOUtils; public class PayloadUtil { @@ -37,7 +38,8 @@ public class PayloadUtil { public static String getResourcePayload(String fileName) throws IOException { - InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/resource/" + fileName); + InputStream inputStream = + PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/resource/" + fileName); String message = String.format("Unable to find the %s in src/test/resources", fileName); assertNotNull(message, inputStream); @@ -50,14 +52,15 @@ public class PayloadUtil { public static String getTemplatePayload(String fileName, Map templateValueMap) throws Exception { - InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/templates/" + fileName); + InputStream inputStream = + PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/templates/" + fileName); String message = String.format("Unable to find the %s in src/test/resources", fileName); assertNotNull(message, inputStream); String resource; - if(cache.containsKey(fileName)){ + if (cache.containsKey(fileName)) { resource = cache.get(fileName); } else { resource = IOUtils.toString(inputStream); @@ -68,21 +71,23 @@ public class PayloadUtil { String resourceWithTemplateValues = resource; - while(matcher.find()){ + while (matcher.find()) { int start = matcher.start() + 2; int end = matcher.end() - 1; String key = resource.substring(start, end); - if(templateValueMap.containsKey(key)){ - resourceWithTemplateValues = resourceWithTemplateValues.replaceAll("\\$\\{" + key +"\\}", templateValueMap.get(key)); + if (templateValueMap.containsKey(key)) { + resourceWithTemplateValues = + resourceWithTemplateValues.replaceAll("\\$\\{" + key + "\\}", templateValueMap.get(key)); } else { - throw new RuntimeException("Unable to find the key value pair in map for the template processing for key " + key); + throw new RuntimeException( + "Unable to find the key value pair in map for the template processing for key " + key); } } inputStream.close(); return resourceWithTemplateValues; } - + public static String getPayload(String fileName) throws IOException { InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/" + fileName); diff --git a/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java b/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java index 7a9ae2d..7e91341 100644 --- a/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java +++ b/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java @@ -17,13 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; + +import javax.net.ssl.SSLContext; + import org.apache.http.client.HttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.client.RestTemplateBuilder; @@ -36,13 +45,6 @@ import org.springframework.util.ResourceUtils; import org.springframework.web.client.ResponseErrorHandler; import org.springframework.web.client.RestTemplate; -import javax.net.ssl.SSLContext; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.KeyStore; - @TestConfiguration public class ResourcesTestConfiguration { @@ -58,9 +60,8 @@ public class ResourcesTestConfiguration { @Bean RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception { - RestTemplate restTemplate = null; - if(env.acceptsProfiles("one-way-ssl", "two-way-ssl")) { + if (env.acceptsProfiles("one-way-ssl", "two-way-ssl")) { char[] trustStorePassword = env.getProperty("server.ssl.trust-store-password").toCharArray(); char[] keyStorePassword = env.getProperty("server.ssl.key-store-password").toCharArray(); @@ -69,22 +70,18 @@ public class ResourcesTestConfiguration { SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); if (env.acceptsProfiles("two-way-ssl")) { - sslContextBuilder = sslContextBuilder.loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword); + sslContextBuilder = + sslContextBuilder.loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword); } - SSLContext sslContext = sslContextBuilder - .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword) - .build(); + SSLContext sslContext = + sslContextBuilder.loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword).build(); - HttpClient client = HttpClients.custom() - .setSSLContext(sslContext) - .setSSLHostnameVerifier((s, sslSession) -> true) - .build(); + HttpClient client = HttpClients.custom().setSSLContext(sslContext) + .setSSLHostnameVerifier((s, sslSession) -> true).build(); - restTemplate = builder - .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)) - .build(); - }else { + restTemplate = builder.requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)).build(); + } else { restTemplate = builder.build(); } restTemplate.setErrorHandler(new ResponseErrorHandler() { @@ -99,7 +96,7 @@ public class ResourcesTestConfiguration { return true; } - if(clientHttpResponse.getRawStatusCode() % 100 == 5){ + if (clientHttpResponse.getRawStatusCode() % 100 == 5) { logger.debug("Call returned a error " + clientHttpResponse.getStatusText()); return true; } diff --git a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java index c7755b0..1e47c42 100644 --- a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java +++ b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java @@ -17,13 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.it.multitenancy; import com.github.dockerjava.api.model.ExposedPort; import com.github.dockerjava.api.model.HostConfig; import com.github.dockerjava.api.model.PortBinding; import com.github.dockerjava.api.model.Ports; + import dasniko.testcontainers.keycloak.KeycloakContainer; + import org.keycloak.adapters.springboot.KeycloakSpringBootProperties; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.KeycloakBuilder; @@ -41,24 +44,20 @@ class KeycloakTestConfiguration { @Bean KeycloakContainer keycloakContainer(KeycloakTestProperties properties) { - KeycloakContainer keycloak = new KeycloakContainer("jboss/keycloak:12.0.4") - .withRealmImportFile(properties.realmJson) - .withCreateContainerCmdModifier(cmd -> cmd.withHostConfig( - new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(Integer.parseInt(properties.port)), new ExposedPort(8080))) - )); + KeycloakContainer keycloak = + new KeycloakContainer("jboss/keycloak:12.0.4").withRealmImportFile(properties.realmJson) + .withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(new HostConfig().withPortBindings( + new PortBinding(Ports.Binding.bindPort(Integer.parseInt(properties.port)), + new ExposedPort(8080))))); keycloak.start(); return keycloak; } @Bean Keycloak keycloakAdminClient(KeycloakContainer keycloak, KeycloakTestProperties properties) { - return KeycloakBuilder.builder() - .serverUrl(keycloak.getAuthServerUrl()) - .realm(properties.realm) - .clientId(properties.adminCli) - .username(keycloak.getAdminUsername()) - .password(keycloak.getAdminPassword()) - .build(); + return KeycloakBuilder.builder().serverUrl(keycloak.getAuthServerUrl()).realm(properties.realm) + .clientId(properties.adminCli).username(keycloak.getAdminUsername()) + .password(keycloak.getAdminPassword()).build(); } @Bean diff --git a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java index df9db84..7f1e34c 100644 --- a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java +++ b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.it.multitenancy; import org.springframework.beans.factory.annotation.Value; diff --git a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java index 9726cc9..300730a 100644 --- a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java +++ b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java @@ -17,9 +17,16 @@ * limitations under the License. * ============LICENSE_END==================================================== */ + package org.onap.aai.it.multitenancy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import dasniko.testcontainers.keycloak.KeycloakContainer; + +import java.util.Collections; + import org.junit.Test; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.KeycloakBuilder; @@ -31,11 +38,6 @@ import org.springframework.context.annotation.Import; import org.springframework.http.*; import org.springframework.test.context.TestPropertySource; -import java.util.Collections; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - @Import(KeycloakTestConfiguration.class) @TestPropertySource(locations = "classpath:it/application-keycloak-test.properties") public class MultiTenancyIT extends AbstractSpringRestTest { @@ -61,14 +63,16 @@ public class MultiTenancyIT extends AbstractSpringRestTest { assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); // get pnf with bob (operator_readOnly) - username = "bob"; password = "bob"; + username = "bob"; + password = "bob"; headers = this.getHeaders(username, password); httpEntity = new HttpEntity("", headers); responseEntity = restTemplate.exchange(endpoint, HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); // get pnf with ted (selector) - username = "ted"; password = "ted"; + username = "ted"; + password = "ted"; headers = this.getHeaders(username, password); httpEntity = new HttpEntity("", headers); responseEntity = restTemplate.exchange(endpoint, HttpMethod.GET, httpEntity, String.class); @@ -82,7 +86,8 @@ public class MultiTenancyIT extends AbstractSpringRestTest { assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); // get pnf with ran - username = "ran"; password = "ran"; + username = "ran"; + password = "ran"; headers = this.getHeaders(username, password); httpEntity = new HttpEntity("", headers); responseEntity = restTemplate.exchange(endpoint, HttpMethod.GET, httpEntity, String.class); @@ -103,14 +108,9 @@ public class MultiTenancyIT extends AbstractSpringRestTest { } private String getStringToken(String username, String password) { - Keycloak keycloakClient = KeycloakBuilder.builder() - .serverUrl(keycloakContainer.getAuthServerUrl()) - .realm(properties.realm) - .clientId(properties.clientId) - .clientSecret(properties.clientSecret) - .username(username) - .password(password) - .build(); + Keycloak keycloakClient = KeycloakBuilder.builder().serverUrl(keycloakContainer.getAuthServerUrl()) + .realm(properties.realm).clientId(properties.clientId).clientSecret(properties.clientSecret) + .username(username).password(password).build(); AccessTokenResponse tokenResponse = keycloakClient.tokenManager().getAccessToken(); assertNotNull(tokenResponse); diff --git a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java index 414c6b9..c9c1fd2 100644 --- a/aai-resources/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java +++ b/aai-resources/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java @@ -17,18 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.it.multitenancy; +import java.util.Collections; + import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.resource.RealmResource; -import java.util.Collections; - class RoleHandler { - /** - Following roles should be the same as given roles in multi-tenancy-realm json file - */ + /** + * Following roles should be the same as given roles in multi-tenancy-realm json file + */ final static String OPERATOR = "operator"; final static String OPERATOR_READ_ONLY = "operator_readOnly"; private final Keycloak adminClient; @@ -41,17 +42,13 @@ class RoleHandler { void addToUser(String role, String username) { RealmResource realm = adminClient.realm(properties.realm); - realm.users().get(username) - .roles() - .realmLevel() + realm.users().get(username).roles().realmLevel() .add(Collections.singletonList(realm.roles().get(role).toRepresentation())); } void removeFromUser(String role, String username) { RealmResource realm = adminClient.realm(properties.realm); - realm.users().get(username) - .roles() - .realmLevel() + realm.users().get(username).roles().realmLevel() .remove(Collections.singletonList(realm.roles().get(role).toRepresentation())); } } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java b/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java index e4684fb..b47485e 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java @@ -17,8 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import java.io.UnsupportedEncodingException; +import java.util.Base64; +import java.util.Collections; + import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.janusgraph.core.JanusGraph; @@ -26,14 +31,14 @@ import org.janusgraph.core.JanusGraphTransaction; import org.junit.*; import org.onap.aai.ResourcesApp; import org.onap.aai.ResourcesTestConfiguration; -import org.onap.aai.restclient.PropertyPasswordConfiguration; import org.onap.aai.dbmap.AAIGraph; import org.onap.aai.exceptions.AAIException; import org.onap.aai.nodes.NodeIngestor; +import org.onap.aai.restclient.PropertyPasswordConfiguration; import org.onap.aai.util.AAIConfig; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -44,10 +49,6 @@ import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; import org.springframework.web.client.RestTemplate; -import java.io.UnsupportedEncodingException; -import java.util.Base64; -import java.util.Collections; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ResourcesApp.class) @TestPropertySource(locations = "classpath:application-test.properties") @ContextConfiguration(initializers = PropertyPasswordConfiguration.class) @@ -65,14 +66,14 @@ public abstract class AbstractSpringRestTest { @Autowired protected NodeIngestor nodeIngestor; - + @LocalServerPort protected int randomPort; protected HttpEntity httpEntity; protected String baseUrl; - protected HttpHeaders headers ; + protected HttpHeaders headers; @BeforeClass public static void setupConfig() throws AAIException { @@ -102,7 +103,7 @@ public abstract class AbstractSpringRestTest { } @After - public void tearDown(){ + public void tearDown() { JanusGraph janusGraph = AAIGraph.getInstance().getGraph(); JanusGraphTransaction transaction = janusGraph.newTransaction(); @@ -111,14 +112,12 @@ public abstract class AbstractSpringRestTest { try { GraphTraversalSource g = transaction.traversal(); - g.V().has("source-of-truth", P.within("JUNIT", "AAI-EXTENSIONS")) - .toList() - .stream() + g.V().has("source-of-truth", P.within("JUNIT", "AAI-EXTENSIONS")).toList().stream() .forEach(v -> v.remove()); - } catch(Exception ex){ + } catch (Exception ex) { success = false; } finally { - if(success){ + if (success) { transaction.commit(); } else { transaction.rollback(); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java index 5366802..de72d5c 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -28,15 +29,14 @@ import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.junit.Test; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; + public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { private static final Logger logger = LoggerFactory.getLogger(BulkAddConsumerTest.class.getName()); - - @Test + @Test public void validBulkAddTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -46,10 +46,11 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 3 {\"201\":null}", 3, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 3 {\"201\":null}", 3, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); } - - @Test + + @Test public void bulkProcessPayloadInBulkAddTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -59,12 +60,15 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 1 {\"201\":null}", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); - assertEquals("Contains 1 {\"400\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); - assertEquals("Contains 1 ERR.5.4.6118", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); + assertEquals("Contains 1 {\"201\":null}", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 1 {\"400\":\"{", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); + assertEquals("Contains 1 ERR.5.4.6118", 1, + StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); } - - @Test + + @Test public void bulkAddInvalidMethodTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -74,12 +78,14 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 1 {\"400\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); - assertEquals("Contains 1 ERR.5.4.6118", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); + assertEquals("Contains 1 {\"400\":\"{", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); + assertEquals("Contains 1 ERR.5.4.6118", 1, + StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); } @Test - public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest(){ + public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest() { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -105,7 +111,7 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { } @Test - public void bulkAddCheckMeetsLimit() throws IOException{ + public void bulkAddCheckMeetsLimit() throws IOException { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -113,11 +119,12 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Created", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 30 {\"201\":null}", 30, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 30 {\"201\":null}", 30, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); } @Test - public void bulkAddCheckExceedsLimit() throws IOException{ + public void bulkAddCheckExceedsLimit() throws IOException { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -127,14 +134,14 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction { assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6147")); } - + @Override - protected BulkConsumer getConsumer(){ + protected BulkConsumer getConsumer() { return new BulkAddConsumer(); } - + @Override protected String getUri() { - return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkadd"; - } + return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkadd"; + } } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java index d2dff7d..a435f45 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -32,7 +33,6 @@ import org.json.JSONException; import org.junit.Test; import org.onap.aai.dbmap.AAIGraph; import org.skyscreamer.jsonassert.JSONAssert; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockHttpServletRequest; @@ -42,7 +42,7 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { private static final Logger logger = LoggerFactory.getLogger(BulkProcessConsumerTest.class.getName()); private LegacyMoxyConsumer legacyMoxyConsumer; - @Test + @Test public void bulkAddPayloadInBulkProcessTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -52,10 +52,11 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 3 {\"201\":null}", 3, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 3 {\"201\":null}", 3, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); } - - @Test + + @Test public void bulkProcessPayloadTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -65,9 +66,12 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 1 {\"201\":null}", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); - assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{")); - assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114")); + assertEquals("Contains 1 {\"201\":null}", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 1 {\"404\":\"{", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{")); + assertEquals("Contains 1 ERR.5.4.6114", 1, + StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114")); } @Test @@ -79,11 +83,12 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { String payload = getBulkPayload("pserver-bulk-process-transactions-with-patch"); Response response = executeRequest(payload); System.out.println(response.getEntity()); - System.out.println(AAIGraph.getInstance().getGraph().newTransaction().traversal().V().has("fqdn", "NEW").count().next()); + System.out.println( + AAIGraph.getInstance().getGraph().newTransaction().traversal().V().has("fqdn", "NEW").count().next()); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); } - - @Test + + @Test public void bulkProcessComplexDeletePayloadTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -94,21 +99,24 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { System.out.println(response.getEntity().toString()); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 0 {\"201\":null}", 0, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); - assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{")); - assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114")); + assertEquals("Contains 0 {\"201\":null}", 0, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 1 {\"404\":\"{", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{")); + assertEquals("Contains 1 ERR.5.4.6114", 1, + StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114")); } - - @Test + + @Test public void testBulkDeletePserverAndComplexRelationship() throws IOException, JSONException { - - legacyMoxyConsumer = new LegacyMoxyConsumer(); + + legacyMoxyConsumer = new LegacyMoxyConsumer(); String pserverData = getPayload("payloads/relationship/pserver-bugfix.json"); String complexData = getPayload("payloads/relationship/complex-bugfix.json"); String hostname = "pserver-9876543210-77-jenkins"; - String physicalLocationId ="complex-987654321-77-jenkins"; + String physicalLocationId = "complex-987654321-77-jenkins"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String complexUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); @@ -116,114 +124,84 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { doSetupResource(pserverUri, pserverData); doSetupResource(complexUri, complexData); - String complexToPserverRelationshipData = getPayload("payloads/relationship/pserver-complex-relationship-for-bulk.json"); - String complexToPserverRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + String complexToPserverRelationshipData = + getPayload("payloads/relationship/pserver-complex-relationship-for-bulk.json"); + String complexToPserverRelationshipUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); - Response response = legacyMoxyConsumer.updateRelationship( - complexToPserverRelationshipData, - schemaVersions.getDefaultVersion().toString(), - complexToPserverRelationshipUri, - httpHeaders, - uriInfo, - new MockHttpServletRequest("DELETE", "http://www.test.com") - ); + Response response = legacyMoxyConsumer.updateRelationship(complexToPserverRelationshipData, + schemaVersions.getDefaultVersion().toString(), complexToPserverRelationshipUri, httpHeaders, uriInfo, + new MockHttpServletRequest("DELETE", "http://www.test.com")); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.OK.getStatusCode(), response.getStatus()); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals("Expected to return status created from the response", Response.Status.OK.getStatusCode(), + response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); // TODO - Need to actually verify the relationship between pserver and cloud-region - + String payload = getBulkPayload("complex-bulk-process-delete-transactions"); Response responseBulkDelete = executeRequest(payload); System.out.println(responseBulkDelete.getEntity().toString()); - + code = responseBulkDelete.getStatus(); - - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity()); - System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity()); - } - assertEquals("Expected to return status created from the response", - Response.Status.CREATED.getStatusCode(), responseBulkDelete.getStatus()); - assertEquals("Contains 0 {\"204\":null}", 1, StringUtils.countMatches(responseBulkDelete.getEntity().toString(), "{\"204\":null}")); - + + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity()); + System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity()); + } + assertEquals("Expected to return status created from the response", Response.Status.CREATED.getStatusCode(), + responseBulkDelete.getStatus()); + assertEquals("Contains 0 {\"204\":null}", 1, + StringUtils.countMatches(responseBulkDelete.getEntity().toString(), "{\"204\":null}")); + } - + protected void doSetupResource(String uri, String payload) throws JSONException { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - "-1", - "-1", - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - new MockHttpServletRequest("GET", "http://www.test.com") - ); + Response response = legacyMoxyConsumer.getLegacy("", "-1", "-1", schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, new MockHttpServletRequest("GET", "http://www.test.com")); assertNotNull("Response from the legacy moxy consumer returned null", response); - assertEquals("Expected to not have the data already in memory", - Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); - - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - new MockHttpServletRequest("PUT", "http://www.test.com") - ); + assertEquals("Expected to not have the data already in memory", Response.Status.NOT_FOUND.getStatusCode(), + response.getStatus()); + + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, new MockHttpServletRequest("PUT", "http://www.test.com")); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("Expected to return status created from the response", Response.Status.CREATED.getStatusCode(), + response.getStatus()); queryParameters.add("depth", "10000"); - response = legacyMoxyConsumer.getLegacy( - "", - "-1", - "-1", - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - new MockHttpServletRequest("GET", "http://www.test.com") - ); + response = legacyMoxyConsumer.getLegacy("", "-1", "-1", schemaVersions.getDefaultVersion().toString(), uri, + "all", "false", httpHeaders, uriInfo, new MockHttpServletRequest("GET", "http://www.test.com")); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals("Expected to return the pserver data that was just put in memory", Response.Status.OK.getStatusCode(), response.getStatus()); - if("".equalsIgnoreCase(payload)){ + if ("".equalsIgnoreCase(payload)) { payload = "{}"; } JSONAssert.assertEquals(payload, response.getEntity().toString(), false); } - - - @Test + + @Test public void bulkAddInvalidMethodTest() throws IOException { when(uriInfo.getPath()).thenReturn(uri); @@ -233,12 +211,14 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 1 {\"400\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); - assertEquals("Contains 1 ERR.5.4.6118", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); + assertEquals("Contains 1 {\"400\":\"{", 1, + StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{")); + assertEquals("Contains 1 ERR.5.4.6118", 1, + StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118")); } @Test - public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest(){ + public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest() { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -262,8 +242,9 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6111")); } + @Test - public void bulkProcessCheckMeetsLimit() throws IOException{ + public void bulkProcessCheckMeetsLimit() throws IOException { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -271,11 +252,12 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { Response response = executeRequest(payload); assertEquals("Created", Response.Status.CREATED.getStatusCode(), response.getStatus()); - assertEquals("Contains 30 {\"201\":null}", 30, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); + assertEquals("Contains 30 {\"201\":null}", 30, + StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}")); } @Test - public void bulkProcessCheckExceedsLimit() throws IOException{ + public void bulkProcessCheckExceedsLimit() throws IOException { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); @@ -285,14 +267,14 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6147")); } - + @Override - protected BulkConsumer getConsumer(){ + protected BulkConsumer getConsumer() { return new BulkProcessConsumer(); } - + @Override protected String getUri() { - return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkprocess"; - } + return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkprocess"; + } } 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 4fd789f..56ab500 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 @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.mockito.ArgumentMatchers.anyObject; @@ -69,33 +70,33 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup { protected List aaiRequestContextList; protected List outputMediaTypes; - + protected String uri; private boolean initialized = false; private static final Logger logger = LoggerFactory.getLogger(BulkProcessorTestAbstraction.class.getName()); @BeforeClass - public static void setupRest(){ - // AAIGraph.getInstance(); - + public static void setupRest() { + // AAIGraph.getInstance(); + } @Before - public void setup(){ - if(!initialized){ - initialized = true; - AAIGraph.getInstance(); - } + public void setup() { + if (!initialized) { + initialized = true; + AAIGraph.getInstance(); + } logger.info("Starting the setup for the integration tests of Rest Endpoints"); - bulkConsumer = getConsumer(); + bulkConsumer = getConsumer(); uri = getUri(); - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -114,7 +115,6 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup { when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); - when(uriInfo.getQueryParameters()).thenReturn(queryParameters); when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); @@ -123,24 +123,19 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup { when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); } - + protected Response executeRequest(String payload) { - MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", "http://www.test.com"); - - return bulkConsumer.bulkProcessor( - payload.replaceAll("", UUID.randomUUID().toString()), - schemaVersions.getDefaultVersion().toString(), - httpHeaders, - uriInfo, - mockReq - ); - } + MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", "http://www.test.com"); + + return bulkConsumer.bulkProcessor(payload.replaceAll("", UUID.randomUUID().toString()), + schemaVersions.getDefaultVersion().toString(), httpHeaders, uriInfo, mockReq); + } protected String getBulkPayload(String bulkPayloadName) throws IOException { return getPayload("payloads/bulk/" + bulkPayloadName + ".json"); } - + protected abstract BulkConsumer getConsumer(); - + protected abstract String getUri(); } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/CloudRegionTest.java b/aai-resources/src/test/java/org/onap/aai/rest/CloudRegionTest.java index a4f9629..0f4a20e 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/CloudRegionTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/CloudRegionTest.java @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END==================================================== */ + package org.onap.aai.rest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + import org.junit.Test; import org.onap.aai.PayloadUtil; import org.springframework.http.HttpEntity; @@ -26,12 +33,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.Assert.assertEquals; - public class CloudRegionTest extends AbstractSpringRestTest { @Test @@ -49,7 +50,8 @@ public class CloudRegionTest extends AbstractSpringRestTest { responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); - responseEntity = restTemplate.exchange(baseUrl + endpoint + "/tenants", HttpMethod.GET, httpEntity, String.class); + responseEntity = + restTemplate.exchange(baseUrl + endpoint + "/tenants", HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertThat(responseEntity.getBody().toString(), containsString("tenant-id")); } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java index caaf91a..d8e02b2 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java @@ -17,34 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.jayway.jsonpath.JsonPath; + +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.UUID; + import org.junit.Before; import org.junit.Test; import org.onap.aai.ResourcesApp; import org.onap.aai.ResourcesTestConfiguration; -import org.onap.aai.restclient.PropertyPasswordConfiguration; import org.onap.aai.config.SpringContextAware; +import org.onap.aai.restclient.PropertyPasswordConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.http.*; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.web.client.RestTemplate; -import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * Test REST requests against configuration resource */ @@ -52,7 +54,9 @@ import static org.junit.Assert.assertTrue; @TestPropertySource(locations = "classpath:application-test.properties") @ContextConfiguration(initializers = PropertyPasswordConfiguration.class, classes = {SpringContextAware.class}) @Import(ResourcesTestConfiguration.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringContextAware.class, ResourcesApp.class}) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = {SpringContextAware.class, ResourcesApp.class}) public class ConfigurationTest extends AbstractSpringRestTest { @Autowired RestTemplate restTemplate; @@ -69,6 +73,7 @@ public class ConfigurationTest extends AbstractSpringRestTest { private String baseUrl; private String actuatorurl; private HttpHeaders headers; + @Before public void setup() throws UnsupportedEncodingException { @@ -90,7 +95,7 @@ public class ConfigurationTest extends AbstractSpringRestTest { @Test public void testGetPutPatchConfiguration() { - String cid = "configtest" + UUID.randomUUID().toString(); + String cid = "configtest" + UUID.randomUUID().toString(); String endpoint = "/aai/v12/network/configurations/configuration/" + cid; ResponseEntity responseEntity = null; @@ -98,96 +103,87 @@ public class ConfigurationTest extends AbstractSpringRestTest { responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); - //String putBody = " configuration-id, configuration-type configuration-sub-type"; - String putBody = "{" + - "\"configuration-id\": \"" + cid + "\"," + - "\"configuration-type\": \"type1\"," + - "\"configuration-sub-type\": \"subtype1\", " + - "\"operational-status\": \"example1\", " + - "\"orchestration-status\": \"example1\", " + - "\"configuration-selflink\": \"example1\", " + - "\"model-customization-id\": \"example1\" " + - "}"; + // String putBody = " configuration-id, configuration-type configuration-sub-type"; + String putBody = "{" + "\"configuration-id\": \"" + cid + "\"," + "\"configuration-type\": \"type1\"," + + "\"configuration-sub-type\": \"subtype1\", " + "\"operational-status\": \"example1\", " + + "\"orchestration-status\": \"example1\", " + "\"configuration-selflink\": \"example1\", " + + "\"model-customization-id\": \"example1\" " + "}"; httpEntityPut = new HttpEntity(putBody, headers); responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntityPut, String.class); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); String vertexId = responseEntity.getHeaders().getFirst("vertex-id"); - responseEntity = restTemplate.exchange(baseUrl + "/aai/v12/resources/id/" + vertexId, HttpMethod.GET, httpEntity, String.class); + responseEntity = restTemplate.exchange(baseUrl + "/aai/v12/resources/id/" + vertexId, HttpMethod.GET, + httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - - String patchBody = "{" + - "\"configuration-id\": \"" + cid + "\"," + - "\"configuration-type\": \"type2\"," + - "\"configuration-sub-type\": \"subtype2\", " + - "\"operational-status\": \"example1\", " + - "\"orchestration-status\": \"example1\", " + - "\"configuration-selflink\": \"example1\", " + - "\"model-customization-id\": \"example1\" " + - "}"; + + String patchBody = "{" + "\"configuration-id\": \"" + cid + "\"," + "\"configuration-type\": \"type2\"," + + "\"configuration-sub-type\": \"subtype2\", " + "\"operational-status\": \"example1\", " + + "\"orchestration-status\": \"example1\", " + "\"configuration-selflink\": \"example1\", " + + "\"model-customization-id\": \"example1\" " + "}"; headers.put("Content-Type", Arrays.asList("application/merge-patch+json")); headers.add("X-HTTP-Method-Override", "PATCH"); - + httpEntityPatch = new HttpEntity(patchBody, headers); - + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.POST, httpEntityPatch, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - + String body = responseEntity.getBody().toString(); String configurationType = JsonPath.read(body, "$.configuration-type"); assertEquals("type2", configurationType); - - patchBody = "{" + - "\"configuration-id\": \"" + cid + "\"," + - "\"configuration-type\": \"type3\"," + - "\"configuration-sub-type\": \"subtype3\" " + - "}"; - + + patchBody = "{" + "\"configuration-id\": \"" + cid + "\"," + "\"configuration-type\": \"type3\"," + + "\"configuration-sub-type\": \"subtype3\" " + "}"; + httpEntityPatch = new HttpEntity(patchBody, headers); responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PATCH, httpEntityPatch, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); - + body = responseEntity.getBody().toString(); configurationType = JsonPath.read(body, "$.configuration-type"); assertEquals("type3", configurationType); - + } - @Test public void TestManagementEndpointConfiguration() { ResponseEntity responseEntity = null; String responseBody = null; - //set Accept as text/plain in order to get access of endpoint "/actuator/prometheus" + // set Accept as text/plain in order to get access of endpoint "/actuator/prometheus" headers.set("Accept", "text/plain"); httpEntity = new HttpEntity(headers); - responseEntity = restTemplate.exchange(actuatorurl + "/actuator/prometheus", HttpMethod.GET, httpEntity, String.class); + responseEntity = + restTemplate.exchange(actuatorurl + "/actuator/prometheus", HttpMethod.GET, httpEntity, String.class); responseBody = (String) responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertTrue(responseBody.contains("group_id")); assertTrue(responseBody.contains("aai_uri")); - - //Set Accept as MediaType.APPLICATION_JSON in order to get access of endpoint "/actuator/info" and "/actuator/health" + + // Set Accept as MediaType.APPLICATION_JSON in order to get access of endpoint "/actuator/info" and + // "/actuator/health" headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); httpEntity = new HttpEntity(headers); - responseEntity = restTemplate.exchange(actuatorurl + "/actuator/info", HttpMethod.GET, httpEntity, String.class); + responseEntity = + restTemplate.exchange(actuatorurl + "/actuator/info", HttpMethod.GET, httpEntity, String.class); responseBody = (String) responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertTrue(responseBody.contains("aai-resources")); - responseEntity = restTemplate.exchange(actuatorurl + "/actuator/health", HttpMethod.GET, httpEntity, String.class); + responseEntity = + restTemplate.exchange(actuatorurl + "/actuator/health", HttpMethod.GET, httpEntity, String.class); responseBody = (String) responseEntity.getBody(); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertTrue(responseBody.contains("UP")); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java b/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java index a52d774..cc35e21 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java @@ -17,18 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; -import org.junit.Test; -import org.onap.aai.PayloadUtil; -import org.springframework.http.*; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import java.util.Base64; import java.util.Collections; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.junit.Test; +import org.onap.aai.PayloadUtil; +import org.springframework.http.*; public class CustomerFilterSearchTest extends AbstractSpringRestTest { @@ -36,7 +37,7 @@ public class CustomerFilterSearchTest extends AbstractSpringRestTest { public void testWhenContentTypeMissingItWillFunctionalAndCreateObjectWithPayloadInJson() throws Exception { String id = "customer-987654321-91"; - String endpoint = "/aai/v11/business/customers/customer/"+ id; + String endpoint = "/aai/v11/business/customers/customer/" + id; HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); 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 c9941dc..1b2e98d 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 @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -74,21 +75,21 @@ public class ExampleConsumerTest extends AAISetup { private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); @BeforeClass - public static void setupRest(){ + public static void setupRest() { AAIGraph.getInstance(); - + } @Before - public void setup(){ + public void setup() { logger.info("Starting the setup for the integration tests of Rest Endpoints"); - exampleConsumer = new ExampleConsumer(); - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + exampleConsumer = new ExampleConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -107,7 +108,6 @@ public class ExampleConsumerTest extends AAISetup { when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); - when(uriInfo.getQueryParameters()).thenReturn(queryParameters); when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); @@ -118,14 +118,10 @@ public class ExampleConsumerTest extends AAISetup { } @Test - public void testGetExampleRespondsWithOkStatusForValidObject(){ + public void testGetExampleRespondsWithOkStatusForValidObject() { - Response response = exampleConsumer.getExample( - schemaVersions.getDefaultVersion().toString(), - "pserver", - httpHeaders, - uriInfo, - null); + Response response = exampleConsumer.getExample(schemaVersions.getDefaultVersion().toString(), "pserver", + httpHeaders, uriInfo, null); assertNotNull("Response from the example consumer returned null", response); @@ -135,17 +131,13 @@ public class ExampleConsumerTest extends AAISetup { } @Test - public void testGetExampleFailureForInvalidObject(){ + public void testGetExampleFailureForInvalidObject() { when(uriInfo.getPath()).thenReturn("examples/fakeObject"); when(uriInfo.getPath(false)).thenReturn("examples/fakeObject"); - Response response = exampleConsumer.getExample( - schemaVersions.getDefaultVersion().toString(), - "testRandomCrazyObject", - httpHeaders, - uriInfo, - null); + Response response = exampleConsumer.getExample(schemaVersions.getDefaultVersion().toString(), + "testRandomCrazyObject", httpHeaders, uriInfo, null); assertNotNull("Response from the example consumer returned null", response); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java index 8eb4722..8a6f469 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java @@ -17,18 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.fasterxml.jackson.core.JsonLocation; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.sun.istack.SAXParseException2; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.aai.AAISetup; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; @@ -36,15 +41,13 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.AAISetup; public class ExceptionHandlerTest extends AAISetup { @@ -60,10 +63,10 @@ public class ExceptionHandlerTest extends AAISetup { private ExceptionHandler handler = new ExceptionHandler(); @Before - public void setup(){ + public void setup() { MockitoAnnotations.initMocks(this); - MultivaluedHashMap headersMultiMap = new MultivaluedHashMap<>(); + MultivaluedHashMap headersMultiMap = new MultivaluedHashMap<>(); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -85,7 +88,7 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNull(response.getEntity()); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); } @Test @@ -97,7 +100,7 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNotNull(response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } @Test @@ -109,7 +112,7 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNotNull(response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } @Test @@ -121,7 +124,7 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNotNull(response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } @Test @@ -134,8 +137,7 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNotNull(response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); - + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } @@ -152,6 +154,6 @@ public class ExceptionHandlerTest extends AAISetup { assertNotNull(response); assertNotNull(response.getEntity()); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java b/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java index ea41872..128a190 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java @@ -17,21 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; - public class InvalidURITest extends AbstractSpringRestTest { @Test - public void testWhenUriNotStartsWithAAIItReturnsProperNotFound(){ + public void testWhenUriNotStartsWithAAIItReturnsProperNotFound() { String endpoint = "/aai1/v11/cloud-infrastructure/pservers/pserver/test"; 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 863b084..4285af8 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 @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -86,29 +87,28 @@ public class LegacyMoxyConsumerTest extends AAISetup { private List outputMediaTypes; private boolean initialized = false; - private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); @BeforeClass - public static void setupRest(){ - // AAIGraph.getInstance(); + public static void setupRest() { + // AAIGraph.getInstance(); } @Before - public void setup(){ - if(!initialized){ - initialized = true; - AAIGraph.getInstance(); - } + public void setup() { + if (!initialized) { + initialized = true; + AAIGraph.getInstance(); + } logger.info("Starting the setup for the integration tests of Rest Endpoints"); - legacyMoxyConsumer = new LegacyMoxyConsumer(); - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + legacyMoxyConsumer = new LegacyMoxyConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -127,7 +127,6 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); - when(uriInfo.getQueryParameters()).thenReturn(queryParameters); when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); @@ -136,7 +135,6 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); - } @Test @@ -148,7 +146,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { assertNotNull("Introspector returned invalid string when marshalling the object", payload); assertNotNull("Introspector failed to return a valid uri", uri); - if(uri.length() != 0 && uri.charAt(0) == '/'){ + if (uri.length() != 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } @@ -156,59 +154,33 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockReq); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + 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( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "10000", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), uri, + "10000", "false", httpHeaders, uriInfo, mockReqGet); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - String pserverEntity = response.getEntity().toString(); + String pserverEntity = response.getEntity().toString(); JSONObject pserverJsonbject = new JSONObject(pserverEntity); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -220,34 +192,18 @@ public class LegacyMoxyConsumerTest extends AAISetup { queryParameters.add("resource-version", resourceVersion); mockReq = new MockHttpServletRequest("DELETE", uri); - response = legacyMoxyConsumer.delete( - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - "", - mockReq - ); + response = legacyMoxyConsumer.delete(schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, uriInfo, + "", mockReq); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + 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( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), uri, + "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @@ -257,7 +213,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String uri = getGetAllPserversURI(); - if(uri.length() != 0 && uri.charAt(0) == '/'){ + if (uri.length() != 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } @@ -265,18 +221,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - "1", - "10", - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", "1", "10", schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); } @@ -287,7 +233,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String complexData = getRelationshipPayload("complex"); String hostname = "590a8943-1200-43b3-825b-75dde6b8f44a"; - String physicalLocationId ="e13d4587-19ad-4bf5-80f5-c021efb5b61c"; + String physicalLocationId = "e13d4587-19ad-4bf5-80f5-c021efb5b61c"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String cloudRegionUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); @@ -296,42 +242,32 @@ public class LegacyMoxyConsumerTest extends AAISetup { doSetupResource(cloudRegionUri, complexData); String cloudToPserverRelationshipData = getRelationshipPayload("pserver-complex-relationship"); - String cloudToPserverRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + String cloudToPserverRelationshipUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", cloudToPserverRelationshipUri); - Response response = legacyMoxyConsumer.updateRelationship( - cloudToPserverRelationshipData, - schemaVersions.getDefaultVersion().toString(), - cloudToPserverRelationshipUri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.updateRelationship(cloudToPserverRelationshipData, + schemaVersions.getDefaultVersion().toString(), cloudToPserverRelationshipUri, httpHeaders, uriInfo, + mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.OK.getStatusCode(), response.getStatus()); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals("Expected to return status created from the response", Response.Status.OK.getStatusCode(), + response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); // TODO - Need to actually verify the relationship between pserver and cloud-region mockReq = new MockHttpServletRequest("DELETE", cloudToPserverRelationshipUri); - response = legacyMoxyConsumer.deleteRelationship( - cloudToPserverRelationshipData, - schemaVersions.getDefaultVersion().toString(), - cloudToPserverRelationshipUri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.deleteRelationship(cloudToPserverRelationshipData, + schemaVersions.getDefaultVersion().toString(), cloudToPserverRelationshipUri, httpHeaders, uriInfo, + mockReq); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -359,17 +295,11 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); int code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); } @@ -382,70 +312,36 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenThrow(new IllegalArgumentException()); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); int code = response.getStatus(); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - response = legacyMoxyConsumer.updateRelationship( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.updateRelationship(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); code = response.getStatus(); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); mockReq = new MockHttpServletRequest("GET", uri); - response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), uri, + "all", "false", httpHeaders, uriInfo, mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); mockReq = new MockHttpServletRequest("DELETE", uri); - response = legacyMoxyConsumer.delete( - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - "", - mockReq - ); + response = legacyMoxyConsumer.delete(schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, uriInfo, + "", mockReq); code = response.getStatus(); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); - response = legacyMoxyConsumer.deleteRelationship( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.deleteRelationship(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); code = response.getStatus(); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); } @@ -459,72 +355,38 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); int code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); - response = legacyMoxyConsumer.updateRelationship( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.updateRelationship(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); mockReq = new MockHttpServletRequest("GET", uri); - response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), uri, + "all", "false", httpHeaders, uriInfo, mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); mockReq = new MockHttpServletRequest("DELETE", uri); queryParameters.add("resource-version", "3434394839483"); - response = legacyMoxyConsumer.delete( - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - "", - mockReq - ); + response = legacyMoxyConsumer.delete(schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, uriInfo, + "", mockReq); code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); - response = legacyMoxyConsumer.deleteRelationship( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.deleteRelationship(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); code = response.getStatus(); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); } @@ -534,9 +396,9 @@ public class LegacyMoxyConsumerTest extends AAISetup { public void testPatchWithValidData() throws IOException { String payload = getResourcePayload("pserver-patch-test"); - String uri = getUri("pserver-patch-test"); + String uri = getUri("pserver-patch-test"); - if(uri.length() != 0 && uri.charAt(0) == '/'){ + if (uri.length() != 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } @@ -544,33 +406,17 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReq = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReq); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); mockReq = new MockHttpServletRequest("PUT", uri); - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockReq); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); @@ -583,18 +429,12 @@ public class LegacyMoxyConsumerTest extends AAISetup { outputMediaTypes.add(MediaType.valueOf("application/merge-patch+json")); mockReq = new MockHttpServletRequest("PATCH", uri); - response = legacyMoxyConsumer.patch( - patchData, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.patch(patchData, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockReq); code = response.getStatus(); assertNotNull("Response from the patch returned null", response); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.OK.getStatusCode(), code); } @@ -607,59 +447,33 @@ public class LegacyMoxyConsumerTest extends AAISetup { HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + uri)); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockRequest - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockRequest); assertNotNull("Response from the legacy moxy consumer returned null", response); - assertEquals("Expected to not have the data already in memory", - Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); - - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockRequest - ); + assertEquals("Expected to not have the data already in memory", Response.Status.NOT_FOUND.getStatusCode(), + response.getStatus()); + + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockRequest); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("Expected to return status created from the response", Response.Status.CREATED.getStatusCode(), + response.getStatus()); queryParameters.add("depth", "10000"); - response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockRequest - ); + response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), uri, + "all", "false", httpHeaders, uriInfo, mockRequest); assertNotNull("Response from the legacy moxy consumer returned null", response); assertEquals("Expected to return the pserver data that was just put in memory", Response.Status.OK.getStatusCode(), response.getStatus()); - if("".equalsIgnoreCase(payload)){ + if ("".equalsIgnoreCase(payload)) { payload = "{}"; } @@ -667,7 +481,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { } @Test - public void testDeleteRelationshipThrowsException(){ + public void testDeleteRelationshipThrowsException() { String payload = ""; String hostname = "testData"; @@ -677,22 +491,16 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReq = new MockHttpServletRequest("DELETE", uri); - Response response = legacyMoxyConsumer.deleteRelationship( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.deleteRelationship(payload, + schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, uriInfo, mockReq); int code = response.getStatus(); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); } // TODO - Change this to be abstract and inheritable - public String getObjectName(){ + public String getObjectName() { return "pserver"; } @@ -704,55 +512,65 @@ public class LegacyMoxyConsumerTest extends AAISetup { return getPayload("payloads/relationship/" + relationshipName + ".json"); } - public String getUri(String hostname){ + public String getUri(String hostname) { return String.format("cloud-infrastructure/pservers/pserver/%s", hostname); } - public String getGetAllPserversURI(){ + + public String getGetAllPserversURI() { return "cloud-infrastructure/pservers"; } - - public String getUri(){ + public String getUri() { return getUri("pserver-hostname-test"); } @Test - public void legacyMoxyCheckTimeoutEnabled() throws Exception{ - boolean isTimeoutEnabled = legacyMoxyConsumer.isTimeoutEnabled("JUNITTESTAPP1", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + public void legacyMoxyCheckTimeoutEnabled() throws Exception { + boolean isTimeoutEnabled = legacyMoxyConsumer.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 legacyMoxyCheckTimeoutEnabledOverride() throws Exception{ - boolean isTimeoutEnabled = legacyMoxyConsumer.isTimeoutEnabled("JUNITTESTAPP2", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + public void legacyMoxyCheckTimeoutEnabledOverride() throws Exception { + boolean isTimeoutEnabled = legacyMoxyConsumer.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 legacyMoxyCheckTimeoutEnabledDefaultLimit() throws Exception{ - boolean isTimeoutEnabled = legacyMoxyConsumer.isTimeoutEnabled("JUNITTESTAPP3", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_ENABLED), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + public void legacyMoxyCheckTimeoutEnabledDefaultLimit() throws Exception { + boolean isTimeoutEnabled = legacyMoxyConsumer.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 = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP3", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + int timeout = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP3", + AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); assertEquals(100000, timeout); } @Test - public void legacyMoxyGetTimeout() throws Exception{ - int timeout = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP1", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + public void legacyMoxyGetTimeout() throws Exception { + int timeout = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP1", + AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); assertEquals(1, timeout); } @Test - public void legacyMoxyGetTimeoutOverride() throws Exception{ - int timeout = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP2", AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); + public void legacyMoxyGetTimeoutOverride() throws Exception { + int timeout = legacyMoxyConsumer.getTimeoutLimit("JUNITTESTAPP2", + AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_APP), AAIConfig.get(AAIConstants.AAI_CRUD_TIMEOUT_LIMIT)); assertEquals(-1, timeout); } + @Ignore("Time sensitive test only times out if the response takes longer than 1 second") @Test - public void testTimeoutGetCall() throws Exception{ + public void testTimeoutGetCall() throws Exception { String uri = getUri(); - if(uri.length() != 0 && uri.charAt(0) == '/'){ + if (uri.length() != 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } @@ -762,26 +580,17 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); } + @Test - public void testBypassTimeoutGetCall() throws Exception{ + public void testBypassTimeoutGetCall() throws Exception { String uri = getUri(); - if(uri.length() != 0 && uri.charAt(0) == '/'){ + if (uri.length() != 0 && uri.charAt(0) == '/') { uri = uri.substring(1); } @@ -791,18 +600,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); } @@ -814,7 +613,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String complexData = getRelationshipPayload("complex2"); String hostname = "590a8943-1200-43b3-825b-75dde6b8f44b"; - String physicalLocationId ="e13d4587-19ad-4bf5-80f5-c021efb5b61d"; + String physicalLocationId = "e13d4587-19ad-4bf5-80f5-c021efb5b61d"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String cloudRegionUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); @@ -823,50 +622,37 @@ public class LegacyMoxyConsumerTest extends AAISetup { doSetupResource(cloudRegionUri, complexData); String cloudToPserverRelationshipData = getRelationshipPayload("pserver-complex-relationship2"); - String cloudToPserverRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + String cloudToPserverRelationshipUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", cloudToPserverRelationshipUri); - Response response = legacyMoxyConsumer.updateRelationship( - cloudToPserverRelationshipData, - schemaVersions.getDefaultVersion().toString(), - cloudToPserverRelationshipUri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.updateRelationship(cloudToPserverRelationshipData, + schemaVersions.getDefaultVersion().toString(), cloudToPserverRelationshipUri, httpHeaders, uriInfo, + mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.OK.getStatusCode(), response.getStatus()); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals("Expected to return status created from the response", Response.Status.OK.getStatusCode(), + response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - String getRelationshipMockRequestUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); - String getRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s", hostname); + String getRelationshipMockRequestUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); + String getRelationshipUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); - when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); - response = legacyMoxyConsumer.getRelationshipList( - "1", - "1", - schemaVersions.getDefaultVersion().toString(), - getRelationshipUri, - "false", - httpHeaders, - mockRequest, - uriInfo - ); + when(mockRequest.getRequestURL()) + .thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); + response = legacyMoxyConsumer.getRelationshipList("1", "1", schemaVersions.getDefaultVersion().toString(), + getRelationshipUri, "false", httpHeaders, mockRequest, uriInfo); String s = response.getEntity().toString(); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -880,7 +666,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String complexData = getRelationshipPayload("complex3"); String hostname = "590a8943-1200-43b3-825b-75dde6b8f44c"; - String physicalLocationId ="e13d4587-19ad-4bf5-80f5-c021efb5b61e"; + String physicalLocationId = "e13d4587-19ad-4bf5-80f5-c021efb5b61e"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String cloudRegionUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); @@ -889,50 +675,37 @@ public class LegacyMoxyConsumerTest extends AAISetup { doSetupResource(cloudRegionUri, complexData); String cloudToPserverRelationshipData = getRelationshipPayload("pserver-complex-relationship3"); - String cloudToPserverRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + String cloudToPserverRelationshipUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", cloudToPserverRelationshipUri); - Response response = legacyMoxyConsumer.updateRelationship( - cloudToPserverRelationshipData, - schemaVersions.getDefaultVersion().toString(), - cloudToPserverRelationshipUri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.updateRelationship(cloudToPserverRelationshipData, + schemaVersions.getDefaultVersion().toString(), cloudToPserverRelationshipUri, httpHeaders, uriInfo, + mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.OK.getStatusCode(), response.getStatus()); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals("Expected to return status created from the response", Response.Status.OK.getStatusCode(), + response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); - String getRelationshipMockRequestUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); - String getRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s", hostname); + String getRelationshipMockRequestUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); + String getRelationshipUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); queryParameters.add("format", "resource"); HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); - when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); - response = legacyMoxyConsumer.getRelationshipList( - "1", - "1", - schemaVersions.getDefaultVersion().toString(), - getRelationshipUri, - "false", - httpHeaders, - mockRequest, - uriInfo - ); + when(mockRequest.getRequestURL()) + .thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); + response = legacyMoxyConsumer.getRelationshipList("1", "1", schemaVersions.getDefaultVersion().toString(), + getRelationshipUri, "false", httpHeaders, mockRequest, uriInfo); queryParameters.remove("format"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -975,7 +748,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String complexData = getRelationshipPayload("complex4"); String hostname = "590a8943-1200-43b3-825b-75dde6b8f44d"; - String physicalLocationId ="e13d4587-19ad-4bf5-80f5-c021efb5b61f"; + String physicalLocationId = "e13d4587-19ad-4bf5-80f5-c021efb5b61f"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String cloudRegionUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); @@ -983,27 +756,20 @@ public class LegacyMoxyConsumerTest extends AAISetup { doSetupResource(pserverUri, pserverData); doSetupResource(cloudRegionUri, complexData); - String getRelationshipMockRequestUri = String.format( - "cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); - String getRelationshipUri = String.format( - "cloud-infrastructure/pservers/pserver/%s", hostname); + String getRelationshipMockRequestUri = + String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list", hostname); + String getRelationshipUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); MockHttpServletRequest mockReq = new MockHttpServletRequest("GET_RELATIONSHIP", getRelationshipMockRequestUri); HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); - when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); - Response response = legacyMoxyConsumer.getRelationshipList( - "1", - "1", - schemaVersions.getDefaultVersion().toString(), - getRelationshipUri, - "false", - httpHeaders, - mockRequest, - uriInfo - ); + when(mockRequest.getRequestURL()) + .thenReturn(new StringBuffer("https://localhost:8447/aai/v15/" + getRelationshipUri)); + Response response = + legacyMoxyConsumer.getRelationshipList("1", "1", schemaVersions.getDefaultVersion().toString(), + getRelationshipUri, "false", httpHeaders, mockRequest, uriInfo); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); @@ -1015,19 +781,22 @@ public class LegacyMoxyConsumerTest extends AAISetup { String vserverData = getResourcePayload("vserver1"); String hostname = "pserver-hostname-test01"; - String cloudRegionId ="testAIC01"; - String tenant ="tenant01"; - String vserver ="vserver01"; + String cloudRegionId = "testAIC01"; + String tenant = "tenant01"; + String vserver = "vserver01"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); - String vserverUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true", cloudRegionId); + String vserverUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true", cloudRegionId); // PUT the resources putResourceWithQueryParam(pserverUri, pserverData); putResourceWithQueryParam(vserverUri, vserverData); - String pserverMockRequestUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); - String vserverMockRequestUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true", + String pserverMockRequestUri = + String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); + String vserverMockRequestUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true", cloudRegionId, tenant, vserver); // === GET - related-to-property should not exist === @@ -1042,12 +811,13 @@ public class LegacyMoxyConsumerTest extends AAISetup { // === Clean up (DELETE) === // vserver - String deleteUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String deleteUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); Response response = deleteServerObject(vserverMockRequestUri, deleteUri, "vserver"); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1055,8 +825,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { deleteUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); response = deleteServerObject(pserverMockRequestUri, deleteUri, "pserver"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); } @@ -1067,9 +837,9 @@ public class LegacyMoxyConsumerTest extends AAISetup { String vserverData = getResourcePayload("vserver2"); String hostname = "pserver-hostname-test02"; - String cloudRegionId ="testAIC02"; - String tenant ="tenant02"; - String vserver ="vserver02"; + String cloudRegionId = "testAIC02"; + String tenant = "tenant02"; + String vserver = "vserver02"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); String vserverUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s", cloudRegionId); @@ -1079,7 +849,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { doSetupResource(vserverUri, vserverData); String pserverMockRequestUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); - String vserverMockRequestUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String vserverMockRequestUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); // === GET - related-to-property should not exist === @@ -1094,12 +865,13 @@ public class LegacyMoxyConsumerTest extends AAISetup { // === Clean up (DELETE) === // vserver - String deleteUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String deleteUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); Response response = deleteServerObject(vserverMockRequestUri, deleteUri, "vserver"); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1107,8 +879,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { deleteUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); response = deleteServerObject(pserverMockRequestUri, deleteUri, "pserver"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); } @@ -1119,19 +891,24 @@ public class LegacyMoxyConsumerTest extends AAISetup { String vserverData = getResourcePayload("vserver3"); String hostname = "pserver-hostname-test03"; - String cloudRegionId ="testAIC03"; - String tenant ="tenant03"; - String vserver ="vserver03"; + String cloudRegionId = "testAIC03"; + String tenant = "tenant03"; + String vserver = "vserver03"; - String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource", hostname); - String vserverUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true&format=resource", cloudRegionId); + String pserverUri = String + .format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource", hostname); + String vserverUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true&format=resource", + cloudRegionId); // PUT the resources putResourceWithQueryParam(pserverUri, pserverData); putResourceWithQueryParam(vserverUri, vserverData); - String pserverMockRequestUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource", hostname); - String vserverMockRequestUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true&format=resource", + String pserverMockRequestUri = String + .format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource", hostname); + String vserverMockRequestUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true&format=resource", cloudRegionId, tenant, vserver); // === GET - related-to-property should not exist === @@ -1146,14 +923,16 @@ public class LegacyMoxyConsumerTest extends AAISetup { // === Clean up (DELETE) === // vserver - String deleteUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String deleteUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); - String vserverMockRequestUriNoFormat = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String vserverMockRequestUriNoFormat = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); Response response = deleteServerObject(vserverMockRequestUriNoFormat, deleteUri, "vserver"); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1161,8 +940,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { deleteUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); response = deleteServerObject(pserverMockRequestUri, deleteUri, "pserver"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1174,19 +953,24 @@ public class LegacyMoxyConsumerTest extends AAISetup { String vserverData = getResourcePayload("vserver4"); String hostname = "pserver-hostname-test04"; - String cloudRegionId ="testAIC04"; - String tenant ="tenant04"; - String vserver ="vserver04"; + String cloudRegionId = "testAIC04"; + String tenant = "tenant04"; + String vserver = "vserver04"; - String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource_and_url", hostname); - String vserverUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true&format=resource_and_url", cloudRegionId); + String pserverUri = String.format( + "cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource_and_url", hostname); + String vserverUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true&format=resource_and_url", + cloudRegionId); // PUT the resources putResourceWithQueryParam(pserverUri, pserverData); putResourceWithQueryParam(vserverUri, vserverData); - String pserverMockRequestUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource_and_url", hostname); - String vserverMockRequestUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true&format=resource_and_url", + String pserverMockRequestUri = String.format( + "cloud-infrastructure/pservers/pserver/%s?skip-related-to=true&format=resource_and_url", hostname); + String vserverMockRequestUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s?skip-related-to=true&format=resource_and_url", cloudRegionId, tenant, vserver); // === GET - related-to-property should not exist === @@ -1201,14 +985,16 @@ public class LegacyMoxyConsumerTest extends AAISetup { // === Clean up (DELETE) === // vserver - String deleteUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String deleteUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); - String vserverMockRequestUriNoFormat = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String vserverMockRequestUriNoFormat = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); Response response = deleteServerObject(vserverMockRequestUriNoFormat, deleteUri, "vserver"); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1216,8 +1002,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { deleteUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); response = deleteServerObject(pserverMockRequestUri, deleteUri, "pserver"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); } @@ -1228,19 +1014,22 @@ public class LegacyMoxyConsumerTest extends AAISetup { String vserverData = getResourcePayload("vserver5"); String hostname = "pserver-hostname-test05"; - String cloudRegionId ="testAIC05"; - String tenant ="tenant05"; - String vserver ="vserver05"; + String cloudRegionId = "testAIC05"; + String tenant = "tenant05"; + String vserver = "vserver05"; String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); - String vserverUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true", cloudRegionId); + String vserverUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s?skip-related-to=true", cloudRegionId); // PUT the resources putResourceWithQueryParam(pserverUri, pserverData); putResourceWithQueryParam(vserverUri, vserverData); - String pserverMockRequestUri = String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); - String vserverMockRequestUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers?vserver-selflink=somelink05&skip-related-to=true", + String pserverMockRequestUri = + String.format("cloud-infrastructure/pservers/pserver/%s?skip-related-to=true", hostname); + String vserverMockRequestUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers?vserver-selflink=somelink05&skip-related-to=true", cloudRegionId, tenant, vserver); // === GET - related-to-property should not exist === @@ -1255,14 +1044,16 @@ public class LegacyMoxyConsumerTest extends AAISetup { // === Clean up (DELETE) === // vserver - String deleteUri = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String deleteUri = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); - String vserverMockRequestUriNoFormat = String.format("cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", + String vserverMockRequestUriNoFormat = String.format( + "cloud-infrastructure/cloud-regions/cloud-region/test-aic/%s/tenants/tenant/%s/vservers/vserver/%s", cloudRegionId, tenant, vserver); Response response = deleteServerObject(vserverMockRequestUriNoFormat, deleteUri, "vserver"); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); @@ -1270,13 +1061,14 @@ public class LegacyMoxyConsumerTest extends AAISetup { deleteUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); response = deleteServerObject(pserverMockRequestUri, deleteUri, "pserver"); code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); } - private Response deleteServerObject(String mockUri, String deleteUri, String nodeType) throws IOException, JSONException { + private Response deleteServerObject(String mockUri, String deleteUri, String nodeType) + throws IOException, JSONException { Response response = getMockResponse(mockUri); String serverEntity = response.getEntity().toString(); JSONObject serverJsonObject = new JSONObject(serverEntity); @@ -1298,14 +1090,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { queryParameters.add("resource-version", resourceVersion); MockHttpServletRequest mockReq = new MockHttpServletRequest("DELETE", deleteUri); - Response deleteResponse = legacyMoxyConsumer.delete( - schemaVersions.getDefaultVersion().toString(), - deleteUri, - httpHeaders, - uriInfo, - resourceVersion, - mockReq - ); + Response deleteResponse = legacyMoxyConsumer.delete(schemaVersions.getDefaultVersion().toString(), deleteUri, + httpHeaders, uriInfo, resourceVersion, mockReq); return deleteResponse; } @@ -1316,7 +1102,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { String[] params; if (!uriSplit[1].contains("&")) { String param = uriSplit[1]; - params = new String[]{param}; + params = new String[] {param}; } else { params = uriSplit[1].split("&"); } @@ -1333,49 +1119,34 @@ public class LegacyMoxyConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - Response response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, + httpHeaders, uriInfo, mockReq); assertNotNull("Response from the legacy moxy consumer returned null", response); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } - assertEquals("Expected to return status created from the response", - Response.Status.CREATED.getStatusCode(), response.getStatus()); - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals("Expected to return status created from the response", Response.Status.CREATED.getStatusCode(), + response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } private Response getMockResponse(String mockUri) throws IOException, JSONException { MockHttpServletRequest mockReq = new MockHttpServletRequest("GET", mockUri); - Response response = legacyMoxyConsumer.getLegacy( - "", - null, - null, - schemaVersions.getDefaultVersion().toString(), - mockUri, - "10000", - "false", - httpHeaders, - uriInfo, - mockReq - ); + Response response = legacyMoxyConsumer.getLegacy("", null, null, schemaVersions.getDefaultVersion().toString(), + mockUri, "10000", "false", httpHeaders, uriInfo, mockReq); String responseEntity = response.getEntity().toString(); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); } return response; } - private boolean isRelatedToPropertiesFieldNullInResponse(Response response, String nodeType) throws IOException, JSONException { + private boolean isRelatedToPropertiesFieldNullInResponse(Response response, String nodeType) + throws IOException, JSONException { String responseEntity = response.getEntity().toString(); boolean noResultsArray = false; JSONObject responseJsonObj = new JSONObject(responseEntity); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java index 7c27477..a4277fb 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java @@ -17,20 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; + import com.jayway.jsonpath.JsonPath; -import org.junit.Test; -import org.springframework.http.*; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Collections; import java.util.UUID; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.springframework.http.*; + public class PserverGenerateUrlTest extends AbstractSpringRestTest { @Test @@ -47,7 +50,8 @@ public class PserverGenerateUrlTest extends AbstractSpringRestTest { assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); String vertexId = responseEntity.getHeaders().getFirst("vertex-id"); - responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/generateurl/id/" + vertexId, HttpMethod.GET, plainHttpEntity(), String.class); + responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/generateurl/id/" + vertexId, HttpMethod.GET, + plainHttpEntity(), String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); assertThat(responseEntity.getBody().toString(), containsString(endpoint)); @@ -57,7 +61,8 @@ public class PserverGenerateUrlTest extends AbstractSpringRestTest { String body = responseEntity.getBody().toString(); String resourceVersion = JsonPath.read(body, "$.resource-version"); - responseEntity = restTemplate.exchange(baseUrl + endpoint+ "?resource-version=" + resourceVersion, HttpMethod.DELETE, httpEntity, String.class); + responseEntity = restTemplate.exchange(baseUrl + endpoint + "?resource-version=" + resourceVersion, + HttpMethod.DELETE, httpEntity, String.class); assertEquals(HttpStatus.NO_CONTENT, responseEntity.getStatusCode()); } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java index 511cf84..e59b772 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java @@ -17,24 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertEquals; + +import java.util.*; + import org.junit.Test; import org.onap.aai.PayloadUtil; import org.springframework.http.*; -import java.util.*; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.Assert.assertEquals; public class PserverMissingTest extends AbstractSpringRestTest { @Test public void testWhenContentTypeMissingItWillFunctionalAndCreateObjectWithPayloadInJson() throws Exception { String id = "test-" + UUID.randomUUID().toString(); - String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/"+ id; + String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/" + id; HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); @@ -62,7 +64,7 @@ public class PserverMissingTest extends AbstractSpringRestTest { public void testWhenAcceptMissingItWillReturnThePayloadInXml() throws Exception { String id = "test-" + UUID.randomUUID().toString(); - String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/"+ id; + String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/" + id; HttpHeaders headers = new HttpHeaders(); headers.add("Real-Time", "true"); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java index 017844e..005ad16 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java @@ -17,8 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + import org.junit.Test; import org.onap.aai.PayloadUtil; import org.onap.aai.util.MapperUtil; @@ -27,17 +39,6 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; - public class PserverRelationshipTest extends AbstractSpringRestTest { @Test @@ -56,7 +57,6 @@ public class PserverRelationshipTest extends AbstractSpringRestTest { httpMethodSet.add(HttpMethod.DELETE); httpMethodSet.add(HttpMethod.OPTIONS); - assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); assertThat(body, containsString("Unrecognized AAI function")); assertThat(responseEntity.getHeaders().getAllow(), containsInAnyOrder(httpMethodSet.toArray())); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java index 7f48ff8..b7dc836 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java @@ -17,18 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; +import static org.junit.Assert.assertEquals; + import com.jayway.jsonpath.JsonPath; + +import java.util.UUID; + import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.util.UUID; - -import static org.junit.Assert.assertEquals; - /** * A sample junit test using spring boot that provides the ability to spin * up the application from the junit layer and run rest requests against @@ -56,7 +58,8 @@ public class PserverTest extends AbstractSpringRestTest { assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); String vertexId = responseEntity.getHeaders().getFirst("vertex-id"); - responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/resources/id/" + vertexId, HttpMethod.GET, httpEntity, String.class); + responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/resources/id/" + vertexId, HttpMethod.GET, + httpEntity, String.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); @@ -65,7 +68,8 @@ public class PserverTest extends AbstractSpringRestTest { String body = responseEntity.getBody().toString(); String resourceVersion = JsonPath.read(body, "$.resource-version"); - responseEntity = restTemplate.exchange(baseUrl + endpoint+ "?resource-version=" + resourceVersion, HttpMethod.DELETE, httpEntity, String.class); + responseEntity = restTemplate.exchange(baseUrl + endpoint + "?resource-version=" + resourceVersion, + HttpMethod.DELETE, httpEntity, String.class); assertEquals(HttpStatus.NO_CONTENT, responseEntity.getStatusCode()); } } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java index 4d75a2e..a1b8cec 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java @@ -17,20 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.rest; - -import org.junit.Test; -import org.springframework.http.*; -import java.util.UUID; +package org.onap.aai.rest; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -public class PserverWrongHeaderTest extends AbstractSpringRestTest{ + +import java.util.UUID; + +import org.junit.Test; +import org.springframework.http.*; + +public class PserverWrongHeaderTest extends AbstractSpringRestTest { @Test - public void testWhenNoHeadersItFailsWithBadRequestAndReturnsXml(){ + public void testWhenNoHeadersItFailsWithBadRequestAndReturnsXml() { HttpHeaders httpHeaders = new HttpHeaders(); 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 f726e2c..5abe263 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 @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -79,27 +80,28 @@ public class URLFromVertexIdConsumerTest extends AAISetup { private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); private boolean initialized = false; + @BeforeClass - public static void setupRest(){ - // AAIGraph.getInstance(); + public static void setupRest() { + // AAIGraph.getInstance(); } @Before - public void setup(){ - if(!initialized){ - initialized = true; - AAIGraph.getInstance(); - } + public void setup() { + if (!initialized) { + initialized = true; + AAIGraph.getInstance(); + } logger.info("Starting the setup for the integration tests of Rest Endpoints"); urlFromVertexIdConsumer = new URLFromVertexIdConsumer(); - legacyMoxyConsumer = new LegacyMoxyConsumer(); + legacyMoxyConsumer = new LegacyMoxyConsumer(); - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -118,7 +120,6 @@ public class URLFromVertexIdConsumerTest extends AAISetup { when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); - when(uriInfo.getQueryParameters()).thenReturn(queryParameters); when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); @@ -138,33 +139,17 @@ public class URLFromVertexIdConsumerTest extends AAISetup { when(uriInfo.getPath(false)).thenReturn(uri); MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - "-1", - "-1", - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", "-1", "-1", schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockReq); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); @@ -175,14 +160,8 @@ public class URLFromVertexIdConsumerTest extends AAISetup { assertTrue("Response doesn't contain the key vertexId", responseHeaders.containsKey("vertex-id")); String vertexId = responseHeaders.get("vertex-id").get(0).toString(); - response = urlFromVertexIdConsumer.generateUrlFromVertexId( - "", - schemaVersions.getDefaultVersion().toString(), - Long.valueOf(vertexId).longValue(), - httpHeaders, - uriInfo, - mockReqGet - ); + response = urlFromVertexIdConsumer.generateUrlFromVertexId("", schemaVersions.getDefaultVersion().toString(), + Long.valueOf(vertexId).longValue(), httpHeaders, uriInfo, mockReqGet); assertNotNull(response); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); @@ -198,14 +177,9 @@ public class URLFromVertexIdConsumerTest extends AAISetup { String vertexId = "384584"; MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = urlFromVertexIdConsumer.generateUrlFromVertexId( - "", - schemaVersions.getDefaultVersion().toString(), - Long.valueOf(vertexId).longValue(), - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = + urlFromVertexIdConsumer.generateUrlFromVertexId("", schemaVersions.getDefaultVersion().toString(), + Long.valueOf(vertexId).longValue(), httpHeaders, uriInfo, mockReqGet); assertNotNull("Check if the response is not null", response); 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 daa87d4..52a5701 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 @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest; import static org.junit.Assert.assertEquals; @@ -50,6 +51,7 @@ import org.onap.aai.exceptions.AAIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockHttpServletRequest; + public class VertexIdConsumerTest extends AAISetup { protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); @@ -78,28 +80,28 @@ public class VertexIdConsumerTest extends AAISetup { private static final Logger logger = LoggerFactory.getLogger(LegacyMoxyConsumerTest.class.getName()); private boolean initialized = false; - + @BeforeClass - public static void setupRest(){ - //AAIGraph.getInstance(); + public static void setupRest() { + // AAIGraph.getInstance(); } @Before - public void setup(){ - if(!initialized){ - initialized = true; - AAIGraph.getInstance(); - } + public void setup() { + if (!initialized) { + initialized = true; + AAIGraph.getInstance(); + } logger.info("Starting the setup for the integration tests of Rest Endpoints"); - vertexIdConsumer = new VertexIdConsumer(); - legacyMoxyConsumer = new LegacyMoxyConsumer(); + vertexIdConsumer = new VertexIdConsumer(); + legacyMoxyConsumer = new LegacyMoxyConsumer(); - httpHeaders = Mockito.mock(HttpHeaders.class); - uriInfo = Mockito.mock(UriInfo.class); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); - headersMultiMap = new MultivaluedHashMap<>(); - queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); @@ -118,7 +120,6 @@ public class VertexIdConsumerTest extends AAISetup { when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); - when(uriInfo.getQueryParameters()).thenReturn(queryParameters); when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); @@ -136,36 +137,20 @@ public class VertexIdConsumerTest extends AAISetup { when(uriInfo.getPath()).thenReturn(uri); when(uriInfo.getPath(false)).thenReturn(uri); - + MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); - Response response = legacyMoxyConsumer.getLegacy( - "", - "-1", - "-1", - schemaVersions.getDefaultVersion().toString(), - uri, - "all", - "false", - httpHeaders, - uriInfo, - mockReqGet - ); + Response response = legacyMoxyConsumer.getLegacy("", "-1", "-1", schemaVersions.getDefaultVersion().toString(), + uri, "all", "false", httpHeaders, uriInfo, mockReqGet); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri); - - response = legacyMoxyConsumer.update( - payload, - schemaVersions.getDefaultVersion().toString(), - uri, - httpHeaders, - uriInfo, - mockReq - ); + + response = legacyMoxyConsumer.update(payload, schemaVersions.getDefaultVersion().toString(), uri, httpHeaders, + uriInfo, mockReq); int code = response.getStatus(); - if(!VALID_HTTP_STATUS_CODES.contains(code)){ - System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + if (!VALID_HTTP_STATUS_CODES.contains(code)) { + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); } assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); @@ -177,15 +162,8 @@ public class VertexIdConsumerTest extends AAISetup { String vertexId = responseHeaders.get("vertex-id").get(0).toString(); - response = vertexIdConsumer.getByVertexId( - "", - schemaVersions.getDefaultVersion().toString(), - Long.valueOf(vertexId).longValue(), - "10000", - httpHeaders, - uriInfo, - mockReqGet - ); + response = vertexIdConsumer.getByVertexId("", schemaVersions.getDefaultVersion().toString(), + Long.valueOf(vertexId).longValue(), "10000", httpHeaders, uriInfo, mockReqGet); assertNotNull(response); String pserverObject = response.getEntity().toString(); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java index 8c24fb4..eaa71a9 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java @@ -17,10 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest.bulk; +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + import com.google.gson.JsonArray; import com.google.gson.JsonParser; + +import java.io.IOException; +import java.util.Iterator; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response; + import org.apache.tinkerpop.gremlin.structure.Property; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; @@ -37,421 +50,321 @@ import org.onap.aai.rest.BulkProcessorTestAbstraction; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.TestPropertySource; -import javax.ws.rs.HttpMethod; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.util.Iterator; +@TestPropertySource(properties = {"delta.events.enabled=true",}) +public class BulkSingleTransactionConsumerTest extends BulkProcessorTestAbstraction { -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.when; + private BulkSingleTransactionConsumer bulkSingleTransactionConsumer = new BulkSingleTransactionConsumer("/aai"); + + @Rule + public TestName name = new TestName(); + + private String sot = "Junit"; + + @Before + public void before() { + sot = "JUNIT-" + name.getMethodName(); + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + headersMultiMap.addFirst("X-FromAppId", sot); + + } + + @Test + public void addPserverPatchSamePserverTest() throws IOException { + + String payload = getBulkPayload("single-transaction/put-patch-same-pserver").replaceAll("", + name.getMethodName()); + Response response = executeRequest(payload); + + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("1 vertex from this test in graph", Long.valueOf(1L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + assertEquals("1 vertex from this test with fqdn = patched-fqdn", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has("fqdn", "patched-fqdn").count().next()); + + } + + @Test + public void putPserverComplexRelBetween() throws IOException { + + String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between").replaceAll("", + name.getMethodName()); + Response response = executeRequest(payload); + + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("2 vertex from this test in graph", Long.valueOf(2L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + assertEquals("1 complex vertex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "complex").count() + .next()); + assertEquals("1 pserver vertex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "pserver").count() + .next()); + assertEquals("pserver has edge to complex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "pserver").bothE() + .otherV().has(AAIProperties.NODE_TYPE, "complex").has(AAIProperties.SOURCE_OF_TRUTH, sot) + .count().next()); + + } + + @Test + public void putPatchSamePserverPutAnotherPserver() throws IOException { + String payload = getBulkPayload("single-transaction/put-patch-same-pserver-put-another-pserver") + .replaceAll("", name.getMethodName()); + Response response = executeRequest(payload); + + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("2 vertex from this test in graph", Long.valueOf(2L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + assertEquals("pserver 1 has hostname pserver-1-" + name.getMethodName() + " fqdn = patched-fqdn", + Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has("hostname", "pserver-1-" + name.getMethodName()) + .has("fqdn", "patched-fqdn").count().next()); + assertEquals("pserver 2 has hostname pserver-2-" + name.getMethodName(), Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has("hostname", "pserver-2-" + name.getMethodName()) + .count().next()); + } + + protected String asString(Vertex v) { + final JSONObject result = new JSONObject(); + Iterator> properties = v.properties(); + Property pk = null; + try { + while (properties.hasNext()) { + pk = properties.next(); + result.put(pk.key(), pk.value()); + } + } catch (JSONException e) { + e.printStackTrace(); + } + + return result.toString(); + } + + @Test + public void putPserverComplexRelBetweenDelExistingGvnf() throws IOException { + + AAIGraph.getInstance().getGraph().traversal().addV().property(AAIProperties.NODE_TYPE, "generic-vnf") + .property(AAIProperties.SOURCE_OF_TRUTH, sot) + .property(AAIProperties.AAI_URI, + "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnf") + .property(AAIProperties.RESOURCE_VERSION, "0").property("vnf-id", "gvnf-" + name.getMethodName()) + .next(); + AAIGraph.getInstance().getGraph().tx().commit(); + + assertEquals("1 generic-vnf vertex exists before payload", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "generic-vnf").count() + .next()); + + String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf") + .replaceAll("", name.getMethodName()); + Response response = executeRequest(payload); + + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + assertEquals("2 vertex from this test in graph", Long.valueOf(2L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + assertEquals("1 complex vertex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "complex").count() + .next()); + assertEquals("1 pserver vertex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "pserver").count() + .next()); + assertEquals("pserver has edge to complex", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "pserver").bothE() + .otherV().has(AAIProperties.NODE_TYPE, "complex").has(AAIProperties.SOURCE_OF_TRUTH, sot) + .count().next()); + assertEquals("0 generic-vnf vertex exists after payload", Long.valueOf(0L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "generic-vnf").count() + .next()); + + assertThat("Response contains 204 status.", response.getEntity().toString(), + containsString("\"response-status-code\":204")); + + } + + @Test + public void putPserverComplexRelBetweenDelExistingGvnfFail() throws IOException { + + AAIGraph.getInstance().getGraph().traversal().addV().property(AAIProperties.NODE_TYPE, "generic-vnf") + .property(AAIProperties.SOURCE_OF_TRUTH, sot) + .property(AAIProperties.AAI_URI, + "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnfFail") + .property(AAIProperties.RESOURCE_VERSION, "0").property("vnf-id", "gvnf-" + name.getMethodName()) + .next(); + AAIGraph.getInstance().getGraph().tx().commit(); + + assertEquals("1 generic-vnf vertex exists before payload", Long.valueOf(1L), + AAIGraph.getInstance().getGraph().newTransaction().traversal().V() + .has(AAIProperties.SOURCE_OF_TRUTH, sot).has(AAIProperties.NODE_TYPE, "generic-vnf").count() + .next()); + + String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf-fail") + .replaceAll("", name.getMethodName()); + Response response = executeRequest(payload); + + System.out.println(response.getEntity().toString()); + + assertEquals("Request failed", Response.Status.PRECONDITION_FAILED.getStatusCode(), response.getStatus()); + + assertEquals("1 vertex exists after payload due to failure", Long.valueOf(1L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + + assertThat("Response contains resource version msg for failed transaction.", response.getEntity().toString(), + containsString("Precondition Failed:resource-version MISMATCH for delete of generic-vnf")); + + assertThat("Response contains correct index of failed operation.", response.getEntity().toString(), + containsString("Operation 3")); + + assertThat("Response contains correct status code.", response.getEntity().toString(), + containsString("failed with status code (412")); + + } + + @Test + public void checkExceedsLimit() throws IOException { + + String payload = getBulkPayload("single-transaction/pserver-bulk-limit-exceed"); + Response response = executeRequest(payload); + + assertEquals("Request fails with 400", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertThat("Response contains payload limit msg.", response.getEntity().toString(), + containsString("Payload Limit Reached, reduce payload: Allowed limit = ")); + } + + @Test + public void invalidJson() { + + String payload = "{]}";// malformed json + Response response = executeRequest(payload); + + assertEquals("Request fails with 400", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertThat("Response contains invalid payload msg.", response.getEntity().toString(), containsString( + "JSON processing error:Input payload does not follow bulk/single-transaction interface")); + } + + @Test + public void noOperations() { + + String payload = "{'operations':[]}"; + Response response = executeRequest(payload); + + assertEquals("Request fails with 400", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertThat("Response contains invalid payload msg.", response.getEntity().toString(), + containsString("Required Field not passed.: Payload has no objects to operate on")); + } + + @Test + public void invalidAction() throws IOException { + + String payload = getBulkPayload("single-transaction/invalid-action"); + Response response = executeRequest(payload); + + assertEquals("Request fails with 400", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertThat("Response contains invalid payload msg.", response.getEntity().toString(), + containsString("JSON processing error:input payload missing required properties")); + assertThat("Response contains invalid payload details.", response.getEntity().toString(), + containsString("[Operation 0 has invalid action 'create', Operation 1 has invalid action 'destroy']")); + + } + + @Test + public void missingFields() throws IOException { + + String payload = getBulkPayload("single-transaction/missing-fields"); + Response response = executeRequest(payload); -@TestPropertySource(properties = { - "delta.events.enabled=true", -}) -public class BulkSingleTransactionConsumerTest extends BulkProcessorTestAbstraction { + assertEquals("Request fails with 400", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertThat("Response contains invalid payload msg.", response.getEntity().toString(), + containsString("JSON processing error:input payload missing required properties")); + assertThat("Response contains invalid payload details.", response.getEntity().toString(), containsString( + "[Operation 0 missing 'body', Operation 1 missing 'action', Operation 2 missing 'uri']")); + + } + + @Test + public void putComplexWithRelToNonExistentPserverBetween() throws IOException { + + String payload = getBulkPayload("single-transaction/put-complex-with-rel-to-non-existent") + .replaceAll("", name.getMethodName()); + Response response = executeRequest(payload); + + assertEquals("Request success", Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + assertEquals("0 vertex from this test in graph", Long.valueOf(0L), AAIGraph.getInstance().getGraph() + .newTransaction().traversal().V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); + assertEquals("Request fails with 404", Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + assertThat("Response contains correct index of failed operation.", response.getEntity().toString(), + containsString("Operation 0")); + + assertThat("Response contains correct status code.", response.getEntity().toString(), + containsString("failed with status code (404")); + + assertThat("Response contains correct msg.", response.getEntity().toString(), + containsString("target node:Node of type pserver. Could not find")); + + assertThat("Response contains correct Error Code.", response.getEntity().toString(), + containsString("ERR.5.4.6129")); + + } - private BulkSingleTransactionConsumer bulkSingleTransactionConsumer = new BulkSingleTransactionConsumer("/aai"); - - @Rule - public TestName name = new TestName(); - - private String sot = "Junit"; - - @Before - public void before() { - sot = "JUNIT-" + name.getMethodName(); - when(uriInfo.getPath()).thenReturn(uri); - when(uriInfo.getPath(false)).thenReturn(uri); - headersMultiMap.addFirst("X-FromAppId", sot); - - } - - @Test - public void addPserverPatchSamePserverTest() throws IOException { - - String payload = getBulkPayload("single-transaction/put-patch-same-pserver").replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - assertEquals("1 vertex from this test in graph", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("1 vertex from this test with fqdn = patched-fqdn", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has("fqdn", "patched-fqdn").count().next()); - - - } - - @Test - public void putPserverComplexRelBetween() throws IOException { - - String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between").replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - assertEquals("2 vertex from this test in graph", - Long.valueOf(2L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("1 complex vertex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "complex").count().next()); - assertEquals("1 pserver vertex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "pserver").count().next()); - assertEquals("pserver has edge to complex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "pserver") - .bothE() - .otherV() - .has(AAIProperties.NODE_TYPE, "complex") - .has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - - - } - - @Test - public void putPatchSamePserverPutAnotherPserver() throws IOException { - String payload = getBulkPayload("single-transaction/put-patch-same-pserver-put-another-pserver") - .replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - assertEquals("2 vertex from this test in graph", - Long.valueOf(2L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("pserver 1 has hostname pserver-1-" + name.getMethodName() + " fqdn = patched-fqdn", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has("hostname", "pserver-1-" + name.getMethodName()) - .has("fqdn", "patched-fqdn").count().next()); - assertEquals("pserver 2 has hostname pserver-2-" + name.getMethodName(), - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has("hostname", "pserver-2-" + name.getMethodName()).count().next()); - } - - - protected String asString(Vertex v) { - final JSONObject result = new JSONObject(); - Iterator> properties = v.properties(); - Property pk = null; - try { - while (properties.hasNext()) { - pk = properties.next(); - result.put(pk.key(), pk.value()); - } - } catch (JSONException e) { - e.printStackTrace(); - } - - return result.toString(); - } - - @Test - public void putPserverComplexRelBetweenDelExistingGvnf() throws IOException { - - AAIGraph.getInstance().getGraph().traversal().addV() - .property(AAIProperties.NODE_TYPE, "generic-vnf") - .property(AAIProperties.SOURCE_OF_TRUTH, sot) - .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnf") - .property(AAIProperties.RESOURCE_VERSION, "0") - .property("vnf-id", "gvnf-" + name.getMethodName()) - .next(); - AAIGraph.getInstance().getGraph().tx().commit(); - - assertEquals("1 generic-vnf vertex exists before payload", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next()); - - String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf") - .replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - assertEquals("2 vertex from this test in graph", - Long.valueOf(2L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("1 complex vertex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "complex").count().next()); - assertEquals("1 pserver vertex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "pserver").count().next()); - assertEquals("pserver has edge to complex", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "pserver") - .bothE() - .otherV() - .has(AAIProperties.NODE_TYPE, "complex") - .has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("0 generic-vnf vertex exists after payload", - Long.valueOf(0L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next()); - - assertThat("Response contains 204 status.", - response.getEntity().toString(), - containsString("\"response-status-code\":204")); - - - } - - @Test - public void putPserverComplexRelBetweenDelExistingGvnfFail() throws IOException { - - AAIGraph.getInstance().getGraph().traversal().addV() - .property(AAIProperties.NODE_TYPE, "generic-vnf") - .property(AAIProperties.SOURCE_OF_TRUTH, sot) - .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnfFail") - .property(AAIProperties.RESOURCE_VERSION, "0") - .property("vnf-id", "gvnf-" + name.getMethodName()) - .next(); - AAIGraph.getInstance().getGraph().tx().commit(); - - assertEquals("1 generic-vnf vertex exists before payload", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot) - .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next()); - - String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf-fail") - .replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - System.out.println(response.getEntity().toString()); - - assertEquals("Request failed", - Response.Status.PRECONDITION_FAILED.getStatusCode(), - response.getStatus()); - - assertEquals("1 vertex exists after payload due to failure", - Long.valueOf(1L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - - assertThat("Response contains resource version msg for failed transaction.", - response.getEntity().toString(), - containsString("Precondition Failed:resource-version MISMATCH for delete of generic-vnf")); - - assertThat("Response contains correct index of failed operation.", - response.getEntity().toString(), - containsString("Operation 3")); - - assertThat("Response contains correct status code.", - response.getEntity().toString(), - containsString("failed with status code (412")); - - } - - @Test - public void checkExceedsLimit() throws IOException{ - - String payload = getBulkPayload("single-transaction/pserver-bulk-limit-exceed"); - Response response = executeRequest(payload); - - assertEquals("Request fails with 400", - Response.Status.BAD_REQUEST.getStatusCode(), - response.getStatus()); - assertThat("Response contains payload limit msg.", - response.getEntity().toString(), - containsString("Payload Limit Reached, reduce payload: Allowed limit = ")); - } - - @Test - public void invalidJson() { - - String payload = "{]}";//malformed json - Response response = executeRequest(payload); - - assertEquals("Request fails with 400", - Response.Status.BAD_REQUEST.getStatusCode(), - response.getStatus()); - assertThat("Response contains invalid payload msg.", - response.getEntity().toString(), - containsString("JSON processing error:Input payload does not follow bulk/single-transaction interface")); - } - - - @Test - public void noOperations() { - - String payload = "{'operations':[]}"; - Response response = executeRequest(payload); - - assertEquals("Request fails with 400", - Response.Status.BAD_REQUEST.getStatusCode(), - response.getStatus()); - assertThat("Response contains invalid payload msg.", - response.getEntity().toString(), - containsString("Required Field not passed.: Payload has no objects to operate on")); - } - - @Test - public void invalidAction() throws IOException { - - String payload = getBulkPayload("single-transaction/invalid-action"); - Response response = executeRequest(payload); - - assertEquals("Request fails with 400", - Response.Status.BAD_REQUEST.getStatusCode(), - response.getStatus()); - assertThat("Response contains invalid payload msg.", - response.getEntity().toString(), - containsString("JSON processing error:input payload missing required properties")); - assertThat("Response contains invalid payload details.", - response.getEntity().toString(), - containsString("[Operation 0 has invalid action 'create', Operation 1 has invalid action 'destroy']")); - - } - - @Test - public void missingFields() throws IOException { - - String payload = getBulkPayload("single-transaction/missing-fields"); - Response response = executeRequest(payload); - - assertEquals("Request fails with 400", - Response.Status.BAD_REQUEST.getStatusCode(), - response.getStatus()); - assertThat("Response contains invalid payload msg.", - response.getEntity().toString(), - containsString("JSON processing error:input payload missing required properties")); - assertThat("Response contains invalid payload details.", - response.getEntity().toString(), - containsString("[Operation 0 missing 'body', Operation 1 missing 'action', Operation 2 missing 'uri']")); - - } - - @Test - public void putComplexWithRelToNonExistentPserverBetween() throws IOException { - - String payload = getBulkPayload("single-transaction/put-complex-with-rel-to-non-existent").replaceAll("", name.getMethodName()); - Response response = executeRequest(payload); - - assertEquals("Request success", - Response.Status.NOT_FOUND.getStatusCode(), - response.getStatus()); - assertEquals("0 vertex from this test in graph", - Long.valueOf(0L), - AAIGraph.getInstance().getGraph().newTransaction().traversal(). - V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next()); - assertEquals("Request fails with 404", - Response.Status.NOT_FOUND.getStatusCode(), - response.getStatus()); - - assertThat("Response contains correct index of failed operation.", - response.getEntity().toString(), - containsString("Operation 0")); - - assertThat("Response contains correct status code.", - response.getEntity().toString(), - containsString("failed with status code (404")); - - assertThat("Response contains correct msg.", - response.getEntity().toString(), - containsString("target node:Node of type pserver. Could not find")); - - assertThat("Response contains correct Error Code.", - response.getEntity().toString(), - containsString("ERR.5.4.6129")); - - } - - - @Test - public void deleteChildRecreateChildTest() throws IOException { - JsonArray requests = new JsonParser().parse( - getBulkPayload("single-transaction/delete-child-recreate-child").replaceAll("", name.getMethodName())) - .getAsJsonObject().getAsJsonArray("array"); - String payload = requests.get(0).toString(); - Response response = executeRequest(payload); - System.out.println(response.getEntity().toString()); - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - - payload = requests.get(1).toString(); - response = executeRequest(payload); - System.out.println(response.getEntity().toString()); - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - } - - @Test - public void deleteNodeRecreateNodeTest() throws IOException { - JsonArray requests = new JsonParser().parse( - getBulkPayload("single-transaction/delete-node-recreate-node").replaceAll("", name.getMethodName())) - .getAsJsonObject().getAsJsonArray("array"); - String payload = requests.get(0).toString(); - Response response = executeRequest(payload); - System.out.println(response.getEntity().toString()); - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - - payload = requests.get(1).toString(); - response = executeRequest(payload); - System.out.println(response.getEntity().toString()); - assertEquals("Request success", - Response.Status.CREATED.getStatusCode(), - response.getStatus()); - } - - - protected Response executeRequest(String finalPayload) { - MockHttpServletRequest mockReq = new MockHttpServletRequest(HttpMethod.POST, "http://www.test.com"); - - return bulkSingleTransactionConsumer.process( - finalPayload, - schemaVersions.getDefaultVersion().toString(), - httpHeaders, - uriInfo, - mockReq - ); - } - - @Override - protected BulkConsumer getConsumer() { - return null; - } - - @Override - protected String getUri() { - return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulk/single-transaction"; - } -} \ No newline at end of file + @Test + public void deleteChildRecreateChildTest() throws IOException { + JsonArray requests = + new JsonParser() + .parse(getBulkPayload("single-transaction/delete-child-recreate-child") + .replaceAll("", name.getMethodName())) + .getAsJsonObject().getAsJsonArray("array"); + String payload = requests.get(0).toString(); + Response response = executeRequest(payload); + System.out.println(response.getEntity().toString()); + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + + payload = requests.get(1).toString(); + response = executeRequest(payload); + System.out.println(response.getEntity().toString()); + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + } + + @Test + public void deleteNodeRecreateNodeTest() throws IOException { + JsonArray requests = new JsonParser().parse(getBulkPayload("single-transaction/delete-node-recreate-node") + .replaceAll("", name.getMethodName())).getAsJsonObject().getAsJsonArray("array"); + String payload = requests.get(0).toString(); + Response response = executeRequest(payload); + System.out.println(response.getEntity().toString()); + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + + payload = requests.get(1).toString(); + response = executeRequest(payload); + System.out.println(response.getEntity().toString()); + assertEquals("Request success", Response.Status.CREATED.getStatusCode(), response.getStatus()); + } + + protected Response executeRequest(String finalPayload) { + MockHttpServletRequest mockReq = new MockHttpServletRequest(HttpMethod.POST, "http://www.test.com"); + + return bulkSingleTransactionConsumer.process(finalPayload, schemaVersions.getDefaultVersion().toString(), + httpHeaders, uriInfo, mockReq); + } + + @Override + protected BulkConsumer getConsumer() { + return null; + } + + @Override + protected String getUri() { + return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulk/single-transaction"; + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java index cdd3a51..ed7f274 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java @@ -17,20 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest.retired; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + import org.junit.Test; import org.onap.aai.rest.AbstractSpringRestTest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; public class RetiredConsumerSpringTest extends AbstractSpringRestTest { private static final Logger LOGGER = LoggerFactory.getLogger(RetiredConsumerSpringTest.class); @@ -38,31 +40,31 @@ public class RetiredConsumerSpringTest extends AbstractSpringRestTest { private Map httpStatusMap; @Test - public void testOldVersionsEndpointReturnRetired(){ + public void testOldVersionsEndpointReturnRetired() { setupOldVersions(); executeRestCalls(); } @Test - public void testOldModelsRetired(){ + public void testOldModelsRetired() { setupModelsRetired(); executeRestCalls(); } @Test - public void testOldNamedQueriesRetired(){ + public void testOldNamedQueriesRetired() { setupNamedQueriesRetired(); executeRestCalls(); } @Test - public void testEdgeTagQueryRetired(){ + public void testEdgeTagQueryRetired() { setupEdgeTagQueriesRetired(); executeRestCalls(); } @Test - public void testSDNZoneQueryRetired(){ + public void testSDNZoneQueryRetired() { setupSDNZoneQueryRetired(); executeRestCalls(); } @@ -110,14 +112,16 @@ public class RetiredConsumerSpringTest extends AbstractSpringRestTest { httpStatusMap.put("/aai/v13/cloud-infrastructure/pservers/pserver/samomaisdjfajsfoas", HttpStatus.NOT_FOUND); - httpStatusMap.put("/aai/v8/service-design-and-creation/named-queries/named-query/samomaisdjfajsfoas", HttpStatus.GONE); + httpStatusMap.put("/aai/v8/service-design-and-creation/named-queries/named-query/samomaisdjfajsfoas", + HttpStatus.GONE); } protected void executeRestCalls() { httpStatusMap.forEach((url, status) -> { ResponseEntity responseEntity; responseEntity = restTemplate.exchange(baseUrl + url, HttpMethod.GET, httpEntity, String.class); - LOGGER.debug("For url {} expected status {} actual status {} and body {}", url, status, responseEntity.getStatusCodeValue(), responseEntity.getBody()); + LOGGER.debug("For url {} expected status {} actual status {} and body {}", url, status, + responseEntity.getStatusCodeValue(), responseEntity.getBody()); assertEquals(status, responseEntity.getStatusCode()); }); } diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java index f17257b..ad3f9c2 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java @@ -17,16 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.aai.rest.util; -import org.junit.Test; +package org.onap.aai.rest.util; import static org.junit.Assert.assertNotNull; +import org.junit.Test; + public class LogFormatToolsTest { @Test - public void testLogFormatTools(){ + public void testLogFormatTools() { String dateTime = new LogFormatTools().getCurrentDateTime(); assertNotNull(dateTime); diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java index 136b64e..442c0fc 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java @@ -17,96 +17,98 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.aai.rest.util; -import org.junit.Test; -import org.mockito.Mockito; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; -import java.io.UnsupportedEncodingException; -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.mockito.Mockito; public class ValidateEncodingTest { - - @Test - public void badPath() throws UnsupportedEncodingException { - String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}"; - UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap()); - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(false, validator.validate(mockUriInfo)); - } - - @Test - public void goodPath() throws UnsupportedEncodingException { - String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D"; - UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap()); - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(true, validator.validate(mockUriInfo)); - } - - @Test - public void badQueryParamsKey() throws UnsupportedEncodingException { - MultivaluedHashMap map = new MultivaluedHashMap(); - map.putSingle("blahblah", "test"); - map.putSingle("blahblah", "test2"); - map.putSingle("bad::bad", "test3"); - UriInfo mockUriInfo = getMockUriInfo("", map); - - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(false, validator.validate(mockUriInfo)); - - } - @Test - public void badQueryParamsValue() throws UnsupportedEncodingException { - MultivaluedHashMap map = new MultivaluedHashMap(); - map.putSingle("blahblah", "test"); - map.putSingle("blahblah", "test//:2"); - map.putSingle("badbad", "test3"); - UriInfo mockUriInfo = getMockUriInfo("", map); - - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(false, validator.validate(mockUriInfo)); - } - - @Test - public void goodQueryParams() throws UnsupportedEncodingException { - MultivaluedHashMap map = new MultivaluedHashMap(); - map.putSingle("blahblah", "test"); - map.putSingle("blahblah", "test2"); - map.putSingle("badbad", "~test%2F%2F%3A3"); - UriInfo mockUriInfo = getMockUriInfo("", map); - - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(true, validator.validate(mockUriInfo)); - } - - @Test - public void testWhenQueryParameterHasPlusSignItShouldPass() throws UnsupportedEncodingException { - - MultivaluedHashMap map = new MultivaluedHashMap(); - map.putSingle("some-key", "test+one+two+three"); - UriInfo mockUriInfo = getMockUriInfo("", map); - - ValidateEncoding validator = ValidateEncoding.getInstance(); - - assertEquals(true, validator.validate(mockUriInfo)); - } - - private UriInfo getMockUriInfo(String path, MultivaluedMap map) { - UriInfo mockUriInfo = Mockito.mock(UriInfo.class); - Mockito.when(mockUriInfo.getPath(false)).thenReturn(path); - Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map); - - return mockUriInfo; - } - + @Test + public void badPath() throws UnsupportedEncodingException { + String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}"; + UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + + @Test + public void goodPath() throws UnsupportedEncodingException { + String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D"; + UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + @Test + public void badQueryParamsKey() throws UnsupportedEncodingException { + MultivaluedHashMap map = new MultivaluedHashMap(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("bad::bad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + + } + + @Test + public void badQueryParamsValue() throws UnsupportedEncodingException { + MultivaluedHashMap map = new MultivaluedHashMap(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test//:2"); + map.putSingle("badbad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + + @Test + public void goodQueryParams() throws UnsupportedEncodingException { + MultivaluedHashMap map = new MultivaluedHashMap(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("badbad", "~test%2F%2F%3A3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + @Test + public void testWhenQueryParameterHasPlusSignItShouldPass() throws UnsupportedEncodingException { + + MultivaluedHashMap map = new MultivaluedHashMap(); + map.putSingle("some-key", "test+one+two+three"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + private UriInfo getMockUriInfo(String path, MultivaluedMap map) { + UriInfo mockUriInfo = Mockito.mock(UriInfo.class); + Mockito.when(mockUriInfo.getPath(false)).thenReturn(path); + Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map); + + return mockUriInfo; + } + } -- cgit 1.2.3-korg