diff options
Diffstat (limited to 'ajsc-aai/src/test/java/org/openecomp')
41 files changed, 10298 insertions, 0 deletions
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/ActionsGraphTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/ActionsGraphTest.java new file mode 100644 index 0000000..dd4d750 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/ActionsGraphTest.java @@ -0,0 +1,2485 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.dbmap; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.Matchers.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.mockito.stubbing.OngoingStubbing; +import org.openecomp.aai.dbgen.DbMeth; +import org.openecomp.aai.dbmap.AAIGraph; +import org.openecomp.aai.dbmap.ActionsGraph; +import org.openecomp.aai.dbmap.GraphHelpersMoxy; +import org.openecomp.aai.domain.model.AAIResource; +import org.openecomp.aai.domain.model.AAIResources; +import org.openecomp.aai.domain.model.AncestryItem; +import org.openecomp.aai.domain.model.AncestryItems; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.extensions.AAIExtensionMap; +import org.openecomp.aai.ingestModel.DbMaps; +import org.openecomp.aai.ingestModel.IngestModelMoxyOxm; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.AAILogger; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAIConstants; +import org.openecomp.aai.util.HttpsAuthClient; +import org.openecomp.aai.util.RestController; +import org.openecomp.aai.util.RestObject; +import org.openecomp.aai.util.RestURL; +import org.openecomp.aai.util.StoreNotificationEvent; + +import static org.powermock.api.support.membermodification.MemberMatcher.constructor; +import static org.powermock.api.support.membermodification.MemberModifier.suppress; + + +import static org.mockito.Mockito.*; + +import org.powermock.api.mockito.PowerMockito; + +import static org.powermock.api.mockito.PowerMockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; +import static org.powermock.api.mockito.PowerMockito.when; + +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.powermock.reflect.internal.WhiteboxImpl; +import org.eclipse.persistence.dynamic.DynamicClassLoader; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.dynamic.DynamicHelper; +import org.eclipse.persistence.dynamic.DynamicType; +import org.eclipse.persistence.internal.dynamic.DynamicEntityImpl; +import org.eclipse.persistence.jaxb.BeanValidationMode; +import org.eclipse.persistence.jaxb.JAXBContext; +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.eclipse.persistence.jaxb.JAXBContextProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; +import org.eclipse.persistence.jaxb.metadata.MetadataSource; +import org.eclipse.persistence.jaxb.metadata.MetadataSourceAdapter; +import org.eclipse.persistence.jpa.dynamic.JPADynamicTypeBuilder; +import org.eclipse.persistence.sessions.DatabaseSession; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.eclipse.persistence.sessions.Project; +import org.eclipse.persistence.sessions.DatabaseLogin; +import org.eclipse.persistence.sessions.DatabaseSession; + +import org.openecomp.aai.domain.yang.GenericVnf; +import org.openecomp.aai.domain.yang.UpdateNodeKey; +import com.google.common.collect.ArrayListMultimap; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanTransaction; +import com.thinkaurelius.titan.core.TitanVertex; + +@RunWith(PowerMockRunner.class) + +@PrepareForTest({DynamicEntity.class, AAIGraph.class, ActionsGraph.class, TitanGraph.class, TitanVertex.class, DbMeth.class, + GraphHelpersMoxy.class, RestURL.class, AAIResource.class, AAIExtensionMap.class, DynamicJAXBContext.class, + StoreNotificationEvent.class, AAIException.class, RestObject.class, RestController.class, + HttpsAuthClient.class, Client.class, ClientResponse.class}) +@SuppressStaticInitializationFor("com.sun.jersey.api.client.ClientResponse") +@PowerMockIgnore( {"javax.management.*"}) + +public class ActionsGraphTest { + + //@Rule + //public PowerMockRule rule = new PowerMockRule(); + + DynamicJAXBContext jaxbContext; + static String defaultApiVersion = null; + static String latestC25version = "v6"; + + private static class SequenceAnswer<T> implements Answer<T> { + + + private Iterator<T> resultIterator; + + // the last element is always returned once the iterator is exhausted, as with thenReturn() + private T last; + + /** + * Instantiates a new sequence answer. + * + * @param results the results + */ + public SequenceAnswer(List<T> results) { + this.resultIterator = results.iterator(); + this.last = results.get(results.size() - 1); + } + + /** + * {@inheritDoc} + */ + //@Override + public T answer(InvocationOnMock invocation) throws Throwable { + if (resultIterator.hasNext()) { + return resultIterator.next(); + } + return last; + } + } + + + + /** + * Sets the up before class. + * + * @throws Exception the exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + try { + defaultApiVersion = AAIConfig.get("aai.default.api.version"); + //System.out.println("defaultApiVersion " + defaultApiVersion); + } catch ( Exception e) { + fail("aaiconfig.properties for aai.default.api.version exception " + e.getMessage()); + } + + //PowerMockito.mockStatic(IngestModelMoxyOxm.class); + //IngestModelMoxyOxm ingestModelMoxyOxmMock = PowerMockito.mock(IngestModelMoxyOxm.class); + + DbMaps dbMaps = new DbMaps(); + + dbMaps.NodeProps.put("customer", "global-customer-id"); + dbMaps.NodeProps.put("customer", "subscriber-name"); + dbMaps.NodeProps.put("service-subscription", "service-type"); + dbMaps.NodeProps.put("service-subscription", "temp-ub-sub-account-id"); + dbMaps.NodeProps.put("cloud-region", "region-owner"); + dbMaps.NodeProps.put("cloud-region", "cloud-region-id"); + dbMaps.NodeProps.put("volume-group", "volume-group-id"); + dbMaps.NodeProps.put("volume-group", "heat-stack-id"); + dbMaps.NodeProps.put("generic-vnf", "vnf-id"); + dbMaps.NodeProps.put("generic-vnf", "prov-status"); + dbMaps.NodeProps.put("vpe", "vnf-id"); + dbMaps.NodeProps.put("vpe", "prov-status"); + dbMaps.NodeProps.put("generic-vnf", "something-else"); + + dbMaps.PropertyDataTypeMap.put("global-customer-id", "String"); + dbMaps.PropertyDataTypeMap.put("subscriber-name", "String"); + dbMaps.PropertyDataTypeMap.put("service-type", "String"); + dbMaps.PropertyDataTypeMap.put("temp-ub-sub-account-id", "String"); + dbMaps.PropertyDataTypeMap.put("cloud-owner", "String"); + dbMaps.PropertyDataTypeMap.put("cloud-region-id", "String"); + dbMaps.PropertyDataTypeMap.put("volume-group-id", "String"); + dbMaps.PropertyDataTypeMap.put("heat-stack-id", "String"); + dbMaps.PropertyDataTypeMap.put("vnf-id", "String"); + dbMaps.PropertyDataTypeMap.put("prov-status", "String"); + dbMaps.PropertyDataTypeMap.put("something-else", "String"); + + HashMap<String, DbMaps> dbMapsContainerMock = new HashMap<String, DbMaps>(); + dbMapsContainerMock.put(defaultApiVersion, dbMaps); + dbMapsContainerMock.put(latestC25version, dbMaps); + + IngestModelMoxyOxm.dbMapsContainer = dbMapsContainerMock; + + HashMap<String, AAIResources> aaiResourceContainerMock = new HashMap<String, AAIResources>(); + AAIResources aaiResources = new AAIResources(); + + aaiResourceContainerMock.put(defaultApiVersion, aaiResources); + IngestModelMoxyOxm.aaiResourceContainer = aaiResourceContainerMock; + + } + + /** + * Tear down after class. + * + * @throws Exception the exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + * Sets the up. + * + * @throws Exception the exception + */ + @Before + public void setUp() throws Exception { + + } + + /** + * Tear down. + * + * @throws Exception the exception + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test property update with update node key. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked" }) + @Test + public void testPropertyUpdate_withUpdateNodeKey() throws Exception { + + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("customer"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + DynamicEntity keyData1DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + + keyData1DynamicEntity.set("keyName", "global-customer-id"); + keyData1DynamicEntity.set("keyValue", "globalCustomerIdVal"); + updateNodeKeyList.add(keyData1DynamicEntity); + + DynamicEntity keyData2DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + keyData2DynamicEntity.set("keyName", "service-subscription"); + keyData2DynamicEntity.set("keyValue", "serviceTypeVal"); + //updateNodeKeyList.add(keyData2DynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "subscriber-name"); + actionDataDynamicEntity.set("propertyValue", "newName"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + // not dependent + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn(""); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update with dependent update node key. + * + * @throws Exception the exception + */ + @Test + public void testPropertyUpdate_withDependentUpdateNodeKey() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("service-subscription"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + DynamicEntity keyData1DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + keyData1DynamicEntity.set("keyName", "customer.global-customer-id"); + keyData1DynamicEntity.set("keyValue", "globalCustomerIdVal"); + updateNodeKeyList.add(keyData1DynamicEntity); + + DynamicEntity keyData2DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + keyData2DynamicEntity.set("keyName", "service-subscription"); + keyData2DynamicEntity.set("keyValue", "serviceTypeVal"); + updateNodeKeyList.add(keyData2DynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "temp-ub-sub-account-id"); + actionDataDynamicEntity.set("propertyValue", "tempUbSubAccountIdVal"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update with missing cloud region update node key. + * + * @throws Exception the exception + */ + @Test + public void testPropertyUpdate_withMissingCloudRegionUpdateNodeKey() throws Exception { + + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + latestC25version + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + latestC25version + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + latestC25version + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("volume-group"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + DynamicEntity keyData1DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + keyData1DynamicEntity.set("keyName", "volume-group-id"); + keyData1DynamicEntity.set("keyValue", "volumeGroupIdVal"); + updateNodeKeyList.add(keyData1DynamicEntity); + + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "heat-stack-id"); + actionDataDynamicEntity.set("propertyValue", "heatStackIdVal"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(latestC25version); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn(""); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update with dependent update node uri. + * + * @throws Exception the exception + */ + @Test + public void testPropertyUpdate_withDependentUpdateNodeUri() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("service-subscription"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("business/customers/customer/globalCustomerIdVal/service-subscriptions/service-subscription/serviceTypeVal"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "service-subscription.service-type"; + String nodeKeyValue = "serviceTypeVal"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + String depNodeKeyName = "customer.global-customer-id"; + String depNodeKeyValue = "globalCustomerIdVal"; + depNodeHash.put(depNodeKeyName, depNodeKeyValue); + returnHash.putAll(depNodeHash); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "temp-ub-sub-account-id"); + actionDataDynamicEntity.set("propertyValue", "tempUbSubAccountIdVal"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update with missing cloud region dependent update node uri. + * + * @throws Exception the exception + */ + @Test + public void testPropertyUpdate_withMissingCloudRegionDependentUpdateNodeUri() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + latestC25version + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + latestC25version + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + latestC25version + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("volume-group"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("cloud-infrastructure/volume-groups/volume-group/volumeGroupIdValue"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "volume-group.volume-group-id"; + String nodeKeyValue = "volumeGroupIdVal"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + String depNodeKeyName = "cloud-region.cloud-owner"; + String depNodeKeyValue = "cloudOwnerVal"; + String depNodeKeyName1 = "cloud-region.cloud-region-id"; + String depNodeKeyValue1 = "cloudRegionIdVal"; + depNodeHash.put(depNodeKeyName, depNodeKeyValue); + depNodeHash.put(depNodeKeyName1, depNodeKeyValue1); + returnHash.putAll(depNodeHash); + + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "heat-stack-id"); + actionDataDynamicEntity.set("propertyValue", "heatStackIdVal"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(latestC25version); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("cloud-region"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update generic vnf prov status PREPRO vwith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_GenericVnfProvStatusPREPROVwithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "PREPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update generic vnf prov status XY zwith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_GenericVnfProvStatusXYZwithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("XYZ"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "NVTPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update invalid action typewith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_InvalidActionTypewithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "PREPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "not-replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + try { + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + fail( "expected exception"); + } catch ( Exception e ) { + assertNotNull(e); + } + + } + + /** + * Test property update udefined propertywith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_UdefinedPropertywithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "x-prov-status"); + actionDataDynamicEntity.set("propertyValue", "PREPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + try { + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + fail( "expected exception"); + } catch ( Exception e ) { + assertNotNull(e); + } + + } + + /** + * Test property update invalid node typewith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_InvalidNodeTypewithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("x-generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "PREPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "not-replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + try { + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + fail( "expected exception"); + } catch ( Exception e ) { + assertNotNull(e); + } + + } + + /** + * Test property update missing node typewith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_MissingNodeTypewithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn(null); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "PREPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "not-replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + try { + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + fail( "expected exception"); + } catch ( Exception e ) { + assertNotNull(e); + } + + } + + /** + * Test property update with key params empty update node key. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked" }) + @Test + public void testPropertyUpdate_withKeyParamsEmptyUpdateNodeKey() throws Exception { + + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("customer"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + DynamicEntity keyData1DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + + keyData1DynamicEntity.set("keyName", "global-customer-id"); + keyData1DynamicEntity.set("keyValue", "globalCustomerIdVal"); + //updateNodeKeyList.add(keyData1DynamicEntity); + + DynamicEntity keyData2DynamicEntity = dynamicHelper.newDynamicEntity(classNameUpdateNodeKey); + keyData2DynamicEntity.set("keyName", "service-subscription"); + keyData2DynamicEntity.set("keyValue", "serviceTypeVal"); + //updateNodeKeyList.add(keyData2DynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "subscriber-name"); + actionDataDynamicEntity.set("propertyValue", "newName"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + // not dependent + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn(""); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + try { + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + fail( "expected exception"); + } catch ( Exception e ) { + assertNotNull(e); + } + + assertTrue("return from propertyUpdate", true); + + } + + + /** + * Test property update generic vnf not prov statuswith update node URI. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_GenericVnfNotProvStatuswithUpdateNodeURI() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + + PowerMockito.mockStatic(RestController.class); + PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "something-else"); + actionDataDynamicEntity.set("propertyValue", "somethingElseValue"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + assertTrue("return from propertyUpdate", true); + + } + + /** + * Test property update exception from get vnf. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testPropertyUpdate_exceptionFromGetVnf() throws Exception { + String classNameUpdateNodeKey = "inventory.aai.openecomp.org." + defaultApiVersion + ".UpdateNodeKey"; + String classNameAction = "inventory.aai.openecomp.org." + defaultApiVersion + ".Action"; + String classNameActionData = "inventory.aai.openecomp.org." + defaultApiVersion + ".ActionData"; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.whenNew(AAIGraph.class).withAnyArguments().thenReturn(graphMock); + PowerMockito.whenNew(AAIGraph.class).withNoArguments().thenReturn(graphMock); + + LogLineBuilder llb = new LogLineBuilder(); + + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + + + + PowerMockito.mockStatic(RestController.class); + //PowerMockito.doNothing().when( RestController.class, "Get", Mockito.anyObject(), anyString(), + //anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + PowerMockito.doThrow(new AAIException()).when( RestController.class, "Get", Mockito.anyObject(), anyString(), + anyString(), anyString(), Mockito.anyObject(), anyBoolean()); + + RestObject<GenericVnf> mockRestObject = PowerMockito.mock(RestObject.class); + PowerMockito.whenNew(RestObject.class).withNoArguments().thenReturn(mockRestObject); + PowerMockito.doNothing().when( mockRestObject).set(isA(GenericVnf.class)); + GenericVnf genericVnf = new GenericVnf(); + genericVnf.setEquipmentRole("VRR"); + genericVnf.setVnfName("vnfNameValue"); + + PowerMockito.when(mockRestObject.get()).thenReturn(genericVnf); + + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + PowerMockito.mockStatic(DbMeth.class); + DbMeth dbMethMock = PowerMockito.mock(DbMeth.class); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + + when(dynamicEntityMock.<String>get("updateNodeType")).thenReturn("generic-vnf"); + + when(dynamicEntityMock.<String>get("updateNodeUri")).thenReturn("network/generic-vnfs/generic-vnf/vnfId"); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> updateNodeKeyClass = dcl.createDynamicClass(classNameUpdateNodeKey); + JPADynamicTypeBuilder updateNodeKey = new JPADynamicTypeBuilder(updateNodeKeyClass, null, "D_UPDATE_NODE_KEY"); + updateNodeKey.addDirectMapping("keyName", String.class, "KEY_NAME"); + updateNodeKey.addDirectMapping("keyValue", String.class, "KEY_VALUE"); + DynamicType type = updateNodeKey.getType(); + dynamicHelper.addTypes(false, false, type); + + + ArrayList <DynamicEntity> updateNodeKeyList = new ArrayList<DynamicEntity>(); + + LinkedHashMap <String,Object> returnHash = new LinkedHashMap<String,Object>(); + + HashMap <String,Object> thisNodeHash = new HashMap <String,Object> (); + String nodeKeyName = "generic-vnf.vnf-id"; + String nodeKeyValue = "vnfId"; + thisNodeHash.put(nodeKeyName, nodeKeyValue); + returnHash.putAll(thisNodeHash); + + HashMap <String,Object> depNodeHash = new HashMap <String,Object> (); + + PowerMockito.mockStatic(RestURL.class); + //RestURL restURLMock = PowerMockito.mock(RestURL.class); + + PowerMockito.when(( RestURL.getKeyHashes(anyString()))).thenReturn(returnHash); + + when(dynamicEntityMock.<List<DynamicEntity>>get("updateNodeKey")).thenReturn(updateNodeKeyList); + + Class<?> actionDataClass = dcl.createDynamicClass(classNameActionData); + + Class<?> actionClass = dcl.createDynamicClass(classNameAction); + JPADynamicTypeBuilder action = new JPADynamicTypeBuilder(actionClass, null, "D_ACTION"); + action.addDirectMapping("actionType", String.class, "ACTION_TYPE"); + action.addDirectMapping("actionData", ArrayList.class, "ACTION_DATA"); + + type = action.getType(); + dynamicHelper.addTypes(false, false, type); + + + JPADynamicTypeBuilder actionData = new JPADynamicTypeBuilder(actionDataClass, action.getType(), "D_ACTION_DATA"); + actionData.addDirectMapping("propertyName", String.class, "PROPERTY_NAME"); + actionData.addDirectMapping("propertyValue", String.class, "PROPERTY_VALUE"); + + type = actionData.getType(); + dynamicHelper.addTypes(false, false, type); + + ArrayList <DynamicEntity> actionDataList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDataDynamicEntity = dynamicHelper.newDynamicEntity(classNameActionData); + actionDataDynamicEntity.set("propertyName", "prov-status"); + actionDataDynamicEntity.set("propertyValue", "NVTPROV"); + actionDataList.add(actionDataDynamicEntity); + + ArrayList <DynamicEntity> actionList = new ArrayList<DynamicEntity>(); + + DynamicEntity actionDynamicEntity = dynamicHelper.newDynamicEntity(classNameAction); + actionDynamicEntity.set("actionType", "replace"); + actionDynamicEntity.set("actionData", actionDataList); + + actionList.add(actionDynamicEntity); + + when(dynamicEntityMock.<List<DynamicEntity>>get("action")).thenReturn(actionList); + + AAIExtensionMap aaiExtensionMapMock = PowerMockito.mock(AAIExtensionMap.class); + + when(aaiExtensionMapMock.getApiVersion()).thenReturn(defaultApiVersion); + + PowerMockito.when(( DbMeth.figureDepNodeTypeForRequest(anyString(), anyString(), anyString(), + isA(HashMap.class), anyString()))).thenReturn("customer"); + + PowerMockito.when(( DbMeth.getUniqueNodeWithDepParams(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), anyString()))).thenReturn(vMock); + + PowerMockito.when(( DbMeth.patchAaiNode(anyString(), anyString(), isA(TitanTransaction.class), anyString(), + isA(HashMap.class), isA(TitanVertex.class), anyString()))).thenReturn(vMock); + + + ActionsGraph actionsGraph = new ActionsGraph(); + + ActionsGraph actionsGraphSpy = PowerMockito.spy(actionsGraph); + + PowerMockito.doReturn("updateNodeURLValue").when(actionsGraphSpy, "setupUEBEventObject", + anyString(), anyString(), Mockito.any(TitanTransaction.class), anyString(), + Mockito.any(TitanVertex.class), anyString()); + + PowerMockito.doNothing().when(actionsGraphSpy, "triggerInstarEquipStatusUpdate", + anyString(), anyString(), anyString()); + + actionsGraphSpy.propertyUpdate("fromAppId", "transId", dynamicEntityMock, aaiExtensionMapMock); + + + assertTrue("return from propertyUpdate", true); + + } + + + + /** + * Test setup UEB event object. + * + * @throws Exception the exception + */ + @Test + public void testSetupUEBEventObject() throws Exception{ + String classNameNotificationEventHeader = "inventory.aai.openecomp.org." + defaultApiVersion + ".NotificationEventHeader"; + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + TitanVertex vMock = PowerMockito.mock(TitanVertex.class); + + GraphHelpersMoxy graphHelpersMoxyMock = PowerMockito.mock(GraphHelpersMoxy.class); + PowerMockito.whenNew( GraphHelpersMoxy.class).withNoArguments().thenReturn(graphHelpersMoxyMock); + + PowerMockito.when(graphHelpersMoxyMock.isEventEnabled(anyString(), anyString(), anyString())).thenReturn(true); + + AncestryItems ancestryItemsMock = PowerMockito.mock(AncestryItems.class); + PowerMockito.whenNew( AncestryItems.class).withNoArguments().thenReturn(ancestryItemsMock); + + AncestryItem ancestryItem = new AncestryItem(); + AAIResource aaiResource = new AAIResource(); + aaiResource.setSimpleName("resourceSimpleNameValue"); + ancestryItem.setAaiResource(aaiResource); + LinkedHashMap<String, AncestryItem> map = new LinkedHashMap<String, AncestryItem>(); + map.put("key", ancestryItem); + when (ancestryItemsMock.getAncestryItems()).thenReturn(map); + + + PowerMockito.mockStatic(RestURL.class); + RestURL restURLMock = PowerMockito.mock(RestURL.class); + + AAIResource aaiResourceMock = PowerMockito.mock(AAIResource.class); + //AAIResources aaiResourcesMock = PowerMockito.mock(AAIResources.class); + + DynamicJAXBContext dynamicJAXBContextMock = PowerMockito.mock(DynamicJAXBContext.class); + + AAIResources aaiResourcesMock = IngestModelMoxyOxm.aaiResourceContainer.get(defaultApiVersion); + aaiResourcesMock.setJaxbContext(dynamicJAXBContextMock); + + StoreNotificationEvent storeNotificationEventMock = PowerMockito.mock(StoreNotificationEvent.class); + PowerMockito.whenNew( StoreNotificationEvent.class).withNoArguments().thenReturn(storeNotificationEventMock); + + PowerMockito.doNothing().when( storeNotificationEventMock).storeDynamicEvent(isA(DynamicJAXBContext.class), anyString(), isA(DynamicEntity.class), + isA(DynamicEntity.class)); + + Project project = new Project(new DatabaseLogin()); + DatabaseSession databaseSession = project.createDatabaseSession(); + DynamicHelper dynamicHelper = new DynamicHelper(databaseSession); + + DynamicClassLoader dcl = dynamicHelper.getDynamicClassLoader(); + + Class<?> notificationEventHeaderClass = dcl.createDynamicClass(classNameNotificationEventHeader); + JPADynamicTypeBuilder notificationEventHeader = new JPADynamicTypeBuilder(notificationEventHeaderClass, null, "D_NOTIFICATION_EVENT_HEADER"); + notificationEventHeader.addDirectMapping("entityType", String.class, "ENTITY_TYPE"); + notificationEventHeader.addDirectMapping("action", String.class, "ACTION"); + notificationEventHeader.addDirectMapping("sourceName", String.class, "SOURCE_NAME"); + notificationEventHeader.addDirectMapping("version", String.class, "VERSION"); + notificationEventHeader.addDirectMapping("entityLink", String.class, "ENTITY_LINK"); + notificationEventHeader.addDirectMapping("topEntityType", String.class, "TOP_ENTITY_TYPE"); + DynamicType type = notificationEventHeader.getType(); + dynamicHelper.addTypes(false, false, type); + + DynamicEntity notificationEventHeaderDynamicEntity = dynamicHelper.newDynamicEntity(classNameNotificationEventHeader); + + + + //notificationEventHeaderDynamicEntity. + PowerMockito.when(graphHelpersMoxyMock.unpackAncestry(isA(TitanTransaction.class), isA(AncestryItems.class), anyString(), + isA(DynamicJAXBContext.class), isA(AAIExtensionMap.class))).thenReturn(notificationEventHeaderDynamicEntity); + + PowerMockito.when(dynamicJAXBContextMock.getDynamicType(anyString())).thenReturn(type); + + PowerMockito.when(( RestURL.get(isA(TitanTransaction.class), isA(TitanVertex.class), + anyString(), anyBoolean(), anyBoolean()))).thenReturn("updatedNodeURLValue"); + PowerMockito.when(( RestURL.parseUri(Mockito.any(HashMap.class), Mockito.any(LinkedHashMap.class), anyString(), + any(AAIExtensionMap.class)))).thenReturn(aaiResourceMock); + ActionsGraph actionsGraph = new ActionsGraph(); + String nodeUrl = actionsGraph.setupUEBEventObject("fromAppId", "transId", gMock, "updateNodeType", vMock, defaultApiVersion); + assertTrue("returned from setupUEBEvent", true); + } + + /** + * Test trigger instar equip status update. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void testTriggerInstarEquipStatusUpdate() throws Exception { + Client mockClient = mock( Client.class ); + WebResource mockWebResource = mock( WebResource.class ); + WebResource.Builder mockBuilder = mock( WebResource.Builder.class ); + PowerMockito.mockStatic(ClientResponse.class); + ClientResponse mockClientResponse = mock( ClientResponse.class ); + ActionsGraph actionsGraph = new ActionsGraph(); + PowerMockito.mockStatic(HttpsAuthClient.class); + HttpsAuthClient mockHttpsAuthClient = PowerMockito.mock(HttpsAuthClient.class); + when(mockHttpsAuthClient.getTwoWaySSLClient()).thenReturn(mockClient); + + when(mockClient.resource(anyString())).thenReturn(mockWebResource); + when(mockWebResource.header(anyString(), anyString())).thenReturn(mockBuilder); + when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder); + when(mockBuilder.accept(anyString())).thenReturn(mockBuilder); + + when(mockBuilder.put(eq(ClientResponse.class))).thenReturn(mockClientResponse); + when(mockClientResponse.getStatus()).thenReturn(200, 500); + // first call returns success + String msg= WhiteboxImpl.invokeMethod(actionsGraph, "triggerInstarEquipStatusUpdate", + "fromAppId", "transId", "urlValue"); + assertTrue("return from triggerInstarEquipStatusUpdate", true); + // 2nd call generates exception + try { + msg= WhiteboxImpl.invokeMethod(actionsGraph, "triggerInstarEquipStatusUpdate", + "fromAppId", "transId", "urlValue"); + fail("Exception expected"); + } catch ( Exception e ) { + assertNotNull(e); + } + } + +} + diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/SearchGraphTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/SearchGraphTest.java new file mode 100644 index 0000000..3a8fc5a --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/dbmap/SearchGraphTest.java @@ -0,0 +1,739 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.dbmap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; + +import javax.ws.rs.core.Response; + +import org.apache.tinkerpop.gremlin.process.traversal.Traversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.aai.dbgen.DbMeth; +import org.openecomp.aai.dbmap.AAIGraph; +import org.openecomp.aai.dbmap.SearchGraph; +import org.openecomp.aai.domain.model.AAIResources; +import org.openecomp.aai.extensions.AAIExtensionMap; +import org.openecomp.aai.ingestModel.DbMaps; +import org.openecomp.aai.ingestModel.IngestModelMoxyOxm; +import org.openecomp.aai.util.RestURL; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.rule.PowerMockRule; + +import com.google.common.collect.ArrayListMultimap; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanGraphQuery; +import com.thinkaurelius.titan.core.TitanTransaction; +import com.thinkaurelius.titan.core.TitanVertex; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AAIGraph.class, TitanGraph.class, DbMeth.class, IngestModelMoxyOxm.class, + AAIResources.class, DynamicJAXBContext.class, DynamicEntity.class, VertexProperty.class, + RestURL.class, TitanTransaction.class, TitanVertex.class, SearchGraph.class}) +@PowerMockIgnore("javax.management.*") +public class SearchGraphTest { +// @Rule +// public PowerMockRule rule = new PowerMockRule(); + + private String fromAppId = "searchGraphId"; + private String transId = "transId"; + private String aaiApiVersion = "v8"; + + /** + * Test run nodes query. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunNodesQuery() throws Exception { + String targetNodeType = "vserver"; + String nodePropsValue = "testNodePropsValue"; + List<String> edgeFilterParams = new ArrayList<String>(); + edgeFilterParams.add("pserver:EXISTS:hostname:test-pserver-hostname"); + List<String> filterParams = new ArrayList<String>(); + filterParams.add("vserver-name2:EXISTS:"); + String serverNodeURL = "testServerNodeURL"; + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph aaiGraphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(aaiGraphMock); + TitanGraph titanGraphMock = PowerMockito.mock(TitanGraph.class); + when(aaiGraphMock.getGraph()).thenReturn(titanGraphMock); + TitanTransaction titanTransactionMock = PowerMockito.mock(TitanTransaction.class); + when(titanGraphMock.newTransaction()).thenReturn(titanTransactionMock); + + HashMap<String, DbMaps> dbMapsContainer = new HashMap<String, DbMaps>(); + DbMaps dbMaps = new DbMaps(); + dbMaps.NodeProps = ArrayListMultimap.create(); + dbMaps.NodeProps.put(targetNodeType, nodePropsValue); + dbMapsContainer.put(aaiApiVersion, dbMaps); + IngestModelMoxyOxm.dbMapsContainer = dbMapsContainer; + + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(titanTransactionMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has("aai-node-type", targetNodeType)).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has("vserver-name2")).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorTitanVertexMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorTitanVertexMock); + when(iteratorTitanVertexMock.hasNext()).thenReturn(true, false); + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + when(iteratorTitanVertexMock.next()).thenReturn(titanVertexMock); + + Iterator<Vertex> iteratorVertexMock = (Iterator<Vertex>) PowerMockito.mock(Iterator.class); + when(titanVertexMock.vertices(Direction.BOTH, "runsOnPserver")).thenReturn(iteratorVertexMock); + when(iteratorVertexMock.hasNext()).thenReturn(true, false); + when(iteratorVertexMock.next()).thenReturn(titanVertexMock); + + VertexProperty<String> vertexPropertyMock = (VertexProperty<String>)PowerMockito.mock(VertexProperty.class); + when(titanVertexMock.<String>property("hostname")).thenReturn(vertexPropertyMock); + when(vertexPropertyMock.orElse(null)).thenReturn("test-pserver-hostname"); + when(vertexPropertyMock.equals("test-pserver-hostname")).thenReturn(true); + + PowerMockito.mockStatic(RestURL.class); + when(RestURL.getSearchUrl(Mockito.any(TitanTransaction.class), Mockito.any(TitanVertex.class), + Mockito.anyString())).thenReturn(serverNodeURL); + when(titanVertexMock.<String>property("aai-node-type")).thenReturn(vertexPropertyMock); + when(vertexPropertyMock.orElse(null)).thenReturn("pserver"); + + PowerMockito.mockStatic(IngestModelMoxyOxm.class); + HashMap<String, AAIResources> aaiResourceContainerMock = new HashMap<String, AAIResources>(); + AAIResources aaiResourcesMock = PowerMockito.mock(AAIResources.class); + aaiResourceContainerMock.put("v8", aaiResourcesMock); + IngestModelMoxyOxm.aaiResourceContainer = aaiResourceContainerMock; + DynamicJAXBContext dynamicJAXBContextMock = PowerMockito.mock(DynamicJAXBContext.class); + when(aaiResourcesMock.getJaxbContext()).thenReturn(dynamicJAXBContextMock); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + when(dynamicJAXBContextMock.newDynamicEntity(Mockito.anyString())).thenReturn(dynamicEntityMock); + + Response respMock = PowerMockito.mock(Response.class); + when(respMock.getStatus()).thenReturn(200); + + SearchGraph searchGraph = new SearchGraph(); + SearchGraph searchGraphSpy = PowerMockito.spy(searchGraph); + PowerMockito.doReturn(respMock).when(searchGraphSpy, "getResponseFromDynamicEntity", + Mockito.any(DynamicEntity.class), Mockito.any(DynamicJAXBContext.class), + Mockito.any(AAIExtensionMap.class)); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + Response resp = searchGraphSpy.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + assertEquals(200, resp.getStatus()); + } + + /** + * Test run nodes query exception. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunNodesQuery_exception() throws Exception { + String targetNodeType = ""; + String nodePropsValue = "testNodePropsValue"; + List<String> edgeFilterParams = new ArrayList<String>(); + edgeFilterParams.add("pserver:EXISTS:hostname:test-pserver-hostname"); + List<String> filterParams = new ArrayList<String>(); + filterParams.add("vserver-name2:EXISTS:"); + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph aaiGraphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(aaiGraphMock); + TitanGraph titanGraphMock = PowerMockito.mock(TitanGraph.class); + when(aaiGraphMock.getGraph()).thenReturn(titanGraphMock); + TitanTransaction titanTransactionMock = PowerMockito.mock(TitanTransaction.class); + when(titanGraphMock.newTransaction()).thenReturn(titanTransactionMock); + + HashMap<String, DbMaps> dbMapsContainer = new HashMap<String, DbMaps>(); + DbMaps dbMaps = new DbMaps(); + dbMaps.NodeProps = ArrayListMultimap.create(); + dbMaps.NodeProps.put(targetNodeType, nodePropsValue); + dbMapsContainer.put(aaiApiVersion, dbMaps); + IngestModelMoxyOxm.dbMapsContainer = dbMapsContainer; + + SearchGraph searchGraph = new SearchGraph(); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + + //targetNodeType is empty + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //dbMaps.NodeProps doesn't contain targetNodeType + targetNodeType = "vserver"; + dbMaps.NodeProps.clear(); + dbMaps.NodeProps.put("pserver", nodePropsValue); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //filterParams.isEmpty() && edgeFilterParams.isEmpty() + dbMaps.NodeProps.clear(); + dbMaps.NodeProps.put(targetNodeType, nodePropsValue); + edgeFilterParams.clear(); + filterParams.clear(); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //Exception : bad filter passed to node query + filterParams.add("vserver-name2"); + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(titanTransactionMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has("aai-node-type", targetNodeType)).thenReturn(titanGraphQueryMock); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //Exception - FilterType EQUALS - No value passed for filter + filterParams.clear(); + filterParams.add("vserver-name2:EQUALS"); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //Exception - FilterType DOES-NOT-EQUAL - No value passed for filter + filterParams.clear(); + filterParams.add("vserver-name2:DOES-NOT-EQUAL"); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //Exception - bad filterType passed + filterParams.clear(); + filterParams.add("vserver-name2:NOT-EQUAL"); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + when(titanGraphQueryMock.has("vserver-name2")).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorTitanVertexMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorTitanVertexMock); + + //Exception - bad filter passed. pieces.length = 3 + filterParams.clear(); + filterParams.add("vserver-name2:EXISTS:"); + edgeFilterParams.clear(); + edgeFilterParams.add("pserver:EXISTS:hostname"); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + //Exception - filterType - bad filterType passed + edgeFilterParams.clear(); + edgeFilterParams.add("pserver:NOT-EXIST:hostname:test-pserver-hostname"); + try { + searchGraph.runNodesQuery(fromAppId, transId, + targetNodeType, edgeFilterParams, filterParams, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + } + + /** + * Test run generic query service instance. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunGenericQuery_serviceInstance() throws Exception { + String startNodeType = "service-instance"; + String serviceSubscriptionURL = "testServiceSubscriptionURL"; + String startNodeKey = "service-instance-id"; + String startNodeValue = "test-service-instance-id"; + String startNodeKeyParam = "service-instance." + startNodeKey + ":" + startNodeValue; + + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(gMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has(startNodeKey, startNodeValue)).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorMock); + when(iteratorMock.hasNext()).thenReturn(true, false); + + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + when(iteratorMock.next()).thenReturn(titanVertexMock); + when(tMock.newTransaction()).thenReturn(gMock); + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.mockStatic(DbMeth.class); + VertexProperty<String> vertexPropertyMock = (VertexProperty<String>)PowerMockito.mock(VertexProperty.class); + when(titanVertexMock.<String>property("aai-node-type")).thenReturn(vertexPropertyMock); + when(vertexPropertyMock.orElse(null)).thenReturn(startNodeType); + + when(DbMeth.getUniqueNodeWithDepParams(Mockito.anyString(), Mockito.anyString(), + Mockito.any(TitanTransaction.class), Mockito.anyString(), (HashMap<String, Object>) + Mockito.anyMapOf(String.class, Object.class), Mockito.anyString())).thenReturn(titanVertexMock); + + PowerMockito.mockStatic(IngestModelMoxyOxm.class); + HashMap<String, AAIResources> aaiResourceContainerMock = new HashMap<String, AAIResources>(); + AAIResources aaiResourcesMock = PowerMockito.mock(AAIResources.class); + aaiResourceContainerMock.put("v8", aaiResourcesMock); + IngestModelMoxyOxm.aaiResourceContainer = aaiResourceContainerMock; + DynamicJAXBContext dynamicJAXBContextMock = PowerMockito.mock(DynamicJAXBContext.class); + when(aaiResourcesMock.getJaxbContext()).thenReturn(dynamicJAXBContextMock); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + when(dynamicJAXBContextMock.newDynamicEntity(Mockito.anyString())).thenReturn(dynamicEntityMock); + + PowerMockito.mockStatic(RestURL.class); + when(RestURL.getSearchUrl(Mockito.any(TitanTransaction.class), Mockito.any(TitanVertex.class), + Mockito.anyString())).thenReturn(serviceSubscriptionURL); + + Response respMock = PowerMockito.mock(Response.class); + when(respMock.getStatus()).thenReturn(200); + + SearchGraph searchGraph = new SearchGraph(); + SearchGraph searchGraphSpy = PowerMockito.spy(searchGraph); + PowerMockito.doReturn(respMock).when(searchGraphSpy, "getResponseFromDynamicEntity", Mockito.any(DynamicEntity.class), + Mockito.any(DynamicJAXBContext.class), Mockito.any(AAIExtensionMap.class)); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add(startNodeKeyParam); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + Response resp = searchGraphSpy.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + assertEquals(200, resp.getStatus()); + } + + /** + * Test run generic query service instance depth 1 vertex is empty. + * + * @throws Exception the exception + */ + @Ignore + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunGenericQuery_serviceInstance_depth1_vertexIsEmpty() throws Exception { + String startNodeType = "service-instance"; + String startNodeKey = "service-instance-id"; + String startNodeValue = "test-service-instance-id"; + String startNodeKeyParam = "service-instance." + startNodeKey + ":" + startNodeValue; + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(gMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has(startNodeKey, startNodeValue)).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorMock); + when(iteratorMock.hasNext()).thenReturn(true, false); + + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + when(iteratorMock.next()).thenReturn(titanVertexMock); + GraphTraversalSource graphTraversalSourceMock = PowerMockito.mock(GraphTraversalSource.class); + when(titanVertexMock.graph()).thenReturn(gMock); + when(gMock.traversal()).thenReturn(graphTraversalSourceMock); + + GraphTraversal graphTraversalMock = PowerMockito.mock(GraphTraversal.class); + when(graphTraversalSourceMock.V(titanVertexMock)).thenReturn(graphTraversalMock); + when(graphTraversalMock.repeat(Mockito.any(Traversal.class))).thenReturn(graphTraversalMock); + when(graphTraversalMock.times(1)).thenReturn(graphTraversalMock); + + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + when(tMock.newTransaction()).thenReturn(gMock); + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + SearchGraph searchGraph = new SearchGraph(); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add(startNodeKeyParam); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("l-interface"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + Response resp = searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 1, aaiExtMap); + assertNull(resp); + } + + /** + * Test run generic query service instance 6112 exception. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunGenericQuery_serviceInstance_6112Exception() throws Exception { + String startNodeType = "service-instance"; + String startNodeKey = "service-instance-id"; + String startNodeValue = "test-service-instance-id"; + String startNodeKeyParam = "service-instance." + startNodeKey + ":" + startNodeValue; + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(gMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has(startNodeKey, startNodeValue)).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorMock); + when(iteratorMock.hasNext()).thenReturn(true); + + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + when(iteratorMock.next()).thenReturn(titanVertexMock); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + when(tMock.newTransaction()).thenReturn(gMock); + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + SearchGraph searchGraph = new SearchGraph(); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add(startNodeKeyParam); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expectd."); + } catch (Exception e) { + assertNotNull(e); + } + } + + /** + * Test run generic query service instance 6114 exception. + * + * @throws Exception the exception + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testRunGenericQuery_serviceInstance_6114Exception() throws Exception { + String startNodeType = "service-instance"; + String startNodeKey = "service-instance-id"; + String startNodeValue = "test-service-instance-id"; + String startNodeKeyParam = "service-instance." + startNodeKey + ":" + startNodeValue; + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + TitanGraphQuery titanGraphQueryMock = PowerMockito.mock(TitanGraphQuery.class); + when(gMock.query()).thenReturn(titanGraphQueryMock); + when(titanGraphQueryMock.has(startNodeKey, startNodeValue)).thenReturn(titanGraphQueryMock); + Iterable<TitanVertex> iterableMock =(Iterable<TitanVertex>) PowerMockito.mock(Iterable.class); + when(titanGraphQueryMock.vertices()).thenReturn(iterableMock); + Iterator<TitanVertex> iteratorMock = (Iterator<TitanVertex>) PowerMockito.mock(Iterator.class); + when(iterableMock.iterator()).thenReturn(iteratorMock); + when(tMock.newTransaction()).thenReturn(gMock); + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + SearchGraph searchGraph = new SearchGraph(); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add(startNodeKeyParam); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + } + + /** + * Test run generic query service subscription. + * + * @throws Exception the exception + */ + @Test + public void testRunGenericQuery_serviceSubscription() throws Exception { + String startNodeType = "service-subscription"; + String serviceSubscriptionURL = "testServiceSubscriptionURL"; + + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-subscription.service-type:test-service-type"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("service-instance"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + + PowerMockito.mockStatic(TitanGraph.class); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.mockStatic(DbMeth.class); + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + @SuppressWarnings("unchecked") + VertexProperty<String> vertexPropertyMock = (VertexProperty<String>)PowerMockito.mock(VertexProperty.class); + when(titanVertexMock.<String>property("aai-node-type")).thenReturn(vertexPropertyMock); + when(vertexPropertyMock.orElse(null)).thenReturn(startNodeType); + + when(DbMeth.getUniqueNodeWithDepParams(Mockito.anyString(), Mockito.anyString(), + Mockito.any(TitanTransaction.class), Mockito.anyString(), (HashMap<String, Object>) + Mockito.anyMapOf(String.class, Object.class), Mockito.anyString())).thenReturn(titanVertexMock); + + PowerMockito.mockStatic(IngestModelMoxyOxm.class); + HashMap<String, AAIResources> aaiResourceContainerMock = new HashMap<String, AAIResources>(); + AAIResources aaiResourcesMock = PowerMockito.mock(AAIResources.class); + aaiResourceContainerMock.put("v8", aaiResourcesMock); + IngestModelMoxyOxm.aaiResourceContainer = aaiResourceContainerMock; + DynamicJAXBContext dynamicJAXBContextMock = PowerMockito.mock(DynamicJAXBContext.class); + when(aaiResourcesMock.getJaxbContext()).thenReturn(dynamicJAXBContextMock); + + DynamicEntity dynamicEntityMock = PowerMockito.mock(DynamicEntity.class); + when(dynamicJAXBContextMock.newDynamicEntity(Mockito.anyString())).thenReturn(dynamicEntityMock); + + PowerMockito.mockStatic(RestURL.class); + when(RestURL.getSearchUrl(Mockito.any(TitanTransaction.class), Mockito.any(TitanVertex.class), + Mockito.anyString())).thenReturn(serviceSubscriptionURL); + +// SearchGraph searchGraphMock = PowerMockito.mock(SearchGraph.class); + Response respMock = PowerMockito.mock(Response.class); + when(respMock.getStatus()).thenReturn(200); +// PowerMockito.when(SearchGraph.class, "getResponseFromDynamicEntity", Mockito.any(DynamicEntity.class), +// Mockito.any(DynamicJAXBContext.class), Mockito.any(AAIExtensionMap.class)).thenReturn(respMock); + SearchGraph searchGraph = new SearchGraph(); + SearchGraph searchGraphSpy = PowerMockito.spy(searchGraph); + PowerMockito.doReturn(respMock).when(searchGraphSpy, "getResponseFromDynamicEntity", Mockito.any(DynamicEntity.class), + Mockito.any(DynamicJAXBContext.class), Mockito.any(AAIExtensionMap.class)); + + Response resp = searchGraphSpy.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + assertEquals(200, resp.getStatus()); + } + + /** + * Test run generic query start node not found exception. + * + * @throws Exception the exception + */ + @Test + public void testRunGenericQuery_startNodeNotFoundException() throws Exception { + String startNodeType = "testStartNodeType"; + + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + when(graphMock.getGraph()).thenReturn(tMock); + + PowerMockito.mockStatic(DbMeth.class); + TitanVertex titanVertexMock = PowerMockito.mock(TitanVertex.class); + @SuppressWarnings("unchecked") + VertexProperty<String> vertexPropertyMock = (VertexProperty<String>)PowerMockito.mock(VertexProperty.class); + when(titanVertexMock.<String>property("aai-node-type")).thenReturn(vertexPropertyMock); + when(vertexPropertyMock.orElse(null)).thenReturn(startNodeType); + when(DbMeth.getUniqueNodeWithDepParams(Mockito.anyString(), Mockito.anyString(), + Mockito.any(TitanTransaction.class), Mockito.anyString(), (HashMap<String, Object>) + Mockito.anyMapOf(String.class, Object.class), Mockito.anyString())).thenReturn(null); + + Response respMock = PowerMockito.mock(Response.class); + when(respMock.getStatus()).thenReturn(200); + SearchGraph searchGraph = new SearchGraph(); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-subscription.service-type:test-service-type"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("service-instance"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + aaiExtMap.setApiVersion(aaiApiVersion); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + } + + /** + * Test run generic query exception. + * + * @throws Exception the exception + */ + @Test + public void testRunGenericQuery_exception() throws Exception { + String startNodeType = "testStartNodeType"; + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + when(graphMock.getGraph()).thenReturn(tMock); + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + SearchGraph searchGraph = new SearchGraph(); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-subscription.service-type:test-service-type"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("service-instance"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + } + + /** + * Test run generic query request error. + * + * @throws Exception the exception + */ + @Test + public void testRunGenericQuery_requestError() throws Exception { + PowerMockito.mockStatic(AAIGraph.class); + AAIGraph graphMock = PowerMockito.mock(AAIGraph.class); + when(AAIGraph.getInstance()).thenReturn(graphMock); + TitanGraph tMock = PowerMockito.mock(TitanGraph.class); + when(graphMock.getGraph()).thenReturn(tMock); + TitanTransaction gMock = PowerMockito.mock(TitanTransaction.class); + when(tMock.newTransaction()).thenReturn(gMock); + + SearchGraph searchGraph = new SearchGraph(); + String startNodeType = null; + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-subscription.service-type:test-service-type"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("service-instance"); + AAIExtensionMap aaiExtMap = new AAIExtensionMap(); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + startNodeType = "testStartNodeType"; + startNodeKeyParams = null; + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-subscription.service-type:test-service-type"); + includeNodeTypes = null; + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + + includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("service-instance"); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 7, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + startNodeKeyParams.add("service-subscription.service-type"); + try { + searchGraph.runGenericQuery(fromAppId, transId, startNodeType, startNodeKeyParams, includeNodeTypes, 0, aaiExtMap); + fail("Exception expected"); + } catch (Exception e) { + assertNotNull(e); + } + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java new file mode 100644 index 0000000..e0253d4 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.exceptions; + +import static org.junit.Assert.assertThat; +import static org.hamcrest.CoreMatchers.containsString; + +import static org.junit.Assert.*; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.HashMap; + +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.logging.ErrorLogHelper; +import org.openecomp.aai.logging.ErrorObject; + +public class AAIExceptionTest { + private static final String code = "4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + private static final Throwable noMessage = new RuntimeException(); + + /** + * Test constructor with 0 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith0Params() throws Exception { + AAIException exception = new AAIException(); + assertEquals(exception, exception); + } + + /** + * Test constructor with 1 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith1Params() throws Exception { + AAIException exception = new AAIException(code); + assertEquals(exception, exception); + } + + /** + * Test constructor with 2 params details. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsDetails() throws Exception { + AAIException exception = new AAIException(code, details); + assertEquals(details, exception.getErrorObject().getDetails()); + } + + /** + * Test constructor with 2 params cause. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsCause() throws Exception { + AAIException exception = new AAIException(code, cause); + assertEquals(cause.getMessage(), exception.getErrorObject().getDetails()); + } + + /** + * Test constructor with 2 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage); + assertEquals(noMessage.toString(), exception.getErrorObject().getDetails()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIException exception = new AAIException(code, cause, details); + String details = "This is a runtime exception.-This is a detailed description of the exception."; + assertEquals(details, exception.getErrorObject().getDetails()); + } + + /** + * Gets the error object test. + * + * @return the error object test + */ + @Test + public void getErrorObjectTest() { + AAIException exception = new AAIException(); + assertEquals(ErrorObject.DefaultErrorObject, exception.getErrorObject()); + } + + /** + * Test constructor with 3 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage, details); + String detailString = new String(noMessage.toString() + "-" + details); + assertEquals(detailString, exception.getErrorObject().getDetails()); + } + + /** + * Gets the stack top test. + * + * @return the stack top test + * @throws Exception the exception + */ + @Test + public void getStackTopTest() throws Exception { + AAIException exception = new AAIException(code, cause); + String classname = "org.openecomp.aai.exceptions.AAIExceptionTest"; + String methodName = "<clinit>"; + String stackTop = exception.getStackTop(); + assertThat(stackTop, containsString(classname.trim())); + assertThat(stackTop, containsString(methodName.trim())); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java new file mode 100644 index 0000000..1b2e36d --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.exceptions; + +import static org.junit.Assert.*; + +import java.util.HashMap; + +import org.junit.Rule; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIExceptionWithInfo; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +public class AAIExceptionWithInfoTest { + + + private static final HashMap<String, Object> map = new HashMap<String, Object>(); + + { + map.put("itemInteger", 1); + map.put("itemString", "Two"); + map.put("itemThree", Boolean.TRUE); + } + + private static final String info = "An error has occurred."; + private static final String code = "4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + + /** + * Test constructor with 2 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params I. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsI() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, details, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(details, exception.getErrorObject().getDetails()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params II. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsII() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(cause.getMessage(), exception.getErrorObject().getDetails()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 5 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith5Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, details, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(cause.getMessage() + "-" + details, exception.getErrorObject().getDetails()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info hash. + */ + @Test + public void testSetInfoHash() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + HashMap<String, Object> newMap = new HashMap<String, Object>(); + newMap.put("itemInteger", 2); + exception.setInfoHash(newMap); + + assertEquals(newMap, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info. + */ + @Test + public void testSetInfo() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + String newInfo = "This is updated info."; + exception.setInfo(newInfo); + + assertEquals(map, exception.getInfoHash()); + assertEquals(newInfo, exception.getInfo()); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java new file mode 100644 index 0000000..3046848 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java @@ -0,0 +1,360 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.db.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class GraphTraversalTest { + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")), + false); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + + /** + * Gets the item affected by default cloud region. + * + * @return the item affected by default cloud region + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void getItemAffectedByDefaultCloudRegion() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("cloud-owner", "CR").has("cloud-region-id", "AAI25") + .has("aai-node-type", "cloud-region") + .out("has") + .has("tenant-id", "key1") + .out("owns") + .has("vserver-id", "key2") + .out("hasLInterface") + .has("interface-name", "key3"); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("cloud-owner", "CR").has("cloud-region-id", "AAI25") + .has("aai-node-type", "cloud-region") + .out("has") + .has("tenant-id", "key1") + .out("owns") + .has("vserver-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for vserver", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be vserver", + "vserver", + query.getParentResultType()); + assertEquals( + "result type should be l-interface", + "l-interface", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the via query param. + * + * @return the via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void getViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/tenants/tenant").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("tenant-name", "Tenant1"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("cloud-owner", "CR").has("cloud-region-id", "AAI25") + .has("aai-node-type", "cloud-region") + .out("has") + .has("tenant-name", "Tenant1"); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("cloud-owner", "CR").has("cloud-region-id", "AAI25") + .has("aai-node-type", "cloud-region"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the plural via query param. + * + * @return the plural via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("prov-status", "up"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "vnfc") + .has("prov-status", "up"); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the all query param naming exception. + * + * @return the all query param naming exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("cvlan-tag", "333"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 333); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void abstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").or( + __.has(AAIProperties.NODE_TYPE, "vce"), + __.has(AAIProperties.NODE_TYPE, "vpe"), + __.has(AAIProperties.NODE_TYPE, "generic-vnf")); + + GraphTraversal<Vertex, Vertex> expectedParent = expected; + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + assertEquals("dependent",false, query.isDependent()); + + + } + + /** + * Non parent abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void nonParentAbstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key2/vnf/key1").build(); + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + + + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GremlinPipelineTraversalTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GremlinPipelineTraversalTest.java new file mode 100644 index 0000000..8528fa0 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/GremlinPipelineTraversalTest.java @@ -0,0 +1,408 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; +/*package org.openecomp.aai.parsers.query; + +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.db.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; +import com.tinkerpop.gremlin.java.GremlinPipeline; +import com.tinkerpop.pipes.IdentityPipe; + +public class GremlinPipelineTraversalTest { + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLINPIPELINE_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v7, new LogLineBuilder("TEST", "TEST")), + false); + + private TransactionalGraphEngine dbEnginev6 = + new TitanDBEngine(QueryStyle.GREMLINPIPELINE_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v6, new LogLineBuilder("TEST", "TEST")), + false); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V().has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("physical-location-id", "key1").has("aai-node-type", "complex") + .out("hasCtagPool") + .has("target-pe", "key2").has("availability-zone-name", "key3"); + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for complex", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getParentResultType()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + 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(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2").out("hasCTag") + .has("cvlan-tag", 655); + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "contaner type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag"); + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + + @Test + public void getViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/tenants/tenant").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + + .has("tenant-name", "Tenant1"); + + .has("tenant-name", "Tenant2"); + + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("cloud-owner", "CR").has("aai-node-type", "cloud-region") + .has("cloud-region-id", "AAI25"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("prov-status", "up"); + QueryParser query = dbEnginev6.getQueryBuilder().createQueryFromURI(uri, map); + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("aai-node-type", "vnfc") + .has("prov-status", "up"); + + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("cvlan-tag", "333"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 333); + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void abstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").or( + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vce"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vpe"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "generic-vnf")); + + GremlinPipeline expectedParent = expected; + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + assertEquals("dependent",false, query.isDependent()); + + + } + + @Test + public void nonParentAbstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key2/vnf/key1").build(); + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + + + } + + @Test + public void parentAbstractTypeWithNesting() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1/vf-modules/vf-module/key2").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GremlinPipeline expected = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").or( + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vce"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vpe"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "generic-vnf")) + .outE().has("isParent", true).inV().has("vf-module-id", "key2"); + GremlinPipeline expectedParent = new GremlinPipeline(new IdentityPipe()).V() + .has("vnf-id", "key1").or( + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vce"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "vpe"), + new GremlinPipeline(new IdentityPipe()).has(AAIProperties.NODE_TYPE, "generic-vnf")); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for ", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().toString()); + assertEquals( + "result type should be vnf", + "vnf", + query.getParentResultType()); + assertEquals( + "result type should be vf-module", + "vf-module", + query.getResultType()); + + assertEquals("dependent",true, query.isDependent()); + + } +} +*/ diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyGremlinQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyGremlinQueryTest.java new file mode 100644 index 0000000..3fc6801 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyGremlinQueryTest.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; +/*package org.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class LegacyGremlinQueryTest { + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v7, new LogLineBuilder("TEST", "TEST")), + false); + + private TransactionalGraphEngine dbEnginev6 = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v6, new LogLineBuilder("TEST", "TEST")), + false); + + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be complex", + "complex", + query.getResultType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".out('hasCtagPool')" + + ".has('target-pe', 'key2').has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for complex", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + 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(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "contaner type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('aai-node-type', 'cvlan-tag')"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + + @Test + public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("prov-status", "up"); + QueryParser query = dbEnginev6.getQueryBuilder().createQueryFromURI(uri, map); + String expected = + ".has('aai-node-type', 'vnfc')" + + ".has('prov-status', 'up')"; + + String expectedParent = + ".has('aai-node-type', 'vnfc')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("cvlan-tag", "333"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 333)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } +} +*/ diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java new file mode 100644 index 0000000..3173cd0 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java @@ -0,0 +1,168 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.xml.bind.JAXBException; + +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class LegacyQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')" + + ".out('hasLAGInterface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')" + + ".out('hasCTag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java new file mode 100644 index 0000000..8533040 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java @@ -0,0 +1,649 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.IntrospectorFactory; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import static org.hamcrest.CoreMatchers.startsWith; + +public class RelationshipGremlinQueryTest { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + private LogLineBuilder llBuilder = new LogLineBuilder("TEST", "TEST"); + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, llBuilder), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver').out('hasLAGInterface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655"; + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Scrambled relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void scrambledRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Reversed relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void reversedRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Ordered ambiguous relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void orderedAmbiguousRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Scrambled relationship spec. + * + * @param content the content + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public void scrambledRelationshipSpec(String content) throws JAXBException, UnsupportedEncodingException, AAIException { + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".out('hasLAGInterface')" + + ".has('interface-name', 'key2').out('hasLInterface')" + + ".has('interface-name', 'key3').out('hasVlan')" + + ".has('vlan-interface', 'key4').out('hasIpAddress')" + + ".has('l3-interface-ipv4-address', 'key5')"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".out('hasLAGInterface')" + + ".has('interface-name', 'key2').out('hasLInterface')" + + ".has('interface-name', 'key3').out('hasVlan')" + + ".has('vlan-interface', 'key4')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for vlan", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be l3-interface-ipv4-address-list", + "l3-interface-ipv4-address-list", + query.getResultType()); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/service-capabilities/service-capability/key1/key2/cvlan-tags/cvlan-tag/655"; + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".out('hasCtagPool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + + /** + * Abstract type. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void abstractType() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"vnf\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + " }]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1')" + + ".or(_().has('aai-node-type', 'vce'),_().has('aai-node-type', 'vpe'),_().has('aai-node-type', 'generic-vnf'))"; + + String expectedParent = + ".has('vnf-id', 'key1')" + + ".or(_().has('aai-node-type', 'vce'),_().has('aai-node-type', 'vpe'),_().has('aai-node-type', 'generic-vnf'))"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + } + + /** + * Invalid node name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidNodeName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-infeaterface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3000")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } + + /** + * Invalid property name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidPropertyName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.intfdaferface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3000")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java new file mode 100644 index 0000000..40d8913 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java @@ -0,0 +1,287 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.IntrospectorFactory; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +public class RelationshipQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private LogLineBuilder llBuilder = new LogLineBuilder("TEST", "TEST"); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, llBuilder), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver').out('hasLAGInterface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655"; + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').out('hasPortGroup')" + + ".has('interface-id', 'key2').out('hasCTag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').out('hasPortGroup')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/service-capabilities/service-capability/key1/key2/cvlan-tags/cvlan-tag/655"; + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".out('hasCtagPool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java new file mode 100644 index 0000000..a200278 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java @@ -0,0 +1,322 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.IntrospectorFactory; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +public class UniqueRelationshipQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private LogLineBuilder llBuilder = new LogLineBuilder("TEST", "TEST"); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, llBuilder), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + private Unmarshaller unmarshaller = null; + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Setup. + * + * @throws JAXBException the JAXB exception + */ + @Before + public void setup() throws JAXBException { + unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + } + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "pserver/key1"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + String resultType = "pserver"; + String containerType = ""; + + testSet(query, expected, expected, resultType, containerType); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "pserver/key1/lag-interface/key2"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "pserver/key1"); + String resultType = "lag-interface"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655"; + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String uri = "/service-capabilities/service-capability/key1/key2"; + String content = + "{" + + "\"related-to\" : \"service-capability\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"service-capability.service-type\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"service-capability.vnf-type\"," + + " \"relationship-value\" : \"key2\"" + + " }]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "service-capability/key1/key2"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "service-capability/key1/key2"); + String resultType = "service-capability"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.-name\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity, llBuilder); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String uri = "network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655"; + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getParentQueryBuilder().getParentQuery()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java new file mode 100644 index 0000000..f108745 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class UniqueURIQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + String key = "complex/key1"; + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + String parentResultType = ""; + String resultType = "complex"; + String containerType = ""; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Parent plural query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void parentPluralQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-node-type", "complex"); + String parentResultType = ""; + String resultType = "complex"; + String containerType = "complexes"; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Child query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "complex/key1"; + String key = parentKey + "/ctag-pool/key2/key3"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey); + String parentResultType = "complex"; + String resultType = "ctag-pool"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Naming exceptions. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + 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(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "vce/key1/port-group/key2"; + String key = parentKey + "/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Gets the all. + * + * @return the all + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + String parentURI = "network/vces/vce/key1/port-groups/port-group/key2"; + String parentKey = "vce/key1/port-group/key2"; + URI uri = UriBuilder.fromPath(parentURI + "/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", parentKey).out("hasCTag").has("aai-node-type", "cvlan-tag"); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key",parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = "cvlan-tags"; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param parentResultType the parent result type + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String parentResultType, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getQueryBuilder().getParentQuery()); + assertEquals( + "parent result type should be " + parentResultType, + parentResultType, + query.getParentResultType()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java new file mode 100644 index 0000000..44822be --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.uri; + +import static org.hamcrest.CoreMatchers.startsWith; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.uri.URIToDBKey; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class URIParserTest { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Invalid path. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + + URIToDBKey parse = new URIToDBKey(loader, uri); + + } + + /** + * Invalid path no name space. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathNoNameSpace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3000")); + + URIToDBKey parse = new URIToDBKey(loader, uri); + + } + + /** + * Invalid path partial. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathPartial() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3000")); + + URIToDBKey parse = new URIToDBKey(loader, uri); + + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java new file mode 100644 index 0000000..43d0682 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToDBKeyTest.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.uri; + +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.uri.URIToDBKey; +import org.powermock.core.classloader.annotations.PrepareForTest; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +@PrepareForTest(ModelInjestor.class) +public class URIToDBKeyTest { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/CR/AAI25/tenant/key1/vserver/key2/l-interface/key3"; + + assertEquals("blah", expected, result); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/CR/AAI25/tenant/key1/vserver/key2/l-interface/key3"; + + assertEquals("blah", expected, result); + + } + + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + + URIToDBKey parse = new URIToDBKey(loader, uri); + + } + + /** + * No valid tokens. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void noValidTokens() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud/blah/blah").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + + URIToDBKey parse = new URIToDBKey(loader, uri); + } + + /** + * Starts with valid namespace. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "cloud-region/CR/AAI25/tenant/key1/vserver/key2/l-interface/key3"; + + assertEquals("blah", expected, result); + } + + /** + * Naming exceptions. + * + * @throws IllegalArgumentException the illegal argument exception + * @throws AAIException the AAI exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void namingExceptions() throws IllegalArgumentException, AAIException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + URIToDBKey parse = new URIToDBKey(loader, uri); + Object result = parse.getResult(); + + String expected = "vce/key1/port-group/key2/cvlan-tag/655"; + + assertEquals("blah", expected, result); + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java new file mode 100644 index 0000000..c875a47 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.uri; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.uri.URIToExtensionInformation; +import org.openecomp.aai.rest.HttpMethod; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class URIToExtensionInformationTest { + + private Loader v8Loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Test spec. + * + * @param info the info + * @param httpMethod the http method + * @param namespace the namespace + * @param preMethodName the pre method name + * @param postMethodName the post method name + * @param topLevel the top level + */ + private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName, String postMethodName, String topLevel) { + + + String namespaceResult = info.getNamespace(); + String methodNameResult = info.getMethodName(httpMethod, true); + + assertEquals("namespace", namespace, namespaceResult); + assertEquals("preprocess method name", preMethodName, methodNameResult); + methodNameResult = info.getMethodName(httpMethod, false); + + assertEquals("postprocess method name", postMethodName, methodNameResult); + + String topLevelResult = info.getTopObject(); + + assertEquals("topLevel", topLevel, topLevelResult); + } + + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java new file mode 100644 index 0000000..721b296 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java @@ -0,0 +1,251 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.uri; + +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.HashMap; + +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.uri.URIToObject; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + + +public class URIToObjectTest { + + private Version version = Version.v8; + private Version currentVersion = Version.v8; + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version, new LogLineBuilder("TEST", "TEST")); + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"CR\",\"cloud-region-id\":\"AAI25\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, currentVersion); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + HashMap<String, Introspector> relatedObjects = new HashMap<>(); + Introspector tenantObj = this.loader.introspectorFromName("tenant"); + tenantObj.setValue("tenant-id", "key1"); + tenantObj.setValue("tenant-name", "name1"); + relatedObjects.put(tenantObj.getObjectId(), tenantObj); + Introspector vserverObj = this.loader.introspectorFromName("vserver"); + vserverObj.setValue("vserver-id", "key2"); + vserverObj.setValue("vserver-name", "name2"); + relatedObjects.put(vserverObj.getObjectId(), vserverObj); + + URIToObject parse = new URIToObject(loader, uri, relatedObjects); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"CR\",\"cloud-region-id\":\"AAI25\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, currentVersion); + + + } + + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + + URIToObject parse = new URIToObject(loader, uri); + + } + + /** + * Starts with valid namespace. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"CR\",\"cloud-region-id\":\"AAI25\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, currentVersion); + + } + + /** + * Single top level. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void singleTopLevel() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/network/generic-vnfs/generic-vnf/key1").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\"}"; + + String topEntity = "generic-vnf"; + String entity = "generic-vnf"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void namingExceptions() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}"; + String topEntity = "vce"; + String entity = "cvlan-tag"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * No list object. + * + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void noListObject() throws IllegalArgumentException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("/aai/v8/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String topEntity = "vpls-pe"; + String entity = "l3-interface-ipv4-address-list"; + String expected = "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}"; + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Test set. + * + * @param json the json + * @param parse the parse + * @param expected the expected + * @param topEntity the top entity + * @param entity the entity + * @param version the version + */ + public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity, Version version) { + assertEquals("blah", expected, json); + + assertEquals("top entity", topEntity, parse.getTopEntityName()); + + assertEquals("entity", entity, parse.getEntityName()); + + assertEquals("entity object", entity, parse.getEntity().getDbName()); + + assertEquals("parent list object", 1, parse.getParentList().size()); + + assertEquals("object version", version, parse.getObjectVersion()); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java new file mode 100644 index 0000000..ca362ec --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java @@ -0,0 +1,165 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.parsers.uri; + +import static org.hamcrest.CoreMatchers.startsWith; +import static org.junit.Assert.assertTrue; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; + +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.uri.URIToObject; +import org.openecomp.aai.parsers.uri.URIToRelationshipObject; + +import com.att.aft.dme2.internal.javaxwsrs.core.UriBuilder; + +public class URIToRelationshipObjectTest { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8, new LogLineBuilder("TEST", "TEST")); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws MalformedURLException the malformed URL exception + */ + @Ignore + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, MalformedURLException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\".*?:8443/aai/v8/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3/\",\"relationship-data\":\\[\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws MalformedURLException the malformed URL exception + */ + @Ignore + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, MalformedURLException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\".*?:8443/aai/v8/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3/\",\"relationship-data\":\\[\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + + } + + + /** + * Double key relationship. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws MalformedURLException the malformed URL exception + */ + @Ignore + @Test + public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, MalformedURLException { + URI uri = UriBuilder.fromPath("/aai/v8/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\".*?:8443/aai/v8/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri with non string key. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws MalformedURLException the malformed URL exception + */ + @Ignore + @Test + public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, MalformedURLException { + URI uri = UriBuilder.fromPath("/aai/v8/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\".*?:8443/aai/v8/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144/\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + } + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Ignore + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expectMessage(startsWith("AAI_3001")); + + URIToObject parse = new URIToObject(loader, uri); + + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/rest/search/SearchProviderTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/rest/search/SearchProviderTest.java new file mode 100644 index 0000000..b9b8147 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/rest/search/SearchProviderTest.java @@ -0,0 +1,372 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.rest.search; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.ext.RuntimeDelegate; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.aai.dbmap.SearchGraph; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.extensions.AAIExtensionMap; +import org.openecomp.aai.logging.LogLine; +import org.openecomp.aai.rest.search.SearchProvider; +import org.openecomp.aai.util.AAIApiVersion; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.springframework.mock.web.MockHttpServletRequest; + + + +//@RunWith(PowerMockRunner.class) +//@PowerMockIgnore( {"javax.management.*"}) +@PrepareForTest({AAIApiVersion.class, SearchGraph.class, SearchProvider.class, ResponseBuilder.class}) +public class SearchProviderTest { + //In VM argument, need to pass the following arguments: + //-noverify + // + @Rule + public PowerMockRule rule = new PowerMockRule(); + + + private String fromAppId = "searchProviderId"; + private String transId = "transId"; + private String aaiApiVersion = "v8"; + private String genericQueryUri = "https://localhost:8443/aai/v8/search" + SearchProvider.GENERIC_QUERY + + "?key=service-instance.service-instance-id:test-service-instance-id" + + "&start-node-type=service-instance&include=generic-vnf&depth=0"; + private String nodeQueryUri = "https://localhost:8443/aai/v8/search" + SearchProvider.NODES_QUERY + + "?search-node-type=vserver&filter=vserver-name2:EXISTS:" + + "&edge-filter=pserver:EXISTS:hostname:test-hostname"; + + + /** + * Sets the up. + */ + @Before + public void setUp() { + RuntimeDelegate.setInstance(runtimeDelegate); + } + + @Mock + private RuntimeDelegate runtimeDelegate; + + class MockSearchProvider extends SearchProvider { + @Override + protected String getFromAppId(HttpHeaders headers, LogLine logline) throws AAIException { + return fromAppId; + } + @Override + protected String getTransId(HttpHeaders headers, LogLine logline) throws AAIException { + return transId; + } + + @Override + protected String genDate() { + return null; + } + @Override + protected String genDate(LogLine logline) { + return null; + } + @Override + public void logTransaction( String appId, String tId, String action, + String input, String rqstTm, String respTm, String request, Response response, LogLine logline) { + } + } + + class MockResponse extends Response { + + @Override + public Object getEntity() { + return null; + } + + @Override + public int getStatus() { + return 200; + } + + @Override + public MultivaluedMap<String, Object> getMetadata() { + return null; + } + } + + + + /** + * Test get generic query response. + * + * @throws Exception the exception + */ + @Test + public void testGetGenericQueryResponse() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + Response mockResp = new MockResponse(); + + when(mockSearchGraph.runGenericQuery(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyListOf(String.class), + Mockito.anyListOf(String.class), Mockito.anyInt(), Mockito.any(AAIExtensionMap.class))) + .thenReturn(mockResp); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-instance.service-instance-id:test-service-instance-id"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(genericQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getGenericQueryResponse(headers, req, + "service-instance", startNodeKeyParams, includeNodeTypes, + 0); + assertEquals(200, resp.getStatus()); + } + + + /** + * Test get generic query response AAI exception. + * + * @throws Exception the exception + */ + @Test + public void testGetGenericQueryResponse_AAIException() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + + Response response = Mockito.mock(Response.class); + when(response.getStatus()).thenReturn(500); + ResponseBuilder responseBuilder = Mockito.mock(ResponseBuilder.class); + when(runtimeDelegate.createResponseBuilder()).thenReturn(responseBuilder); + when((responseBuilder).status(Response.Status.INTERNAL_SERVER_ERROR)).thenReturn(responseBuilder); + when((responseBuilder).entity(Mockito.anyObject())).thenReturn(responseBuilder); + when((responseBuilder).build()).thenReturn(response); + when(mockSearchGraph.runGenericQuery(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyListOf(String.class), + Mockito.anyListOf(String.class), Mockito.anyInt(), Mockito.any(AAIExtensionMap.class))) + .thenThrow(new AAIException()); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-instance.service-instance-id:test-service-instance-id"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(genericQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getGenericQueryResponse(headers, req, + "service-instance", startNodeKeyParams, includeNodeTypes, + 0); + assertEquals(500, resp.getStatus()); + } + + /** + * Test get generic query response exception. + * + * @throws Exception the exception + */ + @Test + public void testGetGenericQueryResponse_Exception() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + + Response response = Mockito.mock(Response.class); + when(response.getStatus()).thenReturn(500); + ResponseBuilder responseBuilder = Mockito.mock(ResponseBuilder.class); + when(runtimeDelegate.createResponseBuilder()).thenReturn(responseBuilder); + when((responseBuilder).status(Response.Status.INTERNAL_SERVER_ERROR)).thenReturn(responseBuilder); + when((responseBuilder).entity(Mockito.anyObject())).thenReturn(responseBuilder); + when((responseBuilder).build()).thenReturn(response); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenThrow(new Exception()); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> startNodeKeyParams = new ArrayList<String>(); + startNodeKeyParams.add("service-instance.service-instance-id:test-service-instance-id"); + List<String> includeNodeTypes = new ArrayList<String>(); + includeNodeTypes.add("generic-vnf"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(genericQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getGenericQueryResponse(headers, req, + "service-instance", startNodeKeyParams, includeNodeTypes, + 0); + assertEquals(500, resp.getStatus()); + } + + /** + * Test get nodes query response. + * + * @throws Exception the exception + */ + @Test + public void testGetNodesQueryResponse() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + Response mockResp = new MockResponse(); + when(mockSearchGraph.runNodesQuery(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyListOf(String.class), + Mockito.anyListOf(String.class), Mockito.any(AAIExtensionMap.class))) + .thenReturn(mockResp); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> searchNodeTypes = new ArrayList<String>(); + searchNodeTypes.add("vserver"); + List<String> edgeFilterList = new ArrayList<String>(); + edgeFilterList.add("pserver:EXISTS"); + edgeFilterList.add("hostname:test-hostname"); + List<String> filterList = new ArrayList<String>(); + filterList.add("vserver-name2:EXISTS:"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(nodeQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getNodesQueryResponse(headers, req , + "vserver", edgeFilterList, + filterList); + assertEquals(200, resp.getStatus()); + } + + /** + * Test get nodes query response AAI exception. + * + * @throws Exception the exception + */ + @Test + public void testGetNodesQueryResponse_AAIException() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + Response response = Mockito.mock(Response.class); + when(response.getStatus()).thenReturn(500); + ResponseBuilder responseBuilder = Mockito.mock(ResponseBuilder.class); + when(runtimeDelegate.createResponseBuilder()).thenReturn(responseBuilder); + when((responseBuilder).status(Response.Status.INTERNAL_SERVER_ERROR)).thenReturn(responseBuilder); + when((responseBuilder).entity(Mockito.anyObject())).thenReturn(responseBuilder); + when((responseBuilder).build()).thenReturn(response); + when(mockSearchGraph.runNodesQuery(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyListOf(String.class), + Mockito.anyListOf(String.class), Mockito.any(AAIExtensionMap.class))) + .thenThrow(new AAIException()); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> searchNodeTypes = new ArrayList<String>(); + searchNodeTypes.add("vserver"); + List<String> edgeFilterList = new ArrayList<String>(); + edgeFilterList.add("pserver:EXISTS"); + edgeFilterList.add("hostname:test-hostname"); + List<String> filterList = new ArrayList<String>(); + filterList.add("vserver-name2:EXISTS:"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(nodeQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getNodesQueryResponse(headers, req , + "vserver", edgeFilterList, + filterList); + assertEquals(500, resp.getStatus()); + } + + /** + * Test get nodes query response exception. + * + * @throws Exception the exception + */ + @Test + public void testGetNodesQueryResponse_Exception() throws Exception { + PowerMockito.mockStatic(AAIApiVersion.class); + when(AAIApiVersion.get()).thenReturn(aaiApiVersion); + + SearchGraph mockSearchGraph = Mockito.mock(SearchGraph.class); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenReturn(mockSearchGraph); + Response response = Mockito.mock(Response.class); + when(response.getStatus()).thenReturn(500); + ResponseBuilder responseBuilder = Mockito.mock(ResponseBuilder.class); + when(runtimeDelegate.createResponseBuilder()).thenReturn(responseBuilder); + when((responseBuilder).status(Response.Status.INTERNAL_SERVER_ERROR)).thenReturn(responseBuilder); + when((responseBuilder).entity(Mockito.anyObject())).thenReturn(responseBuilder); + when((responseBuilder).build()).thenReturn(response); + PowerMockito.whenNew(SearchGraph.class).withNoArguments().thenThrow(new Exception()); + + HttpHeaders headers = Mockito.mock(HttpHeaders.class); + List<MediaType> mediaTypeList = new ArrayList<MediaType>(); + mediaTypeList.add(MediaType.APPLICATION_JSON_TYPE); + when(headers.getAcceptableMediaTypes()).thenReturn(mediaTypeList); + List<String> searchNodeTypes = new ArrayList<String>(); + searchNodeTypes.add("vserver"); + List<String> edgeFilterList = new ArrayList<String>(); + edgeFilterList.add("pserver:EXISTS"); + edgeFilterList.add("hostname:test-hostname"); + List<String> filterList = new ArrayList<String>(); + filterList.add("vserver-name2:EXISTS:"); + MockHttpServletRequest req = new MockHttpServletRequest(); + req.setRequestURI(nodeQueryUri); + MockSearchProvider mockSearchProvider = new MockSearchProvider(); + Response resp = mockSearchProvider.getNodesQueryResponse(headers, req , "vserver", + edgeFilterList, filterList); + assertEquals(500, resp.getStatus()); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java new file mode 100644 index 0000000..db07bbb --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.rest.util; + +import static org.junit.Assert.*; + +import java.io.UnsupportedEncodingException; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; + +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.aai.rest.util.ValidateEncoding; + +public class ValidateEncodingTest { + + + @Test + public void badPath() throws UnsupportedEncodingException { + String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}"; + UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap<String, String>()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + @Ignore + @Test + public void goodPath() throws UnsupportedEncodingException { + String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D"; + UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap<String, String>()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + @Ignore + @Test + public void badQueryParamsKey() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("bad::bad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + + } + @Ignore + @Test + public void badQueryParamsValue() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test//:2"); + map.putSingle("badbad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + @Ignore + @Test + public void goodQueryParams() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("badbad", "~test%2F%2F%3A3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + private UriInfo getMockUriInfo(String path, MultivaluedMap<String, String> map) { + UriInfo mockUriInfo = Mockito.mock(UriInfo.class); + Mockito.when(mockUriInfo.getPath(false)).thenReturn(path); + Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map); + + return mockUriInfo; + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java new file mode 100644 index 0000000..5e93080 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.schema.db; + +import java.io.IOException; + +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.db.schema.AuditDoc; +import org.openecomp.aai.db.schema.AuditOXM; +import org.openecomp.aai.db.schema.Auditor; +import org.openecomp.aai.db.schema.AuditorFactory; +import org.openecomp.aai.introspection.Version; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; + +@Ignore("not ready for testing") +public class AuditOXMTest { + + /** + * Before. + */ + @BeforeClass + public static void before() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + + } + + + /** + * Gets the graph audit. + * + * @return the graph audit + * @throws JsonGenerationException the json generation exception + * @throws JsonMappingException the json mapping exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void getGraphAudit() throws JsonGenerationException, JsonMappingException, IOException { + TitanGraph graph = TitanFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties"); + Auditor a = AuditorFactory.getGraphAuditor(graph); + AuditDoc doc = a.getAuditDoc(); + + ObjectMapper mapper = new ObjectMapper(); + + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); + System.out.println(json); + + } + + /** + * Gets the audit. + * + * @return the audit + * @throws JsonGenerationException the json generation exception + * @throws JsonMappingException the json mapping exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void getAudit() throws JsonGenerationException, JsonMappingException, IOException { + AuditOXM oxm = new AuditOXM(Version.v8); + + AuditDoc doc = oxm.getAuditDoc(); + + ObjectMapper mapper = new ObjectMapper(); + + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); + System.out.println(json); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java new file mode 100644 index 0000000..6a1d0cd --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.schema.db; + +import java.io.IOException; +import java.util.Set; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.db.schema.DBIndex; +import org.openecomp.aai.db.schema.ManageTitanSchema; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +@Ignore("not ready yet") +public class ManageSchemaTest { + + private TitanGraph graph = null; + @BeforeClass + public static void before() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + + } + + @Before + public void beforeTest() { + //graph = TitanFactory.open("src/test/resources/inmemory_titan.properties"); + graph = TitanFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties"); + } + + /* + @Test + public void populateEmptyGraph() { + ManageTitanSchema schema = new ManageTitanSchema(graph); + schema.buildSchema(); + } + + @Test + public void modifyIndex() { + ManageTitanSchema schema = new ManageTitanSchema(graph); + schema.buildSchema(); + Vertex v = graph.addVertex(); + v.setProperty("aai-node-type", "pserver"); + v.setProperty("hostname", "test1"); + v.setProperty("internet-topology", "test2"); + graph.commit(); + DBIndex index = new DBIndex(); + index.setName("internet-topology"); + index.setUnique(false); + schema.updateIndex(index); + + } + */ + @Test + public void closeRunningInstances() { + + TitanManagement mgmt = graph.openManagement(); + Set<String> instances = mgmt.getOpenInstances(); + + for (String instance : instances) { + + if (!instance.contains("(current)")) { + mgmt.forceCloseInstance(instance); + } + } + mgmt.commit(); + + graph.close(); + + } + @Test + public void addNewIndex() throws JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + String content = " {\r\n" + + " \"name\" : \"equipment-name\",\r\n" + + " \"unique\" : false,\r\n" + + " \"properties\" : [ {\r\n" + + " \"name\" : \"equipment-name\",\r\n" + + " \"cardinality\" : \"SINGLE\",\r\n" + + " \"typeClass\" : \"java.lang.String\"\r\n" + + " } ]\r\n" + + " }"; + DBIndex index = mapper.readValue(content, DBIndex.class); + ManageTitanSchema schema = new ManageTitanSchema(graph); + TitanManagement mgmt = graph.openManagement(); + Set<String> instances = mgmt.getOpenInstances(); + System.out.println(instances); + schema.updateIndex(index); + + graph.close(); + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/serialization/db/DBSerializerMaxRetryTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/serialization/db/DBSerializerMaxRetryTest.java new file mode 100644 index 0000000..c8e5ec3 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/serialization/db/DBSerializerMaxRetryTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.serialization.db; + + +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.logging.AAILogger; +import org.openecomp.aai.logging.LogLineBuilder; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.db.DBSerializer; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.thinkaurelius.titan.core.TitanException; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanTransaction; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({QueryParser.class, TransactionalGraphEngine.class, TitanGraph.class, TitanTransaction.class, LoaderFactory.class, AAILogger.class, DBSerializer.class}) +public class DBSerializerMaxRetryTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Test. + * + * @throws Exception the exception + */ + @Ignore + @Test + public void test() throws Exception { + + QueryParser mockQuery = PowerMockito.mock(QueryParser.class); + PowerMockito.when(mockQuery.isDependent()).thenReturn(true); + + TransactionalGraphEngine mockEngine = PowerMockito.mock(TransactionalGraphEngine.class); + PowerMockito.when(mockEngine.getQueryEngine()).thenThrow(new TitanException("mock error")); + + TitanGraph mockGraph = PowerMockito.mock(TitanGraph.class); + PowerMockito.when(mockEngine.getGraph()).thenReturn(mockGraph); + TitanTransaction mockGraphTrans = PowerMockito.mock(TitanTransaction.class); + PowerMockito.when(mockGraph.newTransaction()).thenReturn(mockGraphTrans); + + LogLineBuilder llb = new LogLineBuilder(); + AAILogger mockLogger = PowerMockito.mock(AAILogger.class); + + PowerMockito.whenNew(AAILogger.class).withAnyArguments().thenReturn(mockLogger); + + PowerMockito.mockStatic(LoaderFactory.class); + + DBSerializer dbs = new DBSerializer(mockEngine, mockGraph, null, null, llb); + + thrown.expect(AAIException.class); + thrown.expectMessage("AAI_6134"); + dbs.serializeToDb(null, null, mockQuery, null); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java new file mode 100644 index 0000000..b016c7a --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageImpl; +import org.apache.cxf.phase.PhaseInterceptorChain; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.aai.util.AAIApiServerURLBase; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAIConstants; +import org.powermock.core.classloader.annotations.PrepareForTest; +import static org.mockito.Mockito.*; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.rule.PowerMockRule; + +@PrepareForTest({PhaseInterceptorChain.class, AAIConfig.class}) + +public class AAIApiServerURLBaseTest { + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + /** + * Test get hostname. + * + * @throws Exception the exception + */ + @Test + public void testGetHostname() throws Exception { + PowerMockito.mockStatic(PhaseInterceptorChain.class); + Map <String, List<String>> hm = new HashMap<String, List<String>>(); + List<String> host = new ArrayList<String>(); + host.add("my-localhost"); + hm.put("host", host); + + Message outMessage = new MessageImpl(); + outMessage.put(Message.PROTOCOL_HEADERS, hm); + + when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage); + assertEquals("https://my-localhost/aai/", AAIApiServerURLBase.get()); + } + + /** + * Test get with null hostname. + * + * @throws Exception the exception + */ + @Test + public void testGetWithNullHostname() throws Exception { + PowerMockito.mockStatic(AAIConfig.class); + String defaultHostname = "default-name"; + when(AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE)).thenReturn(defaultHostname); + assertEquals(defaultHostname, AAIApiServerURLBase.get()); + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java new file mode 100644 index 0000000..89f56de --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.*; + +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageImpl; +import org.apache.cxf.phase.PhaseInterceptorChain; +import org.junit.Rule; +import org.junit.Test; +import org.openecomp.aai.util.AAIApiVersion; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAIConstants; +import org.powermock.core.classloader.annotations.PrepareForTest; +import static org.mockito.Mockito.*; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +@PrepareForTest({PhaseInterceptorChain.class, AAIConfig.class}) + +public class AAIApiVersionTest { + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { PowerMockAgent.initializeIfNeeded();} + + /** + * Test get version. + * + * @throws Exception the exception + */ + @Test + public void testGetVersion() throws Exception { + PowerMockito.mockStatic(PhaseInterceptorChain.class); + Message outMessage = new MessageImpl(); + String msg = "/v2/"; + outMessage.put(Message.REQUEST_URI, msg); + when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage); + assertEquals("v2", AAIApiVersion.get()); + } + + /** + * Test get with null version. + * + * @throws Exception the exception + */ + @Test + public void testGetWithNullVersion() throws Exception { + PowerMockito.mockStatic(AAIConfig.class); + String defaultURI = "default-v2"; + when(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION)).thenReturn(defaultURI); + assertEquals(defaultURI, AAIApiVersion.get()); + } + + /** + * Test incorrect version pattern. + * + * @throws Exception the exception + */ + @Test + public void testIncorrectVersionPattern() throws Exception { + PowerMockito.mockStatic(PhaseInterceptorChain.class); + PowerMockito.mockStatic(AAIConfig.class); + Message outMessage = new MessageImpl(); + String msg = "2.0.1"; + String defaultURI = "default-v2"; + outMessage.put(Message.REQUEST_URI, msg); + when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage); + when(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION)).thenReturn(defaultURI); + assertEquals(defaultURI, AAIApiVersion.get()); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java new file mode 100644 index 0000000..05bb288 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java @@ -0,0 +1,179 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.ServletContextEvent; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.openecomp.aai.dbmap.AAIGraph; +import org.openecomp.aai.logging.ErrorLogHelper; +import org.openecomp.aai.util.AAIAppServletContextListener; +import org.openecomp.aai.util.AAIConfig; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.PatternLayout; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.AppenderBase; + +@PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class}) +public class AAIAppServletContextListenerTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + private ServletContextEvent arg; + private AAIAppServletContextListener listener; + + /** + * Initialize. + */ + @Before + @PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class}) + public void initialize(){ + arg = PowerMockito.mock(ServletContextEvent.class); + PowerMockito.mockStatic(AAIGraph.class); + PowerMockito.mockStatic(AAIConfig.class); + PowerMockito.mockStatic(ErrorLogHelper.class); + + listener = new AAIAppServletContextListener(); + configureLog(); + } + + /** + * Test contextDestroyed. + */ + @Test + @Ignore + public void testContextDestroyed(){ + listener.contextDestroyed(arg); + assertTrue(logContains(Level.DEBUG, "AAI Server shutdown")); + assertTrue(logContains(Level.INFO, "AAI graph shutdown")); + } + + /** + * Test contextInitialized. + */ + @Test + @Ignore + public void testContextInitialized(){ + listener.contextInitialized(arg); + assertTrue(logContains(Level.DEBUG, "Loading aaiconfig.properties")); + assertTrue(logContains(Level.DEBUG, "Loading error.properties")); + assertTrue(logContains(Level.DEBUG, "Loading graph database")); + assertTrue(logContains(Level.INFO, "AAI Server initialization")); + } + + + /** + * Helper method to check if a String appears in the desired log level. + * + * @param level Log level to use + * @param expected String to search for + * @return True if search String is found, false otherwise + */ + private boolean logContains(Level level, String expected) { + String actual[] = RecordingAppender.messages(); + for (String log : actual) { + if (log.contains(level.toString()) && log.contains(expected)) + return true; + } + return false; + } + + /** + * Set logging level, and initialize log-appender. + */ + private void configureLog() { + Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); + rootLogger.setLevel(Level.DEBUG); + rootLogger.detachAndStopAllAppenders(); + rootLogger.addAppender(RecordingAppender.appender(new PatternLayout())); + } + +} + + +/** + * Appender class that appends log messages to a String List when some logging event occurs + */ +class RecordingAppender extends AppenderBase<ILoggingEvent> { + private static List<String> messages = new ArrayList<String>(); + private static RecordingAppender appender = new RecordingAppender(); + private PatternLayout patternLayout; + + private RecordingAppender() { + super(); + } + + /** + * @param patternLayout Pattern to format log message + * @return Current appender + */ + public static RecordingAppender appender(PatternLayout patternLayout) { + appender.patternLayout = patternLayout; + appender.clear(); + return appender; + } + + @Override + protected void append(ILoggingEvent event) { + messages.add(patternLayout.doLayout(event)); + } + + public void close() {} + + public boolean requiresLayout() { + return false; + } + + /** + * @return Return logs as a String array + */ + public static String[] messages() { + return (String[]) messages.toArray(new String[messages.size()]); + } + + /** + * Clear the message container + */ + private void clear() { + messages.clear(); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java new file mode 100644 index 0000000..d5e5923 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.util.AAIConfig; + +public class AAIConfigPasswordDecodingTest { + + /** + * Configure. + * + * @throws AAIException the AAI exception + */ + @BeforeClass + public static void configure() throws AAIException { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/java/bundleconfig-local"); //fake prop file for testing + AAIConfig.init(); + } + + /** + * Password check. + * + * @throws AAIException the AAI exception + */ + @Ignore + @Test + public void passwordCheck() throws AAIException { + assertEquals("password", "aaiuser123", AAIConfig.get("ecm.auth.password")); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java new file mode 100644 index 0000000..5454aac --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java @@ -0,0 +1,203 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAIPrimaryHost; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileOutputStream; + +@PrepareForTest({InetAddress.class, AAIPrimaryHost.class}) +public class AAIPrimaryHostTest { + + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + AAIPrimaryHost obj = null; + private static final String transId = UUID.randomUUID().toString(); + private static final String fromAppId = "AAIPrimaryHostTest"; + + /** + * Initialize. + */ + @Before + public void initialize(){ + partialSetupForAAIConfig(); + obj = new AAIPrimaryHost(transId, fromAppId); + + } + + /** + * Test do commandwith failure. + * + * @throws Exception the exception + */ + @Test + public void testDoCommandwithFailure() throws Exception { + List<String> myCommands = new ArrayList<String>(); + String command = "some-command"; + myCommands.add(command); + try { + obj.doCommand(myCommands); + } + catch (Exception e){ + assertTrue(e.getMessage().contains("Cannot run program \"some-command\"")); + } + } + + /** + * Test am I primary with random key name. + */ + @Test + public void testAmIPrimary_withRandomKeyName(){ + assertTrue("If key isn't found in the config file, log exception and return true.", obj.amIPrimary("randomName")); + } + + /** + * Test am I primary with DEFAUL T CHEC K for localhost. + */ + @Test + public void testAmIPrimary_with_DEFAULT_CHECK_for_localhost(){ + assertTrue("localhost name should not be in the server list", obj.amIPrimary(new String("aai.primary.filetransfer."))); + } + + + /** + * Test am I primary with DEFAUL T CHEC K for valid host echo success. + */ + @Test + public void testAmIPrimary_with_DEFAULT_CHECK_for_valid_host_echo_success(){ + mockIP(); + obj = getTestObject(true, ""); + assertTrue("host name should exist in the server list in echo success", obj.amIPrimary(new String("aai.primary.filetransfer."))); + } + + /** + * Test which is primary when missingconfig properties. + * + * @throws Exception the exception + */ + @Test + public void testWhichIsPrimaryWhenMissingconfigProperties() throws Exception { + assertEquals(null, obj.whichIsPrimary("checkName")); + } + + /** + * Test which is primary. + * + * @throws Exception the exception + */ + @Test + public void testWhichIsPrimary() throws Exception { + AAIPrimaryHost primaryHost = getTestObject(true, "primaryHost"); + assertEquals("primaryHost", primaryHost.whichIsPrimary("aai.primary.filetransfer.")); + } + + + + /** + * Mock IP. + */ + public void mockIP(){ + + PowerMockito.mockStatic(InetAddress.class); + InetAddress dummyInetAddress = null; + try { + Mockito.when(InetAddress.getLocalHost()).thenReturn(dummyInetAddress); + Mockito.when(dummyInetAddress.getHostAddress()).thenReturn("localhost"); + } catch (UnknownHostException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * Gets the test object. + * + * @param echoStatus the echo status + * @param host the host + * @return the test object + */ + public AAIPrimaryHost getTestObject(final boolean echoStatus, final String host){ + return new AAIPrimaryHost(transId, fromAppId){ + @Override + public boolean amIPrimaryUsingEcho( String hostname, String aaiPrimaryCheck, String aaiServerList) { + return echoStatus; + } + + @Override + public String whichIsPrimaryUsingEcho( String aaiPrimaryCheck, String aaiServerList) { + return "primaryHost"; + } + + }; + } + + + static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + + /** + * Partial setup for AAI config. + */ + public void partialSetupForAAIConfig(){ + try { + setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties"); + } + catch (Exception e) {fail();} + + AAIConfig.reloadConfig(); + } + + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java new file mode 100644 index 0000000..71ab75f --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAIRSyncUtility; + + +public class AAIRSyncUtilityTest { + + AAIRSyncUtility syncUtil; + AAIRSyncUtility syncUtilOmitDoCommand; + AAIConfig aaiConfig; + String hostName; + String transId = UUID.randomUUID().toString(); + + /** + * Initialize. + */ + @Before + public void initialize(){ + syncUtil = new AAIRSyncUtility(); + + syncUtilOmitDoCommand = new AAIRSyncUtility(){ + /** + * {@inheritDoc} + */ + @Override + public int doCommand(List<String> command) throws Exception + { + return 1; + } + }; + + partialSetupForAAIConfig(); + + InetAddress ip = null; + try { + ip = InetAddress.getLocalHost(); + } catch (UnknownHostException e2) { + e2.printStackTrace(); + } + hostName = ip.getHostName(); + } + + + /** + * Test sendRsync. + */ + @Ignore + @Test + public void testSendRsyncCommand(){ + syncUtilOmitDoCommand.sendRsyncCommand(transId, "RandomFileName"); + //TODO write codes to check what is being logged + } + + /** + * Test getHost. + */ + @Test + public void testGetHost(){ + + String returnedHost = null; + Method getHostMethod = makePublic("getHost"); + try { + returnedHost = (String)getHostMethod.invoke(syncUtil, null); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + + assertEquals("Host name didn't match", returnedHost, hostName); + } + + /** + * Test getRemoteHostList. + */ + @Test + public void testGetRemoteHostList(){ + String localHost = "host_local"; + String remoteHost1 = "hostR1"; + String remoteHost2 = "hostR2"; + ArrayList<String> remotes = new ArrayList<String>(); + remotes.add(remoteHost1); + remotes.add(remoteHost2); + + StringTokenizer stTokenizer = new StringTokenizer(remoteHost1+"\r"+remoteHost2+"\r"+localHost); + + Method m = makePublic("getRemoteHostList"); + try { + assertEquals("Remote host missing", remotes, m.invoke(syncUtil, stTokenizer, localHost)); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + + /** + * Test doCommand. + */ + @Test + public void testDoCommand(){ + + assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath())); + + List<String> commands = new ArrayList<String>(); + commands.add("ping"); + commands.add("google.com"); + try { + assertEquals("Failed to execute commands", 1, syncUtilOmitDoCommand.doCommand(commands)); + } catch (Exception e) { + fail("Failed to execute a command"); + e.printStackTrace(); + } + + } + + /** + * Test doCommand with null. + */ + @Test + public void testDoCommand_withNull(){ + assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath())); + try { + assertEquals("This should be unreachable", 1, syncUtil.doCommand(null)); + } catch (Exception e) { + assertTrue("Expecting an NPE from ProcessBuilder", e instanceof NullPointerException); + } + + } + + + /** + * Helper method to covert access type of a method from private to public . + * + * @param privateMethodName Method which is private originally + * @return method object with 'access type = 'public' + */ + public Method makePublic(String privateMethodName){ + Method targetMethod = null; + try { + if (privateMethodName.equals("getHost")) + targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, null); + else if (privateMethodName.equals("getRemoteHostList")) + targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, StringTokenizer.class, String.class); + } catch (NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } + targetMethod.setAccessible(true); + return targetMethod; + } + + /** + * Helper method to load aai config from test configuration file + * This requires that the 'test_aaiconfig.properties' file is available + */ + static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + + /** + * Helper method to setup AAIConfig for test. + */ + public void partialSetupForAAIConfig(){ + try { + setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties"); + } + catch (SecurityException e) {fail();} + catch (NoSuchFieldException e) {fail();} + catch (Exception e) {fail();} + + AAIConfig.reloadConfig(); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java new file mode 100644 index 0000000..8929e33 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.List; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.HBaseConfiguration; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.HTable; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.ResultScanner; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.util.Bytes; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.aai.domain.notificationEvent.NotificationEvent; +import org.openecomp.aai.domain.translog.TransactionLogEntries; +import org.openecomp.aai.domain.translog.TransactionLogEntry; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.util.AAIConfig; +import org.openecomp.aai.util.AAITxnLog; +import org.openecomp.aai.util.PojoUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.JsonMappingException; + + +@PrepareForTest({HBaseConfiguration.class, Configuration.class, + HTable.class, Result.class, ResultScanner.class, Scan.class, + Get.class, NotificationEvent.class, + NotificationEvent.EventHeader.class, PojoUtils.class, AAITxnLog.class}) + +public class AAITxnLogTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + AAITxnLog aaiTnxLog; + Configuration config; + HTable htable; + Result result; + ResultScanner resScanner; + Scan scan; + Get g; + NotificationEvent notif; + NotificationEvent.EventHeader ehNotif; + PojoUtils pu; + + boolean hasNotifEvent = true; + final String notifPayload = "A random payload"; + final String notifID = "1"; + final String notifEntityLink = "nLink"; + final String notifAction = "nAction"; + final String notifStatus = "nStatus"; + final String notifTopic = "nTopic"; + + final String tid = "tidVal"; + final String status = "statusVal"; + final String rqstTm = "rqstTmVal"; + final String respTm = "respTmVal"; + final String srcId = "srcIdVal"; + final String rsrcId = "rsrcIdVal"; + final String rsrcType = "rsrcTypeVal"; + final String rqstBuf = "rqstBufVal"; + final String respBuf = "respBufVal"; + + + /** + * Initialize. + */ + @Before + public void initialize(){ + partialSetupForAAIConfig(); + PowerMockito.mockStatic(HBaseConfiguration.class); + config = PowerMockito.mock(Configuration.class); + htable = PowerMockito.mock(HTable.class); + result = PowerMockito.mock(Result.class); + resScanner = PowerMockito.mock(ResultScanner.class); + scan = PowerMockito.mock(Scan.class); + g = PowerMockito.mock(Get.class); + notif = PowerMockito.mock(NotificationEvent.class); + ehNotif = PowerMockito.mock(NotificationEvent.EventHeader.class); + pu = PowerMockito.mock(PojoUtils.class); + + + mockNotificationEvent(); + + Mockito.when(HBaseConfiguration.create()).thenReturn(config); + aaiTnxLog = new AAITxnLog(tid, srcId); + + try { + PowerMockito.whenNew(HTable.class).withAnyArguments().thenReturn(htable); + PowerMockito.whenNew(Get.class).withAnyArguments().thenReturn(g); + PowerMockito.whenNew(PojoUtils.class).withAnyArguments().thenReturn(pu); + PowerMockito.whenNew(Scan.class).withAnyArguments().thenReturn(scan); + } catch (Exception e) { + e.printStackTrace(); + } + + mockResult(); + + try { + PowerMockito.when(htable.get(g)).thenReturn(result); + PowerMockito.when(htable.getScanner(scan)).thenReturn(resScanner); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Method to test 'put' operation without a notification event. + */ + @Test + public void testPut_withoutNotifEvent(){ + String htid = aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf); + try { + TransactionLogEntry tle = aaiTnxLog.get(htid); + hasNotifEvent = false; + validateTransactionLogEntry(tle); + } catch (AAIException e) { + fail("Cant read back data from htable"); + e.printStackTrace(); + } + } + + /** + * Method to test 'put' operation with a notification event. + */ + @Test + public void testPut_withNotifEvent(){ + hasNotifEvent = true; + String htid = aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, hasNotifEvent, notif); + try { + TransactionLogEntry tle = aaiTnxLog.get(htid); + validateTransactionLogEntry(tle); + } catch (AAIException e) { + fail("Cant read back data from htable"); + e.printStackTrace(); + } + } + + /** + * Method to test 'scan' over an empty htable. + */ + @Test + public void testScan_withEmptyHTable(){ + String key = tid; + List<String> res = aaiTnxLog.scan(key); + assertTrue("Scan output should be empty", res.size() == 0 ); + } + + /** + * Method to test 'scan' operation. + */ + @Test + public void testScan(){ + try { + PowerMockito.when(resScanner.next()).thenReturn(result).thenReturn(null); + } catch (IOException e) { + e.printStackTrace(); + } + List<String> res = aaiTnxLog.scan(tid); + assertTrue("Scan output should not be empty", res.size()==1); + assertTrue("Did not find entry in 'scan'", res.get(0).equals(result.toString())); + } + + /** + * Method to test 'scanFiltered' with an empty htable. + */ + @Test + public void testScanFiltered_withEmptyHTable(){ + aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, true, new NotificationEvent()); + TransactionLogEntries tles = aaiTnxLog.scanFiltered(0, 100, null, null, null, null, null); + assertTrue ("scanFilstered output should be empty", tles.getTransactionLogEntries().size() == 0); + } + + /** + * Method to test 'scanFiltered' operation. + */ + @Test + public void testScanFiltered(){ + try { + PowerMockito.when(resScanner.next()).thenReturn(result).thenReturn(null); + } catch (IOException e) { + e.printStackTrace(); + } + aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, true, new NotificationEvent()); + TransactionLogEntries tles = aaiTnxLog.scanFiltered(0, 100, null, null, null, null, null); + assertFalse ("scanFilstered output should not be empty", tles.getTransactionLogEntries().size() == 0); + validateTransactionLogEntry(tles.getTransactionLogEntries().get(0)); + } + + /** + * Helper method to validate the contents of a TransactionalLogEntry. + * + * @param tle TransactionalLogEntry to compare against + */ + public void validateTransactionLogEntry(TransactionLogEntry tle){ + String pre = "validateTransactionLogEntry: "; + String post = " didn't match"; + assertEquals(pre + "tid" + post, tle.getTransactionLogEntryId(), tid); + assertEquals(pre + "status" + post, tle.getStatus(), status); + assertEquals(pre + "rqstDate" + post, tle.getRqstDate(), rqstTm); + assertEquals(pre + "respDate" + post, tle.getRespDate(), respTm); + assertEquals(pre + "srcId" + post, tle.getSourceId(), srcId); + assertEquals(pre + "rsrcId" + post, tle.getResourceId(), rsrcId); + assertEquals(pre + "rqstBuf" + post, tle.getRqstBuf(), rqstBuf); + assertEquals(pre + "respBuf" + post, tle.getrespBuf(), respBuf); + if ( hasNotifEvent){ + assertEquals(pre + "notifPayload" + post, tle.getNotificationPayload(), notifPayload); + assertEquals(pre + "notifStatus" + post, tle.getNotificationStatus(), notifStatus); + assertEquals(pre + "notifID" + post, tle.getNotificationId(), notifID); + assertEquals(pre + "notifTopic" + post, tle.getNotificationTopic(), notifTopic); + assertEquals(pre + "notifEntityLink" + post, tle.getNotificationEntityLink(), notifEntityLink); + assertEquals(pre + "notifAction" + post, tle.getNotificationAction(), notifAction); + } + } + + + + /** + * Helper method to mock PojoUtils. + */ + public void mockPojoUtils(){ + + try { + PowerMockito.when(pu.getJsonFromObject(notif)).thenReturn(notifPayload); + } catch (JsonGenerationException e) {e.printStackTrace();} + catch (JsonMappingException e) {e.printStackTrace();} + catch (IOException e) {e.printStackTrace(); } + } + + + + /** + * Helper method to mock a notification event handler. + */ + public void mockNotifEventHandler(){ + PowerMockito.when(ehNotif.getId()).thenReturn(notifID); + PowerMockito.when(ehNotif.getEntityLink()).thenReturn(notifEntityLink); + PowerMockito.when(ehNotif.getAction()).thenReturn(notifAction); + PowerMockito.when(ehNotif.getStatus()).thenReturn(notifStatus); + } + + /** + * Helper method to mock a notification event. + */ + public void mockNotificationEvent(){ + mockPojoUtils(); + mockNotifEventHandler(); + PowerMockito.when(notif.getEventHeader()).thenReturn(ehNotif); + PowerMockito.when(notif.getEventHeader().getEventType()).thenReturn(null); + PowerMockito.when(notif.getEventHeader().getStatus()).thenReturn(null); + } + + + /** + * Helper method to build a mock-Result. + */ + public void mockResult(){ + PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("tid"))).thenReturn(Bytes.toBytes(tid)); + PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("status"))).thenReturn(Bytes.toBytes(status)); + PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("rqstDate"))).thenReturn(Bytes.toBytes(rqstTm)); + PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("respDate"))).thenReturn(Bytes.toBytes(respTm)); + PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("sourceId"))).thenReturn(Bytes.toBytes(srcId)); + + PowerMockito.when(result.getValue(Bytes.toBytes("resource"),Bytes.toBytes("resourceId"))).thenReturn(Bytes.toBytes(rsrcId)); + PowerMockito.when(result.getValue(Bytes.toBytes("resource"),Bytes.toBytes("resourceType"))).thenReturn(Bytes.toBytes(rsrcType)); + + PowerMockito.when(result.getValue(Bytes.toBytes("payload"),Bytes.toBytes("rqstBuf"))).thenReturn(Bytes.toBytes(rqstBuf)); + PowerMockito.when(result.getValue(Bytes.toBytes("payload"),Bytes.toBytes("respBuf"))).thenReturn(Bytes.toBytes(respBuf)); + + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationPayload"))).thenReturn(Bytes.toBytes(notifPayload)); + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationStatus"))).thenReturn(Bytes.toBytes(notifStatus)); + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationId"))).thenReturn(Bytes.toBytes(notifID)); + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationTopic"))).thenReturn(Bytes.toBytes(notifTopic)); + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationEntityLink"))).thenReturn(Bytes.toBytes(notifEntityLink)); + PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationAction"))).thenReturn(Bytes.toBytes(notifAction)); + } + + + /** + * Helper method to load aai config from test configuration file + * This requires that the 'test_aaiconfig.properties' file is available + */ + + static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + + /** + * Partial setup for AAI config. + */ + public void partialSetupForAAIConfig(){ + + try { + setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties"); + } + catch (SecurityException e) {fail();} + catch (NoSuchFieldException e) {fail();} + catch (Exception e) {fail();} + + AAIConfig.reloadConfig(); + } + + /** + * Helper method to set the file name of aaiconfig.properties file + * + * @param field Private static filed for update + * @param newValue New value to be used + * @throws Exception the exception + */ + public void modifyFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java new file mode 100644 index 0000000..5b2d1c4 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.openecomp.aai.util.AAIUtils; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +public class AAIUtilsTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + AAIUtils testObj; + + /** + * Initialize. + */ + @Before + public void initialize(){ + testObj = new AAIUtils(); + } + + /** + * Test nullCheck with null. + */ + @Test + public void testNullCheck_withNull(){ + List<String> newList = null; + assertNotNull("method nullCheck should not return null", AAIUtils.nullCheck(newList)); + } + + /** + * Test nullCheck with a List. + */ + @Test + public void testNullCheck_withList(){ + List<String> newList = new ArrayList<String>(); + newList.add("testString"); + assertNotNull("method nullCheck failed for a List", AAIUtils.nullCheck(newList)); + } + + /** + * Test genDate using a past and a future date. + */ + @Test + public void testGenDate(){ + + Date d1 = new Date(0); + + DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS"); + formatter.setTimeZone(TimeZone.getTimeZone("GMT")); + formatter.setLenient(false); + + Date d2 = null; + + try { + d2 = formatter.parse(AAIUtils.genDate()); + } catch (ParseException e) { + fail("Date parsing exception"); + e.printStackTrace(); + } + + try { + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e1) {} + + Date d3 = new Date(); + + assertTrue("Generated date is not after a past date", d2.after(d1)); + assertTrue("Generated date is not before a future date", d2.before(d3)); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java new file mode 100644 index 0000000..5ba1701 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.security.cert.X509Certificate; + +import javax.security.auth.x500.X500Principal; +import javax.servlet.http.HttpServletRequest; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.aai.util.CNName; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.rule.PowerMockRule; + +import ch.qos.logback.access.spi.IAccessEvent; + +@PowerMockIgnore("javax.security.auth.x500.X500Principal") +@PrepareForTest({IAccessEvent.class, HttpServletRequest.class, X509Certificate.class}) +public class CNNameTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + IAccessEvent mockAccEvent; + HttpServletRequest mockHttpServletRequest; + CNName cnname; + X509Certificate cert; + + /** + * Initialize. + */ + @Before + public void initialize(){ + mockAccEvent = Mockito.mock(IAccessEvent.class); + mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); + cert = Mockito.mock(X509Certificate.class); + } + + + /** + * Test 'convert' when there is no AccessConverter. + */ + @Test + public void testConvert_withoutAccessConverter(){ + cnname = getTestObj(false); + assertTrue("Conversion failed with no AccessConverter", "INACTIVE_HEADER_CONV".equals(cnname.convert(mockAccEvent))); + } + + /** + * Test 'convert' with no CipherSuite. + */ + @Test + public void testConvert_withNullCipherSuite(){ + setupForCipherSuite(null); + assertTrue("Conversion failed for a null CipherSuite", "-".equals(cnname.convert(mockAccEvent))); + } + + + /** + * Test 'convert' with a non-null CipherSuite. + */ + @Test + public void testConvert_withNotNullCipherSuite(){ + + setupForCipherSuite("StrRepOfAValidSuite"); + + final X500Principal principal = new X500Principal("CN=AnAI, OU=DOX, O=BWS, C=CA"); + + Mockito.when(cert.getSubjectX500Principal()).thenReturn(principal); + + final X509Certificate[] certChain = {cert}; + + when(mockHttpServletRequest.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(certChain); + + assertTrue("Conversion failed for a valid CipherSuite", principal.toString().equals(cnname.convert(mockAccEvent))); + } + + + /** + * Helper method to mock IAccessEvent and HttpServletRequest. + * + * @param suite CipherSuite to be used in current test + */ + private void setupForCipherSuite(String suite){ + cnname = getTestObj(true); + when(mockAccEvent.getRequest()).thenReturn(mockHttpServletRequest); + when(mockHttpServletRequest.getAttribute("javax.servlet.request.cipher_suite")).thenReturn(suite); + } + + + /** + * Helper method to create a CNName object with overridden 'start status' . + * + * @param instanceStarted Start status to be used + * @return CNName object to test + */ + private CNName getTestObj(final boolean instanceStarted){ + return new CNName(){ + @Override + public boolean isStarted(){ + return instanceStarted; + } + }; + } +} + + + diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java new file mode 100644 index 0000000..aa946b0 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; +import org.openecomp.aai.util.CNName; +import org.openecomp.aai.util.CustomLogPatternLayout; + +public class CustomLogPatternLayoutTest { + + /** + * Test null when defaultConverterMap doesn't have corresponding entry. + */ + @Test + public void testNull(){ + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + + /** + * Test defaultConverterMap when valid entry exists. + */ + @Test + public void testEntryFor_Z(){ + CustomLogPatternLayout layout = new CustomLogPatternLayout(); + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java new file mode 100644 index 0000000..9df8900 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.assertEquals; + +import org.junit.Rule; +import org.junit.Test; +import org.openecomp.aai.util.DataConversionHelper; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +public class DataConversionHelperTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + /** + * Test convertIPVersionNumToString with value "4". + */ + @Test + public void testConvertIPVersionNumToString_withNum4(){ + assertEquals(DataConversionHelper.IPVERSION_IPV4, DataConversionHelper.convertIPVersionNumToString("4")); + } + + /** + * Test convertIPVersionNumToString with value "6". + */ + @Test + public void testConvertIPVersionNumToString_withNum6(){ + assertEquals(DataConversionHelper.IPVERSION_IPV6, DataConversionHelper.convertIPVersionNumToString("6")); + } + + /** + * Test convertIPVersionNumToString with a value other than "4" or "6". + */ + @Test + public void testConvertIPVersionNumToString_withAThirdNumber(){ + assertEquals(DataConversionHelper.IPVERSION_UNKNOWN, DataConversionHelper.convertIPVersionNumToString("-1")); + } + + /** + * Test convertIPVersionStringToNum with "v4". + */ + @Test + public void testConvertIPVersionStringToNum_withV4(){ + assertEquals("4", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV4)); + } + + /** + * Test convertIPVersionStringToNum with "v6". + */ + @Test + public void testConvertIPVersionStringToNum_withV6(){ + assertEquals("6", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV6)); + } + + /** + * Test convertIPVersionStringToNum with an illegal version. + */ + @Test + public void testConvertIPVersionStringToNum_withRandomString(){ + assertEquals("0", DataConversionHelper.convertIPVersionStringToNum("test string")); + } + + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java new file mode 100644 index 0000000..4f84519 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java @@ -0,0 +1,303 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import java.util.Date; +import java.util.Enumeration; +import java.util.Properties; +import java.util.TimerTask; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Timer; +import java.net.InetAddress; + +public class DbTestConfig { + + public static final String AUDIT_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); + public static final String AUDIT_HOME = (System.getProperty("audit.home") == null) ? AUDIT_FILESEP + "opt" + AUDIT_FILESEP + "audit" : System.getProperty("audit.home"); + public static final String AuditPropFilename = "c:\\tmp\\auditConfig.prop"; + public static final String AUDIT_CONFIG_CHECKINGTIME = "audit.config.checktime"; + public static final String AUDIT_NODENAME = "localhost"; + public static final String AUDIT_DEBUG = "audit.config.debug"; + + private static Properties serverProps; + private static boolean propsInitialized = false; + private static boolean timerSet = false; + private static Timer timer = null; + + private static String propFile = null; + + /** + * Inits the. + * + * @param propertyFile the property file + */ + public synchronized static void init(String propertyFile) { + propFile = propertyFile; + init(); + } + + /** + * Inits the. + */ + public synchronized static void init() { + System.out.println("Initializing Config"); + + DbTestConfig.getConfigFile(); + DbTestConfig.reloadConfig(); + + if ( propFile == null) + propFile = AuditPropFilename; + TimerTask task = null; + task = new DbTestFileWatcher ( new File(propFile)) { + protected void onChange( File file ) { + // here we implement the onChange + DbTestConfig.reloadConfig(); + } + }; + + if (!timerSet) { + timerSet = true; + // repeat the check every second + timer = new Timer(); + String fwi = DbTestConfig.get(AUDIT_CONFIG_CHECKINGTIME); + timer.schedule( task , new Date(), Integer.parseInt(fwi) ); + System.out.println("Config Watcher Interval=" + fwi); + + System.out.println("File" + propFile+" Loaded!"); + } + + } + + /** + * Cleanup. + */ + public static void cleanup() { + timer.cancel(); + } + + /** + * Gets the config file. + * + * @return the config file + */ + public static String getConfigFile() { + return propFile; + } + + /** + * Reload config. + */ + public synchronized static void reloadConfig() { + + String propFileName = propFile; + + Properties newServerProps = null; + + System.out.println("Reloading config from "+propFileName); + + try { + InputStream is = new FileInputStream(propFileName); + newServerProps = new Properties(); + newServerProps.load(is); + propsInitialized = true; + + serverProps = newServerProps; + if (get(AUDIT_DEBUG).equals("on")) { + serverProps.list(System.out); + } + newServerProps = null; + + } catch (FileNotFoundException fnfe) { + System.out.println("AuditConfig: " + propFileName + ". FileNotFoundException: "+fnfe.getMessage()); + } catch (IOException e) { + System.out.println("AuditConfig: " + propFileName + ". IOException: "+e.getMessage()); + } + } + + /** + * Gets the. + * + * @param key the key + * @param defaultValue the default value + * @return the string + */ + public static String get(String key, String defaultValue) { + String result = defaultValue; + try { + result = get (key); + } + catch ( Exception a ) { + } + return result; + } + + /** + * Gets the. + * + * @param key the key + * @return the string + */ + public static String get(String key) { + String response = null; + + if (key.equals(AUDIT_NODENAME)) { + // Get this from InetAddress rather than the properties file + String nodeName = getNodeName(); + if (nodeName != null) { + return nodeName; + } + // else get from property file + } + + if (!propsInitialized || (serverProps == null)) { + reloadConfig(); + } + if (!serverProps.containsKey(key)) { + System.out.println( "Property key "+key+" cannot be found"); + } else { + response = serverProps.getProperty(key); + if (response == null || response.isEmpty()) { + System.out.println("Property key "+key+" is null or empty"); + } + } + return response; + } + + /** + * Gets the int. + * + * @param key the key + * @return the int + */ + public static int getInt(String key) { + return Integer.valueOf(DbTestConfig.get(key)); + } + + /** + * Gets the server props. + * + * @return the server props + */ + public static Properties getServerProps() { + return serverProps; + } + + /** + * Gets the node name. + * + * @return the node name + */ + public static String getNodeName() { + try { + InetAddress ip = InetAddress.getLocalHost(); + if (ip != null) { + String hostname = ip.getHostName(); + if (hostname != null) { + return hostname; + } + } + } catch (Exception e) { + return null; + } + return null; + } + + /** + * Extracts a specific property key subset from the known properties. + * The prefix may be removed from the keys in the resulting dictionary, + * or it may be kept. In the latter case, exact matches on the prefix + * will also be copied into the resulting dictionary. + * + * @param prefix is the key prefix to filter the properties by. + * @param keepPrefix if true, the key prefix is kept in the resulting + * dictionary. As side-effect, a key that matches the prefix exactly + * will also be copied. If false, the resulting dictionary's keys are + * shortened by the prefix. An exact prefix match will not be copied, + * as it would result in an empty string key. + * @return a property dictionary matching the filter key. May be + * an empty dictionary, if no prefix matches were found. + * + * @see #getProperty( String ) is used to assemble matches + */ + public static Properties matchingSubset(String prefix, boolean keepPrefix) { + Properties result = new Properties(); + + // sanity check + if (prefix == null || prefix.length() == 0) { + return result; + } + + String prefixMatch; // match prefix strings with this + String prefixSelf; // match self with this + if (prefix.charAt(prefix.length() - 1) != '.') { + // prefix does not end in a dot + prefixSelf = prefix; + prefixMatch = prefix + '.'; + } else { + // prefix does end in one dot, remove for exact matches + prefixSelf = prefix.substring(0, prefix.length() - 1); + prefixMatch = prefix; + } + // POSTCONDITION: prefixMatch and prefixSelf are initialized! + + // now add all matches into the resulting properties. + // Remark 1: #propertyNames() will contain the System properties! + // Remark 2: We need to give priority to System properties. This is done + // automatically by calling this class's getProperty method. + String key; + for (Enumeration e = serverProps.keys(); e.hasMoreElements(); ) { + key = (String) e.nextElement(); + + if (keepPrefix) { + // keep full prefix in result, also copy direct matches + if (key.startsWith(prefixMatch) || key.equals(prefixSelf)) { + result.setProperty(key, serverProps.getProperty(key)); + } + } else { + // remove full prefix in result, dont copy direct matches + if (key.startsWith(prefixMatch)) { + result.setProperty(key.substring(prefixMatch.length()), serverProps.getProperty(key)); + } + } + } + + // done + return result; + } + + + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + // TODO Auto-generated method stub + DbTestConfig.init( ); + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java new file mode 100644 index 0000000..05a4cfe --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import java.util.*; +import java.io.*; + +public abstract class DbTestFileWatcher extends TimerTask { + private long timeStamp; + private File file; + + /** + * Instantiates a new db test file watcher. + * + * @param file the file + */ + public DbTestFileWatcher( File file ) { + this.file = file; + this.timeStamp = file.lastModified(); + } + + /** + * {@inheritDoc} + */ + public final void run() { + long timeStamp = file.lastModified(); + + if( (timeStamp - this.timeStamp) > 500 ) { + this.timeStamp = timeStamp; + onChange(file); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * On change. + * + * @param file the file + */ + protected abstract void onChange( File file ); +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java new file mode 100644 index 0000000..d56a4d2 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributeView; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileTime; + +public class DbTestGetFileTime { + + + /** + * Creates the file return time. + * + * @param path the path + * @return the file time + * @throws IOException Signals that an I/O exception has occurred. + */ + public FileTime createFileReturnTime( String path) throws IOException { + File file = new File(path); + if(!file.exists()) { + file.createNewFile(); + } + Path p = Paths.get(file.getAbsolutePath()); + BasicFileAttributes view + = Files.getFileAttributeView(p, BasicFileAttributeView.class) + .readAttributes(); + FileTime fileTime=view.creationTime(); + // also available view.lastAccessTine and view.lastModifiedTime + return fileTime; + } +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java new file mode 100644 index 0000000..8d8ebe0 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java @@ -0,0 +1,218 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.attribute.FileTime; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +public class DbTestProcessBuilder { + ///public static Logger clog = Logger.getLogger("auditConsole"); + //public static Logger alog = Logger.getLogger("auditLog"); + + /** + * Start audit process non blocking. + * + * @param wait the wait + * @param cmds the cmds + * @param dir the dir + */ + public void startAuditProcessNonBlocking(final long wait, final String cmds[], final String dir) { + + final ProcessBuilder pb = new ProcessBuilder(cmds).redirectErrorStream(true).directory(new File(dir)); + + new Thread(new Runnable() { + public void run() { + try { + //System.out.println( "sleeping seconds " + wait + " cmds " + Arrays.toString(cmds)); + Thread.sleep(wait*1000); + //System.out.println( "returned from sleep"); + final Process p = pb.start(); + //System.out.println( "returned from pb.start"); + final InputStream is = p.getInputStream(); + final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); + final InputStreamReader isr = new InputStreamReader(is); + final BufferedReader br = new BufferedReader(isr); +//clog.debug("Output of running " + Arrays.toString(cmds) + " is:"); + System.out.println("Output of running is:" ); + String line; + while ((line = br.readLine()) != null ) { + System.out.println(line); + } + System.out.println("stderr of running is:" ); + + while ((line = stdError.readLine()) != null ) { + System.out.println(line); + } + + } catch (IOException ie) { + + } catch (InterruptedException itre) { + Thread.currentThread().interrupt(); + } + } + }).start(); + + } + + + private final ScheduledExecutorService auditProcessScheduler = + Executors.newScheduledThreadPool(10); + + /** + * Run W command every X seconds for Y minutes. + * + * @param w the w + * @param x the x + * @param y the y + * @param runningDir the running dir + */ + public void runWCommandEveryXSecondsForYMinutes(String[] w, int x, int y, final String runningDir) { + final String[] c1 = w; + final Runnable audit = new Runnable() { + public void run() { +//clog.debug("checkpoint "+(new Date()).toString()); + DbTestProcessBuilder a1 = new DbTestProcessBuilder(); + a1.startAuditProcessNonBlocking(1, c1, "/tmp"); + } + }; + + final ScheduledFuture<?> auditHandle = + auditProcessScheduler.scheduleAtFixedRate(audit, 0, x, TimeUnit.SECONDS); + auditProcessScheduler.schedule(new Runnable() { + public void run() { + auditHandle.cancel(true); + } + }, y * 60, TimeUnit.SECONDS); + } + + + /** + * The main method. + * + * @param args the arguments + */ + @SuppressWarnings({ "null", "static-access" }) + public static void main(String args[]) { + String props = "NA"; + if (args.length > 0) { + System.out.println( "DbTestProcessBuilder called with " + args.length + " arguments, " + args[0]); + props = args[0].trim(); + } else { + System.out.print("usage: DbTestProcessBuilder <auditConfig.prop path\n"); + return; + } + DbTestConfig.init(props); + String ail = DbTestConfig.get("audit.list"); + String path = DbTestConfig.get("audit.path"); + final String runningDir = DbTestConfig.get("audit.runningdir"); + try { + DbTestGetFileTime getFileTime = new DbTestGetFileTime(); + FileTime fileTime = getFileTime.createFileReturnTime( path ); + System.out.println(path + " creation time :" + + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss") + .format(fileTime.toMillis()) + " runningDir " + runningDir); + } catch ( IOException io ) { + System.out.println( "IOException getting creation time " + path + " message " + io.getMessage()); + io.printStackTrace(); + } + + List<String> items = Arrays.asList(ail.split("\\s*,\\s*")); + for (String ai: items) { + if (!DbTestConfig.get("audit.task."+ai+".status").startsWith("a")) { + continue; + } +//clog.debug("***audit item = " + ai + " Starting***"); + + String w1 = DbTestConfig.get("audit.task."+ai+".cmd"); + String[] w2 = w1.split("\\s*,\\s*"); + System.out.print( "task items are : " + Arrays.toString(w2)); + // append the audit item name as the prefix of the audit directory name + /*final int N = w2.length; + w2 = Arrays.copyOf(w2, N+1); + w2[N-2] = "\"-Dp=" + DbTestConfig.get("audit.task.odl.output.dir")+ai + "\""; +//clog.debug("***java -D:"+w2[N-2]); + //w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\""; + w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\""; + */ + DbTestProcessBuilder apb = new DbTestProcessBuilder(); + + String ts1 = DbTestConfig.get("audit.task."+ai+".schedule"); + String[] ts2 = ts1.split("\\s*,\\s*"); + // note ts2[0] is the wait-before time, and it is not being used right now. We start with ts2[1] + apb.runWCommandEveryXSecondsForYMinutes(w2,Integer.parseInt(ts2[1]),Integer.parseInt(ts2[2]), runningDir); +//clog.debug("***audit item = " + ai + " started***"); + System.out.println( "started test " + ai); + + /* + int ct = 0; + + while (true) try { + if (DbTestConfig.get("jcl").startsWith("q")) { + System.out.println("***Audit Main Program exiting..."); + System.exit(0); + } + + Thread.currentThread().sleep(1000); + if (ct < 10) { + ct++; + } else { + //clog.debug(AuditConfig.get("jcl").charAt(0)); + ct=0; + } + + } catch (InterruptedException ie) { + + } */ + } + int ct = 0; + + while (true) try { + if (DbTestConfig.get("jcl").startsWith("q")) { + System.out.println("***Audit Main Program exiting..."); + System.exit(0); + } + + Thread.currentThread().sleep(1000); + if (ct < 10) { + ct++; + } else { + //clog.debug(AuditConfig.get("jcl").charAt(0)); + ct=0; + } + + } catch (InterruptedException ie) { + + } + + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java new file mode 100644 index 0000000..efe4a41 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + + + +import static org.junit.Assert.assertEquals; + +import static org.junit.Assert.assertFalse; + +import static org.junit.Assert.assertTrue; + +import static org.junit.Assert.fail; + +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.util.DeleteResource; +import org.openecomp.aai.domain.yang.PhysicalLink; + + + +public class DeleteResourceTest { + + + + /** + * Test getInstance. + */ + + @Test + + public void testGetInstance(){ + + Object obj = null; + + try { + + obj = DeleteResource.getInstance(DeleteResource.class); + + } catch (IllegalAccessException | InstantiationException e) { + + e.printStackTrace(); + + } + + assertTrue("Didn't get right instance", obj instanceof DeleteResource); + + } + + + + /** + * Test GetResourceVersion. + */ + @Ignore + @Test + + public void testGetResourceVersion(){ + + String version = "aVersion"; + + PhysicalLink plink = new PhysicalLink(); + + plink.setResourceVersion(version); + + assertEquals("Versions didn't match", version, DeleteResource.GetResourceVersion(plink)); + + } + + + + /** + * Test null in GetResourceVersion. + */ + + @Test + + public void testGetResourceVersion_withNull(){ + + PhysicalLink plink = new PhysicalLink(); + + assertEquals("Versions didn't match", null, DeleteResource.GetResourceVersion(plink)); + + } + + + +} + diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java new file mode 100644 index 0000000..ff1b53b --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.openecomp.aai.util.HbaseSaltPrefixer; + +public class HbaseSaltPrefixerTest { + + /** + * Test. + */ + @Test + public void test() { + String key = "imakey"; + String saltedKey = HbaseSaltPrefixer.getInstance().prependSalt(key); + assertTrue(saltedKey.equals("0-imakey")); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java new file mode 100644 index 0000000..39fec9b --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.util; + +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; +import org.openecomp.aai.util.JettyObfuscationConversionCommandLineUtil; + + +public class JettyObfuscationConversionCommandLineUtilTest { + private final ByteArrayOutputStream testOut = new ByteArrayOutputStream(); + + /** + * Test. + */ + @Test + public void test() { + //setup, this will catch main's print statements for evaluation + System.setOut(new PrintStream(testOut)); + + /* ------ TEST OBFUSCATION ----*/ + JettyObfuscationConversionCommandLineUtil.main(new String[]{"-e", "hello world"}); + /* + * testOut was also catching any logging statements which interfered with result checking. + * This regex business was the workaround - it tries to find the expected value in + * the results and asserts against that. + */ + String obfResult = testOut.toString(); + String obfExpected = "OBF:1thf1ugo1x151wfw1ylz11tr1ymf1wg21x1h1uh21th7"; + Pattern obfExpectPat = Pattern.compile(obfExpected); + Matcher obfMatch = obfExpectPat.matcher(obfResult); + assertTrue(obfMatch.find()); + + testOut.reset(); //clear out previous result + + /* ------ TEST DEOBFUSCATION ----- */ + JettyObfuscationConversionCommandLineUtil.main(new String[]{"-d", obfExpected}); + String deobfResult = testOut.toString(); + String deobfExpected = "hello world"; + Pattern deobfExpectPat = Pattern.compile(deobfExpected); + Matcher deobfMatch = deobfExpectPat.matcher(deobfResult); + assertTrue(deobfMatch.find()); + + //clean up, resets to stdout + System.setOut(null); + } + +} diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java new file mode 100644 index 0000000..80bcef8 --- /dev/null +++ b/ajsc-aai/src/test/java/org/openecomp/aai/workarounds/RemoveDME2QueryParamsTest.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 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.openecomp.aai.workarounds; + +import static org.junit.Assert.*; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.aai.workarounds.RemoveDME2QueryParams; + +public class RemoveDME2QueryParamsTest { + + private MultivaluedMap<String, String> hasParams; + private MultivaluedMap<String, String> doesNotHaveParams; + private RemoveDME2QueryParams removeParams = new RemoveDME2QueryParams(); + + /** + * Setup. + */ + @Before + public void setup() { + hasParams = new MultivaluedHashMap<>(); + doesNotHaveParams = new MultivaluedHashMap<>(); + + hasParams.add("version", "1"); + hasParams.add("envContext", "DEV"); + hasParams.add("routeOffer", "INT1"); + hasParams.add("test1", "peppermints"); + hasParams.add("test2", "amber"); + + doesNotHaveParams.add("version", "1"); + doesNotHaveParams.add("envContext", "DEV"); + doesNotHaveParams.add("test1", "peppermints"); + doesNotHaveParams.add("test2", "amber"); + + } + + /** + * Test removal. + */ + @Test + public void testRemoval() { + + if (removeParams.shouldRemoveQueryParams(hasParams)) { + removeParams.removeQueryParams(hasParams); + } + + assertEquals("no version", false, hasParams.containsKey("version")); + assertEquals("no envContext", false, hasParams.containsKey("envContext")); + assertEquals("no routeOffer", false, hasParams.containsKey("routeOffer")); + assertEquals("has test1", true, hasParams.containsKey("test1")); + assertEquals("has test2", true, hasParams.containsKey("test2")); + + } + + /** + * Should not remove. + */ + @Test + public void shouldNotRemove() { + + if (removeParams.shouldRemoveQueryParams(doesNotHaveParams)) { + removeParams.removeQueryParams(doesNotHaveParams); + } + + assertEquals("no version", true, doesNotHaveParams.containsKey("version")); + assertEquals("no envContext", true, doesNotHaveParams.containsKey("envContext")); + assertEquals("has test1", true, doesNotHaveParams.containsKey("test1")); + assertEquals("has test2", true, doesNotHaveParams.containsKey("test2")); + } +} |