diff options
Diffstat (limited to 'aai-core/src/test/java')
58 files changed, 5889 insertions, 1742 deletions
diff --git a/aai-core/src/test/java/org/onap/aai/AAISetup.java b/aai-core/src/test/java/org/onap/aai/AAISetup.java index 4bc30b8c..ac9cba68 100644 --- a/aai-core/src/test/java/org/onap/aai/AAISetup.java +++ b/aai-core/src/test/java/org/onap/aai/AAISetup.java @@ -20,15 +20,10 @@ package org.onap.aai; -import java.util.Map; - -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.IntrospectionConfig; -import org.onap.aai.config.RestBeanConfig; -import org.onap.aai.config.SpringContextAware; +import org.onap.aai.config.*; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.MoxyLoader; @@ -47,13 +42,30 @@ import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; +import java.util.Map; + @ContextConfiguration( - classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class, EdgeSerializer.class, - NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, RestBeanConfig.class}) + classes = { + ConfigConfiguration.class, + AAIConfigTranslator.class, + EdgeIngestor.class, + EdgeSerializer.class, + NodeIngestor.class, + SpringContextAware.class, + IntrospectionConfig.class, + RestBeanConfig.class, + XmlFormatTransformerConfiguration.class + } +) @TestPropertySource( - properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.translator.list=config", - "schema.nodes.location=src/test/resources/onap/oxm", - "schema.edges.location=src/test/resources/onap/dbedgerules"}) + properties = { + "schema.uri.base.path = /aai", + "schema.xsd.maxoccurs = 5000", + "schema.translator.list=config", + "schema.nodes.location=src/test/resources/onap/oxm", + "schema.edges.location=src/test/resources/onap/dbedgerules" + } +) public abstract class AAISetup { @ClassRule @@ -88,8 +100,8 @@ public abstract class AAISetup { protected static final String SERVICE_NAME = "JUNIT"; - @Before - public void setupBundleconfig() throws Exception { + @BeforeClass + public static void setupBundleconfig() throws Exception { System.setProperty("AJSC_HOME", "."); System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); System.setProperty("aai.service.name", SERVICE_NAME); diff --git a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java index f4d62d44..8a093669 100644 --- a/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java +++ b/aai-core/src/test/java/org/onap/aai/DataLinkSetup.java @@ -25,10 +25,7 @@ import java.util.Map; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Rule; -import org.onap.aai.config.ConfigConfiguration; -import org.onap.aai.config.IntrospectionConfig; -import org.onap.aai.config.RestBeanConfig; -import org.onap.aai.config.SpringContextAware; +import org.onap.aai.config.*; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.MoxyLoader; @@ -53,7 +50,7 @@ import org.springframework.test.context.junit4.rules.SpringMethodRule; @ContextConfiguration( classes = {ConfigConfiguration.class, TestUtilConfigTranslatorforDataLink.class, EdgeIngestor.class, EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class, IntrospectionConfig.class, - RestBeanConfig.class}) + RestBeanConfig.class, XmlFormatTransformerConfiguration.class}) @TestPropertySource( properties = {"schema.uri.base.path = /aai", "schema.xsd.maxoccurs = 5000", "schema.version.api.default = v4", "schema.version.edge.label.start = v4", "schema.version.depth.start = v3", diff --git a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java index 6a9e7256..588cbc95 100644 --- a/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java +++ b/aai-core/src/test/java/org/onap/aai/HttpTestUtil.java @@ -20,32 +20,20 @@ package org.onap.aai; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.when; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.ws.rs.core.*; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.javatuples.Pair; import org.mockito.Mockito; import org.onap.aai.config.SpringContextAware; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Introspector; import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.parsers.uri.URIToObject; import org.onap.aai.rest.db.DBRequest; import org.onap.aai.rest.db.HttpEntry; +import org.onap.aai.rest.ueb.UEBNotification; import org.onap.aai.restcore.HttpMethod; import org.onap.aai.restcore.RESTAPI; import org.onap.aai.serialization.engines.QueryStyle; @@ -53,15 +41,24 @@ import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.setup.SchemaVersion; import org.onap.aai.setup.SchemaVersions; +import javax.ws.rs.core.*; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.*; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.*; + public class HttpTestUtil extends RESTAPI { protected HttpEntry traversalHttpEntry; protected HttpEntry traversalUriHttpEntry; - private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpTestUtil.class); + private static final Logger logger = LoggerFactory.getLogger(HttpTestUtil.class); protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + protected static final MediaType APPLICATION_XML = MediaType.valueOf("application/xml"); private static final String EMPTY = ""; private final QueryStyle queryStyle; @@ -74,12 +71,40 @@ public class HttpTestUtil extends RESTAPI { protected List<String> aaiRequestContextList; protected List<MediaType> outputMediaTypes; + protected LoaderFactory loaderFactory; + protected SchemaVersions schemaVersions; + protected UEBNotification notification; + protected int notificationDepth; + protected String acceptType; public HttpTestUtil(QueryStyle qs) { + this(qs, "application/json"); + } + + public HttpTestUtil(QueryStyle qs, String acceptType) { this.queryStyle = qs; traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class); traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class); + loaderFactory = SpringContextAware.getBean(LoaderFactory.class); + schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); + notification = null; + this.acceptType = acceptType; + } + + public HttpTestUtil(QueryStyle qs, UEBNotification uebNotification, int notificationDepth) { + this(qs, uebNotification, notificationDepth, "application/json"); + } + + public HttpTestUtil(QueryStyle qs, UEBNotification uebNotification, int notificationDepth, String acceptType) { + this.queryStyle = qs; + this.traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class); + this.traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class); + this.loaderFactory = SpringContextAware.getBean(LoaderFactory.class); + this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); + this.notification = uebNotification; + this.notificationDepth = notificationDepth; + this.acceptType = acceptType; } public void init() { @@ -93,11 +118,15 @@ public class HttpTestUtil extends RESTAPI { headersMultiMap.add("X-FromAppId", "JUNIT"); headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); headersMultiMap.add("Real-Time", "true"); - headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("Accept", acceptType); headersMultiMap.add("aai-request-context", ""); outputMediaTypes = new ArrayList<>(); - outputMediaTypes.add(APPLICATION_JSON); + if(acceptType.equals("application/json")){ + outputMediaTypes.add(APPLICATION_JSON); + } else { + outputMediaTypes.add(APPLICATION_XML); + } aaiRequestContextList = new ArrayList<>(); aaiRequestContextList.add(""); @@ -112,9 +141,127 @@ public class HttpTestUtil extends RESTAPI { doReturn(null).when(queryParameters).remove(anyObject()); when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + + try { + if(notification != null){ + doNothing().when(notification).triggerEvents(); + } + } catch (AAIException e) { + e.printStackTrace(); + } } public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException { + Map<String, String> puts = new HashMap<>(); + puts.put(uri, payload); + return this.doPut(puts); + } + + public Response doPut(Map<String, String> uriPayload) throws UnsupportedEncodingException, AAIException { + + this.init(); + Response response = null; + boolean success = true; + TransactionalGraphEngine dbEngine = null; + + try { + + List<DBRequest> dbRequestList = new ArrayList<>(); + for(Map.Entry<String, String> entry : uriPayload.entrySet()){ + + String uri = entry.getKey(); + String payload = entry.getValue(); + if (uri.startsWith("/aai/")) { + uri = uri.substring(5); + } + + logger.info("Starting the put request for the uri {} with payload {}", uri, payload); + + String[] arr = uri.split("/"); + + SchemaVersion version = null; + + if (arr.length > 1) { + if (arr[0].matches("^v\\d+")) { + version = new SchemaVersion(arr[0]); + uri = uri.replaceAll("^v\\d+", ""); + } + } + + if (version == null) { + version = schemaVersions.getDefaultVersion(); + } + Mockito.when(uriInfo.getPath()).thenReturn(uri); + + if(notification != null){ + traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth); + } else { + traversalHttpEntry.setHttpEntryProperties(version); + } + Loader loader = traversalHttpEntry.getLoader(); + dbEngine = traversalHttpEntry.getDbEngine(); + + URI uriObject = UriBuilder.fromPath(uri).build(); + URIToObject uriToObject = new URIToObject(loader, uriObject); + + 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")); + httpMethod = HttpMethod.PUT_EDGE; + } else { + obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json")); + httpMethod = HttpMethod.PUT; + this.validateIntrospector(obj, loader, uriObject, httpMethod); + } + + DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, + "JUNIT-TRANSACTION").rawRequestContent(payload).build(); + + dbRequestList.add(dbRequest); + + } + + Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = + traversalHttpEntry.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) { + 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()); + } else { + logFailure(HttpMethod.PUT, response); + } + } + dbEngine.commit(); + } else { + if (response != null) { + logFailure(HttpMethod.PUT, response); + } + dbEngine.rollback(); + } + } + + return response; + } + + public Response doPatch(String uri, String payload) throws UnsupportedEncodingException, AAIException { this.init(); Response response = null; @@ -133,22 +280,23 @@ public class HttpTestUtil extends RESTAPI { SchemaVersion version = null; - if (arr != null && arr.length > 1) { + if (arr.length > 1) { if (arr[0].matches("^v\\d+")) { version = new SchemaVersion(arr[0]); uri = uri.replaceAll("^v\\d+", ""); } } - SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); if (version == null) { version = schemaVersions.getDefaultVersion(); } Mockito.when(uriInfo.getPath()).thenReturn(uri); - DBConnectionType type = DBConnectionType.REALTIME; - - traversalHttpEntry.setHttpEntryProperties(version, type); + if(notification != null){ + traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth); + } else { + traversalHttpEntry.setHttpEntryProperties(version); + } Loader loader = traversalHttpEntry.getLoader(); dbEngine = traversalHttpEntry.getDbEngine(); @@ -162,24 +310,18 @@ public class HttpTestUtil extends RESTAPI { Introspector obj; HttpMethod httpMethod; - 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")); - httpMethod = HttpMethod.PUT; - this.validateIntrospector(obj, loader, uriObject, httpMethod); - } + obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json")); + httpMethod = HttpMethod.MERGE_PATCH; + this.validateIntrospector(obj, loader, uriObject, httpMethod); DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, - "JUNIT-TRANSACTION").rawRequestContent(payload).build(); + "JUNIT-TRANSACTION").rawRequestContent(payload).build(); List<DBRequest> dbRequestList = new ArrayList<>(); dbRequestList.add(dbRequest); Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = - traversalHttpEntry.process(dbRequestList, "JUNIT"); + traversalHttpEntry.process(dbRequestList, "JUNIT"); response = responsesTuple.getValue1().get(0).getValue1(); } catch (AAIException e) { @@ -194,7 +336,7 @@ public class HttpTestUtil extends RESTAPI { if (response != null) { if ((response.getStatus() / 100) == 2) { logger.info("Successfully completed the PUT request with status {} and committing it to DB", - response.getStatus()); + response.getStatus()); } else { logFailure(HttpMethod.PUT, response); } @@ -211,7 +353,11 @@ public class HttpTestUtil extends RESTAPI { return response; } - public Response doGet(String uri, String depth) { + public Response doGet(String uri, String depth){ + return doGet(uri, depth, null); + } + + public Response doGet(String uri, String depth, String format) { this.init(); Response response = null; @@ -230,20 +376,22 @@ public class HttpTestUtil extends RESTAPI { SchemaVersion version = null; - if (arr != null && arr.length > 1) { + if (arr.length > 1) { if (arr[0].matches("^v\\d+")) { version = new SchemaVersion(arr[0]); uri = uri.replaceAll("^v\\d+", ""); } } - SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); if (version == null) { version = schemaVersions.getDefaultVersion(); } - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(version, type); + if(notification != null){ + traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth); + } else { + traversalHttpEntry.setHttpEntryProperties(version); + } Loader loader = traversalHttpEntry.getLoader(); dbEngine = traversalHttpEntry.getDbEngine(); @@ -253,6 +401,10 @@ public class HttpTestUtil extends RESTAPI { queryParameters.add("depth", depth); } + if(format != null){ + queryParameters.add("format", format); + } + QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters); Mockito.when(uriInfo.getPath()).thenReturn(uri); @@ -309,7 +461,7 @@ public class HttpTestUtil extends RESTAPI { return this.doGet(uri, "all"); } - public Response doDelete(String uri, String resourceVersion) throws UnsupportedEncodingException, AAIException { + public Response doDelete(Map<String, Pair<String, String>> deletes){ this.init(); Response response = null; @@ -318,77 +470,81 @@ public class HttpTestUtil extends RESTAPI { try { - uri = uri.replaceAll("/aai/", ""); - logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion); + List<DBRequest> dbRequestList = new ArrayList<>(); + for (Map.Entry<String, Pair<String, String>> delete : deletes.entrySet()) { + String uri = delete.getKey(); + String resourceVersion = delete.getValue().getValue0(); + String content = delete.getValue().getValue1(); + 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; + SchemaVersion version = null; - if (arr != null && arr.length > 1) { - if (arr[0].matches("^v\\d+")) { - version = new SchemaVersion(arr[0]); - if (!uri.contains("relationship-list/relationship")) { + if (arr.length > 1) { + if (arr[0].matches("^v\\d+")) { + version = new SchemaVersion(arr[0]); uri = uri.replaceAll("^v\\d+", ""); } } - } - SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions"); - if (version == null) { - version = schemaVersions.getDefaultVersion(); - } + if (version == null) { + version = schemaVersions.getDefaultVersion(); + } - Mockito.when(uriInfo.getPath()).thenReturn(uri); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(version, type); + Mockito.when(uriInfo.getPath()).thenReturn(uri); + if (notification != null) { + traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth); + } else { + traversalHttpEntry.setHttpEntryProperties(version); + } + Loader loader = traversalHttpEntry.getLoader(); + dbEngine = traversalHttpEntry.getDbEngine(); - traversalHttpEntry.setHttpEntryProperties(version, type); - Loader loader = traversalHttpEntry.getLoader(); - dbEngine = traversalHttpEntry.getDbEngine(); + URI uriObject = UriBuilder.fromPath(uri).build(); + URIToObject uriToObject = new URIToObject(loader, uriObject); - URI uriObject = UriBuilder.fromPath(uri).build(); - URIToObject uriToObject = new URIToObject(loader, uriObject); + String objType = uriToObject.getEntityName(); + queryParameters.add("resource-version", resourceVersion); + QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters); - String objType = uriToObject.getEntityName(); - queryParameters.add("resource-version", resourceVersion); - QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters); + logger.info("Unmarshalling the payload to this {}", objType); - logger.info("Unmarshalling the payload to this {}", objType); + Introspector obj; - Introspector obj; - HttpMethod httpMethod; - if (uri.contains("/relationship-list/relationship")) { - obj = loader.introspectorFromName("relationship"); - httpMethod = HttpMethod.DELETE_EDGE; - } else { - obj = loader.introspectorFromName(objType); - httpMethod = HttpMethod.DELETE; - } + HttpMethod httpMethod; - DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, - "JUNIT-TRANSACTION").build(); + if (uri.contains("/relationship-list/relationship")) { + httpMethod = HttpMethod.DELETE_EDGE; + obj = loader.unmarshal("relationship", content, org.onap.aai.restcore.MediaType.getEnum("application/json")); + } else { + obj = loader.introspectorFromName(objType); + httpMethod = HttpMethod.DELETE; + } - List<DBRequest> dbRequestList = new ArrayList<>(); - dbRequestList.add(dbRequest); + DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION").build(); + + dbRequestList.add(dbRequest); + } Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = - traversalHttpEntry.process(dbRequestList, "JUNIT"); + traversalHttpEntry.process(dbRequestList, "JUNIT"); response = responsesTuple.getValue1().get(0).getValue1(); } catch (AAIException e) { - response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e); + response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, e); success = false; } catch (Exception e) { AAIException ex = new AAIException("AAI_4000", e); - response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex); + response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, 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()); + response.getStatus()); } else { logFailure(HttpMethod.DELETE, response); } @@ -403,6 +559,15 @@ public class HttpTestUtil extends RESTAPI { return response; } + public Response doDelete(String uri, String resourceVersion) { + return this.doDelete(uri, resourceVersion, null); + } + public Response doDelete(String uri, String resourceVersion, String content) { + Map<String, Pair<String, String>> deletes = new HashMap<>(); + deletes.put(uri, new Pair<>(resourceVersion, content)); + return this.doDelete(deletes); + } + public static void logFailure(HttpMethod httpMethod, Response response) { logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(), response.getStatus()); diff --git a/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java b/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java deleted file mode 100644 index d6075c1f..00000000 --- a/aai-core/src/test/java/org/onap/aai/auth/AAIAuthCoreTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.auth; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aai.AAISetup; -import org.onap.aai.auth.exceptions.AAIUnrecognizedFunctionException; - -public class AAIAuthCoreTest extends AAISetup { - - private AAIAuthCore authCore; - - @Before - public void setup() { - authCore = new AAIAuthCore("/aai"); - } - - @Test - public void getAuthPolicyFunctionNameTest() { - - String uri = "/aai/v3/search/edge-tag-query"; - assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/v10/search/edge-tag-query"; - assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/search/model"; - assertEquals("Get aai function name from " + uri, "search", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/v9/cloud-infrastructure/cloud-regions/cloud-region/somecloudregion/some-cloud-owner"; - assertEquals("Get aai function name from " + uri, "cloud-infrastructure", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/v8/network/pnfs/pnf/ff4ca01orc/p-interfaces"; - assertEquals("Get aai function name from " + uri, "network", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/util/echo"; - assertEquals("Get aai function name from " + uri, "util", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/tools"; - assertEquals("Get aai function name from " + uri, "tools", authCore.getAuthPolicyFunctName(uri)); - - uri = "/aai/v12/bulk/single-transaction"; - assertEquals("Get aai function name from " + uri, "bulk", authCore.getAuthPolicyFunctName(uri)); - - } - - @Test - public void validUsernameAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("testUser".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void validUsernameInvalidHttpMethodAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("testUser".toLowerCase(), "/aai/v0/testFunction/someUri", "POST", "")); - } - - @Test(expected = AAIUnrecognizedFunctionException.class) - public void validUsernameInvalidFunctionInURIAuthTest() throws AAIUnrecognizedFunctionException { - authCore.authorize("testUser".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", ""); - } - - @Test - public void invalidUsernameAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("invlaidTestUser".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void validUsernameIsTheExactWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("testWildcardId".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void validUsernameContainsTheWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri", - "PUT", "", "aafWildCardIssuer")); - } - - @Test - public void validUsernameContainsTheWildcardIdInvalidIssuerAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, testWildcardId, O=".toLowerCase(), "/aai/v0/testFunction/someUri", - "PUT", "", "invalidIssuer")); - } - - @Test - public void invalidUsernameContainsRegularUsernameAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse( - authCore.authorize("cn=blah, testUser, O=".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void haProxyUsernameAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/util/echo", "GET", "")); - } - - @Test - public void haProxyUsernameInvalidFunctionAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void validUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "testUser".toLowerCase())); - } - - @Test - public void validUsernameInvalidHttpMethodViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "POST", - "testUser".toLowerCase())); - } - - @Test(expected = AAIUnrecognizedFunctionException.class) - public void validUsernameInvalidFunctionInURIViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", - "testUser".toLowerCase()); - } - - @Test - public void invalidUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "invlaidTestUser".toLowerCase())); - } - - @Test - public void validUsernameIsTheExactWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "testWildcardId".toLowerCase())); - } - - @Test - public void validUsernameContainsTheWildcardIdViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer")); - } - - @Test - public void invalidUsernameContainsRegularUsernameViaHaProxyAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "cn=blah, testUser, O=".toLowerCase())); - } - - @Test - public void haProxyUsernameTwiceAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("ha-proxy-user".toLowerCase(), "/aai/v0/testFunction/someUri", "PUT", - "ha-proxy-user".toLowerCase())); - } - - @Test - public void haProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/util/echo", "GET", "", - "aafWildCardIssuer")); - } - - @Test - public void haProxyWildcardIdInvalidFunctionAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), - "/aai/v0/testFunction/someUri", "PUT", "")); - } - - @Test - public void validUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", - "PUT", "testUser".toLowerCase(), "aafWildCardIssuer")); - } - - @Test - public void validUsernameInvalidHttpMethodViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), - "/aai/v0/testFunction/someUri", "POST", "testUser".toLowerCase())); - } - - @Test(expected = AAIUnrecognizedFunctionException.class) - public void validUsernameInvalidFunctionInURIViaHaProxyWildcardIdAuthTest() - throws AAIUnrecognizedFunctionException { - authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/badFunction/someUri", "PUT", - "testUser".toLowerCase()); - } - - @Test - public void invalidUsernameViaHaProxyWildcardIdAuthTest() throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), - "/aai/v0/testFunction/someUri", "PUT", "invlaidTestUser".toLowerCase())); - } - - @Test - public void validUsernameIsTheExactWildcardIdViaHaProxyWildcardIdAuthTest() - throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", - "PUT", "testWildcardId".toLowerCase(), "aafWildCardIssuer")); - } - - @Test - public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdAuthTest() - throws AAIUnrecognizedFunctionException { - assertTrue(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), "/aai/v0/testFunction/someUri", - "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "aafWildCardIssuer")); - } - - @Test - public void validUsernameContainsTheWildcardIdViaHaProxyWildcardIdInvalidIssuerAuthTest() - throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), - "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testWildcardId, O=".toLowerCase(), "invalidIssuer")); - } - - @Test - public void invalidUsernameContainsRegularUsernameViaHaProxyWildcardIdAuthTest() - throws AAIUnrecognizedFunctionException { - assertFalse(authCore.authorize("cn=blah, ha-proxy-wildcard-id, O=".toLowerCase(), - "/aai/v0/testFunction/someUri", "PUT", "cn=blah, testUser, O=".toLowerCase())); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java b/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java deleted file mode 100644 index cf5eafbd..00000000 --- a/aai-core/src/test/java/org/onap/aai/auth/AAIUserTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.auth; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.aai.AAISetup; - -public class AAIUserTest extends AAISetup { - - @Test - public void testIsAuth() { - AAIUser usr = new AAIUser("testUser"); - usr.addRole("testRole"); - usr.setUserAccess("auth", "GET"); - usr.setUserAccess("auth", "PUT"); - usr.setUserAccess("authentication", "PUT", "GET", "POST"); - - assertEquals(true, usr.hasAccess("auth", "GET")); - assertEquals(true, usr.hasAccess("auth", "PUT")); - assertEquals(true, usr.hasAccess("authentication", "POST")); - } - - @Test - public void testIsNotAuth() { - AAIUser usr = new AAIUser("testUser"); - usr.addRole("testRole"); - - assertEquals(false, usr.hasAccess("auth", "GET")); - - usr.setUserAccess("auth", "GET"); - assertEquals(false, usr.hasAccess("auth", "PUT")); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java b/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java index 48d2583d..f2c7b27c 100644 --- a/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java +++ b/aai-core/src/test/java/org/onap/aai/dbmap/AAIGraphTest.java @@ -20,17 +20,6 @@ package org.onap.aai.dbmap; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.matchesPattern; -import static org.junit.Assert.*; - -import java.io.FileNotFoundException; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphFactory; import org.janusgraph.core.schema.JanusGraphIndex; @@ -48,6 +37,17 @@ import org.onap.aai.schema.enums.PropertyMetadata; import org.onap.aai.setup.SchemaVersions; import org.onap.aai.util.AAIConstants; +import java.io.FileNotFoundException; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.Assert.*; + public class AAIGraphTest extends AAISetup { @Before public void setup() { @@ -67,21 +67,9 @@ public class AAIGraphTest extends AAISetup { graphMgt.rollback(); } - @Test - public void getCachedInstanceConnectionName() throws Exception { - - JanusGraphManagement graphMgt = AAIGraph.getInstance().getGraph(DBConnectionType.CACHED).openManagement(); - String connectionInstanceName = - graphMgt.getOpenInstances().stream().filter(c -> c.contains("current")).findFirst().get(); - assertThat(connectionInstanceName, containsString(SERVICE_NAME)); - assertThat(connectionInstanceName, containsString("cached")); - assertThat(connectionInstanceName, - matchesPattern("^\\d+_[\\w\\-\\d]+_" + SERVICE_NAME + "_cached_\\d+\\(current\\)$")); - graphMgt.rollback(); - } @Test - public void JanusGraphOpenNameTest() throws Exception { + public void janusGraphOpenNameTest() throws Exception { JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder(AAIConstants.REALTIME_DB_CONFIG) .forService(SERVICE_NAME).withGraphType("graphType").buildConfiguration()); JanusGraphManagement graphMgt = graph.openManagement(); @@ -94,7 +82,7 @@ public class AAIGraphTest extends AAISetup { } @Test(expected = FileNotFoundException.class) - public void JanusGraphOpenNameWithInvalidFilePathTest() throws Exception { + public void janusGraphOpenNameWithInvalidFilePathTest() throws Exception { JanusGraph graph = JanusGraphFactory.open(new AAIGraphConfig.Builder("invalid").forService(SERVICE_NAME) .withGraphType("graphType").buildConfiguration()); JanusGraphManagement graphMgt = graph.openManagement(); diff --git a/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java index 8b44b312..b684e3fa 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/JSONStrategyTest.java @@ -20,16 +20,18 @@ package org.onap.aai.introspection; -import java.util.HashSet; -import java.util.Set; - import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.onap.aai.AAISetup; +import java.util.HashSet; +import java.util.Set; + +@Ignore("Not a used/flushed out feature") public class JSONStrategyTest extends AAISetup { private JSONStrategy jsonStrategy; private JSONStrategy jsonStrategyContainer; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java index 0e6a9aab..fe128353 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/MoxyEngineTest.java @@ -20,6 +20,7 @@ package org.onap.aai.introspection; +import org.junit.Assert; import org.junit.Test; import org.onap.aai.introspection.exceptions.AAIUnknownObjectException; import org.springframework.test.annotation.DirtiesContext; @@ -43,4 +44,23 @@ public class MoxyEngineTest extends IntrospectorTestSpec { } + @Test + public void testDslStartNodeProps() throws AAIUnknownObjectException { + Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); + Introspector obj = loader.introspectorFromName("pserver"); + Assert.assertFalse(obj.getDslStartNodeProperties().contains("in-maint")); + Assert.assertTrue(obj.getDslStartNodeProperties().contains("pserver-name2")); + + } + + @Test + public void testDslStartNodePropsDefault() throws AAIUnknownObjectException { + /* + * Use indexedprops when there is no dslStartNodeProps + */ + Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); + Introspector obj = loader.introspectorFromName("vserver"); + Assert.assertTrue(obj.getDslStartNodeProperties().contains("in-maint")); + } + } diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java index 79597355..7dadb14a 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataCopyTest.java @@ -20,19 +20,6 @@ package org.onap.aai.introspection.sideeffect; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collection; - import org.apache.commons.io.IOUtils; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -48,10 +35,11 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.edges.enums.EdgeProperty; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.serialization.db.DBSerializer; @@ -59,13 +47,24 @@ import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) public class DataCopyTest extends AAISetup { private static JanusGraph graph; private final static ModelType introspectorFactoryType = ModelType.MOXY; - private final static DBConnectionType type = DBConnectionType.REALTIME; private static Loader loader; private static TransactionalGraphEngine dbEngine; @Mock @@ -77,7 +76,7 @@ public class DataCopyTest extends AAISetup { @Rule public ExpectedException thrown = ExpectedException.none(); - @Parameterized.Parameter(value = 0) + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") @@ -86,27 +85,40 @@ public class DataCopyTest extends AAISetup { } @BeforeClass - public static void setup() throws NoSuchFieldException, SecurityException, Exception { + public static void setup() { graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); System.setProperty("AJSC_HOME", "."); System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); graph.traversal() - .addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key1") - .as("v1") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", - "testValue", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v1", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key3") - .as("v2") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4", - AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true) - .next(); + .addV("model") + .property("aai-node-type", "model") + .property("model-invariant-id", "key1") + .property(AAIProperties.AAI_URI,"/service-design-and-creation/models/model/key1") + .as("v1") + .addV("model-ver") + .property("aai-node-type", "model-ver") + .property("model-ver", "myValue") + .property("model-version-id", "key2") + .property("model-version", "testValue") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2") + .as("v2") + .addE("org.onap.relationships.inventory.BelongsTo").to("v1").from("v2") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV("model") + .property("aai-node-type", "model") + .property("model-invariant-id", "key3") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3") + .as("v3") + .addV() + .property("aai-node-type", "model-ver") + .property("model-ver", "myValue") + .property("model-version-id", "key4") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4") + .as("v4") + .addE("org.onap.relationships.inventory.BelongsTo").to("v3").from("v4") + .property(EdgeProperty.CONTAINS.toString(), true) + .next(); graph.tx().commit(); } @@ -120,13 +132,12 @@ public class DataCopyTest extends AAISetup { public void initMock() { loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion()); MockitoAnnotations.initMocks(this); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); } @Test - public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, - InstantiationException, NoSuchMethodException, MalformedURLException { + public void runPopulatePersonaModelVer() throws AAIException, UnsupportedEncodingException, + IllegalArgumentException, SecurityException { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); final Introspector obj = loader.introspectorFromName("generic-vnf"); @@ -154,13 +165,10 @@ public class DataCopyTest extends AAISetup { } @Test - public void verifyNestedSideEffect() - throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException, - InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException { + public void verifyNestedSideEffect() throws AAIException, IllegalArgumentException, SecurityException, IOException { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); final Introspector obj = loader.unmarshal("customer", this.getJsonString("nested-case.json")); - // System.out.println(obj.marshal(true)); TransactionalGraphEngine spy = spy(dbEngine); TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); Graph g = graph.newTransaction(); @@ -251,15 +259,15 @@ public class DataCopyTest extends AAISetup { runner.execute(obj, self); - assertEquals("no model-version-id", true, obj.getValue("model-version-id") == null); - assertEquals("no model-invariant-id", true, obj.getValue("model-invariant-id") == null); + assertNull("no model-version-id", obj.getValue("model-version-id")); + assertNull("no model-invariant-id", obj.getValue("model-invariant-id")); } private String getJsonString(String filename) throws IOException { FileInputStream is = new FileInputStream("src/test/resources/oxm/sideeffect/" + filename); - String s = IOUtils.toString(is, "UTF-8"); + String s = IOUtils.toString(is, StandardCharsets.UTF_8); IOUtils.closeQuietly(is); return s; diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java index cec342ea..62c366cb 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/DataLinkTest.java @@ -20,54 +20,51 @@ package org.onap.aai.introspection.sideeffect; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.janusgraph.core.Cardinality; import org.janusgraph.core.JanusGraph; import org.janusgraph.core.JanusGraphFactory; +import org.janusgraph.core.schema.JanusGraphManagement; import org.junit.*; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.aai.AAISetup; import org.onap.aai.DataLinkSetup; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.edges.enums.EdgeProperty; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.serialization.db.DBSerializer; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) public class DataLinkTest extends DataLinkSetup { private static JanusGraph graph; private final static ModelType introspectorFactoryType = ModelType.MOXY; - private final static DBConnectionType type = DBConnectionType.REALTIME; private static Loader loader; private static TransactionalGraphEngine dbEngine; @Mock @@ -79,7 +76,7 @@ public class DataLinkTest extends DataLinkSetup { @Rule public ExpectedException thrown = ExpectedException.none(); - @Parameterized.Parameter(value = 0) + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") @@ -88,50 +85,133 @@ public class DataLinkTest extends DataLinkSetup { } @BeforeClass - public static void setup() throws NoSuchFieldException, SecurityException, Exception { + public static void setup() { graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + JanusGraphManagement graphMgt = graph.openManagement(); + graphMgt.makePropertyKey(AAIProperties.CREATED_TS).dataType(Long.class).cardinality(Cardinality.SINGLE) + .make(); + graphMgt.makePropertyKey(AAIProperties.LAST_MOD_TS).dataType(Long.class).cardinality(Cardinality.SINGLE) + .make(); + graphMgt.commit(); graph.traversal() - .addV("aai-node-type", "vpn-binding", "vpn-id", "addKey", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/addKey") - .as("v1") - .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/modifyKey") - .as("v2") - .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", - "modifyRoleKey", "linked", true, AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey/modifyRoleKey") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/deleteKey") - .as("v3") - .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", - "deleteRoleKey", "linked", true, AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/deleteKey/route-targets/route-target/deleteTargetKey/deleteRoleKey") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v3", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/getKey") - .as("v4") - .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", - "getRoleKey", "linked", true, AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/getKey/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v4", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/getKeyNoLink") - .as("v5") - .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", - "getRoleKeyNoLink", AAIProperties.AAI_URI, - "/network/vpn-bindings/vpn-binding/getKeyNoLink/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v5", EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "vpn-binding") + .property("vpn-id", "addKey") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/addKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v1") + .addV() + .property("aai-node-type", "vpn-binding") + .property("vpn-id", "modifyKey") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v2") + .addV() + .property("aai-node-type", "route-target") + .property("global-route-target", "modifyTargetKey") + .property("route-target-role", "modifyRoleKey") + .property("linked", true) + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/modifyKey/route-targets/route-target/modifyTargetKey/modifyRoleKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v3") + .addE("org.onap.relationships.inventory.BelongsTo").to("v2").from("v3") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "vpn-binding") + .property("vpn-id", "deleteKey") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v4") + .addV() + .property("aai-node-type", "route-target") + .property("global-route-target", "deleteTargetKey") + .property("route-target-role", "deleteRoleKey") + .property("linked", true) + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/deleteKey/route-targets/route-target/deleteTargetKey/deleteRoleKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v5") + .addE("org.onap.relationships.inventory.BelongsTo").to("v4").from("v5") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "vpn-binding") + .property("vpn-id", "getKey") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v6") + .addV() + .property("aai-node-type", "route-target") + .property("global-route-target", "getTargetKey") + .property("route-target-role", "getRoleKey") + .property("linked", true) + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKey/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v7") + .addE("org.onap.relationships.inventory.BelongsTo").to("v6").from("v7") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "vpn-binding") + .property("vpn-id", "getKeyNoLink") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v8") + .addV() + .property("aai-node-type", "route-target") + .property("global-route-target", "getTargetKeyNoLink") + .property("route-target-role", "getRoleKeyNoLink") + .property(AAIProperties.AAI_URI, "/network/vpn-bindings/vpn-binding/getKeyNoLink/route-targets/route-target/getTargetKeyNoLink/getRoleKeyNoLink") + .property(AAIProperties.AAI_UUID, UUID.randomUUID().toString()) + .property(AAIProperties.CREATED_TS, 123) + .property(AAIProperties.SOURCE_OF_TRUTH, "sot") + .property(AAIProperties.RESOURCE_VERSION, "123") + .property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot") + .property(AAIProperties.LAST_MOD_TS, 333) + .as("v9") + .addE("org.onap.relationships.inventory.BelongsTo").to("v8").from("v9") + .property(EdgeProperty.CONTAINS.toString(), true) .next(); graph.tx().commit(); - /* - * Commented for SysOut issues - */ - // graph.traversal().V().has("aai-uri","/network/vpn-bindings/vpn-binding/deleteKey").properties().forEachRemaining(p->System.out.println(p.key() - // +" : " + p.value())); - } @AfterClass @@ -144,13 +224,12 @@ public class DataLinkTest extends DataLinkSetup { public void initMock() { loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion()); MockitoAnnotations.initMocks(this); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); } @Test - public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, - InstantiationException, NoSuchMethodException, MalformedURLException { + public void verifyCreationOfVertex() throws AAIException, UnsupportedEncodingException, + IllegalArgumentException, SecurityException { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); final Introspector obj = loader.introspectorFromName("vpn-binding"); @@ -161,25 +240,6 @@ public class DataLinkTest extends DataLinkSetup { TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); Graph g = graph.newTransaction(); GraphTraversalSource traversal = g.traversal(); - // Graph g = graph.newTransaction(); - // GraphTraversalSource traversal = g; - // System.out.println("Begin method inventory:"); - Iterator<Vertex> vertexItr = traversal.V(); - while (vertexItr != null && vertexItr.hasNext()) { - Vertex v = vertexItr.next(); - // System.out.println("\nnodeType="+v.<String>property("aai-node-type")); - for (String key : v.keys()) { - // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+";id= "+v.id()); - } - Direction d = null; - Iterator<Edge> edgeItr = v.edges(Direction.BOTH); - while (edgeItr != null && edgeItr.hasNext()) { - Edge e = edgeItr.next(); - // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= - // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id()); - } - } - // System.out.println("End method inventory:"); when(spy.asAdmin()).thenReturn(adminSpy); when(adminSpy.getTraversalSource()).thenReturn(traversal); when(spy.tx()).thenReturn(g); @@ -192,16 +252,14 @@ public class DataLinkTest extends DataLinkSetup { runner.execute(obj, self); - assertEquals("route-target vertex found", true, traversal.V().has(AAIProperties.NODE_TYPE, "route-target") - .has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext()); + assertTrue("route-target vertex found", traversal.V().has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext()); g.tx().rollback(); } @Test - public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, - InstantiationException, NoSuchMethodException, MalformedURLException { + public void verifyModificationOfVertex() throws AAIException, UnsupportedEncodingException, + IllegalArgumentException, SecurityException { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); final Introspector obj = loader.introspectorFromName("vpn-binding"); @@ -210,30 +268,11 @@ public class DataLinkTest extends DataLinkSetup { obj.setValue("route-target-role", "modifyRoleKey2"); TransactionalGraphEngine spy = spy(dbEngine); TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - // Graph g = graph.newTransaction(); - // GraphTraversalSource traversal = g; Graph g = graph.newTransaction(); GraphTraversalSource traversal = g.traversal(); - Iterator<Vertex> vertexItr = traversal.V(); - while (vertexItr != null && vertexItr.hasNext()) { - Vertex v = vertexItr.next(); - // System.out.println("\nnodeType="+v.<String>property("aai-node-type")); - for (String key : v.keys()) { - // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id()); - } - Direction d = null; - Iterator<Edge> edgeItr = v.edges(Direction.BOTH); - while (edgeItr != null && edgeItr.hasNext()) { - Edge e = edgeItr.next(); - // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= - // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id()); - } - } - // System.out.println("End method inventory:"); when(spy.asAdmin()).thenReturn(adminSpy); when(adminSpy.getTraversalSource()).thenReturn(traversal); - // when(spy.tx()).thenReturn(graph); when(spy.tx()).thenReturn(g); when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); when(prop.orElse(null)).thenReturn(obj.getURI()); @@ -241,44 +280,8 @@ public class DataLinkTest extends DataLinkSetup { new DBSerializer(schemaVersions.getDefaultVersion(), spy, introspectorFactoryType, "AAI_TEST"); SideEffectRunner runner = new SideEffectRunner.Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); - // System.out.println("Traversal Source: "+traversal.toString()); - vertexItr = traversal.V(); - // System.out.println("Begin method inventory:"); - while (vertexItr != null && vertexItr.hasNext()) { - Vertex v = vertexItr.next(); - // System.out.println("\nnodeType="+v.<String>property("aai-node-type")); - for (String key : v.keys()) { - // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id()); - } - Iterator<Edge> edgeItr = v.edges(Direction.BOTH); - while (edgeItr != null && edgeItr.hasNext()) { - Edge e = edgeItr.next(); - // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= - // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id()); - } - } - // System.out.println("End method inventory:"); - try { - runner.execute(obj, self); - } catch (Exception e) { - - } - // runner.execute(obj, self); - // System.out.println("=================\n"); - vertexItr = traversal.V(); - while (vertexItr != null && vertexItr.hasNext()) { - Vertex v = vertexItr.next(); - // System.out.println("\nnodeType="+v.<String>property("aai-node-type")); - for (String key : v.keys()) { - // System.out.println("label="+v.label()+";key= "+key+";value= "+v.value(key)+"/"+v.id()); - } - Iterator<Edge> edgeItr = v.edges(Direction.BOTH); - while (edgeItr != null && edgeItr.hasNext()) { - Edge e = edgeItr.next(); - // System.out.println("outV="+e.outVertex().property(AAIProperties.NODE_TYPE)+"/"+e.outVertex().id()+";inV= - // "+e.inVertex().property(AAIProperties.NODE_TYPE)+"/"+e.inVertex().id()); - } - } + runner.execute(obj, self); + assertThat("new route-target vertex found with/or without link", traversal.V().has(AAIProperties.NODE_TYPE, "route-target") .has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2") @@ -301,9 +304,7 @@ public class DataLinkTest extends DataLinkSetup { } @Test - public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, - InstantiationException, NoSuchMethodException, MalformedURLException { + public void verifyDeleteOfVertex() throws Exception { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); final Introspector obj = loader.introspectorFromName("vpn-binding"); @@ -325,18 +326,14 @@ public class DataLinkTest extends DataLinkSetup { runner.execute(obj, self); - assertEquals("route-target vertex not found", false, - traversal.V().has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey") - .has("route-target-role", "deleteRoleKey").has("linked", true).hasNext()); + assertFalse("route-target vertex not found", traversal.V().has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey").has("route-target-role", "deleteRoleKey").has("linked", true).hasNext()); g.tx().rollback(); } @Test - public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, - InstantiationException, NoSuchMethodException, MalformedURLException { + public void verifyPropertyPopulation() throws Exception { final Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDepthVersion()); final Introspector obj = loader.introspectorFromName("vpn-binding"); @@ -357,17 +354,14 @@ public class DataLinkTest extends DataLinkSetup { runner.execute(obj, self); - assertEquals("both properties have been populated in target object", true, - obj.getValue("global-route-target").equals("getTargetKey") - && obj.getValue("route-target-role").equals("getRoleKey")); + assertTrue("both properties have been populated in target object", obj.getValue("global-route-target").equals("getTargetKey") && obj.getValue("route-target-role").equals("getRoleKey")); g.tx().rollback(); } @Test - public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException, - UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, - SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + public void verifyPropertyPopulationWithV10OnlyPut() throws AAIException, + UnsupportedEncodingException, IllegalArgumentException, SecurityException { final Introspector obj = loader.introspectorFromName("vpn-binding"); obj.setValue("vpn-id", "getKeyNoLink"); final Introspector routeTargets = loader.introspectorFromName("route-targets"); diff --git a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java index 1bae4065..6a7bfd33 100644 --- a/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java +++ b/aai-core/src/test/java/org/onap/aai/introspection/sideeffect/PrivateEdgeTest.java @@ -20,19 +20,6 @@ package org.onap.aai.introspection.sideeffect; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.empty; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.StringContains.containsString; -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -46,29 +33,42 @@ import org.junit.runners.Parameterized; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.edges.enums.EdgeProperty; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.serialization.db.DBSerializer; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.springframework.test.annotation.DirtiesContext; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.StringContains.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class PrivateEdgeTest extends AAISetup { private static JanusGraph graph; private final static ModelType introspectorFactoryType = ModelType.MOXY; - private final static DBConnectionType type = DBConnectionType.REALTIME; - private Loader loader; private static TransactionalGraphEngine dbEngine; @Rule public ExpectedException thrown = ExpectedException.none(); - @Parameterized.Parameter(value = 0) + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") @@ -77,7 +77,7 @@ public class PrivateEdgeTest extends AAISetup { } @BeforeClass - public static void setup() throws Exception { + public static void setup() { graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); @@ -85,28 +85,48 @@ public class PrivateEdgeTest extends AAISetup { System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); graph.traversal() - .addV("aai-node-type", "model", "model-invariant-id", "key1", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key1") - .as("v1") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", - "testValue", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v1", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "model", "model-invariant-id", "key100", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key100") - .as("v5") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key200", - "model-version", "testValue", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key100/model-vers/model-ver/key200") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v5", EdgeProperty.CONTAINS.toString(), true) - .addV("aai-node-type", "model", "model-invariant-id", "key3", AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key3") - .as("v2") - .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4", - AAIProperties.AAI_URI, - "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4") - .addOutE("org.onap.relationships.inventory.BelongsTo", "v2", EdgeProperty.CONTAINS.toString(), true) - .next(); + .addV() + .property("aai-node-type", "model") + .property("model-invariant-id", "key1") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1") + .as("v1") + .addV() + .property("aai-node-type", "model-ver") + .property("model-ver", "myValue") + .property("model-version-id", "key2") + .property("model-version", "testValue") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key1/model-vers/model-ver/key2") + .as("v2") + .addE("org.onap.relationships.inventory.BelongsTo").to("v1").from("v2") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "model") + .property("model-invariant-id", "key100") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key100") + .as("v3") + .addV() + .property("aai-node-type", "model-ver") + .property("model-ver", "myValue") + .property("model-version-id", "key200") + .property("model-version", "testValue") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key100/model-vers/model-ver/key200") + .as("v4") + .addE("org.onap.relationships.inventory.BelongsTo").to("v3").from("v4") + .property(EdgeProperty.CONTAINS.toString(), true) + .addV() + .property("aai-node-type", "model") + .property("model-invariant-id", "key3") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3") + .as("v5") + .addV() + .property("aai-node-type", "model-ver") + .property("model-ver", "myValue") + .property("model-version-id", "key4") + .property(AAIProperties.AAI_URI, "/service-design-and-creation/models/model/key3/model-vers/model-ver/key4") + .as("v6") + .addE("org.onap.relationships.inventory.BelongsTo").to("v5").from("v6") + .property(EdgeProperty.CONTAINS.toString(), true) + .next(); graph.tx().commit(); } @@ -118,9 +138,9 @@ public class PrivateEdgeTest extends AAISetup { @Before public void initMock() { - loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion()); + Loader loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion()); MockitoAnnotations.initMocks(this); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); } @Test @@ -137,8 +157,12 @@ public class PrivateEdgeTest extends AAISetup { when(spy.asAdmin()).thenReturn(adminSpy); when(adminSpy.getTraversalSource()).thenReturn(traversal); - Vertex selfV = traversal.addV("aai-node-type", "generic-vnf", "vnf-id", "myId", "aai-uri", obj.getURI(), - "model-invariant-id", "key1").next(); + Vertex selfV = traversal.addV("generic-vnf") + .property("aai-node-type", "generic-vnf") + .property("vnf-id", "myId") + .property("aai-uri", obj.getURI()) + .property("model-invariant-id", "key1") + .next(); thrown.expectMessage(containsString("Cannot complete privateEdge uri")); DBSerializer serializer = @@ -150,7 +174,7 @@ public class PrivateEdgeTest extends AAISetup { assertNull(edgeList); assertThat(edgeList, is(not(empty()))); - assertThat(edgeList.size(), is(1)); + assertEquals(1, edgeList.size()); g.tx().rollback(); } diff --git a/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java index dce34b53..250cdda8 100644 --- a/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java +++ b/aai-core/src/test/java/org/onap/aai/logging/CustomLogPatternLayoutTest.java @@ -20,13 +20,11 @@ package org.onap.aai.logging; +import org.junit.Test; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Test; -import org.onap.aai.logging.CNName; -import org.onap.aai.logging.CustomLogPatternLayout; - public class CustomLogPatternLayoutTest { /** diff --git a/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java index bc7f9499..72b1150e 100644 --- a/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java +++ b/aai-core/src/test/java/org/onap/aai/logging/DME2RestFlagTest.java @@ -20,12 +20,12 @@ package org.onap.aai.logging; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - import ch.qos.logback.access.spi.IAccessEvent; +import org.junit.Before; +import org.junit.Test; -import org.junit.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; public class DME2RestFlagTest { diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java deleted file mode 100644 index 65c78121..00000000 --- a/aai-core/src/test/java/org/onap/aai/logging/EcompErrorCategoryTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.logging; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.junit.*; - -public class EcompErrorCategoryTest { - - EcompErrorCategory _ecompErrorCategory; - ILoggingEvent mockEvent; - - @Before - public void setUp() throws Exception { - - mockEvent = mock(ILoggingEvent.class); - _ecompErrorCategory = spy(EcompErrorCategory.class); - - } - - @Test - public void warn() { - String defaultCategory = "WARN"; - assertEquals(_ecompErrorCategory.convert(mockEvent), defaultCategory); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java deleted file mode 100644 index 8319f9a3..00000000 --- a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseCodeTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.logging; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.junit.*; - -public class EcompResponseCodeTest { - - EcompResponseCode _ecompResponseCode; - ILoggingEvent mockEvent; - - @Before - public void setUp() throws Exception { - - mockEvent = mock(ILoggingEvent.class); - _ecompResponseCode = spy(EcompResponseCode.class); - - } - - @Test - public void getDefaultCode() { - assertEquals(_ecompResponseCode.convert(mockEvent), LoggingContext.UNKNOWN_ERROR); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java b/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java deleted file mode 100644 index 4bcf79cd..00000000 --- a/aai-core/src/test/java/org/onap/aai/logging/EcompResponseDescriptionTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.logging; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.junit.*; -import org.onap.aai.logging.LoggingContext.LoggingField; - -public class EcompResponseDescriptionTest { - - EcompResponseDescription _ecompResponseDescription; - ILoggingEvent mockEvent; - - @Before - public void setUp() throws Exception { - - mockEvent = mock(ILoggingEvent.class); - _ecompResponseDescription = spy(EcompResponseDescription.class); - - } - - @Test - public void getDefaultDesc() { - assertEquals(_ecompResponseDescription.convert(mockEvent), _ecompResponseDescription.DEFAULT_DESCRIPTION); - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java b/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java deleted file mode 100644 index bc77ae81..00000000 --- a/aai-core/src/test/java/org/onap/aai/logging/EelfClassOfCallerTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.logging; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.junit.*; - -public class EelfClassOfCallerTest { - - EelfClassOfCaller _eelfClassOfCaller; - ILoggingEvent mockEvent; - StackTraceElement[] cdafive = new StackTraceElement[5]; - StackTraceElement[] cdaone = new StackTraceElement[1]; - StackTraceElement[] cdazero = new StackTraceElement[0]; - - @Before - public void setUp() throws Exception { - - mockEvent = mock(ILoggingEvent.class); - _eelfClassOfCaller = spy(EelfClassOfCaller.class); - - } - - @Test - public void getFullyQualifiedNameCDALENFiveTest() { - StackTraceElement temp = new StackTraceElement("classname_five", "methodname", "filename", 4); - cdafive[2] = temp; - when(mockEvent.getCallerData()).thenReturn(cdafive); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "classname_five"); - - } - - @Test - public void getFullyQualifiedNameCDALenOneTest() { - StackTraceElement temp = new StackTraceElement("classname_one", "methodname", "filename", 4); - cdaone[0] = temp; - when(mockEvent.getCallerData()).thenReturn(cdaone); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "classname_one"); - - } - - @Test - public void getFullyQualifiedNameCDALenZeroTest() { - when(mockEvent.getCallerData()).thenReturn(cdazero); - assertEquals(_eelfClassOfCaller.getFullyQualifiedName(mockEvent), "?"); - - } - -} diff --git a/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java index 1c55bc11..cbe5bc6b 100644 --- a/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java +++ b/aai-core/src/test/java/org/onap/aai/logging/ErrorObjectTest.java @@ -20,12 +20,12 @@ package org.onap.aai.logging; -import static org.junit.Assert.*; +import org.junit.Test; -import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import org.junit.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class ErrorObjectTest { @@ -98,7 +98,7 @@ public class ErrorObjectTest { } @Test - public void SetErrorCodeTest() { + public void setErrorCodeTest() { newErrorObject.setErrorCode("newErrorCode"); assertEquals(newErrorObject.getErrorCode(), "newErrorCode"); } diff --git a/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java b/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java deleted file mode 100644 index 74347730..00000000 --- a/aai-core/src/test/java/org/onap/aai/logging/LoggingContextTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.logging; - -import static org.junit.Assert.*; - -import java.util.*; - -import org.junit.Test; - -public class LoggingContextTest { - - private static final int MAX_STORED_CONTEXTS = 100; - - @Test - public void testStopWatch() { - try { - LoggingContext.stopWatchStop(); - throw new AssertionError( - "No exception thrown when LoggingContext.stopWatchStop() called without a prior LoggingContext.stopWatchStart()"); - } catch (StopWatchNotStartedException e) { - // Expected - } - - LoggingContext.stopWatchStart(); - - assertTrue(LoggingContext.stopWatchStop() >= 0); - - try { - LoggingContext.stopWatchStop(); - throw new AssertionError("No exception thrown when LoggingContext.stopWatchStop() twice in succession"); - } catch (StopWatchNotStartedException e) { - // Expected - } - } - - @Test - public void testRequestId() { // AKA Transaction ID - final String sUuid = "57d51eaa-edc6-4f50-a69d-f2d4d2445120"; - - LoggingContext.requestId(sUuid); - - assertEquals(LoggingContext.requestId(), UUID.fromString(sUuid)); - - final UUID uuid = UUID.randomUUID(); - - LoggingContext.requestId(uuid); - - assertEquals(LoggingContext.requestId(), uuid); - - LoggingContext.requestId("foo"); // Illegal - this will result in a new, randomly - // generated UUID as per the logging spec - - assertNotNull(LoggingContext.requestId()); // Make sure ANY UUID was assigned - assertNotEquals(LoggingContext.requestId(), uuid); // Make sure it actually changed from the last - // known valid UUID - } - - @Test - public void testClear() { - LoggingContext.init(); - LoggingContext.clear(); - - assertEquals(Collections.emptyMap(), LoggingContext.getCopy()); - } - - @Test - public void testSaveRestore() { - - final Deque<Map<String, String>> contexts = new LinkedList<Map<String, String>>(); - - LoggingContext.init(); - - for (int i = 0; i < MAX_STORED_CONTEXTS; i++) { - LoggingContext.customField1(String.valueOf(i)); - - assertEquals(LoggingContext.customField1(), String.valueOf(i)); - - LoggingContext.save(); - - contexts.push(LoggingContext.getCopy()); - } - - while (contexts.peek() != null) { - LoggingContext.restore(); - - assertEquals(LoggingContext.getCopy(), contexts.pop()); - } - } -} diff --git a/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java index 4cdc55fa..e8ccdddd 100644 --- a/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java +++ b/aai-core/src/test/java/org/onap/aai/parsers/query/LegacyQueryTest.java @@ -20,15 +20,6 @@ package org.onap.aai.parsers.query; -import static org.junit.Assert.assertEquals; - -import java.io.UnsupportedEncodingException; -import java.net.URI; - -import javax.ws.rs.core.UriBuilder; -import javax.xml.bind.JAXBException; - -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; import org.junit.Ignore; import org.junit.Test; import org.onap.aai.AAISetup; @@ -39,12 +30,18 @@ import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.setup.SchemaVersion; +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.junit.Assert.assertEquals; + @Ignore public class LegacyQueryTest extends AAISetup { private TransactionalGraphEngine dbEngine; private SchemaVersion version; - private DynamicJAXBContext context = nodeIngestor.getContextForVersion(version); public void setup() { version = new SchemaVersion("v10"); @@ -60,7 +57,7 @@ public class LegacyQueryTest extends AAISetup { * @throws AAIException the AAI exception */ @Test - public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + public void parentQuery() throws UnsupportedEncodingException, AAIException { URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build(); @@ -82,7 +79,7 @@ public class LegacyQueryTest extends AAISetup { * @throws AAIException the AAI exception */ @Test - public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + public void childQuery() throws UnsupportedEncodingException, AAIException { URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2") .build(); QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); @@ -104,7 +101,7 @@ public class LegacyQueryTest extends AAISetup { * @throws AAIException the AAI exception */ @Test - public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + public void namingExceptions() throws UnsupportedEncodingException, AAIException { URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655") .build(); diff --git a/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java b/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java new file mode 100644 index 00000000..883c8b61 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/prevalidation/ValidationServiceTest.java @@ -0,0 +1,199 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2018-19 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.prevalidation; + +import com.google.gson.Gson; +import org.apache.http.conn.ConnectTimeoutException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.PayloadUtil; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.restclient.RestClient; +import org.springframework.boot.test.rule.OutputCapture; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.util.List; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; + +public class ValidationServiceTest { + + private RestClient restClient; + + private ValidationService validationService; + + @Rule + public OutputCapture capture = new OutputCapture(); + + private Gson gson; + + @Before + public void setUp() throws Exception { + gson = new Gson(); + restClient = Mockito.mock(RestClient.class); + validationService = Mockito.spy(new ValidationService(restClient, "JUNIT", "generic-vnf", null)); + } + + @Test + public void testNodeTypeThatIsAllowedAndItShouldReturnTrue() { + boolean shouldValidate = validationService.shouldValidate("generic-vnf"); + assertThat(shouldValidate, is(true)); + } + + @Test + public void testNodeTypeThatIsNotAllowedAndItShouldReturnFalse() { + boolean shouldValidate = validationService.shouldValidate("customer"); + assertThat(shouldValidate, is(false)); + } + + @Test + public void testPreValidateWithSuccessRequestAndServiceIsDownAndShouldErrorWithConnectionRefused() throws IOException, AAIException { + + String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + + Mockito + .when( + restClient.execute( + eq(ValidationService.VALIDATION_ENDPOINT), + eq(HttpMethod.POST), + any(), + eq(pserverRequest) + ) + ).thenThrow(new RuntimeException(new ConnectException("Connection refused"))); + + validationService.preValidate(pserverRequest); + + assertThat(capture.toString(), containsString("Connection refused to the validation microservice due to service unreachable")); + } + + @Test + public void testPreValidateWithSuccessRequestAndServiceIsUnreachableAndShouldErrorWithConnectionTimeout() throws IOException, AAIException { + + String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + + Mockito + .when( + restClient.execute( + eq(ValidationService.VALIDATION_ENDPOINT), + eq(HttpMethod.POST), + any(), + eq(pserverRequest) + ) + ).thenThrow(new RuntimeException(new ConnectTimeoutException("Connection timed out"))); + + validationService.preValidate(pserverRequest); + + assertThat(capture.toString(), containsString("Connection timeout to the validation microservice as this could indicate the server is unable to reach port")); + } + + @Test + public void testPreValidateWithSuccessRequestAndRespondSuccessfullyWithinAllowedTime() throws IOException, AAIException { + + String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + String validationResponse = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json"); + + ResponseEntity responseEntity = Mockito.mock(ResponseEntity.class, Mockito.RETURNS_DEEP_STUBS); + + Mockito + .when( + restClient.execute( + eq(ValidationService.VALIDATION_ENDPOINT), + eq(HttpMethod.POST), + any(), + eq(pserverRequest) + ) + ).thenReturn(responseEntity); + + Mockito.when(responseEntity.getStatusCodeValue()).thenReturn(200); + Mockito.when(responseEntity.getBody()).thenReturn(validationResponse); + + Mockito.doReturn(true).when(validationService).isSuccess(responseEntity); + + List<String> errorMessages = validationService.preValidate(pserverRequest); + assertNotNull("Expected the error messages to be not null", errorMessages); + assertThat(errorMessages.size(), is(0)); + } + + @Test + public void testPreValidateWithSuccessRequestAndServiceIsAvailableAndRequestIsTakingTooLongAndClientShouldTimeout() throws IOException, AAIException { + + String pserverRequest = PayloadUtil.getResourcePayload("prevalidation/success-request-with-no-violations.json"); + + Mockito + .when( + restClient.execute( + eq(ValidationService.VALIDATION_ENDPOINT), + eq(HttpMethod.POST), + any(), + eq(pserverRequest) + ) + ).thenThrow(new RuntimeException(new SocketTimeoutException("Request timed out due to taking longer than client expected"))); + + validationService.preValidate(pserverRequest); + + assertThat(capture.toString(), containsString("Request to validation service took longer than the currently set timeout")); + } + + @Test + public void testExtractViolationsReturnsSuccessfullyAListWhenViolationsAreFound() throws IOException { + + String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/failed-response-with-violations.json"); + + Validation validation = gson.fromJson(genericVnfRequest, Validation.class); + List<String> errorMessages = validationService.extractViolations(validation); + assertNotNull("Expected the error messages to be not null", errorMessages); + assertThat(errorMessages.size(), is(1)); + assertThat(errorMessages.get(0), is("Invalid nf values, check nf-type, nf-role, nf-function, and nf-naming-code")); + } + + @Test + public void testErrorMessagesAreEmptyListWhenViolationsReturnEmptyList() throws IOException { + + String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-empty-violations.json"); + + Validation validation = gson.fromJson(genericVnfRequest, Validation.class); + List<String> errorMessages = validationService.extractViolations(validation); + assertNotNull("Expected the error messages to be not null", errorMessages); + assertThat(errorMessages.size(), is(0)); + } + + @Test + public void testErrorMessagesAreEmptyListWhenViolationsIsNotFoundInJson() throws IOException { + + String genericVnfRequest = PayloadUtil.getResourcePayload("prevalidation/success-response-with-exclude-violations.json"); + + Validation validation = gson.fromJson(genericVnfRequest, Validation.class); + List<String> errorMessages = validationService.extractViolations(validation); + assertNotNull("Expected the error messages to be not null", errorMessages); + assertThat(errorMessages.size(), is(0)); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java index 0e527493..44d812c3 100644 --- a/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java +++ b/aai-core/src/test/java/org/onap/aai/query/builder/QueryBuilderTestAbstraction.java @@ -20,16 +20,8 @@ package org.onap.aai.query.builder; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.collection.IsIterableContainingInOrder.contains; -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.apache.tinkerpop.gremlin.process.traversal.Path; +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.process.traversal.step.util.BulkSet; import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; @@ -42,6 +34,7 @@ import org.junit.runner.RunWith; import org.onap.aai.config.ConfigConfiguration; import org.onap.aai.config.IntrospectionConfig; import org.onap.aai.config.SpringContextAware; +import org.onap.aai.config.XmlFormatTransformerConfiguration; import org.onap.aai.db.props.AAIProperties; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.enums.EdgeType; @@ -53,7 +46,6 @@ import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException; import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; -import org.onap.aai.setup.SchemaLocationsBean; import org.onap.aai.setup.SchemaVersions; import org.onap.aai.util.AAIConstants; import org.springframework.beans.factory.annotation.Autowired; @@ -62,10 +54,19 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.*; + @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( classes = {ConfigConfiguration.class, QueryTestsConfigTranslator.class, NodeIngestor.class, EdgeIngestor.class, - EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class}) + EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class, XmlFormatTransformerConfiguration.class}) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestPropertySource( properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm", @@ -95,14 +96,14 @@ public abstract class QueryBuilderTestAbstraction { } @Before - public void configure() throws Exception { + public void configure() { loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); g = graph.traversal(); } @After - public void deConfigure() throws Exception { + public void deConfigure() { g.tx().rollback(); } @@ -111,11 +112,30 @@ public abstract class QueryBuilderTestAbstraction { graph.close(); } + /* + * This helper method was designed to minimize the changes needed due to the eventual + * removal of the addV(String...) method. + * Correct vertex creation addV(label).property(k,v).property(k,v)... + */ + @Deprecated + protected GraphTraversal<Vertex, Vertex> addVHelper(GraphTraversalSource gts, String label, Object... props) { + for (int i = 0; i < props.length; i++) { + if (props[i].equals(AAIProperties.NODE_TYPE)) { + label = props[i+1].toString(); + } + } + GraphTraversal<Vertex, Vertex> v = gts.addV(label); + for (int i = 0; i < props.length; i+=2) { + v.property(props[i], props[i+1]); + } + return v; + } + @Test public void createEdgeGVnfToVnfcTraversal() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "myvnf").next(); - Vertex vnfc = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "myvnf").next(); + Vertex vnfc = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc, "uses"); QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(gvnf); @@ -128,8 +148,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void createEdgeLinterfaceToLogicalLinkTraversal() throws AAIException { - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); - Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex logicalLink = this.addVHelper(g, "vertex", "aai-node-type", "logical-link", "link-name", "logical-link-a").next(); testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface"); QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface); @@ -144,8 +164,8 @@ public abstract class QueryBuilderTestAbstraction { @SuppressWarnings("rawtypes") @Test public void createEdgeLinterfaceToLogicalLinkTraversal_tree() throws AAIException { - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); - Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex logicalLink = this.addVHelper(g, "vertex", "aai-node-type", "logical-link", "link-name", "logical-link-a").next(); testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface"); QueryBuilder<Tree> tQ = getNewTreeTraversalWithTestEdgeRules(lInterface).createEdgeTraversal(EdgeType.COUSIN, @@ -163,9 +183,9 @@ public abstract class QueryBuilderTestAbstraction { @SuppressWarnings("rawtypes") @Test public void createEdgeLinterfaceToLogicalLinkTraversal_Path() throws AAIException { - Vertex pInterface = g.addV("aai-node-type", "p-interface", "interface-name", "p-interface-a").next(); - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); - Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next(); + Vertex pInterface = this.addVHelper(g, "vertex", "aai-node-type", "p-interface", "interface-name", "p-interface-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex logicalLink = this.addVHelper(g, "vertex", "aai-node-type", "logical-link", "link-name", "logical-link-a").next(); testEdgeSer.addEdge(g, lInterface, logicalLink); testEdgeSer.addTreeEdge(g, pInterface, lInterface); @@ -183,8 +203,8 @@ public abstract class QueryBuilderTestAbstraction { @SuppressWarnings("rawtypes") @Test public void parentVertexTest() throws AAIException { - Vertex pInterface = g.addV("aai-node-type", "p-interface", "interface-name", "p-interface-a").next(); - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex pInterface = this.addVHelper(g, "vertex", "aai-node-type", "p-interface", "interface-name", "p-interface-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); testEdgeSer.addTreeEdge(g, pInterface, lInterface); @@ -197,8 +217,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void createEdgeLinterfaceToLogicalLinkIntrospectorTraversal() throws AAIException { - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); - Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex logicalLink = this.addVHelper(g, "vertex", "aai-node-type", "logical-link", "link-name", "logical-link-a").next(); testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface"); QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface); @@ -214,8 +234,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void createEdgeLinterfaceToLogicalLinkVertexToIntrospectorTraversal() throws AAIException { - Vertex lInterface = g.addV("aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); - Vertex logicalLink = g.addV("aai-node-type", "logical-link", "link-name", "logical-link-a").next(); + Vertex lInterface = this.addVHelper(g, "vertex", "aai-node-type", "l-interface", "interface-name", "l-interface-a").next(); + Vertex logicalLink = this.addVHelper(g, "vertex", "aai-node-type", "logical-link", "link-name", "logical-link-a").next(); testEdgeSer.addEdge(g, lInterface, logicalLink, "sourceLInterface"); QueryBuilder<Vertex> tQ = getNewVertexTraversalWithTestEdgeRules(lInterface); @@ -230,8 +250,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc1); @@ -248,8 +268,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexTraversalSingleOutRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, vce, vnfc1); @@ -272,8 +292,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexTraversalSingleInRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, vce, pserver); @@ -290,9 +310,9 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexMultiRuleTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vnfc2 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc1); testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses"); @@ -311,9 +331,9 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexMultiLabelTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc1); testEdgeSer.addEdge(g, pserver, vnfc1); @@ -329,10 +349,10 @@ public abstract class QueryBuilderTestAbstraction { } @Test - public void limitTraversalTest() throws AAIException { + public void limitTraversalTest() { - g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g); tQ.getVerticesByProperty("aai-node-type", "vnfc").limit(1); @@ -344,10 +364,10 @@ public abstract class QueryBuilderTestAbstraction { } @Test - public void getVertexesByPropertiesTraversalTest() throws AAIException { + public void getVertexesByPropertiesTraversalTest() { - g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g); tQ.getVerticesByProperty("vnfc-name", Arrays.asList("a-name", "b-name")); @@ -359,25 +379,38 @@ public abstract class QueryBuilderTestAbstraction { } @Test - public void getVertexesByIndexedPropertyTraversalTest() throws AAIException { + public void getVerticesByCommaSeperatedValueTraversalTest() { - g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g); - tQ.getVerticesByIndexedProperty("aai-node-type", "vnfc"); + tQ.getVerticesByCommaSeperatedValue("vnfc-name","a-name, b-name"); List<Vertex> list = tQ.toList(); assertEquals("Has 2 vertexes ", 2, list.size()); + } + + @Test + public void getVertexesByIndexedPropertyTraversalTest() { + + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g); + tQ.getVerticesByIndexedProperty("aai-node-type", "vnfc"); + + List<Vertex> list = tQ.toList(); + + assertEquals("Has 2 vertexes ", 2, list.size()); } @Test public void dedupTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -395,8 +428,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void storeCapTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -414,8 +447,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void storeCapUnfoldTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -431,10 +464,10 @@ public abstract class QueryBuilderTestAbstraction { } @Test - public void nextAndHasNextTraversalTest() throws AAIException { + public void nextAndHasNextTraversalTest() { - Vertex v1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - Vertex v2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + Vertex v1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex v2 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); QueryBuilder<Vertex> tQ = new GremlinTraversal<>(loader, g); tQ.getVerticesByProperty("aai-node-type", "vnfc"); @@ -453,8 +486,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexMultiRuleOutTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -472,8 +505,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeToVertexMultiRuleInTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex complex = this.addVHelper(g, "vertex", "aai-node-type", "complex", "physical-location-id", "a-name").next(); testEdgeSer.addEdge(g, gvnf, complex); testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B"); @@ -491,8 +524,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeTraversalSingleInRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e = testEdgeSer.addEdge(g, vce, pserver); @@ -509,8 +542,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeTraversalSingleOutRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); Edge e = testEdgeSer.addEdge(g, vce, vnfc1); @@ -527,8 +560,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeTraversalMultiRuleOutTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver); Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -547,8 +580,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeTraversalMultiRuleInTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex complex = this.addVHelper(g, "vertex", "aai-node-type", "complex", "physical-location-id", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, complex); Edge e2 = testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B"); @@ -567,9 +600,9 @@ public abstract class QueryBuilderTestAbstraction { @Test public void edgeTraversalMultiRuleTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vnfc2 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, vnfc1); Edge e2 = testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses"); @@ -589,8 +622,8 @@ public abstract class QueryBuilderTestAbstraction { @Test(expected = NoEdgeRuleFoundException.class) public void getEdgesBetweenWithLabelsEmptyListTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -603,8 +636,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void getEdgesBetweenWithLabelsSingleItemTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver); Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -624,8 +657,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void getEdgesBetweenWithLabelsMultipleItemTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver); Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -656,8 +689,8 @@ public abstract class QueryBuilderTestAbstraction { } private Vertex getVertex() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -667,8 +700,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void createEdgeTraversalWithLabelsSingleItemTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver); Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -688,8 +721,8 @@ public abstract class QueryBuilderTestAbstraction { @Test public void createEdgeTraversalWithLabelsMultipleItemTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); Edge e1 = testEdgeSer.addEdge(g, gvnf, pserver); Edge e2 = testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -706,6 +739,50 @@ public abstract class QueryBuilderTestAbstraction { } + @Test + public void createEdgeTraversalIfParameterIsPresentParameterExistsTest() throws AAIException { + + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver1 = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex pserver2 = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "b-name").next(); + Vertex optionalVce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "optional").next(); + + testEdgeSer.addEdge(g, gvnf, pserver1); + testEdgeSer.addEdge(g, gvnf, pserver2); + testEdgeSer.addEdge(g, optionalVce, pserver1); + + QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf); + tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "pserver"); + + List<Vertex> list = tQ.createEdgeTraversalIfParameterIsPresent(EdgeType.COUSIN, "pserver", "vce", "optional").toList(); + assertEquals("Has 1 vertex ", 1, list.size()); + assertTrue("result has optional-vce vertex ", list.contains(optionalVce)); + } + + @Test + public void createEdgeTraversalIfParameterIsPresentParameterDoesNotExistTest() throws AAIException { + + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver1 = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex pserver2 = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "b-name").next(); + Vertex optionalVce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "optional").next(); + + testEdgeSer.addEdge(g, gvnf, pserver1); + testEdgeSer.addEdge(g, gvnf, pserver2); + testEdgeSer.addEdge(g, optionalVce, pserver1); + + QueryBuilder<Edge> tQ = getNewEdgeTraversalWithTestEdgeRules(gvnf); + tQ.createEdgeTraversal(EdgeType.COUSIN, "generic-vnf", "pserver"); + MissingOptionalParameter missingParameter = MissingOptionalParameter.getInstance(); + + List<Vertex> list = tQ.createEdgeTraversalIfParameterIsPresent(EdgeType.COUSIN, "pserver", "vce", missingParameter).toList(); + assertEquals("Has 2 vertices ", 2, list.size()); + assertTrue("result has pserver-1 vertex ", list.contains(pserver1)); + assertTrue("result has pserver-2 vertex ", list.contains(pserver2)); + assertTrue("result does not have optional-vce vertex ", !list.contains(optionalVce)); + } + + protected abstract QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(Vertex v); protected abstract QueryBuilder<Edge> getNewEdgeTraversalWithTestEdgeRules(); diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java index eb1e57c3..4eac35eb 100644 --- a/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java +++ b/aai-core/src/test/java/org/onap/aai/query/builder/TraversalQueryTest.java @@ -20,14 +20,6 @@ package org.onap.aai.query.builder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; @@ -40,6 +32,14 @@ import org.onap.aai.db.props.AAIProperties; import org.onap.aai.edges.enums.EdgeType; import org.onap.aai.exceptions.AAIException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Override @@ -141,8 +141,8 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc1); @@ -159,8 +159,8 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexTraversalSingleOutRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); testEdgeSer.addEdge(g, vce, vnfc1); @@ -183,8 +183,8 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexTraversalSingleInRuleTest() throws AAIException { - Vertex vce = g.addV("aai-node-type", "vce", "vnf-id", "vce").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex vce = this.addVHelper(g, "vertex", "aai-node-type", "vce", "vnf-id", "vce").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, vce, pserver); @@ -201,9 +201,9 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexMultiRuleTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex vnfc1 = g.addV("aai-node-type", "vnfc", "vnfc-name", "a-name").next(); - Vertex vnfc2 = g.addV("aai-node-type", "vnfc", "vnfc-name", "b-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex vnfc1 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "a-name").next(); + Vertex vnfc2 = this.addVHelper(g, "vertex", "aai-node-type", "vnfc", "vnfc-name", "b-name").next(); testEdgeSer.addEdge(g, gvnf, vnfc1); testEdgeSer.addEdge(g, gvnf, vnfc2, "re-uses"); @@ -222,8 +222,8 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexMultiRuleOutTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex pserver = g.addV("aai-node-type", "pserver", "hostname", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex pserver = this.addVHelper(g, "vertex", "aai-node-type", "pserver", "hostname", "a-name").next(); testEdgeSer.addEdge(g, gvnf, pserver); testEdgeSer.addEdge(g, gvnf, pserver, "generic-vnf-pserver-B"); @@ -241,8 +241,8 @@ public class TraversalQueryTest extends QueryBuilderTestAbstraction { @Test public void abstractEdgeToVertexMultiRuleInTraversalTest() throws AAIException { - Vertex gvnf = g.addV("aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); - Vertex complex = g.addV("aai-node-type", "complex", "physical-location-id", "a-name").next(); + Vertex gvnf = this.addVHelper(g, "vertex", "aai-node-type", "generic-vnf", "vnf-id", "gvnf").next(); + Vertex complex = this.addVHelper(g, "vertex", "aai-node-type", "complex", "physical-location-id", "a-name").next(); testEdgeSer.addEdge(g, gvnf, complex); testEdgeSer.addEdge(g, gvnf, complex, "complex-generic-vnf-B"); diff --git a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java index 911cb20c..b517ced2 100644 --- a/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java +++ b/aai-core/src/test/java/org/onap/aai/query/builder/optimization/AbstractGraphTraversalBuilderOptmizationTest.java @@ -20,16 +20,7 @@ package org.onap.aai.query.builder.optimization; -import static org.junit.Assert.assertEquals; - import com.google.common.base.CaseFormat; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.List; -import java.util.Random; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -38,7 +29,6 @@ import org.junit.AfterClass; import org.onap.aai.AAISetup; import org.onap.aai.db.props.AAIProperties; import org.onap.aai.dbmap.AAIGraph; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.introspection.Introspector; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -50,6 +40,14 @@ import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.springframework.beans.factory.annotation.Autowired; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import static org.junit.Assert.assertEquals; + public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISetup { protected static final List<String> RANDOM_VALUES = Arrays.asList("A", "B", "C", "D", "E"); @@ -74,7 +72,6 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe private static final ModelType introspectorFactoryType = ModelType.MOXY; private static final QueryStyle queryStyle = QueryStyle.TRAVERSAL; - private static final DBConnectionType type = DBConnectionType.REALTIME; private static TransactionalGraphEngine dbEngine; private static DBSerializer dbser; protected static Loader loader; @@ -89,7 +86,7 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, schemaVersions.getDefaultVersion()); graph = AAIGraph.getInstance().getGraph(); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); g = dbEngine.startTransaction().traversal(); dbser = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, introspectorFactoryType, "AAI-TEST-" + prefix); @@ -107,8 +104,12 @@ public abstract class AbstractGraphTraversalBuilderOptmizationTest extends AAISe for (int crCtr = 0; crCtr < 3; crCtr++) { crUri = String.format(crUriPattern, prefix + "cloud-owner-" + crCtr, prefix + "cloud-region-id-" + crCtr); // System.out.println(crUri); - cr = g.addV(AAIProperties.NODE_TYPE, CLOUD_REGION, CLOUD_REGION_ID, prefix + "cloud-region-id-" + crCtr, - CLOUD_OWNER, prefix + "cloud-owner-" + crCtr, AAIProperties.AAI_URI, crUri).next(); + cr = g.addV(CLOUD_REGION) + .property(AAIProperties.NODE_TYPE, CLOUD_REGION) + .property(CLOUD_REGION_ID, prefix + "cloud-region-id-" + crCtr) + .property(CLOUD_OWNER, prefix + "cloud-owner-" + crCtr) + .property(AAIProperties.AAI_URI, crUri) + .next(); for (int i = 0; i < tenantNum; i++) { Introspector intro = loader.introspectorFromName(TENANT); tenant = dbser.createNewVertex(intro); diff --git a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java index a742313a..34477206 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/HPACapabilityTest.java @@ -22,8 +22,8 @@ package org.onap.aai.rest; import static org.junit.Assert.assertEquals; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.jayway.jsonpath.JsonPath; import java.util.*; @@ -45,7 +45,7 @@ import org.skyscreamer.jsonassert.JSONAssert; @RunWith(AAIJunitRunner.class) public class HPACapabilityTest { - private static EELFLogger logger = EELFManager.getInstance().getLogger(HPACapabilityTest.class); + private static Logger logger = LoggerFactory.getLogger(HPACapabilityTest.class); private HttpTestUtil httpTestUtil; private Map<String, String> templateValuesMap; diff --git a/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java new file mode 100644 index 00000000..2b7a5818 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/ImpliedDeleteIntegrationTest.java @@ -0,0 +1,169 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.rest; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.janusgraph.core.JanusGraphTransaction; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.HttpTestUtil; +import org.onap.aai.PayloadUtil; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.rest.ueb.NotificationEvent; +import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.serialization.engines.QueryStyle; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.test.annotation.DirtiesContext; + +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.*; + +@RunWith(value = Parameterized.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class ImpliedDeleteIntegrationTest extends AAISetup { + + private static final Logger LOGGER = LoggerFactory.getLogger(ImpliedDeleteIntegrationTest.class); + + @Parameterized.Parameter(value = 0) + public QueryStyle queryStyle; + + @Parameterized.Parameters(name = "QueryStyle.{0}") + public static Collection<Object[]> data() { + return Arrays.asList(new Object[][] { + { QueryStyle.TRAVERSAL }, + { QueryStyle.TRAVERSAL_URI } + }); + } + + @Test + public void testPutPserverWithMultiplePInterfaceChildrenAndDoPutWithZeroChildren() throws Exception { + + String uri = "/aai/v12/cloud-infrastructure/pservers/pserver/test-pserver-implied-delete"; + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + String resource = PayloadUtil.getResourcePayload("pserver-implied-delete.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject jsonObject = new JSONObject(response.getEntity().toString()); + JSONAssert.assertEquals(resource, response.getEntity().toString(), false); + jsonObject.getJSONObject("p-interfaces").remove("p-interface"); + + notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + response = httpTestUtil.doPut(uri, jsonObject.toString()); + assertEquals("Expecting the pserver to be updated and delete children", 200, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(5)); + + List<String> notificationEventHeaders = notification.getEvents() + .stream() + .map(event -> event.getEventHeader().marshal(false)) + .collect(Collectors.toList()); + + Long deletedEventsCount = notificationEventHeaders.stream().filter(e -> e.contains("\"DELETE\"")).count(); + + assertThat(deletedEventsCount, is(4L)); + + response = httpTestUtil.doGet(uri); + assertThat(response.getEntity().toString(), not(containsString("p-interface"))); + } + + @Test + public void testPutGenericVnf() throws Exception { + + String uri = "/aai/v12/network/generic-vnfs/generic-vnf/generic-vnf-implied-delete"; + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("generic-vnf-implied-delete.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + + JSONObject jsonObject = new JSONObject(response.getEntity().toString()); + JSONAssert.assertEquals(resource, response.getEntity().toString(), false); + jsonObject.getJSONObject("vf-modules").remove("vf-module"); + + response = httpTestUtil.doPut(uri, jsonObject.toString()); + assertEquals("Expecting the generic-vnf to be not deleted and fail with 403", 403, response.getStatus()); + assertThat(response.getEntity().toString(), containsString("User is not allowed to perform implicit delete")); + } + + @After + public void tearDown() { + + JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + g.V().has("source-of-truth", "JUNIT").toList().forEach(v -> v.remove()); + + } catch (Exception ex) { + success = false; + LOGGER.error("Unable to remove the vertexes", ex); + } finally { + if (success) { + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to teardown the graph"); + } + } + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java b/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java new file mode 100644 index 00000000..16783180 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/NotificationDmaapEventTest.java @@ -0,0 +1,1028 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.rest; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.JanusGraphTransaction; +import org.javatuples.Pair; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.HttpTestUtil; +import org.onap.aai.PayloadUtil; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.rest.ueb.NotificationEvent; +import org.onap.aai.rest.ueb.UEBNotification; +import org.onap.aai.serialization.engines.QueryStyle; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.test.annotation.DirtiesContext; + +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.*; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.junit.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + +@RunWith(value = Parameterized.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class NotificationDmaapEventTest extends AAISetup { + + @Parameterized.Parameter + public QueryStyle queryStyle; + + @Parameterized.Parameters(name = "QueryStyle.{0}") + public static Collection<Object[]> data() { + return Arrays.asList(new Object[][] { + { QueryStyle.TRAVERSAL }, + { QueryStyle.TRAVERSAL_URI } + }); + } + + @Test + public void testCreateWithPserverWithAllChildrenAndVerifyMultipleNotificationsWhenNotificationDepthIsZero() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + int expectedCreateEvents = 17; + + assertThat(notification.getEvents().size(), is(expectedCreateEvents)); + + // Verify all the events are create since its a new PUT + notification.getEvents().forEach((event) -> { + + String header = event.getEventHeader().marshal(false); + + assertThat( + event.getEventHeader().marshal(false), + containsString("\"CREATE\"") + ); + + assertThat( + header, + containsString("\"top-entity-type\":\"pserver\"") + ); + + }); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + } + + // Test existing pserver create new pinterface check dmaap event for pinterface is CREATE + @Test + public void testExistingPserverCreateNewChildPInterfaceAndCheckDmaapEventForPInterfaceIsCreateWhenNotificationDepthIsZero() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, pserverResource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + notification.clearEvents(); + + + response = httpTestUtil.doGet(uri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverJson = new JSONObject(response.getEntity().toString()); + JSONObject pInterfaceObject = new JSONObject(); + pInterfaceObject.put("interface-name", "p-interface-1"); + + pserverJson.getJSONObject("p-interfaces").getJSONArray("p-interface").put(pInterfaceObject); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + response = httpTestUtil.doPut(uri, pserverJson.toString()); + assertEquals("Expecting the pserver to be updated with a new p-interface", 200, response.getStatus()); + + response = httpTestUtil.doGet(uri + "/p-interfaces/p-interface/p-interface-1", "0"); + assertEquals("Expecting the p-interface to be found", 200, response.getStatus()); + + List<NotificationEvent> events = notification.getEvents(); + assertThat(events.size(), is(2)); + + String notificationEventHeader = events.get(1).getEventHeader().marshal(false); + String notificationEventBody = events.get(1).getObj().marshal(false); + + assertThat(notificationEventHeader, containsString("\"action\":\"CREATE\"")); + assertThat(notificationEventHeader, containsString("\"entity-type\":\"p-interface\"")); + assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\"")); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-header-create-child-on-existing-obj.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-body-create-child-on-existing-obj.json"); + + JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false); + } + + @Test + public void testExistingPserverCreateNewChildPInterfaceAndCheckDmaapEventForPserverIsSentWithNewPInterfaceWhenNotificationDepthIsAll() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, pserverResource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverJson = new JSONObject(response.getEntity().toString()); + String pserverResourceVersion = pserverJson.getString("resource-version"); + + JSONObject pInterfaceObject = new JSONObject(); + pInterfaceObject.put("interface-name", "p-interface-1"); + + pserverJson.getJSONObject("p-interfaces").getJSONArray("p-interface").put(pInterfaceObject); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doPut(uri, pserverJson.toString()); + assertEquals("Expecting the pserver to be updated with a new p-interface", 200, response.getStatus()); + + response = httpTestUtil.doGet(uri + "/p-interfaces/p-interface/p-interface-1", "0"); + assertEquals("Expecting the p-interface to be found", 200, response.getStatus()); + + List<NotificationEvent> events = notification.getEvents(); + assertThat(events.size(), is(1)); + + String notificationEventHeader = events.get(0).getEventHeader().marshal(false); + String notificationEventBody = events.get(0).getObj().marshal(false); + + assertThat(notificationEventHeader, containsString("\"action\":\"UPDATE\"")); + assertThat(notificationEventHeader, containsString("\"entity-type\":\"pserver\"")); + assertThat(notificationEventHeader, containsString("\"top-entity-type\":\"pserver\"")); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-header-create-child-on-existing-obj.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-body-create-child-on-existing-obj.json"); + + JSONAssert.assertEquals(expectedNotificationHeader, notificationEventHeader, false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEventBody, false); + + response = httpTestUtil.doGet(uri, "0"); + pserverJson = new JSONObject(response.getEntity().toString()); + String newPserverResourceVersion = pserverJson.getString("resource-version"); + + // After an pserver's p-interface is updated on the pserver, even though + // the pserver nothing changed, expecting the pserver resource version to be changed + assertThat( + "Expecting the new pserver resource version and old resource version to be not same", + newPserverResourceVersion, + is(not(pserverResourceVersion)) + ); + assertEquals("Expecting the p-interface to be found", 200, response.getStatus()); + } + + // Test Bulk Scenario + @Test + public void testBulkScenarioWhereMultipleCreatesAndEnsureNoDuplicationInDmaapEventsWhenNotificationDepthIsZero() throws UnsupportedEncodingException, AAIException { + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/random-pserver"; + String cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id"; + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + Map<String, String> uriPayload = new LinkedHashMap<>(); + + uriPayload.put(pserverUri, "{}"); + uriPayload.put(cloudRegionUri, "{}"); + + Response response = httpTestUtil.doPut(uriPayload); + assertThat(response.getStatus(), is(201)); + + int numberOfEventsActual = notification.getEvents().size(); + int expectedEvents = 2; + + assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents)); + + notification.getEvents().forEach((event) -> { + String notificationEventHeader = event.getEventHeader().marshal(false); + assertThat(notificationEventHeader, containsString("\"CREATE\"")); + }); + } + + + @Test + public void testBulkScenarioWhereMultipleCreatesAndEnsureNoDuplicationInDmaapEventsWhenNotificationDepthIsAll() throws UnsupportedEncodingException, AAIException { + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/random-pserver"; + String cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/random-cloud-region-owner/random-cloud-region-id"; + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + + Map<String, String> uriPayload = new LinkedHashMap<>(); + + uriPayload.put(pserverUri, "{}"); + uriPayload.put(cloudRegionUri, "{}"); + + Response response = httpTestUtil.doPut(uriPayload); + assertThat(response.getStatus(), is(201)); + + int numberOfEventsActual = notification.getEvents().size(); + int expectedEvents = 2; + + assertThat("Expecting the number of dmaap events to be 2", numberOfEventsActual, is(expectedEvents)); + + notification.getEvents().forEach((event) -> { + String notificationEventHeader = event.getEventHeader().marshal(false); + assertThat(notificationEventHeader, containsString("\"CREATE\"")); + }); + } + + @Test + public void testDeleteOnExistingPserverAndCheckIfNotificationDepthIsZeroThatAllEventsHaveDeleteAndThatDepthIsZeroOnEachNotificationEvent() throws IOException, AAIException { + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, pserverResource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverObject = new JSONObject(response.getEntity().toString()); + String resourceVersion = pserverObject.getString("resource-version"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + response = httpTestUtil.doDelete(uri, resourceVersion); + assertEquals("Expecting the pserver to be deleted", 204, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(17)); + + notificationEvents.forEach((event) -> { + + String header = event.getEventHeader().marshal(false); + + assertThat( + event.getEventHeader().marshal(false), + containsString("\"DELETE\"") + ); + + assertThat( + header, + containsString("\"top-entity-type\":\"pserver\"") + ); + }); + } + + + @Test + public void testDeleteOnExistingResourceVersionMismatchNoEventGenerated() throws IOException, AAIException { + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, pserverResource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverObject = new JSONObject(response.getEntity().toString()); + String resourceVersion = pserverObject.getString("resource-version"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + response = httpTestUtil.doDelete(uri, resourceVersion+"123"); + assertEquals("Resource version mismatch exception", 412, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(0)); + } + + + // Test notification depth set to all + // Scenario for testing the creation of pserver with children, grandchildren + // Default behaviour is for one event to be sent out + // which includes all the children and grandchildren, etc + @Test + public void testCreateWithPserverWithAllChildrenAndVerifyOneNotificationWhenNotificationDepthIsAll() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + assertThat(notification.getEvents().size(), is(1)); + + NotificationEvent notificationEvent = notification.getEvents().get(0); + + // Verify all the events are create since its a new PUT + String header = notificationEvent.getEventHeader().marshal(false); + + assertThat( + header, + containsString("\"CREATE\"") + ); + + assertThat( + header, + containsString("\"entity-type\":\"pserver\"") + ); + + assertThat( + header, + containsString("\"top-entity-type\":\"pserver\"") + ); + + assertThat( + header, + containsString("\"entity-link\":\"" + uri + "\"") + ); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONAssert.assertEquals(response.getEntity().toString(), notificationEvent.getObj().marshal(false), false); + } + + @Test + public void testPatchExistingPserverWithChildrenAndModifyOnlyOneObjectAndVerifyThatOnlyOneNotificationEventNoChildrenWhenNotificationDepthIsZero() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverObject = new JSONObject(); + pserverObject.put("equip-type", "new-equip-patch-type"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + response = httpTestUtil.doPatch(uri, pserverObject.toString()); + assertThat(response.getStatus(), is(200)); + + response = httpTestUtil.doGet(uri, "0"); + assertThat(response.getEntity().toString(), containsString("new-equip-patch-type")); + + assertThat(notification.getEvents().size(), is(1)); + String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + + // Check that everything in notification event is also response body + // Not comparing the other way as notification only includes parents main properties + JSONAssert.assertEquals(updateNotificationEvent, response.getEntity().toString(), false); + } + + @Test + public void testPatchExistingPserverWithChildrenAndModifyOnlyOneObjectAndVerifyThatOnlyOneNotificationEventIncludeChildrenWhenNotificationDepthIsAll() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverObject = new JSONObject(); + pserverObject.put("equip-type", "new-equip-patch-type"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doPatch(uri, pserverObject.toString()); + assertThat(response.getStatus(), is(200)); + + response = httpTestUtil.doGet(uri, "all"); + assertThat(response.getEntity().toString(), containsString("new-equip-patch-type")); + + assertThat(notification.getEvents().size(), is(1)); + String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + + // Check that everything in notification event is also response body + // Not comparing the other way as notification only includes parents main properties + JSONAssert.assertEquals(updateNotificationEvent, response.getEntity().toString(), false); + } + + // Test notification depth set to all + // Scenario where we are only updating one field in p-interface + // Make sure the parent and children are included + @Test + public void testUpdateExistingPserverWithChildrenAndModifyOnlyOneObjectAndVerifyThatOnlyOneNotificationEventIncludingChildrenWhenNotificationDepthIsAll() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(uri + "/p-interfaces/p-interface/example-interface-name-val-46147", "0"); + assertEquals("Expecting the p-interface to be found", 200, response.getStatus()); + + JSONObject pInterfaceObject = new JSONObject(response.getEntity().toString()); + pInterfaceObject.put("equipment-identifier", "new-equipment-identifier"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doPut(uri + "/p-interfaces/p-interface/example-interface-name-val-46147", pInterfaceObject.toString()); + assertThat(response.getStatus(), is(200)); + + // Get the parent uri as the notification event json has parent structure it makes it easy to compare + response = httpTestUtil.doGet(uri); + assertThat(response.getEntity().toString(), containsString("new-equipment-identifier")); + + assertThat(notification.getEvents().size(), is(1)); + String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + + // Check that everything in notification event is also response body + // Not comparing the other way as notification only includes parents main properties + JSONAssert.assertEquals(updateNotificationEvent, response.getEntity().toString(), false); + } + + // Test notification depth set to 0 + // Scenario where we are only updating one field in p-interface + @Test + public void testUpdateExistingPserverWithChildrenAndModifyOnlyPInterfaceAndVerifyThatOnlyOneNotificationForPInterfaceIsCreatedWhenNotificationDepthIsZero() throws IOException, AAIException { + + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(uri + "/p-interfaces/p-interface/example-interface-name-val-46147", "0"); + assertEquals("Expecting the p-interface to be found", 200, response.getStatus()); + + JSONObject pInterfaceObject = new JSONObject(response.getEntity().toString()); + pInterfaceObject.put("equipment-identifier", "new-equipment-identifier"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + response = httpTestUtil.doPut(uri + "/p-interfaces/p-interface/example-interface-name-val-46147", pInterfaceObject.toString()); + assertThat(response.getStatus(), is(200)); + + response = httpTestUtil.doGet(uri); + assertThat(notification.getEvents().size(), is(1)); + String updateNotificationEvent = notification.getEvents().get(0).getObj().marshal(true); + System.out.println("Update notification " + updateNotificationEvent); + + // Check that everything in notification event is also response body + // Not comparing the other way as notification only includes parents main properties + JSONAssert.assertEquals(updateNotificationEvent, response.getEntity().toString(), false); + } + + @Test + public void testExistingPserverWithChildAndGenericVnfAndCreateEdgeBetweenThemAndCheckNoChildWhenNotificationDepthIsZero() throws IOException, AAIException { + + String hostname = "example-hostname-val-85598"; + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; + String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + String genericVnfResource = PayloadUtil.getResourcePayload("generic-vnf-notification.json"); + + Response response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(pserverUri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(genericVnfUri, genericVnfResource); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), not(containsString(hostname))); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); + + response = httpTestUtil.doPut(pserverUri + "/relationship-list/relationship", relationship); + assertEquals("Expecting the pserver to generic-vnf relationship to be created", 200, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(2)); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-header-create-edge-between-pserver-and-generic-vnf.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json"); + + JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + + response = httpTestUtil.doGet(genericVnfUri); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + } + + @Test + public void testExistingPserverWithChildAndGenericVnfAndCreateEdgeBetweenThemAndCheckChildrenIncludedWhenNotificationDepthIsAll() throws IOException, AAIException { + + String hostname = "example-hostname-val-85598"; + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; + String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + String genericVnfResource = PayloadUtil.getResourcePayload("generic-vnf-notification.json"); + + Response response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(pserverUri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(genericVnfUri, genericVnfResource); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), not(containsString(hostname))); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + + String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); + + response = httpTestUtil.doPut(pserverUri + "/relationship-list/relationship", relationship); + assertEquals("Expecting the pserver to generic-vnf relationship to be created", 200, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(2)); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-header-create-edge-between-pserver-and-generic-vnf.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-body-create-edge-between-pserver-and-generic-vnf.json"); + + System.out.println("Notification Body: " + notificationEvents.get(0).getObj().marshal(false)); + JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + + response = httpTestUtil.doGet(genericVnfUri); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + } + + @Test + public void testExistingPserverWithChildAndGenericVnfAndExistingEdgeBetweenThemAndDeleteEdgeAndCheckNoChildWhenNotificationDepthIsZero() throws IOException, AAIException { + + String hostname = "example-hostname-val-85598"; + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; + String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; + + String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + String genericVnfResource = PayloadUtil.getResourcePayload("generic-vnf-notification.json"); + + Response response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(pserverUri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(genericVnfUri, genericVnfResource); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), not(containsString(hostname))); + + + response = httpTestUtil.doPut(pserverUri + "/relationship-list/relationship", relationship); + assertEquals("Expecting the pserver to generic-vnf relationship to be created", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverJson = new JSONObject(response.getEntity().toString()); + String resourceVersion = pserverJson.getString("resource-version"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MINIMUM_DEPTH); + + response = httpTestUtil.doDelete(pserverUri + "/relationship-list/relationship", resourceVersion, relationship); + assertThat("Expected the pserver relationship to generic-vnf to be deleted", response.getStatus(), is(204)); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + + assertThat(notificationEvents.size(), is(2)); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-header-delete-edge-between-pserver-and-generic-vnf.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-zero/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json"); + + JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + + } + + @Test + public void testExistingPserverWithChildAndGenericVnfAndExistingEdgeBetweenThemAndDeleteEdgeAndCheckChildrenWhenNotificationDepthIsAll() throws IOException, AAIException { + + String hostname = "example-hostname-val-85598"; + + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/" + hostname; + String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/generic-vnf-notification"; + + String relationship = PayloadUtil.getResourcePayload("pserver-to-gvnf-relationship-notification.json"); + + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String resource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + String genericVnfResource = PayloadUtil.getResourcePayload("generic-vnf-notification.json"); + + Response response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(pserverUri, resource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(genericVnfUri, genericVnfResource); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), not(containsString(hostname))); + + + response = httpTestUtil.doPut(pserverUri + "/relationship-list/relationship", relationship); + assertEquals("Expecting the pserver to generic-vnf relationship to be created", 200, response.getStatus()); + + response = httpTestUtil.doGet(genericVnfUri); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString(hostname)); + + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverJson = new JSONObject(response.getEntity().toString()); + String resourceVersion = pserverJson.getString("resource-version"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + + response = httpTestUtil.doDelete(pserverUri + "/relationship-list/relationship", resourceVersion, relationship); + assertThat("Expected the pserver relationship to generic-vnf to be deleted", response.getStatus(), is(204)); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(2)); + + String expectedNotificationHeader = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-header-delete-edge-between-pserver-and-generic-vnf.json"); + String expectedNotificationBody = PayloadUtil.getResourcePayload("notification-dmaap-events/depth-all/expected-notification-body-delete-edge-between-pserver-and-generic-vnf.json"); + + JSONAssert.assertEquals(expectedNotificationHeader, notificationEvents.get(0).getEventHeader().marshal(false), false); + JSONAssert.assertEquals(expectedNotificationBody, notificationEvents.get(0).getObj().marshal(false), false); + + } + + @Test + public void testDeleteOnExistingResourceVersionMismatchNoEventGeneratedFullDepth() throws IOException, AAIException { + String uri = "/aai/v14/cloud-infrastructure/pservers/pserver/example-hostname-val-85598"; + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + String pserverResource = PayloadUtil.getResourcePayload("pserver-with-children-for-notification.json"); + + Response response = httpTestUtil.doGet(uri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(uri, pserverResource); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doGet(uri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + + JSONObject pserverObject = new JSONObject(response.getEntity().toString()); + String resourceVersion = pserverObject.getString("resource-version"); + + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doDelete(uri, resourceVersion+"123"); + assertEquals("Resource version mismatch exception", 412, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat(notificationEvents.size(), is(0)); + } + + @Test + public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenDeleteCustomerVerifyingVlanRV() throws IOException, AAIException { + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + JsonObject paylaods = new JsonParser().parse( + PayloadUtil.getResourcePayload("customer_with_children_and_generic-vnf_with_children_and_edge_between_service-instance_vlan.json")) + .getAsJsonObject(); + String gvnfPaylaod = paylaods.get("generic-vnf").toString(); + String custPaylaod = paylaods.get("customer").toString(); + String gvnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/gvnf"; + String custUri = "/aai/v14/business/customers/customer/cust"; + String vlanUri = "/aai/v14/network/generic-vnfs/generic-vnf/gvnf/l-interfaces/l-interface/lint/vlans/vlan/vlan"; + + //Setup generic vnf + Response response = httpTestUtil.doGet(gvnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + response = httpTestUtil.doPut(gvnfUri, gvnfPaylaod); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + response = httpTestUtil.doGet(gvnfUri , "all"); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan to be found", 200, response.getStatus()); + String vlanResourceVersion = new JSONObject(response.getEntity().toString()).getString("resource-version"); + + //Setup customer with service instance relation to vlan + response = httpTestUtil.doGet(custUri); + assertEquals("Expecting the customer to be not found", 404, response.getStatus()); + response = httpTestUtil.doPut(custUri, custPaylaod); + assertEquals("Expecting the customer to be created", 201, response.getStatus()); + response = httpTestUtil.doGet(custUri , "all"); + assertEquals("Expecting the customer to be found", 200, response.getStatus()); + String custResourceVersion = new JSONObject(response.getEntity().toString()).getString("resource-version"); + + //Verify vlan rv was updated + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan to be found", 200, response.getStatus()); + String vlanResourceVersionAfterCustPut = new JSONObject(response.getEntity().toString()).getString("resource-version"); + assertThat("Expecting the vlan resource version to be updated", vlanResourceVersionAfterCustPut, not(is(vlanResourceVersion))); + + //Delete customer + notification.clearEvents(); + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doDelete(custUri, custResourceVersion); + assertEquals("Expecting customer to be deleted", 204, response.getStatus()); + + //Verify vlan rv was updated + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan to be found", 200, response.getStatus()); + String vlanResourceVersionAfterDelete = new JSONObject(response.getEntity().toString()).getString("resource-version"); + assertThat("Expecting the vlan resource version to be updated", vlanResourceVersionAfterDelete, not(is(vlanResourceVersionAfterCustPut))); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat("Expect the delete to generate 4 events customer, its children and vlan", notificationEvents.size(), is(4)); + } + + + @Test + public void testBulkCreateOfComplexAndPserverWithRelationshipThenBulkDeleteBoth() throws IOException, AAIException { + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + + JsonObject paylaods = new JsonParser().parse( + PayloadUtil.getResourcePayload("complex_pserver_with_relation.json")) + .getAsJsonObject(); + String complexPaylaod = paylaods.get("complex").toString(); + String pserverPaylaod = paylaods.get("pserver").toString(); + String complexUri = "/aai/v14/cloud-infrastructure/complexes/complex/complex-1"; + String pserverUri = "/aai/v14/cloud-infrastructure/pservers/pserver/pserver-1"; + + Response response = httpTestUtil.doGet(complexUri); + assertEquals("Expecting the complex to be not found", 404, response.getStatus()); + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + Map<String,String> puts = new LinkedHashMap<>(); + puts.put(complexUri, complexPaylaod); + puts.put(pserverUri, pserverPaylaod); + + response = httpTestUtil.doPut(puts); + assertEquals("Expecting the puts request to succeed", 201, response.getStatus()); + assertEquals("Expect 2 messages to be created", 2, notification.getEvents().size()); + response = httpTestUtil.doGet(complexUri , "all"); + assertEquals("Expecting the complex to be found", 200, response.getStatus()); + String complexRV = new JSONObject(response.getEntity().toString()).getString("resource-version"); + response = httpTestUtil.doGet(pserverUri , "all"); + assertEquals("Expecting the pserver to be found", 200, response.getStatus()); + String pserverRv = new JSONObject(response.getEntity().toString()).getString("resource-version"); + assertThat("Resource versions match", complexRV, is(pserverRv)); + + Map<String, Pair<String, String>> deletes = new LinkedHashMap<>(); + deletes.put(pserverUri, new Pair<>(pserverRv, null)); + deletes.put(complexUri, new Pair<>(complexRV, null)); + notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + httpTestUtil.doDelete(deletes); + + response = httpTestUtil.doGet(complexUri); + assertEquals("Expecting the complex to be not found", 404, response.getStatus()); + response = httpTestUtil.doGet(pserverUri); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + } + + @Test + public void testCreateVnfWithChildrenCreateCustomerWithChildrenAndCousinBetweenVlanAndServiceInstanceThenImplicitDeleteVlanVerifyingServiceInstanceRV() throws IOException, AAIException { + UEBNotification notification = Mockito.spy(new UEBNotification(ModelType.MOXY, loaderFactory, schemaVersions)); + HttpTestUtil httpTestUtil = new HttpTestUtil(queryStyle); + + JsonObject paylaods = new JsonParser().parse( + PayloadUtil.getResourcePayload("customer_with_children_and_generic-vnf_with_children_and_edge_between_service-instance_vlan.json")) + .getAsJsonObject(); + String gvnfPaylaod = paylaods.get("generic-vnf").toString(); + String custPaylaod = paylaods.get("customer").toString(); + String custUri = "/aai/v14/business/customers/customer/cust"; + String ssUri = custUri + "/service-subscriptions/service-subscription/ss"; + String siUri = ssUri + "/service-instances/service-instance/si"; + String gvnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/gvnf"; + String lintUri = gvnfUri + "/l-interfaces/l-interface/lint"; + String vlanUri = lintUri + "/vlans/vlan/vlan"; + + //Setup generic vnf + Response response = httpTestUtil.doGet(gvnfUri); + assertEquals("Expecting the generic-vnf to be not found", 404, response.getStatus()); + response = httpTestUtil.doPut(gvnfUri, gvnfPaylaod); + assertEquals("Expecting the generic-vnf to be created", 201, response.getStatus()); + response = httpTestUtil.doGet(gvnfUri , "all"); + assertEquals("Expecting the generic-vnf to be found", 200, response.getStatus()); + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan to be found", 200, response.getStatus()); + String vlanResourceVersion = new JSONObject(response.getEntity().toString()).getString("resource-version"); + + //Setup customer with service instance relation to vlan + response = httpTestUtil.doGet(custUri); + assertEquals("Expecting the customer to be not found", 404, response.getStatus()); + response = httpTestUtil.doPut(custUri, custPaylaod); + assertEquals("Expecting the customer to be created", 201, response.getStatus()); + response = httpTestUtil.doGet(custUri , "all"); + assertEquals("Expecting the customer to be found", 200, response.getStatus()); + response = httpTestUtil.doGet(siUri , "all"); + assertEquals("Expecting the service-instance to be found", 200, response.getStatus()); + String serviceInstanceResourceVersion = new JSONObject(response.getEntity().toString()).getString("resource-version"); + + //Verify vlan rv was updated + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan to be found", 200, response.getStatus()); + String vlanResourceVersionAfterCustPut = new JSONObject(response.getEntity().toString()).getString("resource-version"); + assertThat("Expecting the vlan resource version to be updated", vlanResourceVersionAfterCustPut, not(is(vlanResourceVersion))); + + //Get linterface, replace vlans with empty json (implicit delete) and put triggering implicit delete + response = httpTestUtil.doGet(lintUri , "all"); + assertEquals("Expecting the l-interface to be found", 200, response.getStatus()); + JSONObject lintJson = new JSONObject(response.getEntity().toString()); + lintJson.put("vlans", new JsonObject()); + notification.clearEvents(); + httpTestUtil = new HttpTestUtil(queryStyle, notification, AAIProperties.MAXIMUM_DEPTH); + response = httpTestUtil.doPut(lintUri, lintJson.toString()); + assertEquals("Expecting the l-interface to be updated", 200, response.getStatus()); + + List<NotificationEvent> notificationEvents = notification.getEvents(); + assertThat("Expect the implied delete to generate 2", notificationEvents.size(), is(2)); + + //Verify vlan is no longer there anf get service-instance and compare rv + response = httpTestUtil.doGet(vlanUri , "all"); + assertEquals("Expecting the vlan not to be found", 404, response.getStatus()); + response = httpTestUtil.doGet(siUri , "all"); + assertEquals("Expecting the service-instance to be found", 200, response.getStatus()); + String serviceInstanceResourceVersionAfterImplicitDelete = new JSONObject(response.getEntity().toString()).getString("resource-version"); + assertThat("Expecting the service-instance resource version to be updated after implicit delete of vlan", + serviceInstanceResourceVersionAfterImplicitDelete, + not(is(serviceInstanceResourceVersion))); + } + + @After + public void teardown() { + + JanusGraph janusGraph = AAIGraph.getInstance().getGraph(); + JanusGraphTransaction transaction = janusGraph.newTransaction(); + + GraphTraversalSource g = transaction.traversal(); + + g.V() + .has(AAIProperties.SOURCE_OF_TRUTH, "JUNIT") + .forEachRemaining(Vertex::remove); + + transaction.commit(); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java index d3452153..3bb017d6 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/PrivateEdgeIntegrationTest.java @@ -29,8 +29,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.jayway.jsonpath.JsonPath; import java.util.*; @@ -55,7 +55,7 @@ import org.onap.aai.setup.SchemaVersion; @RunWith(value = Parameterized.class) public class PrivateEdgeIntegrationTest extends AAISetup { - private static EELFLogger logger = EELFManager.getInstance().getLogger(PserverTest.class); + private static Logger logger = LoggerFactory.getLogger(PserverTest.class); private HttpTestUtil httpTestUtil; private Map<String, String> relationshipMap; diff --git a/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java b/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java index 5fe3bd00..cdaf1010 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/PserverDuplicateTest.java @@ -24,8 +24,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.UUID; @@ -52,7 +52,7 @@ import org.onap.aai.serialization.engines.QueryStyle; public class PserverDuplicateTest extends AAISetup { - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(PserverDuplicateTest.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PserverDuplicateTest.class); private HttpTestUtil testUtil; diff --git a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java index 8ede3c32..80ced5ea 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/PserverTest.java @@ -20,20 +20,12 @@ package org.onap.aai.rest; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.jayway.jsonpath.JsonPath; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.core.Response; - +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.janusgraph.core.JanusGraphTransaction; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,16 +33,31 @@ import org.junit.runners.Parameterized; import org.onap.aai.AAISetup; import org.onap.aai.HttpTestUtil; import org.onap.aai.PayloadUtil; -import org.onap.aai.introspection.*; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.serialization.engines.QueryStyle; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.test.annotation.DirtiesContext; +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import static junit.framework.TestCase.fail; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + @RunWith(value = Parameterized.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class PserverTest extends AAISetup { - private static EELFLogger logger = EELFManager.getInstance().getLogger(PserverTest.class); + private static Logger logger = LoggerFactory.getLogger(PserverTest.class); private HttpTestUtil httpTestUtil; private Map<String, String> relationshipMap; @@ -69,6 +76,39 @@ public class PserverTest extends AAISetup { } @Test + public void testPutPserverCreateGetInXmlForFormats() throws Exception { + httpTestUtil = new HttpTestUtil(queryStyle, "application/xml"); + String pserverUri = "/aai/v12/cloud-infrastructure/pservers/pserver/test-pserver-xml"; + String cloudRegionUri = "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/cloud-region-random1/cloud-region-random1-region"; + + Response response = httpTestUtil.doGet(pserverUri); + assertNotNull("Expected the response to be not null", response); + assertEquals("Expecting the pserver to be not found", 404, response.getStatus()); + + response = httpTestUtil.doPut(pserverUri, "{}"); + assertNotNull("Expected the response to be not null", response); + assertEquals("Expecting the pserver to be created", 201, response.getStatus()); + + response = httpTestUtil.doPut(cloudRegionUri, "{}"); + assertNotNull("Expected the response to be not null", response); + assertEquals("Expecting the cloud-region to be created", 201, response.getStatus()); + + relationshipMap.put("related-to", "pserver"); + relationshipMap.put("related-link", pserverUri); + + String pserverRelationshipPayload = PayloadUtil.getTemplatePayload("relationship.json", relationshipMap); + // Creates the relationship between cloud region and pserver + response = httpTestUtil.doPut(cloudRegionUri + "/relationship-list/relationship", pserverRelationshipPayload); + assertNotNull("Expected the response to be not null", response); + assertEquals("Expecting the cloud-region to pserver relationship to be created", 200, response.getStatus()); + + response = httpTestUtil.doGet(pserverUri , "0", "raw"); + assertNotNull("Expected the response to be not null", response); + assertEquals("Expecting the pserver to be created", 200, response.getStatus()); + assertThat(response.getEntity().toString(), containsString("<related-to><node><relationship-label>org.onap.relationships.inventory.LocatedIn</relationship-label><node-type>cloud-region</node-type>")); + } + + @Test public void testPutPServerCreateGetAndDeleteAndCreateRelationshipBetweenPserverAndCloudRegion() throws Exception { logger.info("Starting the pserver testPutServerCreateGetAndDelete"); @@ -148,4 +188,29 @@ public class PserverTest extends AAISetup { logger.info("Ending the pserver testPutServerCreateGetAndDelete"); } + @After + public void tearDown() { + + JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + g.V().has("source-of-truth", "JUNIT").toList().forEach(v -> v.remove()); + + } catch (Exception ex) { + success = false; + logger.error("Unable to remove the vertexes", ex); + } finally { + if (success) { + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to teardown the graph"); + } + } + + } } diff --git a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java index cba81d73..494d7e4e 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/RestHandlerTest.java @@ -35,7 +35,7 @@ public class RestHandlerTest { RestHandlerService secondInstance = RestHandlerService.getInstance(); assertNotNull(firstInstance); assertNotNull(secondInstance); - assertTrue(firstInstance == secondInstance); + assertSame(firstInstance, secondInstance); } } diff --git a/aai-core/src/test/java/org/onap/aai/rest/VnfcRelationshipIssueTest.java b/aai-core/src/test/java/org/onap/aai/rest/VnfcRelationshipIssueTest.java new file mode 100644 index 00000000..ae611717 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/VnfcRelationshipIssueTest.java @@ -0,0 +1,111 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.rest; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.janusgraph.core.JanusGraphTransaction; +import org.junit.*; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.onap.aai.AAISetup; +import org.onap.aai.HttpTestUtil; +import org.onap.aai.PayloadUtil; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.serialization.engines.QueryStyle; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.junit4.rules.SpringClassRule; +import org.springframework.test.context.junit4.rules.SpringMethodRule; + +import javax.ws.rs.core.Response; +import java.util.Arrays; +import java.util.Collection; + +import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertEquals; + +@RunWith(value = Parameterized.class) +public class VnfcRelationshipIssueTest extends AAISetup { + + private static final Logger LOGGER = LoggerFactory.getLogger(VnfcRelationshipIssueTest.class); + private HttpTestUtil httpTestUtil; + + @ClassRule + public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); + + @Rule + public final SpringMethodRule springMethodRule = new SpringMethodRule(); + + @Parameterized.Parameter(value = 0) + public QueryStyle queryStyle; + + @Parameterized.Parameters(name = "QueryStyle.{0}") + public static Collection<Object[]> data() { + return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}}); + } + + @Before + public void setUp() { + httpTestUtil = new HttpTestUtil(queryStyle); + } + + @Test + public void testCreateVnfWithVfModuleAndCreateVnfcRelatedToVfModule() throws Exception { + + String genericVnfUri = "/aai/v14/network/generic-vnfs/generic-vnf/test-vnf11"; + String genericVnfPayload = PayloadUtil.getResourcePayload("generic-vnf-with-vf-module.json"); + + Response response = httpTestUtil.doPut(genericVnfUri, genericVnfPayload); + assertEquals("Expected the generic vnf to be created", 201, response.getStatus()); + + String vnfcUri = "/aai/v14/network/vnfcs/vnfc/test-vnfc11"; + String vnfcPaylaod = PayloadUtil.getResourcePayload("vnfc-related-to-vf-module.json"); + + response = httpTestUtil.doPut(vnfcUri, vnfcPaylaod); + assertEquals("Expected the generic vnf to be created", 201, response.getStatus()); + } + + @After + public void tearDown() { + + JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + g.V().has("source-of-truth", "JUNIT").toList().forEach(v -> v.remove()); + + } catch (Exception ex) { + success = false; + LOGGER.error("Unable to remove the vertexes", ex); + } finally { + if (success) { + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to teardown the graph"); + } + } + + } +} diff --git a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java index c01d270e..95220b1f 100644 --- a/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java +++ b/aai-core/src/test/java/org/onap/aai/rest/db/HttpEntryTest.java @@ -20,23 +20,8 @@ package org.onap.aai.rest.db; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.when; - import com.google.gson.JsonObject; import com.google.gson.JsonParser; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.*; - -import javax.ws.rs.core.*; - import org.javatuples.Pair; import org.junit.Before; import org.junit.FixMethodOrder; @@ -47,11 +32,9 @@ import org.junit.runners.Parameterized; import org.mockito.Mockito; import org.onap.aai.AAISetup; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Introspector; import org.onap.aai.introspection.Loader; -import org.onap.aai.introspection.LoaderFactory; import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.rest.ueb.UEBNotification; @@ -60,6 +43,19 @@ import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.util.AAIConfig; +import javax.ws.rs.core.*; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.*; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class HttpEntryTest extends AAISetup { @@ -139,7 +135,7 @@ public class HttpEntryTest extends AAISetup { if (uri.endsWith("relationship")) { objType = "relationship"; } - Introspector obj = null; + Introspector obj; if (method.equals(HttpMethod.GET)) { obj = loader.introspectorFromName(objType); } else { @@ -163,8 +159,7 @@ public class HttpEntryTest extends AAISetup { /* * TODO do the same with uri */ - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -178,8 +173,7 @@ public class HttpEntryTest extends AAISetup { @Test public void test2PutOnPserverNoPInterface() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -193,8 +187,7 @@ public class HttpEntryTest extends AAISetup { @Test public void test3PutOnPInterface() { try { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -212,14 +205,11 @@ public class HttpEntryTest extends AAISetup { @Test public void test4GetOnPserver() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); - URI uriObject = UriBuilder.fromPath("/cloud-infrastructure/pservers/pserver/junit-test1").build(); - String uri = "/cloud-infrastructure/pservers/pserver/junit-test1"; String content = "{\"hostname\":\"junit-test1\", \"equip-type\":\"junit-equip-type\"}"; Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, content); @@ -230,8 +220,7 @@ public class HttpEntryTest extends AAISetup { @Test public void test5MergePatchOnPserver() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -246,8 +235,7 @@ public class HttpEntryTest extends AAISetup { private int doDelete(String resourceVersion, String uri, String nodeType) throws UnsupportedEncodingException, AAIException { queryParameters.add("resource-version", resourceVersion); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -274,12 +262,10 @@ public class HttpEntryTest extends AAISetup { @Test public void test6DeleteOnPserver() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); - URI uriObject = UriBuilder.fromPath("/cloud-infrastructure/pservers/pserver/junit-test1").build(); String uri = "/cloud-infrastructure/pservers/pserver/junit-test1"; String content = ""; Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.GET, uri, content); @@ -297,8 +283,7 @@ public class HttpEntryTest extends AAISetup { @Test public void test7DeleteOnPserverNoPinterface() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -320,8 +305,7 @@ public class HttpEntryTest extends AAISetup { @Test public void test8FailedGetOnPserver() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -337,8 +321,7 @@ public class HttpEntryTest extends AAISetup { @Test public void putEdgeTest() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -368,8 +351,7 @@ public class HttpEntryTest extends AAISetup { Loader ld = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion()); UEBNotification uebNotification = Mockito.spy(new UEBNotification(ld, loaderFactory, schemaVersions)); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type, uebNotification); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), uebNotification); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -390,31 +372,32 @@ public class HttpEntryTest extends AAISetup { doNothing().when(uebNotification).triggerEvents(); Response response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.PUT_EDGE, uri, content); - response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content); - dbEngine.rollback(); - assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus()); - assertEquals("Two notifications", 2, uebNotification.getEvents().size()); + assertEquals("Expected the pserver relationship to be deleted", 200, response.getStatus()); + assertEquals("Two notifications", 2, uebNotification.getEvents().size()); assertEquals("Notification generated for PUT edge", "UPDATE", uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString()); assertThat("Event body for the edge create has the related to", uebNotification.getEvents().get(0).getObj().marshal(false), containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver")); + response = doRequest(traversalHttpEntry, loader, dbEngine, HttpMethod.DELETE_EDGE, uri, content); + assertEquals("Expected the pserver relationship to be deleted", 204, response.getStatus()); + assertEquals("Two notifications", 2, uebNotification.getEvents().size()); assertEquals("Notification generated for DELETE edge", "UPDATE", - uebNotification.getEvents().get(1).getEventHeader().getValue("action").toString()); + uebNotification.getEvents().get(0).getEventHeader().getValue("action").toString()); assertThat("Event body for the edge delete does not have the related to", - uebNotification.getEvents().get(1).getObj().marshal(false), + uebNotification.getEvents().get(0).getObj().marshal(false), not(containsString("cloud-infrastructure/pservers/pserver/junit-edge-test-pserver"))); + dbEngine.rollback(); } @Test public void putEdgeWrongLabelTest() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -449,8 +432,7 @@ public class HttpEntryTest extends AAISetup { final String testName = new Object() {}.getClass().getEnclosingMethod().getName(); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL, // type); Loader loader = traversalHttpEntry.getLoader(); @@ -496,9 +478,7 @@ public class HttpEntryTest extends AAISetup { final String testName = new Object() {}.getClass().getEnclosingMethod().getName(); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); - // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -532,10 +512,7 @@ public class HttpEntryTest extends AAISetup { @Test public void testSetGetPaginationMethods() { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); - // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, QueryStyle.TRAVERSAL, - // type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); traversalHttpEntry.setPaginationBucket(10); traversalHttpEntry.setPaginationIndex(1); traversalHttpEntry.setTotalsForPaging(101, traversalHttpEntry.getPaginationBucket()); @@ -549,9 +526,7 @@ public class HttpEntryTest extends AAISetup { @Test public void relatedToTest() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); - // HttpEntry httpEntry = new HttpEntry(schemaVersions.getDefaultVersion(), ModelType.MOXY, queryStyle, type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); @@ -585,14 +560,12 @@ public class HttpEntryTest extends AAISetup { } @Test - public void setDepthTest() throws UnsupportedEncodingException, AAIException { + public void setDepthTest() throws AAIException { System.setProperty("AJSC_HOME", "."); System.setProperty("BUNDLECONFIG_DIR", "src/main/test/resources"); String depthParam = AAIConfig.get("aai.rest.getall.depthparam"); - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); - // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, QueryStyle.TRAVERSAL, type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); int depth = traversalHttpEntry.setDepth(null, depthParam); assertEquals(AAIProperties.MAXIMUM_DEPTH.intValue(), depth); } @@ -600,9 +573,7 @@ public class HttpEntryTest extends AAISetup { @Test public void getAbstractTest() throws UnsupportedEncodingException, AAIException { - DBConnectionType type = DBConnectionType.REALTIME; - traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion(), type); - // HttpEntry httpEntry = new HttpEntry(Version.getLatest(), ModelType.MOXY, queryStyle, type); + traversalHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion()); Loader loader = traversalHttpEntry.getLoader(); TransactionalGraphEngine dbEngine = traversalHttpEntry.getDbEngine(); diff --git a/aai-core/src/test/java/org/onap/aai/rest/ueb/UEBNotificationTest.java b/aai-core/src/test/java/org/onap/aai/rest/ueb/UEBNotificationTest.java new file mode 100644 index 00000000..58b96e49 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/rest/ueb/UEBNotificationTest.java @@ -0,0 +1,112 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.rest.ueb; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.serialization.db.EdgeSerializer; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import javax.ws.rs.core.Response; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class UEBNotificationTest extends AAISetup { + + public static final String BASE_PATH = "/aai"; + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + + public QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI; + + + @Before + public void setup() throws Exception { + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + } + + @Test + public void verifyUriNoIssues() throws AAIException, URISyntaxException, UnsupportedEncodingException { + + Introspector pserver = loader.introspectorFromName("pserver"); + pserver.setValue("hostname", "hn"); + URI uri = new URI("/cloud-infrastructure/pservers/pserver/hn"); + UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions); + uebNotification.createNotificationEvent( + UUID.randomUUID().toString(), + "JUNIT-SOT", + Response.Status.CREATED, + uri, + pserver, + new HashMap<>(), + BASE_PATH); + + assertEquals("One event created", 1, uebNotification.getEvents().size()); + assertEquals( + "Uri is correct", + BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn", + uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString()); + } + + @Test + public void verifyUriWithBaseAndUri() throws AAIException, URISyntaxException, UnsupportedEncodingException { + + Introspector pserver = loader.introspectorFromName("pserver"); + pserver.setValue("hostname", "hn"); + URI uri = new URI(BASE_PATH + "/v12/cloud-infrastructure/pservers/pserver/hn"); + UEBNotification uebNotification = new UEBNotification(loader, loaderFactory, schemaVersions); + uebNotification.createNotificationEvent( + UUID.randomUUID().toString(), + "JUNIT-SOT", + Response.Status.CREATED, + uri, + pserver, + new HashMap<>(), BASE_PATH); + + assertEquals("One event created", 1, uebNotification.getEvents().size()); + assertEquals( + "Uri is correct", + BASE_PATH + "/" + schemaVersions.getDefaultVersion() + "/cloud-infrastructure/pservers/pserver/hn", + uebNotification.getEvents().get(0).getEventHeader().getValue("entity-link").toString()); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java index 944a4067..454aa218 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbAliasTest.java @@ -20,20 +20,6 @@ package org.onap.aai.serialization.db; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -44,11 +30,12 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import org.onap.aai.AAISetup; import org.onap.aai.DataLinkSetup; -import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.db.props.AAIProperties; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.schema.enums.PropertyMetadata; import org.onap.aai.serialization.engines.JanusGraphDBEngine; @@ -57,6 +44,18 @@ import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.setup.SchemaVersion; import org.springframework.test.annotation.DirtiesContext; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class DbAliasTest extends DataLinkSetup { @@ -65,11 +64,10 @@ public class DbAliasTest extends DataLinkSetup { private SchemaVersion version; private final ModelType introspectorFactoryType = ModelType.MOXY; - private final DBConnectionType type = DBConnectionType.REALTIME; private Loader loader; private TransactionalGraphEngine dbEngine; - @Parameterized.Parameter(value = 0) + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") @@ -78,11 +76,11 @@ public class DbAliasTest extends DataLinkSetup { } @Before - public void setup() throws Exception { + public void setup() { version = schemaVersions.getDepthVersion(); graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); } @After @@ -92,9 +90,7 @@ public class DbAliasTest extends DataLinkSetup { } @Test - public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, - NoSuchMethodException, InterruptedException { + public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalArgumentException { final String property = "persona-model-customization-id"; String dbPropertyName = property; TransactionalGraphEngine spy = spy(this.dbEngine); @@ -108,6 +104,13 @@ public class DbAliasTest extends DataLinkSetup { spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")); Introspector obj = loader.introspectorFromName("generic-vnf"); Vertex v = g.addVertex(); + v.property("aai-uri", "abc"); + v.property("aai-uuid", "b"); + v.property(AAIProperties.CREATED_TS, 123L); + v.property(AAIProperties.SOURCE_OF_TRUTH, "sot"); + v.property(AAIProperties.RESOURCE_VERSION, "123"); + v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot"); + v.property(AAIProperties.LAST_MOD_TS, 123L); Object id = v.id(); obj.setValue("vnf-id", "key1"); obj.setValue(property, "hello"); @@ -126,14 +129,12 @@ public class DbAliasTest extends DataLinkSetup { } @Test - public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, - IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, - NoSuchMethodException, InterruptedException, MalformedURLException { + public void checkOnRead() throws AAIException, UnsupportedEncodingException, SecurityException, IllegalArgumentException { final String property = "persona-model-customization-id"; TransactionalGraphEngine spy = spy(dbEngine); TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); - Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next(); + Vertex v = graph.traversal().addV().property("vnf-id", "key1").property("model-customization-id", "hello").next(); graph.tx().commit(); Graph g = graph.newTransaction(); GraphTraversalSource traversal = g.traversal(); diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerDeltasTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerDeltasTest.java new file mode 100644 index 00000000..de8f2224 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerDeltasTest.java @@ -0,0 +1,764 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.db; + +import com.google.gson.FieldNamingPolicy; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphFactory; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.onap.aai.util.delta.DeltaAction; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.TestPropertySource; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.*; + +@RunWith(value = Parameterized.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +@TestPropertySource(properties = { + "delta.events.enabled=true", + }) +public class DbSerializerDeltasTest extends AAISetup { + + // to use, set thrown.expect to whatever your test needs + // this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected static Graph graph; + + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + private TransactionalGraphEngine dbEngine; + private TransactionalGraphEngine engine; // for tests that aren't mocking the engine + + @Parameterized.Parameter(value = 0) + public QueryStyle queryStyle; + + @Parameterized.Parameters(name = "QueryStyle.{0}") + public static Collection<Object[]> data() { + return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}}); + } + + @BeforeClass + public static void init() throws Exception { + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + + } + + @Before + public void setup() throws Exception { + // createGraph(); + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); + engine = new JanusGraphDBEngine(queryStyle, loader); + } + + @Test + public void createTopLevelThenUpdateTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + Vertex gvnfVert = dbserLocal.createNewVertex(gvnf); + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI("/network/generic-vnfs/generic-vnf/myvnf")); + + gvnf.setValue("vnf-id", "myvnf"); + gvnf.setValue("vnf-type", "typo"); + dbserLocal.serializeToDb(gvnf, gvnfVert, uriQuery, "generic-vnf", gvnf.marshal(false)); + assertTrue("Original created vertex exists", engine.tx().traversal().V() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .has("vnf-type", "typo") + .hasNext()); + + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(5L, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + gvnf = dbserLocal.getLatestVersionView(gvnfVert); + gvnf.setValue("vnf-type", "new-typo"); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + dbserLocal.serializeToDb(gvnf, gvnfVert, uriQuery, "generic-vnf", gvnf.marshal(false)); + assertTrue("Vertex is updated", engine.tx().traversal().V() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .has("vnf-type", "new-typo") + .hasNext()); + + + assertEquals(DeltaAction.UPDATE, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get("/network/generic-vnfs/generic-vnf/myvnf").getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.UPDATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + } + + @Test + public void createTopLevelThenCreateChildTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + Vertex gvnfVert = dbserLocal.createNewVertex(gvnf); + final String vnfUri = "/network/generic-vnfs/generic-vnf/myvnf"; + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(vnfUri)); + + gvnf.setValue("vnf-id", "myvnf"); + gvnf.setValue("vnf-type", "typo"); + dbserLocal.serializeToDb(gvnf, gvnfVert, uriQuery, "generic-vnf", gvnf.marshal(false)); + assertTrue("Original created vertex exists", engine.tx().traversal().V() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .has("vnf-type", "typo") + .hasNext()); + + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(vnfUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vnfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(5L, dbserLocal.getObjectDeltas().get(vnfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector vf = loader.introspectorFromName("vf-module"); + Vertex vfVertex = dbserLocal.createNewVertex(vf); + final String vfUri = "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/myvf"; + uriQuery = engine.getQueryBuilder(gvnfVert).createQueryFromURI(new URI(vfUri)); + + vf.setValue("vf-module-id", "myvf"); + dbserLocal.serializeToDb(vf, vfVertex, uriQuery, "vf-module", vf.marshal(false)); + assertTrue("Vertex is creted", engine.tx().traversal().V() + .has("aai-node-type", "vf-module") + .has("vf-module-id", "myvf") + .hasNext()); + assertTrue("Vf module has edge to gvnf", engine.tx().traversal().V() + .has("aai-node-type", "vf-module") + .has("vf-module-id", "myvf") + .both() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .hasNext()); + + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(vfUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + } + + @Test + public void createTopWithChildThenDeleteTopTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + Vertex gvnfVert = dbserLocal.createNewVertex(gvnf); + final String vnfUri = "/network/generic-vnfs/generic-vnf/myvnf"; + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(vnfUri)); + + gvnf.setValue("vnf-id", "myvnf"); + gvnf.setValue("vnf-type", "typo"); + + Introspector vf = loader.introspectorFromName("vf-module"); + vf.setValue("vf-module-id", "myvf"); + final String vfUri = "/network/generic-vnfs/generic-vnf/myvnf/vf-modules/vf-module/myvf"; + + Introspector vfs = loader.introspectorFromName("vf-modules"); + vfs.setValue("vf-module", Collections.singletonList(vf.getUnderlyingObject())); + gvnf.setValue("vf-modules", vfs.getUnderlyingObject()); + + dbserLocal.serializeToDb(gvnf, gvnfVert, uriQuery, "generic-vnf", gvnf.marshal(false)); + + Gson gson = new GsonBuilder().create(); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertTrue("Original created vertex exists", engine.tx().traversal().V() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .has("vnf-type", "typo") + .hasNext()); + assertTrue("Vertex is creted", engine.tx().traversal().V() + .has("aai-node-type", "vf-module") + .has("vf-module-id", "myvf") + .hasNext()); + assertTrue("Vf module has edge to gvnf", engine.tx().traversal().V() + .has("aai-node-type", "vf-module") + .has("vf-module-id", "myvf") + .both() + .has("aai-node-type", "generic-vnf") + .has("vnf-id", "myvnf") + .hasNext()); + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(vnfUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vnfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(5L, dbserLocal.getObjectDeltas().get(vnfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(vfUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(vfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(vfUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE_REL)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + gvnf = dbserLocal.getLatestVersionView(gvnfVert); + String rv = gvnf.getValue(AAIProperties.RESOURCE_VERSION); + dbserLocal.delete(engine.tx().traversal().V(gvnfVert).next(), rv, true); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertFalse("generic-vnf no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "generic-vnf") + .hasNext()); + assertFalse("vf-module no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "vf-module") + .hasNext()); + + assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(vnfUri).getAction()); + assertEquals(12L, dbserLocal.getObjectDeltas().get(vnfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count());assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(vfUri).getAction()); + assertEquals(11L, dbserLocal.getObjectDeltas().get(vfUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count()); + } + + + + @Test + public void createComplexPserverWithRelDeleteRel() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector complex = loader.introspectorFromName("complex"); + Vertex complexV = dbserLocal.createNewVertex(complex); + final String complexUri = "/cloud-infrastructure/complexes/complex/c-id"; + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(complexUri)); + + complex.setValue("physical-location-id", "c-id"); + complex.setValue("physical-location-type", "type"); + complex.setValue("street1", "streetA"); + complex.setValue("city", "cityA"); + complex.setValue("postal-code", "11111"); + complex.setValue("country", "abc"); + complex.setValue("region", "ef"); + dbserLocal.serializeToDb(complex, complexV, uriQuery, "complex", complex.marshal(false)); + assertTrue("Complex created", engine.tx().traversal().V() + .has("aai-node-type", "complex") + .has("physical-location-id", "c-id") + .hasNext()); + + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(complexUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(complexUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(10L, dbserLocal.getObjectDeltas().get(complexUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + Introspector pserver = loader.introspectorFromName("pserver"); + Vertex pserverV = dbserLocal.createNewVertex(pserver); + final String pserverUri = "/cloud-infrastructure/pservers/pserver/ps"; + uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(pserverUri)); + + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "complex"); + relationship.setValue("related-link", complexUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + + pserver.setValue("relationship-list", relationshipList.getUnderlyingObject()); + pserver.setValue("hostname", "ps"); + + System.out.println(pserver.marshal(true)); + + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + assertTrue("Pserver created", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps") + .hasNext()); + assertTrue("Pserver has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(pserverUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(pserverUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE_REL)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST", AAIProperties.MINIMUM_DEPTH); + dbserLocal.touchStandardVertexProperties(pserverV, false); + dbserLocal.deleteEdge(relationship, pserverV); + assertFalse("Pserver no longer has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + + + assertEquals(DeltaAction.UPDATE, dbserLocal.getObjectDeltas().get(pserverUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(3L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.UPDATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(pserverUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE_REL)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + } + + @Test + public void createComplexPserverWithRelUpdatePserverToDeleteRelAddPinterfaceThenDeleteComplex() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + Gson gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) + .create(); + + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-complex", AAIProperties.MINIMUM_DEPTH); + Introspector complex = loader.introspectorFromName("complex"); + Vertex complexV = dbserLocal.createNewVertex(complex); + final String complexUri = "/cloud-infrastructure/complexes/complex/c-id-b"; + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(complexUri)); + + complex.setValue("physical-location-id", "c-id-b"); + complex.setValue("physical-location-type", "type"); + complex.setValue("street1", "streetA"); + complex.setValue("city", "cityA"); + complex.setValue("postal-code", "11111"); + complex.setValue("country", "abc"); + complex.setValue("region", "ef"); + dbserLocal.serializeToDb(complex, complexV, uriQuery, "complex", complex.marshal(false)); + + System.out.println("Create Complex"); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertTrue("Complex created", engine.tx().traversal().V() + .has("aai-node-type", "complex") + .has("physical-location-id", "c-id-b") + .hasNext()); + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(complexUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(complexUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(10L, dbserLocal.getObjectDeltas().get(complexUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-pserver", AAIProperties.MINIMUM_DEPTH); + Introspector pserver = loader.introspectorFromName("pserver"); + Vertex pserverV = dbserLocal.createNewVertex(pserver); + final String pserverUri = "/cloud-infrastructure/pservers/pserver/ps-b"; + uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(pserverUri)); + + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "complex"); + relationship.setValue("related-link", complexUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + + pserver.setValue("relationship-list", relationshipList.getUnderlyingObject()); + pserver.setValue("hostname", "ps-b"); + pserver.setValue("number-of-cpus", 20); + + Introspector pint = loader.introspectorFromName("p-interface"); + pint.setValue("interface-name", "pint-1"); + final String pintUri = pserverUri + "/p-interfaces/p-interface/pint-1"; + + Introspector pints = loader.introspectorFromName("p-interfaces"); + pints.setValue("p-interface", Collections.singletonList(pint.getUnderlyingObject())); + pserver.setValue("p-interfaces", pints.getUnderlyingObject()); + + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + + System.out.println("Create Pserver with pinterface and relationship to complex "); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertTrue("Pserver created", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .hasNext()); + assertTrue("Pserver has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + assertTrue("Pserver has edge to pinterface", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "p-interface") + .hasNext()); + + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(pserverUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(5L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(pserverUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE_REL)).count()); + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(pintUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pintUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pintUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(pintUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE_REL)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "update-pserver", AAIProperties.MINIMUM_DEPTH); + pserver = dbserLocal.getLatestVersionView(pserverV); + relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.emptyList()); + pserver.setValue("relationship-list", relationshipList.getUnderlyingObject()); + pserver.setValue("equip-type", "server-a"); + pserver.setValue("number-of-cpus", 99); + + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + + System.out.println("Update pserver removing relationship to complex"); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertFalse("Pserver no longer has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + + assertEquals(DeltaAction.UPDATE, dbserLocal.getObjectDeltas().get(pserverUri).getAction()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.UPDATE)).count()); + assertEquals(1L, dbserLocal.getObjectDeltas().get(pserverUri).getRelationshipDeltas().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE_REL)).count()); + assertFalse(dbserLocal.getObjectDeltas().containsKey(pintUri)); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "delete-pserver", AAIProperties.MINIMUM_DEPTH); + pserver = dbserLocal.getLatestVersionView(pserverV); + String rv = pserver.getValue(AAIProperties.RESOURCE_VERSION); + dbserLocal.delete(engine.tx().traversal().V(pserverV).next(), rv, true); + + System.out.println("Delete pserver"); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertFalse("pserver no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .hasNext()); + + assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(pserverUri).getAction()); + assertEquals(12L, dbserLocal.getObjectDeltas().get(pserverUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count()); + assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(pintUri).getAction()); + assertEquals(10L, dbserLocal.getObjectDeltas().get(pintUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + } + + + // /network/ipsec-configurations/ipsec-configuration/{ipsec-configuration-id}/vig-servers/vig-server/{vig-address-type} + // ipaddress-v4-vig + @Test + public void createNodeWithListTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + Gson gson = new GsonBuilder() + .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES) + .create(); + + engine.startTransaction(); + + /* + * Create the parent ipsec-configuration + */ + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-ipsec", AAIProperties.MINIMUM_DEPTH); + Introspector ipsec = loader.introspectorFromName("ipsec-configuration"); + Vertex ipsecVert = dbserLocal.createNewVertex(ipsec); + final String ipsecUri = "/network/ipsec-configurations/ipsec-configuration/ipsec"; + QueryParser uriQuery = + dbEngine.getQueryBuilder().createQueryFromURI(new URI(ipsecUri)); + + ipsec.setValue("ipsec-configuration-id", "ipsec"); + dbserLocal.serializeToDb(ipsec, ipsecVert, uriQuery, "generic-vnf", ipsec.marshal(false)); + assertTrue("Original created vertex exists", engine.tx().traversal().V() + .has("aai-node-type", "ipsec-configuration") + .has("ipsec-configuration-id", "ipsec") + .hasNext()); + + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(ipsecUri).getAction()); + assertEquals(4L, + dbserLocal.getObjectDeltas().get(ipsecUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, + dbserLocal.getObjectDeltas().get(ipsecUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + /* + * Create child vig-server with list property vig-address-type + */ + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-child-vig-server", AAIProperties.MINIMUM_DEPTH); + Introspector vig = loader.introspectorFromName("vig-server"); + Vertex vigVertex = dbserLocal.createNewVertex(vig); + final String vigUri = "/network/ipsec-configurations/ipsec-configuration/ipsec/vig-servers/vig-server/vig"; + uriQuery = engine.getQueryBuilder(ipsecVert).createQueryFromURI(new URI(vigUri)); + + vig.setValue("vig-address-type", "vig"); + List<String> list = new ArrayList<>(); + list.add("address-1"); + list.add("address-2"); + vig.setValue("ipaddress-v4-vig", list); + dbserLocal.serializeToDb(vig, vigVertex, uriQuery, "vf-module", vig.marshal(false)); + assertTrue("Vertex is creted", engine.tx().traversal().V() + .has("aai-node-type", "vig-server") + .has("vig-address-type", "vig") + .hasNext()); + assertTrue("Vf module has edge to gvnf", engine.tx().traversal().V() + .has("aai-node-type", "vig-server") + .has("vig-address-type", "vig") + .both() + .has("aai-node-type", "ipsec-configuration") + .has("ipsec-configuration-id", "ipsec") + .hasNext()); + + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + assertEquals(DeltaAction.CREATE, dbserLocal.getObjectDeltas().get(vigUri).getAction()); + assertEquals(4L, + dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(5L, + dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.CREATE)).count()); + assertThat(dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().get("ipaddress-v4-vig").getValue(), instanceOf(List.class)); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + + /* + * Update child vig-server with new list for vig-address-type + */ + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "update-child-vig-server", AAIProperties.MINIMUM_DEPTH); + vig = dbserLocal.getLatestVersionView(vigVertex); + uriQuery = engine.getQueryBuilder(ipsecVert).createQueryFromURI(new URI(vigUri)); + + new ArrayList<>(); + list.add("address-3"); + list.add("address-4"); + vig.setValue("ipaddress-v4-vig", list); + dbserLocal.serializeToDb(vig, vigVertex, uriQuery, "vf-module", vig.marshal(false)); + assertTrue("Vertex is still there", engine.tx().traversal().V() + .has("aai-node-type", "vig-server") + .has("vig-address-type", "vig") + .hasNext()); + assertTrue("Vf module has edge to gvnf", engine.tx().traversal().V() + .has("aai-node-type", "vig-server") + .has("vig-address-type", "vig") + .both() + .has("aai-node-type", "ipsec-configuration") + .has("ipsec-configuration-id", "ipsec") + .hasNext()); + + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + assertEquals(DeltaAction.UPDATE, dbserLocal.getObjectDeltas().get(vigUri).getAction()); + assertEquals(4L, + dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.STATIC)).count()); + assertEquals(4L, + dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.UPDATE)).count()); + assertThat(dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().get("ipaddress-v4-vig").getValue(), instanceOf(List.class)); + assertThat(dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().get("ipaddress-v4-vig").getOldValue(), instanceOf(List.class)); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + /* + * Delete top level + */ + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "delete-ipsec", AAIProperties.MINIMUM_DEPTH); + ipsec = dbserLocal.getLatestVersionView(ipsecVert); + String rv = ipsec.getValue(AAIProperties.RESOURCE_VERSION); + dbserLocal.delete(engine.tx().traversal().V(ipsecVert).next(), rv, true); + System.out.println(gson.toJsonTree(dbserLocal.getObjectDeltas().values())); + + assertFalse("ipsec-configuration no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "ipsec-configuration") + .hasNext()); + assertFalse("vig-server no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "vig-server") + .hasNext()); + + assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(ipsecUri).getAction()); + assertEquals(9L, dbserLocal.getObjectDeltas().get(ipsecUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count());assertEquals(DeltaAction.DELETE, dbserLocal.getObjectDeltas().get(vigUri).getAction()); + assertEquals(10L, dbserLocal.getObjectDeltas().get(vigUri).getPropertyDeltas().values().stream().filter(d -> d.getAction().equals(DeltaAction.DELETE)).count()); + dbserLocal.getObjectDeltas().values().forEach(od -> { + if (!od.getPropertyDeltas().containsKey(AAIProperties.AAI_UUID) ) { + fail(od.getUri() + " is missing " + AAIProperties.AAI_UUID); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID) == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " is null"); + } else if (od.getPropertyDeltas().get(AAIProperties.AAI_UUID).getValue() == null) { + fail(od.getUri() + " " + AAIProperties.AAI_UUID + " value is null"); + } + }); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerNotificationEventsTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerNotificationEventsTest.java new file mode 100644 index 00000000..cc1fc03d --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerNotificationEventsTest.java @@ -0,0 +1,330 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphFactory; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +@RunWith(value = Parameterized.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class DbSerializerNotificationEventsTest extends AAISetup { + + // to use, set thrown.expect to whatever your test needs + // this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected static Graph graph; + + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + private TransactionalGraphEngine engine; // for tests that aren't mocking the engine + + @Parameterized.Parameter(value = 0) + public QueryStyle queryStyle; + + @Parameterized.Parameters(name = "QueryStyle.{0}") + public static Collection<Object[]> data() { + return Arrays.asList(new Object[][] {{QueryStyle.TRAVERSAL}, {QueryStyle.TRAVERSAL_URI}}); + } + + @BeforeClass + public static void init() throws Exception { + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + + } + + @Before + public void setup() throws Exception { + // createGraph(); + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + engine = new JanusGraphDBEngine(queryStyle, loader); + } + + /* + Create Complex + Create Pserver with pinterface and relationship to complex + Update pserver removing relationship to complex + Update pserver adding a second p-interface + Add l-interface directly to the 2nd p-interface + Delete pserver + */ + @Test + public void createComplexPserverWithRelUpdatePserverToDeleteRelAddPinterfaceThenDeleteComplexCheckingUpdatedListTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + engine.startTransaction(); + + System.out.println("Create Complex"); + DBSerializer dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-complex", AAIProperties.MINIMUM_DEPTH); + Introspector complex = loader.introspectorFromName("complex"); + Vertex complexV = dbserLocal.createNewVertex(complex); + final String complexUri = "/cloud-infrastructure/complexes/complex/c-id-b"; + QueryParser uriQuery = + engine.getQueryBuilder().createQueryFromURI(new URI(complexUri)); + + complex.setValue("physical-location-id", "c-id-b"); + complex.setValue("physical-location-type", "type"); + complex.setValue("street1", "streetA"); + complex.setValue("city", "cityA"); + complex.setValue("postal-code", "11111"); + complex.setValue("country", "abc"); + complex.setValue("region", "ef"); + dbserLocal.serializeToDb(complex, complexV, uriQuery, "complex", complex.marshal(false)); + + assertTrue("Complex created", engine.tx().traversal().V() + .has("aai-node-type", "complex") + .has("physical-location-id", "c-id-b") + .hasNext()); + Map<Vertex, Boolean> updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 1, updated.size()); + assertThat("Only modified vertexes are in the updated set", + updated.keySet().stream().map(v -> v.<String>value(AAIProperties.AAI_URI)).collect(Collectors.toSet()), + is(Collections.singleton(complexUri))); + List<String> didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + + + System.out.println("Create Pserver with pinterface and relationship to complex "); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-pserver", AAIProperties.MINIMUM_DEPTH); + Introspector pserver = loader.introspectorFromName("pserver"); + Vertex pserverV = dbserLocal.createNewVertex(pserver); + final String pserverUri = "/cloud-infrastructure/pservers/pserver/ps-b"; + uriQuery = + engine.getQueryBuilder().createQueryFromURI(new URI(pserverUri)); + + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "complex"); + relationship.setValue("related-link", complexUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + + pserver.setValue("relationship-list", relationshipList.getUnderlyingObject()); + pserver.setValue("hostname", "ps-b"); + pserver.setValue("number-of-cpus", 20); + + Introspector pint = loader.introspectorFromName("p-interface"); + pint.setValue("interface-name", "pint-1"); + final String pintUri = pserverUri + "/p-interfaces/p-interface/pint-1"; + + Introspector pints = loader.introspectorFromName("p-interfaces"); + pints.setValue("p-interface", Collections.singletonList(pint.getUnderlyingObject())); + pserver.setValue("p-interfaces", pints.getUnderlyingObject()); + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + + assertTrue("Pserver created", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .hasNext()); + assertTrue("Pserver has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + assertTrue("Pserver has edge to pinterface", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "p-interface") + .hasNext()); + updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 3, updated.size()); + assertThat("Only modified vertexes are in the updated set", + updated.keySet().stream().map(v -> v.<String>value(AAIProperties.AAI_URI)).collect(Collectors.toSet()), + is(new HashSet<>(Arrays.asList(pserverUri, pintUri, complexUri)))); + didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + System.out.println("Update pserver removing relationship to complex"); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "update-pserver", AAIProperties.MINIMUM_DEPTH); + pserver = dbserLocal.getLatestVersionView(pserverV); + relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.emptyList()); + pserver.setValue("relationship-list", relationshipList.getUnderlyingObject()); + pserver.setValue("equip-type", "server-a"); + pserver.setValue("number-of-cpus", 99); + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + + assertFalse("Pserver no longer has edge to complex", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "complex") + .hasNext()); + updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 2, updated.size()); + assertThat("Only modified vertexes are in the updated set", + updated.keySet().stream().map(v -> v.<String>value(AAIProperties.AAI_URI)).collect(Collectors.toSet()), + is(new HashSet<>(Arrays.asList(pserverUri, complexUri)))); + didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + + System.out.println("Update pserver adding a second p-interface"); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "update-pserver", AAIProperties.MINIMUM_DEPTH); + pserver = dbserLocal.getLatestVersionView(pserverV); + Introspector pint2 = loader.introspectorFromName("p-interface"); + pint2.setValue("interface-name", "pint-2"); + pints = pserver.getWrappedValue("p-interfaces"); + List<Object> pintList = pserver.getWrappedValue("p-interfaces").getWrappedListValue("p-interface") + .stream().map(Introspector::getUnderlyingObject).collect(Collectors.toList()); + pintList.add(pint2.getUnderlyingObject()); + pints.setValue("p-interface", pintList); + pserver.setValue("p-interfaces", pints.getUnderlyingObject()); + final String pint2Uri = pserverUri + "/p-interfaces/p-interface/pint-2"; + dbserLocal.serializeToDb(pserver, pserverV, uriQuery, "pserver", pserver.marshal(false)); + + assertTrue("Pserver has edge to pinterface 2", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .in() + .has("aai-node-type", "p-interface") + .has("interface-name","pint-2") + .hasNext()); + assertTrue("p-interface 2 created", engine.tx().traversal().V() + .has("aai-node-type", "p-interface") + .has("interface-name", "pint-2") + .has(AAIProperties.AAI_URI, pint2Uri) + .hasNext()); + updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 1, updated.size()); + assertThat("Only modified vertexes are in the updated set", + updated.keySet().stream().map(v -> v.<String>value(AAIProperties.AAI_URI)).collect(Collectors.toSet()), + is(Collections.singleton(pint2Uri))); + didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + System.out.println("Add l-interface directly to the 2nd p-interface"); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "create-pserver", AAIProperties.MINIMUM_DEPTH); + Introspector lInt = loader.introspectorFromName("l-interface"); + Vertex lIntV = dbserLocal.createNewVertex(lInt); + final String lIntUri = pint2Uri + "/l-interfaces/l-interface/lint-1"; + uriQuery = + engine.getQueryBuilder().createQueryFromURI(new URI(lIntUri)); + lInt.setValue("interface-name", "lint-1"); + dbserLocal.serializeToDb(lInt, lIntV, uriQuery, "l-interface", lInt.marshal(false)); + + assertTrue("l-interface created", engine.tx().traversal().V() + .has("aai-node-type", "l-interface") + .has("interface-name", "lint-1") + .hasNext()); + + assertTrue("Pserver has edge to pinterface to l-interface", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .has("hostname", "ps-b") + .bothE() + .otherV() + .has("aai-node-type", "p-interface") + .bothE() + .otherV() + .has("aai-node-type", "l-interface") + .hasNext()); + updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 1, updated.size()); + assertThat("Only modified vertexes are in the updated set", + updated.keySet().stream().map(v -> v.<String>value(AAIProperties.AAI_URI)).collect(Collectors.toSet()), + is(new HashSet<>(Collections.singletonList(lIntUri)))); + didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + System.out.println("Delete pserver"); + dbserLocal = new DBSerializer(version, engine, introspectorFactoryType, "delete-pserver", AAIProperties.MINIMUM_DEPTH); + pserver = dbserLocal.getLatestVersionView(pserverV); + String rv = pserver.getValue(AAIProperties.RESOURCE_VERSION); + dbserLocal.delete(engine.tx().traversal().V(pserverV).next(), rv, true); + + assertFalse("pserver no longer exists", engine.tx().traversal().V() + .has("aai-node-type", "pserver") + .hasNext()); + updated = getUpdatedVertexes(dbserLocal); + assertEquals("Number of updated vertexes", 0, updated.size()); + didNotUpdateStandardVertexProps = updated.entrySet().stream() + .filter(e -> !e.getValue()) + .map(e -> e.getKey().<String>value(AAIProperties.AAI_URI)).collect(Collectors.toList()); + assertThat("Vertexes should all have their standard props updated", didNotUpdateStandardVertexProps, is(Collections.emptyList())); + + + } + + private Map<Vertex, Boolean> getUpdatedVertexes(DBSerializer dbserLocal) { + Map<Vertex, Boolean> updated = new LinkedHashMap<>(dbserLocal.getUpdatedVertexes()); + dbserLocal.touchStandardVertexPropertiesForEdges().forEach(v -> updated.putIfAbsent(v, true)); + return updated; + } + + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java index b50adf2a..dd4454d5 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializerTest.java @@ -20,18 +20,11 @@ package org.onap.aai.serialization.db; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.*; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import org.janusgraph.core.JanusGraphFactory; import org.junit.*; @@ -40,11 +33,12 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.onap.aai.AAISetup; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.edges.enums.EdgeType; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; @@ -54,6 +48,16 @@ import org.onap.aai.util.AAIConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.*; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @RunWith(value = Parameterized.class) @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class DbSerializerTest extends AAISetup { @@ -72,15 +76,14 @@ public class DbSerializerTest extends AAISetup { private SchemaVersion version; private final ModelType introspectorFactoryType = ModelType.MOXY; - private final DBConnectionType type = DBConnectionType.REALTIME; private Loader loader; private TransactionalGraphEngine dbEngine; private TransactionalGraphEngine engine; // for tests that aren't mocking the engine private DBSerializer dbser; - TransactionalGraphEngine spy; - TransactionalGraphEngine.Admin adminSpy; + private TransactionalGraphEngine spy; + private TransactionalGraphEngine.Admin adminSpy; - @Parameterized.Parameter(value = 0) + @Parameterized.Parameter public QueryStyle queryStyle; @Parameterized.Parameters(name = "QueryStyle.{0}") @@ -89,7 +92,7 @@ public class DbSerializerTest extends AAISetup { } @BeforeClass - public static void init() throws Exception { + public static void init() { graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); } @@ -99,11 +102,11 @@ public class DbSerializerTest extends AAISetup { // createGraph(); version = schemaVersions.getDefaultVersion(); loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); spy = spy(dbEngine); adminSpy = spy(dbEngine.asAdmin()); - engine = new JanusGraphDBEngine(queryStyle, type, loader); + engine = new JanusGraphDBEngine(queryStyle, loader); dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST"); } @@ -146,7 +149,7 @@ public class DbSerializerTest extends AAISetup { } @After - public void tearDown() throws Exception { + public void tearDown() { engine.rollback(); } @@ -155,46 +158,124 @@ public class DbSerializerTest extends AAISetup { graph.close(); } - public void subnetSetup() throws AAIException { + private void subnetSetup() throws AAIException, UnsupportedEncodingException { /* * This setus up the test graph, For future junits , add more vertices * and edges */ - Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list", - "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next(); - Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next(); - Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list", - "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next(); - Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next(); - Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next(); - Vertex l3network_6 = graph.traversal() - .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6") - .next(); + Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list", + "l3-interface-ipv4-address", "l3-interface-ipv4-address-1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex subnet_2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-2", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex l3interipv6addresslist_3 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list", + "l3-interface-ipv6-address", "l3-interface-ipv6-address-3", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex subnet_4 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-4", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex subnet_5 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-5", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex l3network_6 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); GraphTraversalSource g = graph.traversal(); edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2); edgeSer.addEdge(g, l3interipv6addresslist_3, subnet_4); edgeSer.addTreeEdge(g, subnet_5, l3network_6); + + l3interipv4addresslist_1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3interipv4addresslist_1).toString()); + subnet_2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(subnet_2).toString()); + l3interipv6addresslist_3.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3interipv6addresslist_3).toString()); + subnet_4.property(AAIProperties.AAI_URI, dbser.getURIForVertex(subnet_4).toString()); + subnet_5.property(AAIProperties.AAI_URI, dbser.getURIForVertex(subnet_5).toString()); + l3network_6.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3network_6).toString()); + } - public void l3NetworkSetup() throws AAIException { + private void l3NetworkSetup() throws AAIException, UnsupportedEncodingException { /* * This setus up the test graph, For future junits , add more vertices * and edges */ Vertex l3network1 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v1", - "network-name", "network-name-v1"); + "network-name", "network-name-v1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex l3network2 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-v2", - "network-name", "network-name-v2"); - Vertex subnet1 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v1"); - Vertex subnet2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v2"); + "network-name", "network-name-v2", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex subnet1 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex subnet2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-v2", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list", - "l3-interface-ipv4-address", "l3-intr-v1"); + "l3-interface-ipv4-address", "l3-intr-v1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex l3interipv6addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list", - "l3-interface-ipv6-address", "l3-interface-ipv6-v1"); + "l3-interface-ipv6-address", "l3-interface-ipv6-v1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); GraphTraversalSource g = graph.traversal(); edgeSer.addTreeEdge(g, subnet1, l3network1); @@ -203,28 +284,77 @@ public class DbSerializerTest extends AAISetup { edgeSer.addTreeEdge(g, subnet2, l3network2); + subnet1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(subnet1).toString()); + l3interipv4addresslist_1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3interipv4addresslist_1).toString()); + l3network1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3network1).toString()); + subnet2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(subnet2).toString()); + l3network2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3network2).toString()); + + + } - public void vserverSetup() throws AAIException { + private void vserverSetup() throws AAIException, UnsupportedEncodingException { /* * This setus up the test graph, For future junits , add more vertices * and edges */ Vertex vserver1 = graph.addVertex("aai-node-type", "vserver", "vserver-id", "vss1", - AAIProperties.AAI_URI.toString(), - "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vss1"); - - Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr1"); - Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr2"); - - Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink1"); - Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink2"); + AAIProperties.AAI_URI, "/cloud-infrastructure/cloud-regions/cloud-region/me/123/tenants/tenant/453/vservers/vserver/vss1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + + Vertex lInterface1 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex lInterface2 = graph.addVertex("aai-node-type", "l-interface", "interface-name", "lIntr2", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + + Vertex logicalLink1 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex logicalLink2 = graph.addVertex("aai-node-type", "logical-link", "link-name", "logLink2", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list", - "l3-interface-ipv4-address", "l3-intr-ipv4-address-1"); + "l3-interface-ipv4-address", "l3-intr-ipv4-address-1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex l3interipv6addresslist_2 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list", - "l3-interface-ipv4-address", "l3-intr-ipv6-address-1"); + "l3-interface-ipv4-address", "l3-intr-ipv6-address-1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); GraphTraversalSource g = graph.traversal(); @@ -235,10 +365,18 @@ public class DbSerializerTest extends AAISetup { edgeSer.addEdge(g, lInterface1, logicalLink1); edgeSer.addEdge(g, lInterface2, logicalLink2); + + vserver1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(vserver1).toString()); + lInterface1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(lInterface1).toString()); + lInterface2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(lInterface2).toString()); + l3interipv4addresslist_1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3interipv4addresslist_1).toString()); + l3interipv6addresslist_2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(l3interipv6addresslist_2).toString()); + logicalLink1.property(AAIProperties.AAI_URI, dbser.getURIForVertex(logicalLink1).toString()); + logicalLink2.property(AAIProperties.AAI_URI, dbser.getURIForVertex(logicalLink2).toString()); } @Test - public void subnetDelWithInEdgesIpv4Test() throws AAIException { + public void subnetDelWithInEdgesIpv4Test() throws AAIException, UnsupportedEncodingException { subnetSetup(); String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv4-address-list]"; @@ -254,7 +392,7 @@ public class DbSerializerTest extends AAISetup { } @Test - public void subnetDelWithInEdgesIpv6Test() throws AAIException { + public void subnetDelWithInEdgesIpv6Test() throws AAIException, UnsupportedEncodingException { subnetSetup(); String expected_message = "Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types [l3-interface-ipv6-address-list]"; @@ -269,7 +407,7 @@ public class DbSerializerTest extends AAISetup { } @Test - public void subnetDelWithInEdgesL3network() throws AAIException { + public void subnetDelWithInEdgesL3network() throws AAIException, UnsupportedEncodingException { subnetSetup(); String expected_message = ""; @@ -283,7 +421,7 @@ public class DbSerializerTest extends AAISetup { } - public String testCascadeDelete(Vertex v) throws AAIException { + private String testCascadeDelete(Vertex v) throws AAIException { GraphTraversalSource traversal = graph.traversal(); when(spy.asAdmin()).thenReturn(adminSpy); @@ -297,25 +435,7 @@ public class DbSerializerTest extends AAISetup { try { serializer.delete(v, deletableVertices, "resourceVersion", false); } catch (AAIException exception) { - exceptionMessage = exception.getMessage(); - } - return exceptionMessage; - - } - - public String testDelete(Vertex v) throws AAIException { - - GraphTraversalSource traversal = graph.traversal(); - when(spy.asAdmin()).thenReturn(adminSpy); - when(adminSpy.getTraversalSource()).thenReturn(traversal); - when(adminSpy.getReadOnlyTraversalSource()).thenReturn(traversal); - - String exceptionMessage = ""; - DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); - - try { - serializer.delete(v, "resourceVersion", false); - } catch (AAIException exception) { + exception.printStackTrace(); exceptionMessage = exception.getMessage(); } return exceptionMessage; @@ -331,7 +451,7 @@ public class DbSerializerTest extends AAISetup { Vertex testVertex = dbser.createNewVertex(testObj); Vertex fromGraph = engine.tx().traversal().V().has("aai-node-type", "generic-vnf").toList().get(0); assertEquals(testVertex.id(), fromGraph.id()); - assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH.toString()).value()); + assertEquals("AAI-TEST", fromGraph.property(AAIProperties.SOURCE_OF_TRUTH).value()); } @@ -343,17 +463,17 @@ public class DbSerializerTest extends AAISetup { // different value Thread.sleep(2); DBSerializer dbser2 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-2"); - Vertex vert = graph.addVertex("aai-node-type", "generic-vnf"); + Vertex vert = graph.addVertex("aai-node-type", "generic-vnf", "aai-uri", "a"); // Upon first creation of the Vertex and the DBSerializer // the source of truth and created-ts should be the same as their modified counterparts dbser2.touchStandardVertexProperties(vert, true); - String createTS = (String) vert.property(AAIProperties.CREATED_TS).value(); - String modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value(); + String createTS = String.valueOf(vert.property(AAIProperties.CREATED_TS).value()); + String modTS = String.valueOf(vert.property(AAIProperties.LAST_MOD_TS).value()); String sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value(); String lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value(); - assertTrue(createTS.equals(modTS)); - assertTrue(sot.equals(lastModSOT)); + assertEquals(createTS, modTS); + assertEquals(sot, lastModSOT); // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a // different value @@ -363,12 +483,12 @@ public class DbSerializerTest extends AAISetup { // Here the vertex will be modified by a different source of truth DBSerializer dbser3 = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST-3"); dbser3.touchStandardVertexProperties(vert, false); - createTS = (String) vert.property(AAIProperties.CREATED_TS).value(); - modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value(); + createTS = String.valueOf(vert.property(AAIProperties.CREATED_TS).value()); + modTS = String.valueOf(vert.property(AAIProperties.LAST_MOD_TS).value()); sot = (String) vert.property(AAIProperties.SOURCE_OF_TRUTH).value(); lastModSOT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value(); - assertFalse(createTS.equals(modTS)); - assertFalse(sot.equals(lastModSOT)); + assertNotEquals(createTS, modTS); + assertNotEquals(sot, lastModSOT); // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a // different value @@ -380,10 +500,10 @@ public class DbSerializerTest extends AAISetup { // Using an existing vertex, but treating it as new && using an older DBSerializer dbser.touchStandardVertexProperties(vert, true); String resverStart = (String) vert.property(AAIProperties.RESOURCE_VERSION).value(); - String lastModTimeStart = (String) vert.property(AAIProperties.LAST_MOD_TS).value(); - createTS = (String) vert.property(AAIProperties.CREATED_TS).value(); - modTS = (String) vert.property(AAIProperties.LAST_MOD_TS).value(); - assertTrue(createTS.equals(modTS)); + String lastModTimeStart = String.valueOf(vert.property(AAIProperties.LAST_MOD_TS).value()); + createTS = String.valueOf(vert.property(AAIProperties.CREATED_TS).value()); + modTS = String.valueOf(vert.property(AAIProperties.LAST_MOD_TS).value()); + assertEquals(createTS, modTS); assertEquals("AAI-TEST", vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value()); // if this test runs through too fast the value may not change, causing the test to fail. sleeping ensures a @@ -392,16 +512,16 @@ public class DbSerializerTest extends AAISetup { dbser2.touchStandardVertexProperties(vert, false); String resourceVer = (String) vert.property(AAIProperties.RESOURCE_VERSION).value(); - String lastModTs = (String) vert.property(AAIProperties.LAST_MOD_TS).value(); + String lastModTs = String.valueOf(vert.property(AAIProperties.LAST_MOD_TS).value()); String lastModSoT = (String) vert.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH).value(); - assertFalse(resverStart.equals(resourceVer)); - assertFalse(lastModTimeStart.equals(lastModTs)); + assertNotEquals(resverStart, resourceVer); + assertNotEquals(lastModTimeStart, lastModTs); assertEquals("AAI-TEST-2", lastModSoT); } @Test - public void touchStandardVertexPropertiesAAIUUIDTest() throws AAIException, InterruptedException { + public void touchStandardVertexPropertiesAAIUUIDTest() { engine.startTransaction(); Graph graph = TinkerGraph.open(); @@ -466,7 +586,7 @@ public class DbSerializerTest extends AAISetup { } @Test - public void trimClassNameTest() throws AAIException { + public void trimClassNameTest() { assertEquals("GenericVnf", dbser.trimClassName("GenericVnf")); assertEquals("GenericVnf", dbser.trimClassName("org.onap.aai.GenericVnf")); } @@ -526,9 +646,21 @@ public class DbSerializerTest extends AAISetup { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc); @@ -540,7 +672,7 @@ public class DbSerializerTest extends AAISetup { relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); relationship.setValue("relationship-data", relData); - assertTrue(dbser.deleteEdge(relationship, gvnf)); + assertTrue(dbser.deleteEdge(relationship, gvnf).isPresent()); assertFalse(engine.tx().traversal().V(gvnf).both("uses").hasNext()); assertFalse(engine.tx().traversal().V(vnfc).both("uses").hasNext()); @@ -552,9 +684,9 @@ public class DbSerializerTest extends AAISetup { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", "aai-uuid", "a"); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", "aai-uuid", "b"); // sunny day case Introspector relData = loader.introspectorFromName("relationship-data"); @@ -565,7 +697,7 @@ public class DbSerializerTest extends AAISetup { relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); relationship.setValue("relationship-data", relData); - assertTrue(dbser.createEdge(relationship, gvnf)); + assertNotNull(dbser.createEdge(relationship, gvnf)); assertTrue(engine.tx().traversal().V(gvnf).both("org.onap.relationships.inventory.BelongsTo").hasNext()); assertTrue(engine.tx().traversal().V(vnfc).both("org.onap.relationships.inventory.BelongsTo").hasNext()); @@ -634,9 +766,9 @@ public class DbSerializerTest extends AAISetup { Vertex gvnfVert = dbser.createNewVertex(gvnf); gvnf.setValue("vnf-id", "myvnf"); + gvnf.setValue("vnf-type", "typo"); dbser.serializeSingleVertex(gvnfVert, gvnf, "test"); assertTrue(engine.tx().traversal().V().has("aai-node-type", "generic-vnf").has("vnf-id", "myvnf").hasNext()); - } @Test @@ -666,19 +798,14 @@ public class DbSerializerTest extends AAISetup { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "vnf-123", "aai-uri", - "/network/generic-vnfs/generic-vnf/vnf-123"); + "/network/generic-vnfs/generic-vnf/vnf-123", "aai-uuid", "a"); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-123", "aai-uri", - "/network/vnfcs/vnfc/vnfc-123"); + "/network/vnfcs/vnfc/vnfc-123", "aai-uuid", "b"); edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc); Introspector obj = loader.introspectorFromName("generic-vnf"); - obj = this.dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false"); - - MarshallerProperties properties = - new MarshallerProperties.Builder(org.onap.aai.restcore.MediaType.getEnum("application/json")) - .formatted(true).build(); - System.out.println(obj.marshal(properties)); + obj = this.dbser.dbToObject(Collections.singletonList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false"); assertEquals("edge label between generic-vnf and vnfs is uses", "org.onap.relationships.inventory.BelongsTo", obj.getWrappedValue("relationship-list").getWrappedListValue("relationship").get(0) @@ -704,22 +831,21 @@ public class DbSerializerTest extends AAISetup { edgeSer.addEdge(engine.tx().traversal(), gvnf, vnfc); Introspector obj = loader.introspectorFromName("generic-vnf"); - obj = dbser.dbToObject(Arrays.asList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false"); + obj = dbser.dbToObject(Collections.singletonList(gvnf), obj, AAIProperties.MAXIMUM_DEPTH, false, "false"); - assertEquals("Relationship does not contain edge-property", false, obj.getWrappedValue("relationship-list") - .getWrappedListValue("relationship").get(0).hasProperty("relationship-label")); + assertFalse("Relationship does not contain edge-property", obj.getWrappedValue("relationship-list").getWrappedListValue("relationship").get(0).hasProperty("relationship-label")); } @Test public void createEdgeWithInvalidLabelTest() throws AAIException, UnsupportedEncodingException, - NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + SecurityException, IllegalArgumentException { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); - engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name"); + "/network/generic-vnfs/generic-vnf/myvnf", "aai-uuid", "a"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", "aai-uuid", "b"); Introspector relData = loader.introspectorFromName("relationship-data"); relData.setValue("relationship-key", "vnfc.vnfc-name"); @@ -738,6 +864,26 @@ public class DbSerializerTest extends AAISetup { } @Test + public void createEdgeUsingIntrospectorTest() throws AAIException, UnsupportedEncodingException, SecurityException, IllegalArgumentException { + + engine.startTransaction(); + + Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", + "/network/generic-vnfs/generic-vnf/myvnf", "aai-uuid", "a"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", "aai-uuid", "b"); + + Introspector relData = loader.introspectorFromName("relationship-data"); + relData.setValue("relationship-key", "vnfc.vnfc-name"); + relData.setValue("relationship-value", "a-name"); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "vnfc"); + relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); + relationship.setValue("relationship-data", relData); + + dbser.createEdge(relationship, gvnf); + } + + @Test public void addRelatedToPropertyTest() throws AAIException { engine.startTransaction(); @@ -789,7 +935,7 @@ public class DbSerializerTest extends AAISetup { Introspector res = dbser.dbToObject(vertices, gvContainer, 0, true, "true"); List<Introspector> gvs = res.getWrappedListValue("generic-vnf"); - assertTrue(gvs.size() == 2); + assertEquals(2, gvs.size()); for (Introspector i : gvs) { String vnfId = i.getValue("vnf-id"); assertTrue("id1".equals(vnfId) || "id2".equals(vnfId)); @@ -814,16 +960,31 @@ public class DbSerializerTest extends AAISetup { public void deleteItemsWithTraversal() throws AAIException { DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST"); engine.startTransaction(); - Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1"); - Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1"); + Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", + AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/id1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", "interface-name", "name1", + AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/id1/l-interfaces/l-interface/name1", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); assertTrue(engine.tx().traversal().V().has("vnf-id", "id1").hasNext()); assertTrue(engine.tx().traversal().V().has("interface-name", "name1").hasNext()); - dbser.deleteItemsWithTraversal(Arrays.asList(gv, lint)); + dbser.deleteWithTraversal(gv); + dbser.deleteWithTraversal(lint); - assertTrue(!engine.tx().traversal().V().has("vnf-id", "id1").hasNext()); - assertTrue(!engine.tx().traversal().V().has("interface-name", "name1").hasNext()); + assertFalse(engine.tx().traversal().V().has("vnf-id", "id1").hasNext()); + assertFalse(engine.tx().traversal().V().has("interface-name", "name1").hasNext()); } @@ -832,8 +993,20 @@ public class DbSerializerTest extends AAISetup { DBSerializer dbser = new DBSerializer(version, engine, ModelType.MOXY, "AAI-TEST"); engine.startTransaction(); Vertex gv = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "id1", "aai-uri", - "/network/generic-vnfs/generic-vnf/id1"); - Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface"); + "/network/generic-vnfs/generic-vnf/id1", "aai-uuid", "a", + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); + Vertex lint = engine.tx().addVertex("aai-node-type", "l-interface", + "aai-uri", "abc", + "aai-uuid", "b", + AAIProperties.CREATED_TS, 123L, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333L); edgeSer.addTreeEdge(engine.tx().traversal(), gv, lint); Introspector lintIntro = loader.introspectorFromName("l-interface"); @@ -855,13 +1028,13 @@ public class DbSerializerTest extends AAISetup { "very-fast", "service-provider-bandwidth-up-units", "things"); Introspector res = dbser.getLatestVersionView(phys); - assertTrue("zaldo".equals(res.getValue("link-name"))); - assertTrue("very-fast".equals(res.getValue("speed-value"))); - assertTrue("things".equals(res.getValue("service-provider-bandwidth-up-units"))); + assertEquals("zaldo", res.getValue("link-name")); + assertEquals("very-fast", res.getValue("speed-value")); + assertEquals("things", res.getValue("service-provider-bandwidth-up-units")); } @Test - public void cascadeVserverDeleteTest() throws AAIException { + public void cascadeVserverDeleteTest() throws AAIException, UnsupportedEncodingException { vserverSetup(); String expected_message = ""; @@ -877,7 +1050,7 @@ public class DbSerializerTest extends AAISetup { } @Test - public void cascadeL3NetworkPreventDeleteTest() throws AAIException { + public void cascadeL3NetworkPreventDeleteTest() throws AAIException, UnsupportedEncodingException { l3NetworkSetup(); ArrayList expected_messages = new ArrayList<String>(); expected_messages.add( @@ -898,7 +1071,7 @@ public class DbSerializerTest extends AAISetup { } @Test - public void cascadeL3NetworkDeleteTest() throws AAIException { + public void cascadeL3NetworkDeleteTest() throws AAIException, UnsupportedEncodingException { l3NetworkSetup(); String expected_message = ""; @@ -913,4 +1086,5 @@ public class DbSerializerTest extends AAISetup { assertEquals(expected_message, exceptionMessage); } + } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java index 808dd631..9a78a433 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/DbSerializer_needsFakeRulesTest.java @@ -20,17 +20,10 @@ package org.onap.aai.serialization.db; -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.*; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; import org.janusgraph.core.JanusGraphFactory; import org.junit.*; import org.junit.rules.ExpectedException; @@ -38,18 +31,20 @@ import org.junit.runner.RunWith; import org.onap.aai.config.ConfigConfiguration; import org.onap.aai.config.IntrospectionConfig; import org.onap.aai.config.SpringContextAware; +import org.onap.aai.config.XmlFormatTransformerConfiguration; import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.edges.EdgeIngestor; import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.*; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; import org.onap.aai.nodes.NodeIngestor; import org.onap.aai.parsers.query.QueryParser; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; -import org.onap.aai.setup.SchemaLocationsBean; import org.onap.aai.setup.SchemaVersion; import org.onap.aai.setup.SchemaVersions; import org.onap.aai.util.AAIConstants; @@ -58,11 +53,23 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + //@RunWith(value = Parameterized.class) TODO replace this functionality @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( classes = {ConfigConfiguration.class, AAICoreFakeEdgesConfigTranslator.class, NodeIngestor.class, - EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class}) + EdgeIngestor.class, EdgeSerializer.class, SpringContextAware.class, IntrospectionConfig.class, XmlFormatTransformerConfiguration.class}) @TestPropertySource( properties = {"schema.translator.list = config", "schema.nodes.location=src/test/resources/onap/oxm", "schema.edges.location=src/test/resources/onap/dbedgerules"}) @@ -84,7 +91,6 @@ public class DbSerializer_needsFakeRulesTest { private SchemaVersion version; private final ModelType introspectorFactoryType = ModelType.MOXY; - private final DBConnectionType type = DBConnectionType.REALTIME; private Loader loader; private TransactionalGraphEngine dbEngine; private TransactionalGraphEngine engine; // for tests that aren't mocking the engine @@ -92,19 +98,8 @@ public class DbSerializer_needsFakeRulesTest { TransactionalGraphEngine spy; TransactionalGraphEngine.Admin adminSpy; - // @Parameterized.Parameter(value = 0) public QueryStyle queryStyle = QueryStyle.TRAVERSAL; - /* - * @Parameterized.Parameters(name = "QueryStyle.{0}") - * public static Collection<Object[]> data() { - * return Arrays.asList(new Object[][]{ - * {QueryStyle.TRAVERSAL}, - * {QueryStyle.TRAVERSAL_URI} - * }); - * } - */ - @BeforeClass public static void init() throws Exception { graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); @@ -117,15 +112,14 @@ public class DbSerializer_needsFakeRulesTest { @Before public void setup() throws Exception { - // createGraph(); version = schemaVersions.getDefaultVersion(); loader = SpringContextAware.getBean(LoaderFactory.class).createLoaderForVersion(introspectorFactoryType, version); - dbEngine = new JanusGraphDBEngine(queryStyle, type, loader); + dbEngine = new JanusGraphDBEngine(queryStyle, loader); spy = spy(dbEngine); adminSpy = spy(dbEngine.asAdmin()); - engine = new JanusGraphDBEngine(queryStyle, type, loader); + engine = new JanusGraphDBEngine(queryStyle, loader); dbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST"); } @@ -145,16 +139,14 @@ public class DbSerializer_needsFakeRulesTest { * and edges */ - Vertex l3interipv4addresslist_1 = graph.traversal().addV("aai-node-type", "l3-interface-ipv4-address-list", - "l3-interface-ipv4-address", "l3-interface-ipv4-address-1").next(); - Vertex subnet_2 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-2").next(); - Vertex l3interipv6addresslist_3 = graph.traversal().addV("aai-node-type", "l3-interface-ipv6-address-list", - "l3-interface-ipv6-address", "l3-interface-ipv6-address-3").next(); - Vertex subnet_4 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-4").next(); - Vertex subnet_5 = graph.traversal().addV("aai-node-type", "subnet", "subnet-id", "subnet-id-5").next(); - Vertex l3network_6 = graph.traversal() - .addV("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6") - .next(); + Vertex l3interipv4addresslist_1 = graph.addVertex("aai-node-type", "l3-interface-ipv4-address-list", + "l3-interface-ipv4-address", "l3-interface-ipv4-address-1"); + Vertex subnet_2 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-2"); + Vertex l3interipv6addresslist_3 = graph.addVertex("aai-node-type", "l3-interface-ipv6-address-list", + "l3-interface-ipv6-address", "l3-interface-ipv6-address-3"); + Vertex subnet_4 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-4"); + Vertex subnet_5 = graph.addVertex("aai-node-type", "subnet", "subnet-id", "subnet-id-5"); + Vertex l3network_6 = graph.addVertex("aai-node-type", "l3-network", "network-id", "network-id-6", "network-name", "network-name-6"); GraphTraversalSource g = graph.traversal(); edgeSer.addEdge(g, l3interipv4addresslist_1, subnet_2); @@ -190,7 +182,13 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "vnfc-" + testName, AAIProperties.AAI_URI, - "/network/vnfcs/vnfc/vnfc-" + testName); + "/network/vnfcs/vnfc/vnfc-" + testName, + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relationship = loader.introspectorFromName("relationship"); relationship.setValue("related-to", "vnfc"); @@ -222,9 +220,19 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", "aai-uuid", "a", + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", "aai-uuid", "b", + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); // sunny day case Introspector relData = loader.introspectorFromName("relationship-data"); @@ -236,7 +244,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("relationship-data", relData); relationship.setValue("relationship-label", "over-uses"); - assertTrue(localDbser.createEdge(relationship, gvnf)); + assertNotNull(dbser.createEdge(relationship, gvnf)); assertTrue(engine.tx().traversal().V(gvnf).both("over-uses").hasNext()); assertTrue(engine.tx().traversal().V(vnfc).both("over-uses").hasNext()); @@ -264,7 +272,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("relationship-data", relData); relationship.setValue("relationship-label", "re-uses"); - assertTrue(localDbser.createEdge(relationship, gvnf)); + assertNotNull(dbser.createEdge(relationship, gvnf)); assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext()); assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext()); assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), @@ -280,9 +288,21 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses"); Introspector relData = loader.introspectorFromName("relationship-data"); @@ -297,7 +317,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("relationship-label", "re-uses"); - assertTrue(localDbser.createEdge(relationship, gvnf)); + assertNotNull(dbser.createEdge(relationship, gvnf)); assertTrue(engine.tx().traversal().V(gvnf).both("re-uses").hasNext()); assertTrue(engine.tx().traversal().V(vnfc).both("re-uses").hasNext()); assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext()); @@ -317,9 +337,21 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relData = loader.introspectorFromName("relationship-data"); relData.setValue("relationship-key", "vnfc.vnfc-name"); @@ -330,7 +362,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("relationship-data", relData); localDbser.createEdge(relationship, gvnf); - assertTrue(localDbser.createEdge(relationship, gvnf)); + assertNotNull(dbser.createEdge(relationship, gvnf)); assertTrue(engine.tx().traversal().V(gvnf).both("uses").hasNext()); assertTrue(engine.tx().traversal().V(vnfc).both("uses").hasNext()); assertEquals("Number of edges between vertexes is 1", Long.valueOf(1), @@ -348,9 +380,21 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses"); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses"); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses"); @@ -363,7 +407,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("related-link", "/network/vnfcs/vnfc/a-name"); relationship.setValue("relationship-data", relData); - assertTrue(localDbser.deleteEdge(relationship, gvnf)); + assertTrue(localDbser.deleteEdge(relationship, gvnf).isPresent()); assertFalse("generic-vnf has no edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext()); assertFalse("vnfc has no edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext()); assertTrue("generic-vnf has edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext()); @@ -386,9 +430,21 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); Vertex gvnf = engine.tx().addVertex("aai-node-type", "generic-vnf", "vnf-id", "myvnf", "aai-uri", - "/network/generic-vnfs/generic-vnf/myvnf"); + "/network/generic-vnfs/generic-vnf/myvnf", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Vertex vnfc = engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", - "/network/vnfcs/vnfc/a-name"); + "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "uses"); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "re-uses"); edgeSer.addEdge(graph.traversal(), gvnf, vnfc, "over-uses"); @@ -402,7 +458,7 @@ public class DbSerializer_needsFakeRulesTest { relationship.setValue("relationship-data", relData); relationship.setValue("relationship-label", "re-uses"); - assertTrue(localDbser.deleteEdge(relationship, gvnf)); + assertTrue(localDbser.deleteEdge(relationship, gvnf).isPresent()); assertTrue("generic-vnf has edge uses", engine.tx().traversal().V(gvnf).both("uses").hasNext()); assertTrue("vnfc has edge uses", engine.tx().traversal().V(vnfc).both("uses").hasNext()); assertFalse("generic-vnf has no edge re-uses", engine.tx().traversal().V(gvnf).both("re-uses").hasNext()); @@ -456,7 +512,12 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); - engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", "aai-uuid", "b", + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relationship = loader.introspectorFromName("relationship"); relationship.setValue("related-to", "vnfc"); @@ -505,7 +566,13 @@ public class DbSerializer_needsFakeRulesTest { engine.startTransaction(); - engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relationship = loader.introspectorFromName("relationship"); relationship.setValue("related-to", "vnfc"); @@ -585,7 +652,13 @@ public class DbSerializer_needsFakeRulesTest { DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules(); engine.startTransaction(); - engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relationship; Introspector relationshipList; @@ -652,7 +725,13 @@ public class DbSerializer_needsFakeRulesTest { DBSerializer localDbser = getDBSerializerWithSpecificEdgeRules(); engine.startTransaction(); - engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name"); + engine.tx().addVertex("aai-node-type", "vnfc", "vnfc-name", "a-name", "aai-uri", "/network/vnfcs/vnfc/a-name", + AAIProperties.AAI_UUID, UUID.randomUUID().toString(), + AAIProperties.CREATED_TS, 123, + AAIProperties.SOURCE_OF_TRUTH, "sot", + AAIProperties.RESOURCE_VERSION, "123", + AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, "lmsot", + AAIProperties.LAST_MOD_TS, 333); Introspector relationship; Introspector relationshipList; @@ -713,10 +792,8 @@ public class DbSerializer_needsFakeRulesTest { } - private DBSerializer getDBSerializerWithSpecificEdgeRules() - throws NoSuchFieldException, AAIException, IllegalAccessException { + private DBSerializer getDBSerializerWithSpecificEdgeRules() throws AAIException { - DBSerializer localDbser = new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST"); - return localDbser; + return new DBSerializer(version, engine, introspectorFactoryType, "AAI-TEST"); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/EdgerPairCanBeBothCousinAndParentChildTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgerPairCanBeBothCousinAndParentChildTest.java new file mode 100644 index 00000000..d00408e8 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/EdgerPairCanBeBothCousinAndParentChildTest.java @@ -0,0 +1,234 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphFactory; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; + +import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class EdgerPairCanBeBothCousinAndParentChildTest extends AAISetup { + + // to use, set thrown.expect to whatever your test needs + // this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected static Graph graph; + + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + private TransactionalGraphEngine engine; + + public QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI; + + public static final String SOURCE_OF_TRUTH = "EdgerPairCanBeBothCousinAndParentChildTest"; + private static final String gvnfAUri = "/network/generic-vnfs/generic-vnf/gvnf-a" + SOURCE_OF_TRUTH; + private static final String lagIntAUri = gvnfAUri + "/lag-interfaces/lag-interface/lagint-a"; + private static final String lintUri = lagIntAUri + "/l-interfaces/l-interface/lint"; + + private static final String gvnfBUri = "/network/generic-vnfs/generic-vnf/gvnf-b" + SOURCE_OF_TRUTH; + private static final String lagIntBUri = gvnfBUri + "/lag-interfaces/lag-interface/lagint-b"; + + @BeforeClass + public static void init() { + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + + } + + @Before + public void setup() throws UnsupportedEncodingException, AAIException, URISyntaxException { + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + engine = new JanusGraphDBEngine(queryStyle, loader); + initData(); + } + + @After + public void cleanup() { + engine.rollback(); + } + + /** + * Using latest version (see schema-ingest.properties) + * Create generic-vnf with lag-interface that has an l-interface + * Create generic-vnf with lag-interface relationship the l-interface + */ + private void initData() throws UnsupportedEncodingException, AAIException, URISyntaxException { + engine.startTransaction(); + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + gvnf.setValue("vnf-id", "gvnf-a" + SOURCE_OF_TRUTH); + gvnf.setValue("vnf-name", "gvnf" + SOURCE_OF_TRUTH + "-name"); + + Introspector lagInt = loader.introspectorFromName("lag-interface"); + lagInt.setValue("interface-name", "lagint-a"); + + Introspector lint = loader.introspectorFromName("l-interface"); + lint.setValue("interface-name", "lint"); + + Introspector lagints = loader.introspectorFromName("lag-interfaces"); + Introspector lints = loader.introspectorFromName("l-interfaces"); + + lints.setValue("l-interface", Collections.singletonList(lint.getUnderlyingObject())); + lagInt.setValue("l-interfaces", lints.getUnderlyingObject()); + lagints.setValue("lag-interface", Collections.singletonList(lagInt.getUnderlyingObject())); + gvnf.setValue("lag-interfaces", lagints.getUnderlyingObject()); + + + + Vertex gvnfV = serializer.createNewVertex(gvnf); + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfAUri)); + serializer.serializeToDb(gvnf, gvnfV, uriQuery, "generic-vnf", gvnf.marshal(false)); + + assertTrue("generic-vnf-a created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, gvnfAUri) + .hasNext()); + assertTrue("lag-int-a created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lagIntAUri) + .hasNext()); + assertTrue("l-int created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lintUri) + .hasNext()); + + + + gvnf = loader.introspectorFromName("generic-vnf"); + gvnf.setValue("vnf-id", "gvnf-b" + SOURCE_OF_TRUTH); + gvnf.setValue("vnf-name", "gvnf" + SOURCE_OF_TRUTH + "-name"); + + lagInt = loader.introspectorFromName("lag-interface"); + lagInt.setValue("interface-name", "lagint-b"); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-link", lintUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + lagInt.setValue("relationship-list", relationshipList.getUnderlyingObject()); + + lagints = loader.introspectorFromName("lag-interfaces"); + lagints.setValue("lag-interface", Collections.singletonList(lagInt.getUnderlyingObject())); + gvnf.setValue("lag-interfaces", lagints.getUnderlyingObject()); + + gvnfV = serializer.createNewVertex(gvnf); + uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfAUri)); + serializer.serializeToDb(gvnf, gvnfV, uriQuery, "generic-vnf", gvnf.marshal(false)); + + engine.tx().traversal().V().forEachRemaining(v -> System.out.println(v.<String>value(AAIProperties.AAI_URI))); + assertTrue("generic-vnf-b created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, gvnfBUri) + .hasNext()); + assertTrue("lag-int-b created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lagIntBUri) + .hasNext()); + assertTrue("lag-interface relationship l-interface created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lagIntBUri) + .both() + .has(AAIProperties.AAI_URI, lintUri) + .hasNext()); + } + + + @Test + public void verifyReadOfGenericVnfATest() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfALatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfAUri).next()).marshal(false); + + assertThat(gvnfALatestView, + hasJsonPath( + "$.lag-interfaces.lag-interface[*]", + hasSize(1) + )); + assertThat(gvnfALatestView, + hasJsonPath( + "$.lag-interfaces.lag-interface[*].l-interfaces.l-interface[*]", + hasSize(1) + )); + assertThat(gvnfALatestView, + hasJsonPath( + "$.lag-interfaces.lag-interface[*].l-interfaces.l-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + lagIntBUri + ) + )); + } + + @Test + public void verifyReadOfGenericVnfBTest() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfBLatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfBUri).next()).marshal(false); + + assertThat(gvnfBLatestView, + hasJsonPath( + "$.lag-interfaces.lag-interface[*]", + hasSize(1) + )); + assertThat(gvnfBLatestView, + not(hasJsonPath( + "$.lag-interfaces.lag-interface[*].l-interfaces.l-interface[*]" + ))); + assertThat(gvnfBLatestView, + hasJsonPath( + "$.lag-interfaces.lag-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + lintUri + ) + )); + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/ImpliedDeleteUnitTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/ImpliedDeleteUnitTest.java new file mode 100644 index 00000000..20e300a1 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/ImpliedDeleteUnitTest.java @@ -0,0 +1,331 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.serialization.engines.query.QueryEngine; +import org.onap.aai.util.AAIConstants; +import org.springframework.boot.test.rule.OutputCapture; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Matchers.eq; + +public class ImpliedDeleteUnitTest { + + private TransactionalGraphEngine mockEngine; + private DBSerializer mockSerializer; + + private ImpliedDelete impliedDelete; + + @Rule + public final OutputCapture outputCapture = new OutputCapture(); + + @Before + public void setup(){ + mockEngine = Mockito.mock(TransactionalGraphEngine.class); + mockSerializer = Mockito.mock(DBSerializer.class); + impliedDelete = Mockito.spy(new ImpliedDelete(mockEngine, mockSerializer)); + } + + // aai.implied.delete.whitelist.sdnc=* + @Test + public void testImpliedDeleteWhenUserIsAllowedToInvokeAnyMethod() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("*") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + + } + + // aai.implied.delete.whitelist.sdnc='vserver' + @Test + public void testImpliedDeleteWhenUserIsAllowedToInvokeCertainMethod() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("'vserver'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + } + + // aai.implied.delete.whitelist.sdnc='vserver' + @Test + public void testImpliedDeleteWhenUserIsAllowedAndTryVariationsOfSOTValueSDNC() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("'vserver'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + impliedDelete.execute(vserver.id(), "sDNC", "vserver", vertices); + impliedDelete.execute(vserver.id(), "sdNC", "vserver", vertices); + impliedDelete.execute(vserver.id(), "sdnC", "vserver", vertices); + impliedDelete.execute(vserver.id(), "sdnc", "vserver", vertices); + } + + // aai.implied.delete.whitelist.sdnc='vserver','vce','pserver' + @Test + public void testImpliedDeleteWhenUserIsAllowedToInvokeMultipleMethods() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("'vce','pserver','vserver','cloud-region'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + } + + // aai.implied.delete.whitelist.sdnc='vserver','vce','pserver' + @Test + public void testImpliedDeleteWhenUserIsAllowedToInvokeMultipleMethodsAndDeletableReturnsMultipleVertexes() + throws AAIException, UnsupportedEncodingException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + // On a spy the syntax should be doReturn => when => method to spy + // On a mock the syntax should be when => thenReturn|thenAnswer + Mockito + .doReturn("'vserver'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + + Introspector mockIntrospector = Mockito.mock(Introspector.class); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume1 = graph.addVertex("vertex"); + volume1.property("volume-id", "volume-1"); + + Vertex volume2 = graph.addVertex("vertex"); + volume1.property("volume-id", "volume-2"); + + Vertex volume3 = graph.addVertex("vertex"); + volume1.property("volume-id", "volume-3"); + + Vertex volume4 = graph.addVertex("vertex"); + volume1.property("volume-id", "volume-4"); + + List<Vertex> vertices = new ArrayList<>(); + + vertices.add(volume1); + vertices.add(volume2); + vertices.add(volume3); + vertices.add(volume4); + + Mockito + .when(mockQueryEngine.findDeletable(Mockito.anyList())) + .thenReturn(vertices); + + Mockito + .when(mockSerializer.getLatestVersionView(Mockito.anyObject())) + .thenReturn(mockIntrospector); + + Mockito + .when(mockIntrospector.marshal(false)) + .thenReturn("{\"volume-id\":\"volume-1\"}") + .thenReturn("{\"volume-id\":\"volume-2\"}") + .thenReturn("{\"volume-id\":\"volume-3\"}") + .thenReturn("{\"volume-id\":\"volume-4\"}"); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + } + + // aai.implied.delete.whitelist.sdnc= + @Test(expected = AAIException.class) + public void testImpliedDeleteWhenUserIsNotAllowedToDelete() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + } + + // aai.implied.delete.whitelist.sdnc='vce' + @Test(expected = AAIException.class) + public void testImpliedDeleteWhenUserIsAllowedToDeleteVceChildrenButRequestedToDeleteVserverChildren() throws AAIException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + Mockito + .doReturn("'vce'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume = graph.addVertex("vertex"); + volume.property("volume-id", "some-id"); + + List<Vertex> vertices = new ArrayList<>(); + vertices.add(volume); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + } + + @Test + public void testImpliedDeleteWhenUserIsAllowedToDeleteAndPrintingDeletingVertexItThrowsExceptionVerifyLog() throws AAIException, UnsupportedEncodingException { + + QueryEngine mockQueryEngine = Mockito.mock(QueryEngine.class); + + // On a spy the syntax should be doReturn => when => method to spy + // On a mock the syntax should be when => thenReturn|thenAnswer + Mockito + .doReturn("'vserver'") + .when(impliedDelete) + .get(AAIConstants.AAI_IMPLIED_DELETE_WHITELIST + "sdnc",""); + + + Introspector mockIntrospector = Mockito.mock(Introspector.class); + + Mockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); + + TinkerGraph graph = TinkerGraph.open(); + + Vertex vserver = graph.addVertex("vertex"); + vserver.property("vserver-id", "some-id"); + + Vertex volume1 = graph.addVertex("vertex"); + volume1.property("volume-id", "volume-1"); + + List<Vertex> vertices = new ArrayList<>(); + + vertices.add(volume1); + + Mockito + .when(mockQueryEngine.findDeletable(Mockito.anyList())) + .thenReturn(vertices); + + Mockito + .when(mockSerializer.getLatestVersionView(Mockito.anyObject())) + .thenThrow(new RuntimeException("Unable to find node")); + + impliedDelete.execute(vserver.id(), "SDNC", "vserver", vertices); + + outputCapture.expect( + CoreMatchers.containsString("Encountered an exception during retrieval of vertex properties with vertex-id " + vserver.id()) + ); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/OneToOneEdgeUpdateTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/OneToOneEdgeUpdateTest.java new file mode 100644 index 00000000..0c90c735 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/OneToOneEdgeUpdateTest.java @@ -0,0 +1,300 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphFactory; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Collections; + +import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class OneToOneEdgeUpdateTest extends AAISetup { + + // to use, set thrown.expect to whatever your test needs + // this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected static Graph graph; + + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + private TransactionalGraphEngine engine; + + public QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI; + + public static final String SOURCE_OF_TRUTH = "EdgerPairCanBeBothCousinAndParentChildTest"; + private static final String gvnfAUri = "/network/generic-vnfs/generic-vnf/gvnf-a" + SOURCE_OF_TRUTH; + private static final String lintUri = gvnfAUri + "/l-interfaces/l-interface/lint"; + private static final String lintAUri = gvnfAUri + "/l-interfaces/l-interface/lint-a"; + private static final String sriovVfUri = lintUri + "/sriov-vfs/sriov-vf/sriov-vf"; + private static final String sriovVfAUri = lintAUri + "/sriov-vfs/sriov-vf/sriov-vf-a"; + + private static final String gvnfBUri = "/network/generic-vnfs/generic-vnf/gvnf-b" + SOURCE_OF_TRUTH; + private static final String lIntBUri = gvnfBUri + "/l-interfaces/l-interface/lint-b"; + + @BeforeClass + public static void init() { + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + + } + + @Before + public void setup() throws UnsupportedEncodingException, AAIException, URISyntaxException { + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + engine = new JanusGraphDBEngine(queryStyle, loader); + initData(); + } + + @After + public void cleanup() { + engine.rollback(); + } + + /** + * Using latest version (see schema-ingest.properties) - sriov-vf to l-interface is one ot one + * Create generic-vnf with l-interface that has an sriov-vf + * Create generic-vnf with l-interface relationship the sriov-vf + */ + private void initData() throws UnsupportedEncodingException, AAIException, URISyntaxException { + engine.startTransaction(); + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + gvnf.setValue("vnf-id", "gvnf-a" + SOURCE_OF_TRUTH); + gvnf.setValue("vnf-name", "gvnf" + SOURCE_OF_TRUTH + "-name"); + + Introspector lint = loader.introspectorFromName("l-interface"); + lint.setValue("interface-name", "lint"); + + Introspector sriovVf = loader.introspectorFromName("sriov-vf"); + sriovVf.setValue("pci-id", "sriov-vf"); + + Introspector sriovVfs = loader.introspectorFromName("sriov-vfs"); + sriovVfs.setValue("sriov-vf", Collections.singletonList(sriovVf.getUnderlyingObject())); + lint.setValue("sriov-vfs", sriovVfs.getUnderlyingObject()); + + Introspector lintA = loader.introspectorFromName("l-interface"); + lintA.setValue("interface-name", "lint-a"); + + Introspector sriovVfA = loader.introspectorFromName("sriov-vf"); + sriovVfA.setValue("pci-id", "sriov-vf-a"); + + sriovVfs = loader.introspectorFromName("sriov-vfs"); + sriovVfs.setValue("sriov-vf", Collections.singletonList(sriovVfA.getUnderlyingObject())); + lintA.setValue("sriov-vfs", sriovVfs.getUnderlyingObject()); + + Introspector lints = loader.introspectorFromName("l-interfaces"); + lints.setValue("l-interface", Arrays.asList(lint.getUnderlyingObject(), lintA.getUnderlyingObject())); + gvnf.setValue("l-interfaces", lints.getUnderlyingObject()); + + + System.out.println(gvnf.marshal(true)); + Vertex gvnfV = serializer.createNewVertex(gvnf); + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfAUri)); + serializer.serializeToDb(gvnf, gvnfV, uriQuery, "generic-vnf", gvnf.marshal(false)); + + assertTrue("generic-vnf-a created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, gvnfAUri) + .hasNext()); + assertTrue("l-int created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lintUri) + .hasNext()); + assertTrue("l-int-a created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lintAUri) + .hasNext()); + assertTrue("sriov-vf created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, sriovVfUri) + .hasNext()); + assertTrue("sriov-vf-a created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, sriovVfAUri) + .hasNext()); + + + gvnf = loader.introspectorFromName("generic-vnf"); + gvnf.setValue("vnf-id", "gvnf-b" + SOURCE_OF_TRUTH); + gvnf.setValue("vnf-name", "gvnf" + SOURCE_OF_TRUTH + "-name"); + + lint = loader.introspectorFromName("l-interface"); + lint.setValue("interface-name", "lint-b"); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-link", sriovVfUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + lint.setValue("relationship-list", relationshipList.getUnderlyingObject()); + + lints = loader.introspectorFromName("l-interfaces"); + lints.setValue("l-interface", Collections.singletonList(lint.getUnderlyingObject())); + gvnf.setValue("l-interfaces", lints.getUnderlyingObject()); + + gvnfV = serializer.createNewVertex(gvnf); + uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfAUri)); + serializer.serializeToDb(gvnf, gvnfV, uriQuery, "generic-vnf", gvnf.marshal(false)); + + engine.tx().traversal().V().forEachRemaining(v -> System.out.println(v.<String>value(AAIProperties.AAI_URI))); + assertTrue("generic-vnf-b created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, gvnfBUri) + .hasNext()); + assertTrue("l-int-b created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lIntBUri) + .hasNext()); + assertTrue("l-interface relationship sriov-vf created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lIntBUri) + .both() + .has(AAIProperties.AAI_URI, sriovVfUri) + .hasNext()); + + } + + + @Test + public void verifyReadOfGenericVnfATest() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfALatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfAUri).next()).marshal(false); + + assertThat(gvnfALatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*]", + hasSize(2) + )); + assertThat(gvnfALatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].sriov-vfs.sriov-vf[*]", + hasSize(2) + )); + assertThat(gvnfALatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].sriov-vfs.sriov-vf[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + lIntBUri + ) + )); + } + + @Test + public void verifyReadOfGenericVnfBTest() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfBLatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfBUri).next()).marshal(false); + + assertThat(gvnfBLatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*]", + hasSize(1) + )); + assertThat(gvnfBLatestView, + not(hasJsonPath( + "$.l-interfaces.l-interface[*].sriov-vfs.sriov-vf[*]" + ))); + assertThat(gvnfBLatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + sriovVfUri + ) + )); + } + + @Test + public void replaceRelationshipToSriovVfTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + Introspector lint = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, lIntBUri).next()); + String lintView = lint.marshal(false); + + assertThat(lintView, + hasJsonPath( + "$.relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + sriovVfUri + ) + )); + + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-link", sriovVfAUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + lint.setValue("relationship-list", relationshipList.getUnderlyingObject()); + + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(lIntBUri)); + serializer.serializeToDb(lint, engine.tx().traversal().V().has(AAIProperties.AAI_URI, lIntBUri).next(), + uriQuery, "generic-vnf", lint.marshal(false)); + } + + + @Test + public void createRelationshipForNonExistentRuleTest() throws AAIException, UnsupportedEncodingException, URISyntaxException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + Vertex gvnfAV = engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfAUri).next(); + Introspector gvnfA = serializer.getLatestVersionView(gvnfAV); + Introspector relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-link", gvnfBUri); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", Collections.singletonList(relationship.getUnderlyingObject())); + gvnfA.setValue("relationship-list", relationshipList.getUnderlyingObject()); + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfAUri)); + try { + serializer.serializeToDb(gvnfA, gvnfAV, uriQuery, "generic-vnf", gvnfA.marshal(false)); + } catch (AAIException e) { + assertEquals("AAI_6120", e.getCode()); + assertThat(e.getMessage(), containsString("generic-vnf")); + } + } + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/db/VersionedScenariosTest.java b/aai-core/src/test/java/org/onap/aai/serialization/db/VersionedScenariosTest.java new file mode 100644 index 00000000..8e77c549 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/db/VersionedScenariosTest.java @@ -0,0 +1,426 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.db; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphFactory; +import org.junit.*; +import org.junit.rules.ExpectedException; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.edges.EdgeIngestor; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Introspector; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.parsers.query.QueryParser; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static com.jayway.jsonpath.matchers.JsonPathMatchers.hasJsonPath; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class VersionedScenariosTest extends AAISetup { + + // to use, set thrown.expect to whatever your test needs + // this line establishes default of expecting no exception to be thrown + @Rule + public ExpectedException thrown = ExpectedException.none(); + + protected static Graph graph; + + @Autowired + protected EdgeSerializer edgeSer; + @Autowired + protected EdgeIngestor ei; + + private SchemaVersion version; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private Loader loader; + private TransactionalGraphEngine engine; + + public QueryStyle queryStyle = QueryStyle.TRAVERSAL_URI; + + public static final String SOURCE_OF_TRUTH = "VersionedScenariosTest"; + private static final String gvnfUri = "/network/generic-vnfs/generic-vnf/gvnf" + SOURCE_OF_TRUTH; + private static final String llDefaultUri = "/network/logical-links/logical-link/llDefault"; + private static final String lintSourceUri = gvnfUri + "/l-interfaces/l-interface/source"; + private static final String lintDestinationUri = gvnfUri + "/l-interfaces/l-interface/destination"; + private static final String llLabeledUri = "/network/logical-links/logical-link/llLabeled"; + + @BeforeClass + public static void init() { + graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open(); + + } + + @Before + public void setup() throws UnsupportedEncodingException, AAIException, URISyntaxException { + version = schemaVersions.getDefaultVersion(); + loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version); + engine = new JanusGraphDBEngine(queryStyle, loader); + initData(); + } + + @After + public void cleanup() { + engine.rollback(); + } + + /** + * Using latest version (see schema-ingest.properties) + * Create generic-vnf with l-interfaces source, destination + * Create logical-link with relationship to interfaces source, destination (will use the default labels) + * Create logical-link with relationship to interfaces source, destination with specific labels + */ + private void initData() throws UnsupportedEncodingException, AAIException, URISyntaxException { + engine.startTransaction(); + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + + Introspector gvnf = loader.introspectorFromName("generic-vnf"); + gvnf.setValue("vnf-id", "gvnf" + SOURCE_OF_TRUTH); + gvnf.setValue("vnf-name", "gvnf" + SOURCE_OF_TRUTH + "-name"); + + Introspector lintSource = loader.introspectorFromName("l-interface"); + lintSource.setValue("interface-name", "source"); + + Introspector lintDestination = loader.introspectorFromName("l-interface"); + lintDestination.setValue("interface-name", "destination"); + + List<Object> lIntList = new ArrayList<>(); + lIntList.add(lintSource.getUnderlyingObject()); + lIntList.add(lintDestination.getUnderlyingObject()); + Introspector lints = loader.introspectorFromName("l-interfaces"); + lints.setValue("l-interface", lIntList); + gvnf.setValue("l-interfaces", lints.getUnderlyingObject()); + + Vertex gvnfV = serializer.createNewVertex(gvnf); + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfUri)); + serializer.serializeToDb(gvnf, gvnfV, uriQuery, "generic-vnf", gvnf.marshal(false)); + + assertTrue("generic-vnf created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, gvnfUri) + .hasNext()); + assertTrue("source created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lintSourceUri) + .hasNext()); + assertTrue("destination created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, lintDestinationUri) + .hasNext()); + + + + Introspector llDefault = loader.introspectorFromName("logical-link"); + llDefault.setValue("link-name", "llDefault"); + List<Object> relList = new ArrayList<>(); + Introspector relationship = loader.introspectorFromName("relationship"); + //relationship.setValue("related-to", "l-interface"); + relationship.setValue("related-link", lintSourceUri); + relList.add(relationship.getUnderlyingObject()); + relationship = loader.introspectorFromName("relationship"); + //relationship.setValue("related-to", "l-interface"); + relationship.setValue("related-link", lintDestinationUri); + relList.add(relationship.getUnderlyingObject()); + Introspector relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", relList); + llDefault.setValue("relationship-list", relationshipList.getUnderlyingObject()); + + Vertex llDefaultV = serializer.createNewVertex(llDefault); + uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(llDefaultUri)); + serializer.serializeToDb(llDefault, llDefaultV, uriQuery, "logical-link", llDefault.marshal(false)); + + assertTrue("logical-link created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llDefaultUri) + .hasNext()); + assertTrue("default source relationship created",engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llDefaultUri) + .both() + .has(AAIProperties.AAI_URI, lintSourceUri) + .hasNext()); + assertTrue("default destination relationship created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llDefaultUri) + .both() + .has(AAIProperties.AAI_URI, lintDestinationUri) + .hasNext()); + + + Introspector llLabeled = loader.introspectorFromName("logical-link"); + llLabeled.setValue("link-name", "llLabeled"); + relList = new ArrayList<>(); + relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "l-interface"); + relationship.setValue("relationship-label", "org.onap.relationships.inventory.Source"); + relationship.setValue("related-link", lintSourceUri); + relList.add(relationship.getUnderlyingObject()); + relationship = loader.introspectorFromName("relationship"); + relationship.setValue("related-to", "l-interface"); + relationship.setValue("relationship-label", "org.onap.relationships.inventory.Destination"); + relationship.setValue("related-link", lintDestinationUri); + relList.add(relationship.getUnderlyingObject()); + relationshipList = loader.introspectorFromName("relationship-list"); + relationshipList.setValue("relationship", relList); + llLabeled.setValue("relationship-list", relationshipList.getUnderlyingObject()); + + Vertex llLabeledV = serializer.createNewVertex(llLabeled); + uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(llLabeledUri)); + serializer.serializeToDb(llLabeled, llLabeledV, uriQuery, "logical-link", llLabeled.marshal(false)); + + assertTrue("logical-link created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llLabeledUri) + .hasNext()); + assertTrue("labeled source relationship created",engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llLabeledUri) + .both("org.onap.relationships.inventory.Source") + .has(AAIProperties.AAI_URI, lintSourceUri) + .hasNext()); + assertTrue("labeled destination relationship created", engine.tx().traversal().V() + .has(AAIProperties.AAI_URI, llLabeledUri) + .both("org.onap.relationships.inventory.Destination") + .has(AAIProperties.AAI_URI, lintDestinationUri) + .hasNext()); + } + + + @Test + public void verifyRelsOfLatestViewOfGenericVnf() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfLatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfUri).next()).marshal(false); + assertThat(gvnfLatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*]", + hasSize(4) + )); + assertThat(gvnfLatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + llDefaultUri, + "/aai/" + schemaVersions.getDefaultVersion() + llDefaultUri, + "/aai/" + schemaVersions.getDefaultVersion() + llLabeledUri, + "/aai/" + schemaVersions.getDefaultVersion() + llLabeledUri + ) + )); + assertThat(gvnfLatestView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].relationship-label", + containsInAnyOrder( + "tosca.relationships.network.LinksTo", + "tosca.relationships.network.LinksTo", + "org.onap.relationships.inventory.Source", + "org.onap.relationships.inventory.Destination") + )); + } + + @Test + public void verifyRelsOfLatestViewOfLLDefault() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String llDefaultLatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, llDefaultUri).next()).marshal(false); + assertThat(llDefaultLatestView, + hasJsonPath( + "$.relationship-list.relationship[*]", + hasSize(2) + )); + assertThat(llDefaultLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + lintSourceUri, + "/aai/" + schemaVersions.getDefaultVersion() + lintDestinationUri + ) + )); + assertThat(llDefaultLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].relationship-label", + containsInAnyOrder("tosca.relationships.network.LinksTo","tosca.relationships.network.LinksTo") + )); + assertThat(llDefaultLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].relationship-label", + not(contains("org.onap.relationships.inventory.Source", "org.onap.relationships.inventory.Destination")) + )); + + } + + @Test + public void verifyRelsOfLatestViewOfLLLabeled() throws AAIException, UnsupportedEncodingException { + DBSerializer serializer = new DBSerializer(version, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String llLabeledLatestView = serializer.getLatestVersionView( + engine.tx().traversal().V().has(AAIProperties.AAI_URI, llLabeledUri).next()).marshal(false); + assertThat(llLabeledLatestView, + hasJsonPath( + "$.relationship-list.relationship[*]", + hasSize(2) + )); + assertThat(llLabeledLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + schemaVersions.getDefaultVersion() + lintSourceUri, + "/aai/" + schemaVersions.getDefaultVersion() + lintDestinationUri + ) + )); + assertThat(llLabeledLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].relationship-label", + not(containsInAnyOrder("tosca.relationships.network.LinksTo","tosca.relationships.network.LinksTo")) + )); + assertThat(llLabeledLatestView, + hasJsonPath( + "$.relationship-list.relationship[*].relationship-label", + contains("org.onap.relationships.inventory.Source", "org.onap.relationships.inventory.Destination") + )); + + } + + + @Test + public void verifyRelsOfOldViewOfGenericVnf() throws AAIException, UnsupportedEncodingException { + SchemaVersion oldVersion = new SchemaVersion("v11"); + Loader oldLoader = loaderFactory.getLoaderStrategy(introspectorFactoryType, oldVersion); + DBSerializer oldSerializer = new DBSerializer(oldVersion, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String gvnfOldView = oldSerializer.dbToObject( + Collections.singletonList(engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfUri).next()), + oldLoader.introspectorFromName("generic-vnf"), + AAIProperties.MAXIMUM_DEPTH, false, "false") + .marshal(false); + assertThat(gvnfOldView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*]", + hasSize(2) + )); + assertThat(gvnfOldView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].relationship-label", + emptyCollectionOf(String.class) + )); + assertThat(gvnfOldView, + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + oldVersion + llDefaultUri, + "/aai/" + oldVersion + llDefaultUri + ) + )); + } + + @Test + public void verifyRelsOfOldViewOfLLDefault() throws AAIException, UnsupportedEncodingException { + SchemaVersion oldVersion = new SchemaVersion("v11"); + Loader oldLoader = loaderFactory.getLoaderStrategy(introspectorFactoryType, oldVersion); + DBSerializer oldSerializer = new DBSerializer(oldVersion, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String llDefaultOldView = oldSerializer.dbToObject( + Collections.singletonList(engine.tx().traversal().V().has(AAIProperties.AAI_URI, llDefaultUri).next()), + oldLoader.introspectorFromName("logical-link"), + AAIProperties.MAXIMUM_DEPTH, false, "false") + .marshal(false); + assertThat(llDefaultOldView, + hasJsonPath( + "$.relationship-list.relationship[*]", + hasSize(2) + )); + assertThat(llDefaultOldView, + hasJsonPath( + "$.relationship-list.relationship[*].relationship-label", + emptyCollectionOf(String.class) + )); + assertThat(llDefaultOldView, + hasJsonPath( + "$.relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + oldVersion + lintSourceUri, + "/aai/" + oldVersion + lintDestinationUri + ) + )); + + } + + @Test + public void verifyRelsOfOldViewOfLLLabeled() throws AAIException, UnsupportedEncodingException { + SchemaVersion oldVersion = new SchemaVersion("v11"); + Loader oldLoader = loaderFactory.getLoaderStrategy(introspectorFactoryType, oldVersion); + DBSerializer oldSerializer = new DBSerializer(oldVersion, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + String llLabeledtOldView = oldSerializer.dbToObject( + Collections.singletonList(engine.tx().traversal().V().has(AAIProperties.AAI_URI, llLabeledUri).next()), + oldLoader.introspectorFromName("logical-link"), + AAIProperties.MAXIMUM_DEPTH, false, "false") + .marshal(false); + assertThat(llLabeledtOldView, + not(hasJsonPath( + "$.relationship-list.relationship[*]" + ))); + } + + + @Test + public void useOldVersionToUpdatedGenericVnfAndVerifyLatestVersionRels() throws AAIException, UnsupportedEncodingException, URISyntaxException { + SchemaVersion oldVersion = new SchemaVersion("v11"); + Loader oldLoader = loaderFactory.getLoaderStrategy(introspectorFactoryType, oldVersion); + DBSerializer oldSerializer = new DBSerializer(oldVersion, engine, introspectorFactoryType, SOURCE_OF_TRUTH, AAIProperties.MINIMUM_DEPTH); + + Vertex oldGvnfV = engine.tx().traversal().V().has(AAIProperties.AAI_URI, gvnfUri).next(); + Introspector oldGvnf = oldSerializer.dbToObject( + Collections.singletonList(oldGvnfV), + oldLoader.introspectorFromName("generic-vnf"), + AAIProperties.MAXIMUM_DEPTH, false, "false"); + assertThat(oldGvnf.marshal(false), + hasJsonPath( + "$.l-interfaces.l-interface[*].relationship-list.relationship[*].related-link", + containsInAnyOrder( + "/aai/" + oldVersion + llDefaultUri, + "/aai/" + oldVersion + llDefaultUri + ) + )); + oldGvnf.setValue("in-maint", true); + QueryParser uriQuery = engine.getQueryBuilder().createQueryFromURI(new URI(gvnfUri)); + oldSerializer.serializeToDb(oldGvnf, oldGvnfV, uriQuery, "generic-vnf", oldGvnf.marshal(false)); + + verifyRelsOfLatestViewOfGenericVnf(); + verifyRelsOfOldViewOfGenericVnf(); + } + + + + +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/AggregateFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/AggregateFormatTest.java new file mode 100644 index 00000000..0b6ffd9e --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/AggregateFormatTest.java @@ -0,0 +1,136 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.serialization.queryformats; + +import com.google.gson.JsonObject; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.AAISetup; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.db.EdgeSerializer; +import org.onap.aai.serialization.engines.JanusGraphDBEngine; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; +import org.onap.aai.setup.SchemaVersion; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; + +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class AggregateFormatTest extends AAISetup { + + @Mock + private UrlBuilder urlBuilder; + + private Graph graph; + private TransactionalGraphEngine dbEngine; + private Loader loader; + private Aggregate aggregate; + private final ModelType factoryType = ModelType.MOXY; + + @Autowired + private EdgeSerializer rules; + + private SchemaVersion version; + private Vertex pserver; + private Vertex complex; + + @Before + public void setUp() throws Exception { + + version = schemaVersions.getDefaultVersion(); + + MockitoAnnotations.initMocks(this); + + graph = TinkerGraph.open(); + + Vertex pserver1 = + graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "hostname-1"); + Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", + "physical-location-id", "physical-location-id-1", "country", "US"); + + GraphTraversalSource g = graph.traversal(); + rules.addEdge(g, pserver1, complex1); + + pserver = pserver1; + complex = complex1; + + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + + createLoaderEngineSetup(); + } + + private void createLoaderEngineSetup() throws AAIException { + + if (loader == null) { + loader = loaderFactory.createLoaderForVersion(factoryType, version); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); + DBSerializer serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); + aggregate = new Aggregate.Builder(loader, serializer, urlBuilder).build(); + + TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); + + when(dbEngine.tx()).thenReturn(graph); + when(dbEngine.asAdmin()).thenReturn(spyAdmin); + + when(spyAdmin.getReadOnlyTraversalSource()) + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); + when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); + } + } + + @Test + public void run() throws AAIFormatVertexException { + assertNotNull(dbEngine.tx()); + System.out.println(dbEngine.tx()); + assertNotNull(graph.traversal()); + JsonObject json = aggregate.createPropertiesObject(pserver).get(); + json.entrySet().forEach((System.out::println)); + assertTrue(json.has("hostname")); + assertFalse(json.has("node-type")); + Map<String, List<String>> propMap = new HashMap<>(); + List<String> selectedProps = new ArrayList<String>( Arrays.asList("'physical-location-id'")); + propMap.put("complex",selectedProps); + JsonObject json1 = aggregate.createSelectedPropertiesObject(complex, propMap).get(); + json1.entrySet().forEach((System.out::println)); + assertFalse(json1.has("country")); + assertTrue(json1.has("physical-location-id")); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java index a2976e0c..e128c2f6 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/CountQuerySupportTest.java @@ -20,15 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - import com.google.gson.JsonObject; - -import java.util.Arrays; -import java.util.List; - import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -38,10 +30,8 @@ import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -52,10 +42,16 @@ import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported; import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.onap.aai.serialization.queryformats.utils.UrlBuilder; import org.onap.aai.setup.SchemaVersion; import org.springframework.beans.factory.annotation.Autowired; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + public class CountQuerySupportTest extends AAISetup { @Autowired @@ -147,7 +143,7 @@ public class CountQuerySupportTest extends AAISetup { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, version); // loader = LoaderFactory.createLoaderForVersion(factoryType, version); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); ff = new FormatFactory(loader, serializer, schemaVersions, basePath); @@ -159,7 +155,7 @@ public class CountQuerySupportTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java index 847a45ed..22b500f8 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/GraphSONTest.java @@ -26,8 +26,8 @@ import static org.hamcrest.core.IsNot.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.gson.JsonArray; import com.google.gson.JsonObject; @@ -63,7 +63,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @DirtiesContext public class GraphSONTest { - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(GraphSONTest.class); + private static final Logger LOGGER = LoggerFactory.getLogger(GraphSONTest.class); private Graph graph; private Vertex v1; @@ -111,7 +111,7 @@ public class GraphSONTest { /** * Case where there is only one private edge - * + * * <pre> * { * "id": 21, @@ -167,7 +167,7 @@ public class GraphSONTest { /** * Case where there is one private edge and regular edge * with the same edge label name - * + * * <pre> * { * "id": 21, @@ -230,7 +230,7 @@ public class GraphSONTest { /** * Case where there is one private edge and regular edge to same label * And another regular edge to a different label - * + * * <pre> * { * "id": 21, @@ -328,7 +328,7 @@ public class GraphSONTest { /** * Case where there is one private edge and regular edge to same label * And another regular edge to a different label - * + * * <pre> * { * "id": 21, @@ -395,7 +395,7 @@ public class GraphSONTest { /** * Case where there is one private edge and regular edge to same label * And another regular edge to a different label - * + * * <pre> * { * "id": 21, diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java index 9ac79ca8..a59b1147 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/MultiFormatTest.java @@ -20,15 +20,8 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.*; - import com.google.gson.JsonObject; import com.google.gson.JsonParser; - -import java.io.UnsupportedEncodingException; - import org.apache.tinkerpop.gremlin.process.traversal.Path; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; @@ -42,10 +35,10 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; +import org.onap.aai.serialization.db.DBSerializer; import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; @@ -57,6 +50,13 @@ import org.onap.aai.setup.SchemaVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; +import javax.ws.rs.core.MultivaluedHashMap; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.*; + @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class MultiFormatTest extends AAISetup { @@ -79,7 +79,12 @@ public class MultiFormatTest extends AAISetup { private JsonObject expectedPathIdFormat = new JsonParser().parse( "{\"path\":[{\"resource-type\":\"generic-vnf\"},{\"resource-type\":\"vserver\"},{\"resource-type\":\"pserver\"},{\"resource-type\":\"complex\"}]}") .getAsJsonObject(); - + private JsonObject expectedAsTreeWithResourceFormat = new JsonParser().parse( + "{\"results\":[{\"generic-vnf\":{\"vnf-id\":\"vnf-id-1\",\"vnf-name\":\"vnf-name-1\",\"related-nodes\":[{\"vserver\":{\"vserver-id\":\"vserver-id-1\",\"vserver-name\":\"vserver-name-1\",\"related-nodes\":[{\"pserver\":{\"hostname\":\"hostname-1\"}}]}},{\"pserver\":{\"hostname\":\"hostname-2\",\"related-nodes\":[{\"complex\":{\"physical-location-id\":\"physical-location-id-2\",\"country\":\"US\"}}]}}]}}]}") + .getAsJsonObject(); + private JsonObject expectedAsTreeWithSimpleFormat = new JsonParser().parse( + "{\"results\":[{\"id\":\"0\",\"node-type\":\"generic-vnf\",\"url\":null,\"properties\":{\"vnf-id\":\"vnf-id-1\",\"vnf-name\":\"vnf-name-1\"},\"related-to\":[{\"id\":\"1\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"vserver\",\"url\":null},{\"id\":\"5\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"pserver\",\"url\":null}],\"related-nodes\":[{\"id\":\"1\",\"node-type\":\"vserver\",\"url\":null,\"properties\":{\"vserver-id\":\"vserver-id-1\",\"vserver-name\":\"vserver-name-1\"},\"related-to\":[{\"id\":\"0\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"generic-vnf\",\"url\":null},{\"id\":\"2\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"pserver\",\"url\":null}],\"related-nodes\":[{\"id\":\"2\",\"node-type\":\"pserver\",\"url\":null,\"properties\":{\"hostname\":\"hostname-1\"},\"related-to\":[{\"id\":\"1\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"vserver\",\"url\":null},{\"id\":\"3\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\",\"node-type\":\"complex\",\"url\":null}]}]},{\"id\":\"5\",\"node-type\":\"pserver\",\"url\":null,\"properties\":{\"hostname\":\"hostname-2\"},\"related-to\":[{\"id\":\"0\",\"relationship-label\":\"tosca.relationships.HostedOn\",\"node-type\":\"generic-vnf\",\"url\":null},{\"id\":\"6\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\",\"node-type\":\"complex\",\"url\":null}],\"related-nodes\":[{\"id\":\"6\",\"node-type\":\"complex\",\"url\":null,\"properties\":{\"physical-location-id\":\"physical-location-id-2\",\"country\":\"US\"},\"related-to\":[{\"id\":\"5\",\"relationship-label\":\"org.onap.relationships.inventory.LocatedIn\",\"node-type\":\"pserver\",\"url\":null}]}]}]}]}") + .getAsJsonObject(); @Before public void setUp() throws Exception { @@ -130,6 +135,42 @@ public class MultiFormatTest extends AAISetup { } @Test + public void testAsTreeParamAndSimpleFormat() + throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { + + createLoaderEngineSetup(); + DBSerializer serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); + MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>(); + params.add("as-tree", "true"); + SimpleFormat sf = new SimpleFormat(new RawFormat.Builder(loader, serializer, urlBuilder).isTree(true)); + + assertNotNull(dbEngine.tx()); + assertNotNull(dbEngine.asAdmin()); + + JsonObject json = sf.formatObject(resultTree).get(); + assertEquals(this.expectedAsTreeWithSimpleFormat, json); + + } + + @Test + public void testAsTreeParamAndResourceFormat() + throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { + + createLoaderEngineSetup(); + DBSerializer serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); + MultivaluedHashMap<String, String> params = new MultivaluedHashMap<>(); + params.add("as-tree", "true"); + Resource sf = new Resource(new Resource.Builder(loader, serializer, urlBuilder, params).isTree(true)); + + assertNotNull(dbEngine.tx()); + assertNotNull(dbEngine.asAdmin()); + + JsonObject json = sf.formatObject(resultTree).get(); + assertEquals(this.expectedAsTreeWithResourceFormat, json); + } + + + @Test public void testPathResultQueryIdFormat() throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { @@ -159,7 +200,7 @@ public class MultiFormatTest extends AAISetup { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, version); // loader = LoaderFactory.createLoaderForVersion(factoryType, version); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); @@ -167,7 +208,7 @@ public class MultiFormatTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java index 03990b1d..f05e36dd 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java @@ -46,7 +46,7 @@ public class QueryFormatTestHelper { public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException { Answer<String> answer = new Answer<String>() { public String answer(InvocationOnMock invocation) throws Throwable { - Vertex v = invocation.getArgument(0); + Vertex v = invocation.getArgumentAt(0, Vertex.class); return v.<String>property(AAIProperties.AAI_URI).orElse("urimissing"); } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java index 2d8c66c3..f88de4fb 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/RawFormatTest.java @@ -20,10 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - +import com.google.gson.JsonObject; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; @@ -35,7 +32,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -44,13 +40,18 @@ import org.onap.aai.serialization.db.EdgeSerializer; import org.onap.aai.serialization.engines.JanusGraphDBEngine; import org.onap.aai.serialization.engines.QueryStyle; import org.onap.aai.serialization.engines.TransactionalGraphEngine; -import org.onap.aai.serialization.queryformats.exceptions.AAIFormatQueryResultFormatNotSupported; import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; import org.onap.aai.serialization.queryformats.utils.UrlBuilder; import org.onap.aai.setup.SchemaVersion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class RawFormatTest extends AAISetup { @@ -70,8 +71,6 @@ public class RawFormatTest extends AAISetup { private Vertex pserver; private Vertex complex; - private DBSerializer serializer; - @Before public void setUp() throws Exception { @@ -100,39 +99,34 @@ public class RawFormatTest extends AAISetup { @Test public void verifyPserverRelatedToHasEdgeLabel() - throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { - assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("relationship-label") - .getAsString().equals("org.onap.relationships.inventory.LocatedIn")); + throws AAIFormatVertexException { + assertEquals("org.onap.relationships.inventory.LocatedIn", rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("relationship-label").getAsString()); } @Test public void verifyPserverRelatedToComplexLabel() - throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { - assertTrue(rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("node-type").getAsString() - .equals("complex")); + throws AAIFormatVertexException { + assertEquals("complex", rawFormat.createRelationshipObject(pserver).get(0).getAsJsonObject().get("node-type").getAsString()); } @Test public void verifyComplexRelatedToHasEdgeLabel() - throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { - assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("relationship-label") - .getAsString().equals("org.onap.relationships.inventory.LocatedIn")); + throws AAIFormatVertexException { + assertEquals("org.onap.relationships.inventory.LocatedIn", rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("relationship-label").getAsString()); } @Test public void verifyComplexRelatedToPserverLabel() - throws AAIFormatVertexException, AAIException, AAIFormatQueryResultFormatNotSupported { - assertTrue(rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("node-type").getAsString() - .equals("pserver")); + throws AAIFormatVertexException { + assertEquals("pserver", rawFormat.createRelationshipObject(complex).get(0).getAsJsonObject().get("node-type").getAsString()); } - public void createLoaderEngineSetup() throws AAIException { + private void createLoaderEngineSetup() throws AAIException { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, version); - // loader = LoaderFactory.createLoaderForVersion(factoryType, version); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); - serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); + DBSerializer serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); rawFormat = new RawFormat.Builder(loader, serializer, urlBuilder).build(); TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); @@ -141,8 +135,27 @@ public class RawFormatTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } + + @Test + public void run() throws AAIFormatVertexException { + assertNotNull(dbEngine.tx()); + System.out.println(dbEngine.tx()); + assertNotNull(graph.traversal()); + JsonObject json = rawFormat.createPropertiesObject(pserver).get(); + json.entrySet().forEach((System.out::println)); + assertTrue(json.has("hostname")); + Map<String, List<String>> propMap = new HashMap<>(); + List<String> selectedProps = new ArrayList<String>( Arrays.asList("'physical-location-id'")); + propMap.put("complex",selectedProps); + JsonObject json1 = rawFormat.createSelectedPropertiesObject(complex, propMap).get(); + json1.entrySet().forEach((System.out::println)); + assertFalse(json1.has("aai-node-type")); + assertTrue(json1.has("physical-location-id")); + } + + } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java index 1a301b33..a891230c 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java @@ -20,18 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.*; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - import com.google.gson.JsonObject; - -import java.util.Arrays; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; @@ -42,7 +31,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -54,6 +42,14 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti import org.onap.aai.serialization.queryformats.utils.UrlBuilder; import org.springframework.test.annotation.DirtiesContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.util.Arrays; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class ResourceFormatTest extends AAISetup { @@ -144,7 +140,7 @@ public class ResourceFormatTest extends AAISetup { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getAppRootVersion()); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); @@ -152,7 +148,7 @@ public class ResourceFormatTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java index 75fe6ec6..c2e5f814 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/ResourceWithSoTTest.java @@ -20,15 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - import com.google.gson.JsonObject; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -38,7 +30,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -50,6 +41,10 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti import org.onap.aai.serialization.queryformats.utils.UrlBuilder; import org.onap.aai.setup.SchemaVersion; +import static org.junit.Assert.*; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + public class ResourceWithSoTTest extends AAISetup { @Mock private UrlBuilder urlBuilder; @@ -79,7 +74,7 @@ public class ResourceWithSoTTest extends AAISetup { graph = TinkerGraph.open(); - Long currentTimeMs = System.currentTimeMillis(); + long currentTimeMs = System.currentTimeMillis(); String timeNowInMs = Long.toString(currentTimeMs); // PUT / CREATE @@ -119,8 +114,7 @@ public class ResourceWithSoTTest extends AAISetup { // This test is to simulate a PUT request @Test public void testGetJsonFromVertexWithCreateVertex() throws AAIFormatVertexException, AAIException { - if (putVertex == null) - assertTrue("The vertex used for this test is null. Fail immediately.", false); + if (putVertex == null) fail("The vertex used for this test is null. Fail immediately."); JsonObject json = resourceWithSoT.getJsonFromVertex(putVertex).get(); assertEquals(jsonPutObj, json); @@ -129,10 +123,8 @@ public class ResourceWithSoTTest extends AAISetup { // This test is to simulate PATCH requests @Test public void testGetJsonFromVertexWithModifyVertex() throws AAIFormatVertexException, AAIException { - if (patchVertex1 == null) - assertTrue("The vertex 1 used for this test is null. Fail immediately.", false); - if (patchVertex2 == null) - assertTrue("The vertex 2 used for this test is null. Fail immediately.", false); + if (patchVertex1 == null) fail("The vertex 1 used for this test is null. Fail immediately."); + if (patchVertex2 == null) fail("The vertex 2 used for this test is null. Fail immediately."); // Differing Source of Truths will indicate that the action performed modified the vertex JsonObject json1 = resourceWithSoT.getJsonFromVertex(patchVertex1).get(); @@ -155,7 +147,7 @@ public class ResourceWithSoTTest extends AAISetup { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, version); // loader = LoaderFactory.createLoaderForVersion(factoryType, version); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); serializer = new DBSerializer(version, dbEngine, factoryType, "Junit"); resourceWithSoT = new ResourceWithSoT.Builder(loader, serializer, urlBuilder).build(); @@ -165,7 +157,7 @@ public class ResourceWithSoTTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java index ab899c01..886a660b 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/SimpleFormatTest.java @@ -20,22 +20,7 @@ package org.onap.aai.serialization.queryformats; -import static org.junit.Assert.*; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.*; - import com.google.gson.JsonObject; - -import java.io.UnsupportedEncodingException; -import java.util.Arrays; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.T; @@ -47,7 +32,6 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.aai.AAISetup; -import org.onap.aai.dbmap.DBConnectionType; import org.onap.aai.exceptions.AAIException; import org.onap.aai.introspection.Loader; import org.onap.aai.introspection.ModelType; @@ -60,6 +44,15 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti import org.onap.aai.serialization.queryformats.utils.UrlBuilder; import org.springframework.test.annotation.DirtiesContext; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import java.io.UnsupportedEncodingException; +import java.util.Arrays; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) public class SimpleFormatTest extends AAISetup { @@ -182,7 +175,7 @@ public class SimpleFormatTest extends AAISetup { if (loader == null) { loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getRelatedLinkVersion()); - dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.CACHED, loader)); + dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader)); TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin()); @@ -190,7 +183,7 @@ public class SimpleFormatTest extends AAISetup { when(dbEngine.asAdmin()).thenReturn(spyAdmin); when(spyAdmin.getReadOnlyTraversalSource()) - .thenReturn(graph.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()))); + .thenReturn(graph.traversal().withStrategies(ReadOnlyStrategy.instance())); when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal()); } } diff --git a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java index 0b689d88..f039d7cb 100644 --- a/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java +++ b/aai-core/src/test/java/org/onap/aai/serialization/queryformats/utils/QueryParamInjectorTest.java @@ -48,11 +48,11 @@ public class QueryParamInjectorTest { MockitoAnnotations.initMocks(this); QueryParamInjector injector = QueryParamInjector.getInstance(); - Builder b = new Builder(loader, serializer, urlBuilder); MultivaluedMap<String, String> params = new MultivaluedHashMap<>(); params.putSingle("nodesOnly", "true"); params.putSingle("depth", "10"); params.putSingle("invalid", "1000"); + Builder b = new Builder(loader, serializer, urlBuilder, params); injector.injectParams(b, params); assertEquals("is nodes only", true, b.isNodesOnly()); diff --git a/aai-core/src/test/java/org/onap/aai/stress/IndexStressTest.java b/aai-core/src/test/java/org/onap/aai/stress/IndexStressTest.java new file mode 100644 index 00000000..143004ac --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/stress/IndexStressTest.java @@ -0,0 +1,132 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.aai.stress; + +import org.apache.commons.lang.RandomStringUtils; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraphTransaction; +import org.junit.Before; +import org.junit.Test; +import org.junit.Ignore; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.annotation.DirtiesContext; + +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; + +@Ignore("Run this only to test indexes limit") +@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) +public class IndexStressTest extends AAISetup { + + private static final Logger LOGGER = LoggerFactory.getLogger(IndexStressTest.class); + + @Before + public void setup(){ + AAIGraph.getInstance().getGraph(); + } + + @Test + public void testIndexStress(){ + JanusGraphTransaction tx = AAIGraph.getInstance().getGraph().newTransaction(); + + GraphTraversalSource g = tx.traversal(); + + Set<String> linkNameSet = new HashSet<>(); + Set<String> aaiUriSet = new HashSet<>(); + + int TOTAL_LINKS = 101000; + + for(int i = 0; i <TOTAL_LINKS; i++){ + + String linkName = generateName(linkNameSet); + aaiUriSet.add("/network/logical-links/logical-link/" + linkName); + + Vertex v = g.addV() + .property("aai-node-type", "logical-link") + .property("link-name", linkName) + .property("aai-uri", "/network/logical-links/logical-link/" + linkName) + .next(); + + if(i % 1000 == 0){ + LOGGER.debug("Committing up to index {}", i); + tx.commit(); + tx = AAIGraph.getInstance().getGraph().newTransaction(); + g = tx.traversal(); + } + } + + tx.commit(); + + tx = AAIGraph.getInstance().getGraph().newTransaction(); + g = tx.traversal(); + + int totalLinks= 0; + int totalLinksWithNodeType = 0; + int totalLinksUsingUri = 0; + + int index = 0; + for (String linkName : linkNameSet) { + + if(g.V().has("aai-node-type", "logical-link").has("link-name", linkName).hasNext()){ + totalLinksWithNodeType++; + } + + if(g.V().has("link-name", linkName).hasNext()){ + totalLinks++; + } + + if(g.V().has("aai-uri", "/network/logical-links/logical-link/" + linkName).hasNext()){ + totalLinksUsingUri++; + } + + index++; + + if(index%1000 == 0){ + LOGGER.debug("Processed {} many queries and has {} many to go", index, (TOTAL_LINKS-index)); + LOGGER.debug("Total links using linkname found: {}", totalLinks); + LOGGER.debug("Total links using nodetype and linkname found: {}", totalLinksWithNodeType); + LOGGER.debug("Total links using uri found: {}", totalLinksUsingUri); + } + } + + tx.rollback(); + + LOGGER.debug("Total links using linkname found: {}", totalLinks); + LOGGER.debug("Total links using nodetype and linkname found: {}", totalLinksWithNodeType); + LOGGER.debug("Total links using uri found: {}", totalLinksUsingUri); + } + + String generateName(Set<String> uniqueKeys){ + + while(true) { + String data = RandomStringUtils.randomAlphabetic(20); + if (!uniqueKeys.contains(data)){ + uniqueKeys.add(data); + return data; + } + } + } +} diff --git a/aai-core/src/test/java/org/onap/aai/transforms/XmlFormatTransformerTest.java b/aai-core/src/test/java/org/onap/aai/transforms/XmlFormatTransformerTest.java new file mode 100644 index 00000000..6d6ae194 --- /dev/null +++ b/aai-core/src/test/java/org/onap/aai/transforms/XmlFormatTransformerTest.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.transforms; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.PayloadUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + +public class XmlFormatTransformerTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(XmlFormatTransformerTest.class); + + private XmlFormatTransformer xmlFormatTransformer; + + @Before + public void setup(){ + this.xmlFormatTransformer = new XmlFormatTransformer(); + } + + @Test + public void testTransformJsonToXml() throws IOException { + + String input = PayloadUtil.getResourcePayload("transform-results-to-result.json"); + String expected = PayloadUtil.getExpectedPayload("transform-json-to-xml.xml"); + // Remove all the whitespace in the xml + expected = expected.replaceAll("\\s", ""); + + LOGGER.debug("Converting the following input to xml: {}", input); + String output = xmlFormatTransformer.transform(input); + + LOGGER.debug("Converted xml payload: {}", output); + assertThat(output, is(expected)); + } +} diff --git a/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java b/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java deleted file mode 100644 index 2e870f6e..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/FileWatcherTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.util; - -import static org.junit.Assert.*; - -import java.io.File; - -import org.junit.Test; -import org.mockito.Mockito; - -public class FileWatcherTest { - - class FileWatcherExtension extends FileWatcher { - - public FileWatcherExtension(File file) { - super(file); - } - - @Override - protected void onChange(File file) { - System.out.println("do nothing"); - } - } - - @Test - public void testFileWatcher() { - File file = new File("helloworld"); - file.setLastModified(new Long(123)); - FileWatcher fileWatcher = new FileWatcherExtension(file); - assertNotNull(fileWatcher); - file.deleteOnExit(); - } - - @Test(expected = NullPointerException.class) - public void testFileWatcher_nullConstructor() { - FileWatcher fileWatcher = new FileWatcherExtension(null); - assertNull(fileWatcher); - } - - @Test - public void testRun() { - // verify that code is reachable outside of conditional check in run() - File file = new File("helloworld"); - file.setLastModified(new Long(100)); - FileWatcher fileWatcher = new FileWatcherExtension(file); - fileWatcher.run(); - file.deleteOnExit(); - } - - @Test - public void testOnChange() throws Exception { - FileWatcher fileWatcher = Mockito.mock(FileWatcher.class, Mockito.CALLS_REAL_METHODS); - - File file=Mockito.mock(File.class); - fileWatcher.onChange(file); - - Mockito.verify(fileWatcher).onChange(file); - - } -} diff --git a/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java b/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java deleted file mode 100644 index 33da9c04..00000000 --- a/aai-core/src/test/java/org/onap/aai/util/MapperUtilTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright © 2018 IBM. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.aai.util; - -import static org.junit.Assert.assertEquals; - -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; - -public class MapperUtilTest { - - private JSONObject expectedJson; - private JSONObject sampleJson; - - @Before - public void setup() { - expectedJson = new JSONObject(); - sampleJson = new JSONObject(); - } - - @Test - public void writeAsJSONStringTest() throws Exception { - expectedJson.put("color", "black"); - expectedJson.put("shape", "box"); - SampleClass sample = new SampleClass("black", "box"); - assertEquals(expectedJson.toString(), MapperUtil.writeAsJSONString(sample)); - } - - @Test - public void readAsObjectOfTest() throws Exception { - sampleJson.put("color", "black"); - sampleJson.put("shape", "box"); - SampleClass expectedObject = new SampleClass("black", "box"); - SampleClass actualObject = MapperUtil.readAsObjectOf(SampleClass.class, sampleJson.toString()); - assertEquals(expectedObject.getColor(), actualObject.getColor()); - assertEquals(expectedObject.getShape(), actualObject.getShape()); - } -} - - -class SampleClass { - private String color; - private String shape; - - public SampleClass() { - - } - - public SampleClass(String c, String s) { - color = c; - shape = s; - } - - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - - public String getShape() { - return shape; - } - - public void setShape(String shape) { - this.shape = shape; - } -} diff --git a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java index 08cbba20..b4b8810e 100644 --- a/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java +++ b/aai-core/src/test/java/org/onap/aai/util/StoreNotificationEventTest.java @@ -66,19 +66,19 @@ public class StoreNotificationEventTest extends AAISetup { @Test(expected = AAIException.class) public void testStoreEventNullObj() throws AAIException { - sne.storeEvent(new EventHeader(), null); + sne.storeEventAndSendToJms(new EventHeader(), null); } @Test(expected = AAIException.class) public void testStoreEventInvalidObjForPojoUtils() throws AAIException { - sne.storeEvent(new EventHeader(), new Object()); + sne.storeEventAndSendToJms(new EventHeader(), new Object()); } @Test public void testStoreEventEmptyEventHeader() throws AAIException, JsonGenerationException, JsonMappingException, IOException { JsonObject object = Json.createObjectBuilder().add("hello", "world").build(); - String res = sne.storeEvent(new EventHeader(), object); + String res = sne.storeEventAndSendToJms(new EventHeader(), object); assertNotNull(res); assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); @@ -118,7 +118,7 @@ public class StoreNotificationEventTest extends AAISetup { eh.setSeverity("ALERT"); eh.setVersion("v12"); - String res = sne.storeEvent(eh, object); + String res = sne.storeEventAndSendToJms(eh, object); assertNotNull(res); assertTrue(res.contains("\"cambria.partition\" : \"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); @@ -161,7 +161,7 @@ public class StoreNotificationEventTest extends AAISetup { @Test(expected = AAIException.class) public void testStoreEventIntrospectorNullObj() throws Exception { Loader loader = Mockito.mock(Loader.class); - sne.storeEvent(loader, null, null); + sne.storeEventAndSendToJms(loader, null, null); } @Ignore("Stopped working since the model driven story") @@ -180,7 +180,7 @@ public class StoreNotificationEventTest extends AAISetup { eventHeader.setValue("severity", "ALERT"); eventHeader.setValue("version", "v12"); Introspector obj = loader.introspectorFromName("notification-event"); - String res = sne.storeEvent(loader, eventHeader, obj); + String res = sne.storeEventAndSendToJms(loader, eventHeader, obj); assertNotNull(res); assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); @@ -205,7 +205,7 @@ public class StoreNotificationEventTest extends AAISetup { Introspector eventHeader = loader.introspectorFromName("notification-event-header"); Introspector obj = loader.introspectorFromName("notification-event"); - String res = sne.storeEvent(loader, eventHeader, obj); + String res = sne.storeEventAndSendToJms(loader, eventHeader, obj); assertNotNull(res); assertTrue(res.contains("\"cambria.partition\":\"" + AAIConstants.UEB_PUB_PARTITION_AAI + "\"")); |