diff options
Diffstat (limited to 'dcaedt_be/src/test/java/org')
7 files changed, 1186 insertions, 0 deletions
diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/VesStructureLoaderMock.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/VesStructureLoaderMock.java new file mode 100644 index 0000000..34db9fa --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/VesStructureLoaderMock.java @@ -0,0 +1,116 @@ +package org.onap.sdc.dcae; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; +import com.google.gson.JsonSyntaxException; +import com.google.gson.reflect.TypeToken; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.sdc.dcae.ves.EventListenerDefinition; +import org.onap.sdc.dcae.ves.VesDataItemsDefinition; +import org.onap.sdc.dcae.ves.VesDataTypeDefinition; +import org.onap.sdc.dcae.ves.VesJsonDeserializer; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FilenameFilter; +import java.lang.reflect.Type; +import java.util.*; +import java.util.stream.Collectors; + +public class VesStructureLoaderMock { + + private Map<String, EventListenerDefinition> eventListeners = new HashMap<>(); + private Type type = new TypeToken<VesDataItemsDefinition>() { + }.getType(); + private Gson gson = new GsonBuilder().registerTypeAdapter(type, new VesJsonDeserializer()).create(); + private final String schemaNamePrefix = "CommonEventFormat_v"; + private final String schemaNameSuffix = ".json"; + private List<String> initErrors; + + public VesStructureLoaderMock() { + this(true); + } + + public VesStructureLoaderMock(boolean validateAndResolve) { + this(validateAndResolve, System.getProperty("user.dir") + "/src/test/resources/ves-schema"); + } + + public VesStructureLoaderMock(boolean validateAndResolve, String path) { + initErrors = init(validateAndResolve, path); + } + + public List<String> init(boolean validateAndResolve, String pathToSchemaDir) { + + List<String> parseErrors = new ArrayList<>(); + File dir = new File(pathToSchemaDir); + File[] files = dir.listFiles(new FilenameFilter() { + @Override public boolean accept(File dir, String name) { + return name.startsWith(schemaNamePrefix) && name.endsWith(schemaNameSuffix); + } + }); + if (ArrayUtils.isEmpty(files)) { + parseErrors.add("No VES schema files found"); + } else { + for (File f : files) { + String error = parseJsonFileAndSaveToMap(f, validateAndResolve); + if (StringUtils.isNotBlank(error)) { + parseErrors.add("Error: parsing VES schema file " + f.getName() + " failed due to " + error); + } + } + } + return parseErrors; + + } + + public Map<String, VesDataTypeDefinition> getEventListenerDefinitionByVersion(String version) { + return eventListeners.get(version).getProperties().get(EventListenerDefinition.EVENT_ROOT).getProperties(); + } + + public Set<String> getAvailableVersionsList() { + return eventListeners.keySet(); + } + + public Map<String, Set<String>> getAvailableVersionsAndEventTypes() { + return eventListeners.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> getEventListenerDefinitionByVersion(e.getKey()).keySet())); + } + + public Set<String> getEventTypeListByVersion(String version) { + return getEventListenerDefinitionByVersion(version).keySet(); + } + + public String getVersionFromFileName(String fileName) { + return fileName.replace(schemaNamePrefix, "").replace(schemaNameSuffix, ""); + } + + private String parseJsonFileAndSaveToMap(File file, boolean validateAndResolve) { + String validationError = null; + try { + EventListenerDefinition eventListener = gson.fromJson(new FileReader(file), EventListenerDefinition.class); + if (validateAndResolve) + validationError = getValidatorMessage(eventListener); + if (StringUtils.isEmpty(validationError)) + eventListeners.put(getVersionFromFileName(file.getName()), eventListener); + } catch (FileNotFoundException | JsonIOException | JsonSyntaxException e) { + validationError = e.getMessage(); + } + return validationError; + } + + public Map<String, EventListenerDefinition> getEventListeners() { + return eventListeners; + } + + public List<String> getInitErrors() { + return initErrors; + } + + private String getValidatorMessage(EventListenerDefinition eventListenerDefinition) { + String validationError = eventListenerDefinition.validate(); + if (StringUtils.isBlank(validationError)) + validationError = eventListenerDefinition.resolveRefTypes(); + return validationError; + } +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java new file mode 100644 index 0000000..c353701 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/ReferenceBusinessLogicTest.java @@ -0,0 +1,123 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; +import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.*; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; + +@RunWith(MockitoJUnitRunner.class) +public class ReferenceBusinessLogicTest { + private String userId = "me"; + private String requestId = "1"; + private String monitoringComponentName = "monitoringComponentName"; + private String serviceUuid = "serviceUuid"; + private String vfiName = "vfiName"; + + @Mock + private ISdcClient sdcClientMock; + @Mock + private ResourceDetailed templateMC; + + @InjectMocks + ReferenceBusinessLogic classUnderTest; + + @Before + public void setup(){ + classUnderTest.setSdcRestClient(sdcClientMock); + new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + } + + @Test + public void successfulFetchMonitoringComponents() throws Exception { + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + ExternalReferencesMap refs = new ExternalReferencesMap(); + refs.put("vfi1", Arrays.asList("a","b","c","d")); + refs.put("vfi2", Arrays.asList("u","v","w","x","y","z")); + Map<String, List<MonitoringComponent>> result = classUnderTest.fetchMonitoringComponents(refs, requestId); + verify(sdcClientMock,times(10)).getResource(anyString(),anyString()); + Assert.assertEquals(1, result.size()); + Assert.assertEquals(10, result.get("monitoringComponents").size()); + } + + @Test + public void partialSuccessfulFetchMonitoringComponents() throws Exception { + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + when(sdcClientMock.getResource(eq("no_such_uuid"),anyString())).thenThrow(new HttpClientErrorException(HttpStatus.NOT_FOUND)); + ExternalReferencesMap refs = new ExternalReferencesMap(); + refs.put("vfi1", Collections.singletonList("abc")); + refs.put("vfi2", Collections.singletonList("xyz")); + refs.put("vfi3", Collections.singletonList("no_such_uuid")); + Map<String, List<MonitoringComponent>> result = classUnderTest.fetchMonitoringComponents(refs, requestId); + verify(sdcClientMock,times(3)).getResource(anyString(),anyString()); + Assert.assertEquals(2, result.size()); + Assert.assertEquals(2, result.get("monitoringComponents").size()); + Assert.assertEquals(1, result.get("unavailable").size()); + } + + @Test(expected=RuntimeException.class) + public void deleteVfcmtReference_deleteFailed() { + doThrow(RuntimeException.class).when(sdcClientMock).deleteExternalMonitoringReference(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + classUnderTest.deleteVfcmtReference(userId, "", "", "", "", requestId); + } + @Test + public void deleteVfcmtReference_deleteSuccess() { + classUnderTest.deleteVfcmtReference(userId, "", "", "", "", requestId); + verify(sdcClientMock).deleteExternalMonitoringReference(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + } + + private void mockGetService() throws Exception { + ServiceDetailed serviceDetailed = new ServiceDetailed(); + ResourceInstance resourceInstance = new ResourceInstance(); + Artifact artifact = new Artifact(); + artifact.setArtifactName(monitoringComponentName); + resourceInstance.setArtifacts(Collections.singletonList(artifact)); + resourceInstance.setResourceInstanceName(vfiName); + serviceDetailed.setResources(Collections.singletonList(resourceInstance)); + when(sdcClientMock.getService(serviceUuid, requestId)).thenReturn(serviceDetailed); + } + + @Test + public void deleteVfcmtReferenceBlueprint_deleteSuccess() throws Exception { + mockGetService(); + ResponseEntity responseEntity = classUnderTest.deleteVfcmtReferenceBlueprint(userId, "", monitoringComponentName, serviceUuid, vfiName, "", requestId); + verify(sdcClientMock).getService(serviceUuid, requestId); + verify(sdcClientMock).deleteInstanceResourceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + public void deleteVfcmtReferenceBlueprint_exceptionSdcGetService() throws Exception { + when(sdcClientMock.getService(serviceUuid, requestId)).thenThrow(new RuntimeException("")); + + ResponseEntity<ResponseFormat> responseEntity = classUnderTest.deleteVfcmtReferenceBlueprint(userId, "", monitoringComponentName, serviceUuid, vfiName, "", requestId); + + Assert.assertEquals("The request was partially successful. Removing the attached Blueprint from the service has failed. You must manually delete the artifact.", responseEntity.getBody().getRequestError().getServiceException().getFormattedErrorMessage()); + } + + @Test + public void deleteVfcmtReferenceBlueprint_exceptionSdcdeleteInstanceResourceArtifact() throws Exception { + mockGetService(); + doThrow(new RuntimeException("")).when(sdcClientMock).deleteInstanceResourceArtifact(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()); + + ResponseEntity<ResponseFormat> responseEntity = classUnderTest.deleteVfcmtReferenceBlueprint(userId, "", monitoringComponentName, serviceUuid, vfiName, "", requestId); + + Assert.assertEquals("The request was partially successful. Removing the attached Blueprint from the service has failed. You must manually delete the artifact.", responseEntity.getBody().getRequestError().getServiceException().getFormattedErrorMessage()); + } +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java new file mode 100644 index 0000000..12ed040 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/VfcmtBusinessLogicTest.java @@ -0,0 +1,310 @@ +package org.onap.sdc.dcae.composition.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.dcae.catalog.asdc.ASDCException; +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.client.SdcRestClient; +import org.onap.sdc.dcae.composition.restmodels.CreateVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.ImportVFCMTRequest; +import org.onap.sdc.dcae.composition.restmodels.MonitoringComponent; +import org.onap.sdc.dcae.composition.restmodels.VfcmtData; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +import org.onap.sdc.dcae.composition.restmodels.sdc.ExternalReferencesMap; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.PolicyException; +import org.onap.sdc.dcae.errormng.RequestError; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.HttpClientErrorException; + +import java.util.*; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; +import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum.CERTIFIED; +import static org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT; + +public class VfcmtBusinessLogicTest { + + private ISdcClient sdcClientMock = Mockito.mock(SdcRestClient.class); + private ResourceDetailed templateMC = Mockito.mock(ResourceDetailed.class); + + private VfcmtBusinessLogic vfcmtBusinessLogic = new VfcmtBusinessLogic(); + private ImportVFCMTRequest request = new ImportVFCMTRequest(); + + private String userId = "me"; + private String requestId = "1"; + + @Before + public void setup(){ + MockitoAnnotations.initMocks(this); + new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + vfcmtBusinessLogic.setSdcRestClient(sdcClientMock); + request.setTemplateUuid("577"); + request.setVfiName("vfi_XX"); + request.setDescription("description"); + request.setFlowType("SNMP"); + request.setName("newVfcmt"); + request.setServiceUuid("service99999"); + request.setContextType("services"); + } + + @Test + public void sdcIsDown_creatingVfcmt_gotResponseWithError500() throws Exception{ + RequestError requestError = new RequestError(); + requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); + when(sdcClientMock.createResource(userId,request,requestId)).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); + + ResponseEntity res = vfcmtBusinessLogic.createMcFromTemplate(userId,request,requestId); + verify(sdcClientMock).getResource("577",requestId); + verify(sdcClientMock,times(0)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(500, res.getStatusCodeValue()); + } + + @Test + public void uploadCloneCdumpFailed_creatingVfcmt_createVfcmtRolledBack() throws Exception { + RequestError requestError = new RequestError(); + requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); + when(sdcClientMock.createResourceArtifact(anyString(),anyString(),any(),anyString())).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); + when(sdcClientMock.createResource(userId,request,requestId)).thenReturn(templateMC); + when(sdcClientMock.getResourceArtifact(anyString(), anyString(), anyString())).thenReturn("{\"flowType\":\"don't override\""); + when(templateMC.getUuid()).thenReturn("3"); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + emulateListOfArtifactsWithCompositionYml(); + + vfcmtBusinessLogic.createMcFromTemplate(userId, request, requestId); + + // making sure rollback is performed if exception is thrown + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + // happy happy joy joy + @Test + public void successfulCreationAndAttachmentOfVfcmt() throws Exception { + when(templateMC.getUuid()).thenReturn("3"); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + ResourceDetailed mockedVfcmt = Mockito.mock(ResourceDetailed.class); + when(mockedVfcmt.getUuid()).thenReturn("5"); + when(sdcClientMock.createResource(anyString(),any(),anyString())).thenReturn(mockedVfcmt); + when(sdcClientMock.getResourceArtifact(anyString(),anyString(),anyString())).thenReturn("3243324"); + + emulateListOfArtifactsWithCompositionYml(); + + vfcmtBusinessLogic.createMcFromTemplate(userId, request,requestId); + + verify(sdcClientMock).createResource(userId, request,requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock).getResourceArtifact(anyString(),anyString(),anyString()); + verify(sdcClientMock, times(2)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock).addExternalMonitoringReference(anyString(),any(),any(),anyString()); + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + @Test + public void successfulImportAndAttachmentOfVfcmtAlreadyConnectedWithoutEditDoCheckin() throws Exception { + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + when(sdcClientMock.getResourceArtifact(anyString(),anyString(),anyString())).thenReturn("{\"flowType\":\"don't override\"}"); + when(templateMC.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKOUT"); + emulateListOfArtifactsWithCompositionYmlAndSvcRef(); + request.setCloneVFCMT(false); + request.setUpdateFlowType(false); + vfcmtBusinessLogic.importMC(userId, request, requestId); + + verify(sdcClientMock, times(0)).createResource(userId, request, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock).getResourceArtifact(anyString(),anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock, times(0)).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock).addExternalMonitoringReference(anyString(),any(),any(),anyString()); + verify(sdcClientMock).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + + @Test + public void successfulImportAndAttachmentOfVfcmtAlreadyConnectedUpdateFlowTypeCheckoutCheckin() throws Exception { + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + when(templateMC.getUuid()).thenReturn("3"); + when(sdcClientMock.changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(templateMC); + when(sdcClientMock.updateResourceArtifact(anyString(), anyString(), any(), anyString())).thenReturn(new Artifact()); + when(sdcClientMock.getResourceArtifact(anyString(),anyString(),anyString())).thenReturn("{\"cid\":\"xsssdaerrwr\"}"); + when(templateMC.getLifecycleState()).thenReturn("NOT_CERTIFIED_CHECKIN").thenReturn("NOT_CERTIFIED_CHECKOUT"); + emulateListOfArtifactsWithCompositionYmlAndSvcRef(); + request.setCloneVFCMT(false); + request.setUpdateFlowType(true); + vfcmtBusinessLogic.importMC(userId, request, requestId); + + verify(sdcClientMock, times(0)).createResource(userId, request, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock).getResourceArtifact(anyString(),anyString(),anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(),anyString(),any(),anyString()); + verify(sdcClientMock, times(1)).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock).addExternalMonitoringReference(anyString(),any(),any(),anyString()); + verify(sdcClientMock, times(2)).changeResourceLifecycleState(anyString(),anyString(),anyString(),anyString(),anyString()); + } + + + @Test + public void successfulFetchVfcmtDataFull() throws Exception { + String templateUuid = "3"; + when(templateMC.getUuid()).thenReturn(templateUuid); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + emulateListOfArtifactsWithCompositionYmlAndSvcRef(); + when(sdcClientMock.getResourceArtifact(templateUuid, "svcRefArtifactUuid", requestId)).thenReturn("thisIsTheServiceId/resources/thisIsTheVfiName"); + when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn("\"flowType\":\"Syslog\""); + ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock,times(2)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(200, result.getStatusCodeValue()); + Assert.assertEquals("Syslog", result.getBody().getFlowType()); + Assert.assertEquals("thisIsTheServiceId", result.getBody().getServiceUuid()); + Assert.assertEquals("thisIsTheVfiName", result.getBody().getVfiName()); + } + + @Test + public void successfulFetchVfcmtDataPartial() throws Exception { + String templateUuid = "3"; + when(templateMC.getUuid()).thenReturn(templateUuid); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn("\"flowType\":\"Syslog\""); + ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock,times(1)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(200, result.getStatusCodeValue()); + Assert.assertEquals("Syslog", result.getBody().getFlowType()); + Assert.assertEquals(null, result.getBody().getServiceUuid()); + Assert.assertEquals(null, result.getBody().getVfiName()); + } + + @Test + public void successfulFetchVfcmtDataEmpty() throws Exception { + + String templateUuid = "3"; + when(templateMC.getUuid()).thenReturn(templateUuid); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + emulateListOfArtifactsWithCompositionYml(); + when(sdcClientMock.getResourceArtifact(templateUuid, "compositionArtifactUuid", requestId)).thenReturn(""); + ResponseEntity<VfcmtData> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock,times(1)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(200, result.getStatusCodeValue()); + Assert.assertEquals(null, result.getBody().getFlowType()); + Assert.assertEquals(null, result.getBody().getServiceUuid()); + Assert.assertEquals(null, result.getBody().getVfiName()); + } + + @Test + public void fetchVfcmtDataNoCompositionFound() throws Exception { + + String templateUuid = "3"; + when(templateMC.getUuid()).thenReturn(templateUuid); + when(templateMC.getName()).thenReturn(templateUuid); + when(sdcClientMock.getResource(anyString(),anyString())).thenReturn(templateMC); + ResponseEntity<ResponseFormat> result = vfcmtBusinessLogic.getVfcmtReferenceData(templateUuid, requestId); + verify(sdcClientMock).getResource(anyString(),anyString()); + verify(sdcClientMock,times(0)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(404, result.getStatusCodeValue()); + Assert.assertEquals("Error – Could not read component 3 details.", result.getBody().getRequestError().getServiceException().getFormattedErrorMessage()); + + } + + @Test + public void getVfcmtsForMigration() throws Exception { + ExternalReferencesMap connectedVfcmts = new ExternalReferencesMap(); + connectedVfcmts.put("11",Arrays.asList("Red", "Blue", "Yellow")); + connectedVfcmts.put("22",Arrays.asList("Ibiza", "Bora Bora", "Mykonos")); + connectedVfcmts.put("33",Arrays.asList("Large", "Medium", "Small")); + connectedVfcmts.put("44",Arrays.asList("Basket", "Foot", "Volley")); + + when(sdcClientMock.getMonitoringReferences(anyString(),anyString(),anyString(),anyString())).thenReturn(connectedVfcmts); + + Resource myRedResource = new Resource(); + myRedResource.setUuid("Red"); + myRedResource.setLastUpdaterUserId("me"); + myRedResource.setLifecycleState(NOT_CERTIFIED_CHECKOUT.name()); + + Resource herRaphaelResource = new Resource(); + herRaphaelResource.setUuid("Raphael"); + herRaphaelResource.setLastUpdaterUserId("her"); + herRaphaelResource.setLifecycleState(NOT_CERTIFIED_CHECKOUT.name()); + + Resource myMediumResource = new Resource(); + myMediumResource.setUuid("Medium"); + myMediumResource.setLastUpdaterUserId("me"); + + Resource herDonateloResource = new Resource(); + herDonateloResource.setUuid("Donatelo"); + herDonateloResource.setLastUpdaterUserId("her"); + herDonateloResource.setVersion("1.0"); + + Resource hisMykonosResource = new Resource(); + hisMykonosResource.setUuid("Mykonos"); + hisMykonosResource.setLastUpdaterUserId("his"); + hisMykonosResource.setLifecycleState(NOT_CERTIFIED_CHECKOUT.name()); + + Resource hisMichaelangeloResource = new Resource(); + hisMichaelangeloResource.setUuid("Michaelangelo"); + hisMichaelangeloResource.setLastUpdaterUserId("his"); + hisMykonosResource.setLifecycleState(CERTIFIED.name()); + hisMykonosResource.setVersion("1.1"); + + // Versions and connectivity to service shouldn't be part of this test as these are passed to SDC to be + // filtered by SDC requests (getMonitoringReference and getResource) + + List<Resource> theVfcmts = Arrays.asList(myRedResource,herRaphaelResource,myMediumResource,herDonateloResource,hisMykonosResource,hisMichaelangeloResource); + + when(sdcClientMock.getResources(anyString(),anyString(),anyString(),anyString())).thenReturn(theVfcmts); + + ResponseEntity<List<Resource>> response = vfcmtBusinessLogic.getVfcmtsForMigration(userId,"service","5544","1.0",requestId); + + Assert.assertEquals(2, response.getBody().size()); + Assert.assertEquals(200, response.getStatusCodeValue()); + } + + private void emulateListOfArtifactsWithCompositionYml() { + List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); + Artifact compositionArtifact = Mockito.mock(Artifact.class); + when(compositionArtifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + when(compositionArtifact.getArtifactUUID()).thenReturn("compositionArtifactUuid"); + when(compositionArtifact.getPayloadData()).thenReturn("{\"flowType\":\"don't override\"}"); + listOfArtifactCompositionYml.add(compositionArtifact); + when(templateMC.getArtifacts()).thenReturn(listOfArtifactCompositionYml); + } + + private void emulateListOfArtifactsWithCompositionYmlAndSvcRef() { + List<Artifact> listOfArtifactCompositionYml = new ArrayList<>(); + Artifact compositionArtifact = Mockito.mock(Artifact.class); + Artifact svcRefArtifact = Mockito.mock(Artifact.class); + when(compositionArtifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.COMPOSITION_YML); + when(compositionArtifact.getArtifactUUID()).thenReturn("compositionArtifactUuid"); + when(compositionArtifact.getPayloadData()).thenReturn("{\"flowType\":\"don't override\"}"); + when(svcRefArtifact.getArtifactName()).thenReturn(DcaeBeConstants.Composition.fileNames.SVC_REF); + when(svcRefArtifact.getArtifactUUID()).thenReturn("svcRefArtifactUuid"); + listOfArtifactCompositionYml.add(compositionArtifact); + listOfArtifactCompositionYml.add(svcRefArtifact); + when(templateMC.getArtifacts()).thenReturn(listOfArtifactCompositionYml); + } + + @Test + public void uiHasABug_creatingVfcmtWithBadRequestNoServiceUuid_gotResponseWithError400() throws Exception{ + RequestError requestError = new RequestError(); + requestError.setPolicyException(new PolicyException("POL5000", "Error: Internal Server Error. Please try again later.", null)); + when(sdcClientMock.createResource(userId,request,requestId)).thenThrow(new ASDCException(HttpStatus.INTERNAL_SERVER_ERROR, requestError)); + CreateVFCMTRequest req = new CreateVFCMTRequest(); + req.setServiceUuid(null); + ResponseEntity res = vfcmtBusinessLogic.createMcFromTemplate(userId,req,requestId); + verify(sdcClientMock,times(0)).getResource(anyString(),anyString()); + verify(sdcClientMock,times(0)).getResourceArtifact(anyString(),anyString(),anyString()); + Assert.assertEquals(400, res.getStatusCodeValue()); + } +}
\ No newline at end of file diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java new file mode 100644 index 0000000..d3ae600 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/rule/editor/impl/RulesBusinessLogicTest.java @@ -0,0 +1,304 @@ +package org.onap.sdc.dcae.rule.editor.impl; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.ResponseFormatManager; +import org.onap.sdc.dcae.errormng.ServiceException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.*; + +public class RulesBusinessLogicTest { + private static Gson gson = new GsonBuilder() + .registerTypeAdapter(BaseAction.class, new ActionDeserializer()) + .registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()).create(); + + @InjectMocks + private RulesBusinessLogic rulesBusinessLogic = new RulesBusinessLogic(); + private ResponseFormatManager responseFormatManager = null; + + @Before + public void setup(){ + MockitoAnnotations.initMocks(this); + ErrorConfigurationLoader errorConfigurationLoader = new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + responseFormatManager = ResponseFormatManager.getInstance(); + } + + @Test + public void translateSingleRuleSingleCopyActionAddSnmpHeader() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\"},\"class\":\"Set\"}]}," + + "{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + + Rule rule = new Rule(); + rule.setActions(new ArrayList<>()); + rule.getActions().add(buildCopyAction("2.0","event.commonEventHeader.version")); + rule.setDescription("description"); + MappingRules mr = new MappingRules(rule); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void translateSingleRuleSingleDateFormatterActionSnmpFlow() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"fromFormat\":\"fromFormat\",\"fromTz\":\"fromTZ\",\"toField\":\"targetField\",\"toFormat\":\"toFormat\",\"toTz\":\"toTz\",\"value\":\"fromField\",\"class\":\"DateFormatter\"}]}," + + "{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + + Rule rule = new Rule(); + rule.setActions(new ArrayList<>()); + rule.getActions().add(buildDateFormatterAction()); + rule.setDescription("description"); + MappingRules mr = new MappingRules(rule); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void translateSingleRuleMultipleCopyActionsAddSnmpHeader() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\"," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + + MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void translateMultipleRulesMultipleCopyActionsAddSnmpHeader() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\"," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\"," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + + MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); + mr.addOrReplaceRule(buildRuleWithMultipleCopyActions()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void emptyStringTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"map\":{\"\":\"\"},\"field\":\"\",\"toField\":\"mapTargetField\",\"default\":\"\",\"class\":\"MapAlarmValues\"}]}," + + "{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String ruleRequestBody = "{version:4.1,eventType:syslogFields,description:description,actions:[{actionType:map,from:{value:'\"\"'},target:mapTargetField,map:{values:[{key:'\"\"',value:'\"\"'}],haveDefault:true,default:'\"\"'}}]}"; + Rule myRule = gson.fromJson(ruleRequestBody, Rule.class); + MappingRules mr = new MappingRules(myRule); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void singleStringConditionTranslationTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"syslog_map\",\"processors\":[{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"filter\":{\"string\":\"left\",\"value\":\"right\",\"class\":\"Contains\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String input = "{operator:contains,left:left,right:[right]}"; + Rule rule = buildRuleWithMultipleCopyActions(); + rule.setCondition(gson.fromJson(input, BaseCondition.class)); + MappingRules mr = new MappingRules(rule); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "syslog_map", "map_publish", "phase_1")); + } + + @Test + public void multiStringConditionTranslationTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"foi_map\",\"processors\":[{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]}," + + "{\"phase\":\"phase_1\",\"filter\":{\"filters\":[{\"string\":\"left\",\"value\":\"right1\",\"class\":\"Contains\"},{\"string\":\"left\",\"value\":\"right2\",\"class\":\"Contains\"}],\"class\":\"Or\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String input = "{operator:contains,left:left,right:[right1, right2]}"; + Rule rule = buildRuleWithMultipleCopyActions(); + rule.setCondition(gson.fromJson(input, BaseCondition.class)); + MappingRules mr = new MappingRules(rule); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "foi_map", "map_publish", "phase_1")); + } + + @Test + public void singleFieldConditionTranslationTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"filter\":{\"field\":\"left\",\"value\":\"right\",\"class\":\"Equals\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String input = "{operator:equals,left:left,right:[right]}"; + Rule rule = buildRuleWithMultipleCopyActions(); + rule.setCondition(gson.fromJson(input, BaseCondition.class)); + MappingRules mr = new MappingRules(rule); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void multiFieldConditionTranslationTest() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"snmp_map\",\"processors\":[{\"array\":\"varbinds\",\"datacolumn\":\"varbind_value\",\"keycolumn\":\"varbind_oid\",\"class\":\"SnmpConvertor\"}," + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"filter\":{\"field\":\"left\",\"values\":[\"right1\",\"right2\"],\"class\":\"NotOneOf\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\",\"event.commonEventHeader.eventId\":\"${event.commonEventHeader.sourceName}_${eventGroup}\"},\"class\":\"Set\"}," + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String input = "{operator:notequal,left:left,right:[right1,right2]}"; + Rule rule = buildRuleWithMultipleCopyActions(); + rule.setCondition(gson.fromJson(input, BaseCondition.class)); + MappingRules mr = new MappingRules(rule); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + } + + @Test + public void reorderRuleActionsDuringValidationSuccessTest() { + Rule rule1 = buildValidRuleWithDependentActions(); + Rule rule2 = buildValidRuleWithDependentActions(); + assertEquals(rule1, rule2); + List<ServiceException> errors = rulesBusinessLogic.validateRule(rule1); + assertTrue(errors.isEmpty()); + assertNotEquals(rule1, rule2); + //after validation actions are reordered: 1, 3, 4, 2, 5 + rule2.getActions().add(1, rule2.getActions().get(2)); // 1, 2, 3, 4, 5 -> 1, 3, 2, 3, 4, 5 + rule2.getActions().remove(3); // 1, 3, 2, 3, 4, 5 -> 1, 3, 2, 4, 5 + rule2.getActions().add(2, rule2.getActions().get(3)); // 1, 3, 2, 4, 5 -> 1, 3, 4, 2, 4, 5 + rule2.getActions().remove(4); // 1, 3, 4, 2, 4, 5 -> 1, 3, 4, 2, 5 + assertEquals(rule1, rule2); + } + + @Test + public void reorderRuleActionsDuringValidationFailureTest() { + String expectedError = "A circular dependency was detected between actions. The following fields should be resolved: event.commonEventHeader.eventId, event.commonEventHeader.sourceName, invalidSelfDependency, circularDependencyTarget_3"; + Rule rule1 = buildRuleWithCircularActionDependencies(); + List<ServiceException> errors = rulesBusinessLogic.validateRule(rule1); + assertEquals(expectedError, errors.get(0).getFormattedErrorMessage()); + } + + + @Test + public void reorderMappingRulesByDependencySuccessTest() { + MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); + Rule rule = new Rule(); + rule.setDescription("description"); + rule.setActions(new ArrayList<>()); + // create a dependency between rules + rule.getActions().add(buildCopyAction("${event.commonEventHeader.someField}","event.commonEventHeader.sourceName")); + mr.addOrReplaceRule(rule); + List<String> ruleUids = new ArrayList<>(mr.getRules().keySet()); + String translateBefore = rulesBusinessLogic.translateRules(mr,"snmp_map", "map_publish", "phase_1"); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + List<String> ruleUidsMod = new ArrayList<>(mr.getRules().keySet()); + assertEquals(ruleUids.get(0), ruleUidsMod.get(1)); + assertEquals(ruleUids.get(1), ruleUidsMod.get(0)); + assertNotEquals(translateBefore, rulesBusinessLogic.translateRules(mr,"snmp_map", "map_publish", "phase_1")); + } + + @Test + public void reorderMappingRulesCircularDependencyFailureTest() { + + MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); + List<ServiceException> errors = rulesBusinessLogic.validateRules(mr); + assertTrue(errors.isEmpty()); + Rule rule = new Rule(); + rule.setDescription("description"); + rule.setActions(new ArrayList<>()); + // create a circular dependency between rules + rule.getActions().add(buildCopyAction("${event.commonEventHeader.version}","event.commonEventHeader.sourceName")); + String input = "{operator:equals,left:\"${event.commonEventHeader.version}\",right:[\"${event.commonEventHeader.eventId}\"]}"; + rule.setCondition(gson.fromJson(input, BaseCondition.class)); + assertTrue(rulesBusinessLogic.addOrEditRule(mr, rule)); + errors = rulesBusinessLogic.validateRules(mr); + assertFalse(errors.isEmpty()); + String expectedError = String.format("A circular dependency was detected between rules: %s, %s within fields: event.commonEventHeader.sourceName, event.commonEventHeader.version, event.commonEventHeader.eventId", mr.getRules().keySet().toArray()); + assertEquals(expectedError, errors.get(0).getFormattedErrorMessage()); + } + + + @Test + public void translateNestedComplexConditionSuccessTest() { + String expectedTranslation = "{\"processing\":[{\"phase\":\"foi_map\",\"processors\":[{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]}," + + "{\"phase\":\"phase_1\",\"filter\":{\"filters\":[{\"field\":\"${event.commonEventHeader.version}\",\"value\":\"${event.commonEventHeader.eventId}\",\"class\":\"Equals\"}," + + "{\"filters\":[{\"field\":\"left\",\"value\":\"right\",\"class\":\"NotEqual\"},{\"string\":\"${XXX}\",\"value\":\"right1\",\"class\":\"Contains\"}," + + "{\"string\":\"${XXX}\",\"value\":\"right2\",\"class\":\"Contains\"}],\"class\":\"Or\"}],\"class\":\"And\"}," + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\"},\"class\":\"Set\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + + Rule rule = new Rule(); + rule.setActions(new ArrayList<>()); + rule.getActions().add(buildCopyAction("2.0","event.commonEventHeader.version")); + rule.setDescription("description"); + String condition = "{type:All,children:[{operator:equals,left:\"${event.commonEventHeader.version}\",right:[\"${event.commonEventHeader.eventId}\"]}," + + "{type:Any,children:[{operator:contains,left:\"${XXX}\",right:[right1,right2]},{operator:notEqual,left:left,right:[right]}]}]}"; + rule.setCondition(gson.fromJson(condition, BaseCondition.class)); + List<ServiceException> errors = rulesBusinessLogic.validateRule(rule); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(new MappingRules(rule),"foi_map", "map_publish", "phase_1")); + } + + private Rule buildRuleWithMultipleCopyActions() { + Rule rule = new Rule(); + rule.setDescription("description"); + List<BaseAction> actions = new ArrayList<>(); + actions.add(buildCopyAction("2.0","event.commonEventHeader.version")); + actions.add(buildConcatAction(Arrays.asList("${event.commonEventHeader.sourceName}","_","${eventGroup}"), "event.commonEventHeader.eventId")); + actions.add(buildRegexAction("extractFromHere", "targetField", "([^:]*):.*")); + rule.setActions(actions); + return rule; + } + + private Rule buildValidRuleWithDependentActions() { + Rule rule = buildRuleWithMultipleCopyActions(); + rule.getActions().add(buildConcatAction(Arrays.asList("${targetField}","_","${circularDependencyTarget_3}"), "event.commonEventHeader.sourceName")); + rule.getActions().add(buildConcatAction(Arrays.asList("${validSelfDependency}","_","${event.commonEventHeader.version}"), "validSelfDependency")); + return rule; + } + + private Rule buildRuleWithCircularActionDependencies() { + Rule rule = buildValidRuleWithDependentActions(); + rule.getActions().add(buildCopyAction("${invalidSelfDependency}", "invalidSelfDependency")); + rule.getActions().add(buildCopyAction("${event.commonEventHeader.eventId}", "circularDependencyTarget_3")); + return rule; + } + + private BaseAction buildCopyAction(String from, String to) { + BaseAction action = new BaseAction(); + action.setActionType("copy"); + action.setFrom(from); + action.setTarget(to); + return action; + } + + private BaseAction buildConcatAction(List<String> from, String to) { + BaseAction action = new BaseAction(); + action.setActionType("concat"); + action.setFrom(from); + action.setTarget(to); + return action; + } + + private BaseAction buildRegexAction(String from, String to, String regex) { + BaseAction action = new BaseAction(); + action.setActionType("copy"); + action.setFrom(from, regex); + action.setTarget(to); + return action; + } + + private DateFormatterAction buildDateFormatterAction() { + DateFormatterAction action = new DateFormatterAction(); + action.setActionType("date formatter"); + action.setFrom("fromField"); + action.setTarget("targetField"); + action.setFromFormat("fromFormat"); + action.setToFormat("toFormat"); + action.setFromTz("fromTZ"); + action.setToTz("toTz"); + return action; + } +}
\ No newline at end of file diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/services/GetServicesTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/services/GetServicesTest.java new file mode 100644 index 0000000..68f055f --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/services/GetServicesTest.java @@ -0,0 +1,143 @@ +package org.onap.sdc.dcae.services; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.onap.sdc.dcae.composition.restmodels.DcaeMinimizedService; +import org.onap.sdc.dcae.composition.controller.ServicesController; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants.LifecycleStateEnum; +import org.testng.annotations.Test; + +public class GetServicesTest { + + + @Test + public void parseAndFliterServicesByUser_nullServices_TBD() { +// fail("TODO Auto-generated method stub"); + } + + + @Test + public void parseAndFliterServicesByUser_emptyList_emptyList() { + // arrange + ServicesController target = new ServicesController(); + String user_id = "test"; + String lastUpdaterUserId = "test"; + List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>(); + // act + List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id); + // assert + assertThat(result).isEqualTo(new ArrayList<DcaeMinimizedService>()); + } + + + @Test + public void parseAndFliterServicesByUser_singleServicesAsMap_singleServiceParsed() { + // arrange + String user_id = "test"; + String lastUpdaterUserId = user_id; + String uuid = "a"; + String invariantUUID = "1"; + String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); + String version = "0.1"; + String serviceName = "TestService"; + + ServicesController target = new ServicesController(); + LinkedHashMap<String, String> service = createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, + lifecycleState, version, serviceName); + List<LinkedHashMap<String, String>> services = new ArrayList<LinkedHashMap<String, String>>( + Arrays.asList(service)); + + DcaeMinimizedService expected = new DcaeMinimizedService(uuid, serviceName, lastUpdaterUserId, lifecycleState, + version, invariantUUID); + // act + List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, services, user_id); + // assert + assertThat(result).usingRecursiveFieldByFieldElementComparator().contains(expected); + } + + + @Test + public void parseAndFliterServicesByUser_unsortedServices_sortedServices() { + // arrange + String user_id = "test"; + String lastUpdaterUserId = user_id; + String uuid = "a"; + String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); + String version = "0.1"; + + List<LinkedHashMap<String, String>> unsortedServices = Arrays.asList("d", "a", "c", "b").stream() + .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, UUID.randomUUID().toString(), lifecycleState, version, x)) + .collect(Collectors.toList()); + + ServicesController target = new ServicesController(); + + // act + List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, unsortedServices, + user_id); + // assert + assertThat(result).extracting("name").containsExactly("a","b","c","d"); + } + + + @Test + public void parseAndFliterServicesByUser_allOptionsForLastUpdaterAndIsCheckout_allOptionsButIsCheckoutAndNotLastUpdater() { + // ------------user == last_updater + // -----------------True----False-- + // isCheckout---------------------- + // --------True------V--------X---- + // --------False-----V--------V---- + // -------------------------------- +// fail("TODO Auto-generated method stub"); + } + + + @Test + public void parseAndFliterServicesByUser_singleServiceWithMultiVersions_singleServiceWithLatestVersion() { + // arrange + String user_id = "test"; + String lastUpdaterUserId = user_id; + String uuid = "a"; + String invariantUUID = "1"; + String lifecycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); + String serviceName = "TestService"; + + List<LinkedHashMap<String, String>> singleServiceWithMultiVersions = Arrays.asList("1.0", "0.3", "11.0", "2.0", "1.8").stream() + .map(x -> createServiceAsMap(lastUpdaterUserId, uuid, invariantUUID, lifecycleState, x, serviceName)) + .collect(Collectors.toList()); + + ServicesController target = new ServicesController(); + + // act + List<DcaeMinimizedService> result = target.parseAndFilterServicesByUser(lastUpdaterUserId, singleServiceWithMultiVersions, user_id); + + // assert + assertThat(result).extracting("version").containsExactly("11.0"); + } + + + private static LinkedHashMap<String, String> createServiceAsMap(String lastUpdaterUserId, String uuid, + String invariantUUID, String lifecycleState, String version, String serviceName) { + + LinkedHashMap<String, String> service = new LinkedHashMap<String, String>() { + { + put("invariantUUID", invariantUUID); + put("uuid", uuid); + put("name", serviceName); + put("lastUpdaterUserId", lastUpdaterUserId); + put("lifecycleState", lifecycleState); + put("version", version); + } + }; + + return service; + } + +} diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/EventListenerDefinitionTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/EventListenerDefinitionTest.java new file mode 100644 index 0000000..3e9edf5 --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/EventListenerDefinitionTest.java @@ -0,0 +1,61 @@ +package org.onap.sdc.dcae.ves; + +import org.apache.commons.lang.StringUtils; +import org.junit.Test; +import org.onap.sdc.dcae.VesStructureLoaderMock; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class EventListenerDefinitionTest { + VesStructureLoaderMock loader = new VesStructureLoaderMock(false); + + @Test + public void resolveRefTypesSimpleTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("4.1"); + assertTrue(eventListenerDefinition.propertiesContainReference()); + eventListenerDefinition.resolveRefTypes(); + assertFalse(eventListenerDefinition.propertiesContainReference()); + } + + @Test + public void resolveRefTypesSimpleUnresolvableTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("Unresolvable"); + assertTrue(eventListenerDefinition.propertiesContainReference()); + String resolverError = eventListenerDefinition.resolveRefTypes(); + assertTrue(eventListenerDefinition.propertiesContainReference()); + assertEquals("the following definitions containing unresolvable references: [\"otherFields\",\"stateChangeFields\",\"syslogFields\",\"thresholdCrossingAlertFields\"]",resolverError); + } + + @Test + public void validateSuccessTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("4.1"); + assertTrue(StringUtils.isBlank(eventListenerDefinition.validate())); + } + + @Test + public void validateTypesFailureTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("InvalidType"); + String error = eventListenerDefinition.validate(); + assertEquals("invalid type declaration: invalid", error); + } + + @Test + public void validateRequiredFailureTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("InvalidRequiredEntry"); + String error = eventListenerDefinition.validate(); + assertEquals("invalid required entry: codecIdentifier(invalid)", error); + } + + @Test + public void validateEventPropertyFailureTest() throws Exception { + EventListenerDefinition eventListenerDefinition = loader.getEventListeners().get("NoEventProperty"); + String error = eventListenerDefinition.validate(); + assertEquals("schema not containing property: event", error); + } + + + +}
\ No newline at end of file diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/VesStructureLoaderTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/VesStructureLoaderTest.java new file mode 100644 index 0000000..3172eec --- /dev/null +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/ves/VesStructureLoaderTest.java @@ -0,0 +1,129 @@ +package org.onap.sdc.dcae.ves; + +import org.junit.Test; +import org.onap.sdc.dcae.VesStructureLoaderMock; + +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class VesStructureLoaderTest { + + // the file names of test schema files + private final String UNRESOLVABLE_REFERENCES = "CommonEventFormat_vUnresolvable.json"; + private final String VALID_VERSION_4_1 = "CommonEventFormat_v4.1.json"; + private final String VALID_VERSION_5_3 = "CommonEventFormat_v5.3.json"; + private final String INVALID_JSON = "CommonEventFormat_vInvalidJson.json"; + private final String UNSUPPORTED_FILENAME = "unsupportedFilename.json"; + private final String INVALID_SCHEMA_STRUCTURE = "CommonEventFormat_vInvalidSchemaStructure.json"; + private final String INVALID_TYPE = "CommonEventFormat_vInvalidType.json"; + private final String INVALID_REQUIRED_ENTRY = "CommonEventFormat_vInvalidRequiredEntry.json"; + private final String NO_EVENT_PROPERTY = "CommonEventFormat_vNoEventProperty.json"; + private final String NO_COMMON_EVENT_HEADER = "CommonEventFormat_v4.1WithoutCommonEventHeader.json"; + + // schema directory test paths + private final String EMPTY_SCHEMA_DIR = System.getProperty("user.dir") + "/src/test/resources/ves-schema/empty"; + private final String NONE_EXISTING_DIR = EMPTY_SCHEMA_DIR + "/null"; + + private final String ERROR_TEXT = "Error: parsing VES schema file "; + + // files loaded from default path, only valid files are kept, errors logged for invalid files (initError); + @Test + public void defaultInit() { + VesStructureLoaderMock loader = new VesStructureLoaderMock(); + Set<String> expectedAvailableVersions = new HashSet<>(); + expectedAvailableVersions.add(loader.getVersionFromFileName(VALID_VERSION_4_1)); + expectedAvailableVersions.add(loader.getVersionFromFileName(VALID_VERSION_5_3)); + expectedAvailableVersions.add(loader.getVersionFromFileName(NO_COMMON_EVENT_HEADER)); + assertEquals(expectedAvailableVersions, loader.getAvailableVersionsList()); + List<String> expectedLoggedErrors = Arrays + .asList(getExpectedInvalidJsonError(), getExpectedInvalidRequiredEntryError(), getExpectedInvalidStructureError(), getExpectedInvalidTypeError(), getExpectedNoEventDefinitionError(), getExpectedUnresolvableError()); + assertTrue(loader.getInitErrors().containsAll(expectedLoggedErrors)); + assertEquals(expectedLoggedErrors.size(), loader.getInitErrors().size()); + } + + @Test + public void initWithEmptyDir() { + VesStructureLoaderMock loader = new VesStructureLoaderMock(true, EMPTY_SCHEMA_DIR); + assertTrue(loader.getAvailableVersionsList().isEmpty()); + assertEquals("No VES schema files found", loader.getInitErrors().get(0)); + } + + @Test + public void initWithNoneExistingDir() { + VesStructureLoaderMock loader = new VesStructureLoaderMock(true, NONE_EXISTING_DIR); + assertTrue(loader.getAvailableVersionsList().isEmpty()); + assertEquals("No VES schema files found", loader.getInitErrors().get(0)); + } + + @Test + public void complexDataTypeLoaderOutputTest() { + VesStructureLoaderMock loader = new VesStructureLoaderMock(); + VesDataTypeDefinition loaded = loader.getEventListenerDefinitionByVersion("5.3").get("stateChangeFields"); + assertEquals(buildStateChangeFieldsDefinition(), loaded); + } + + private String getExpectedInvalidJsonError() { + return ERROR_TEXT + INVALID_JSON + " failed due to java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at path $"; + } + + private String getExpectedUnresolvableError() { + return ERROR_TEXT + UNRESOLVABLE_REFERENCES + " failed due to the following definitions containing unresolvable references: [\"otherFields\",\"stateChangeFields\",\"syslogFields\",\"thresholdCrossingAlertFields\"]"; + } + + private String getExpectedInvalidStructureError() { + return ERROR_TEXT + INVALID_SCHEMA_STRUCTURE + " failed due to java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 8 column 20 path $.definitions..properties[0]"; + } + + private String getExpectedInvalidTypeError() { + return ERROR_TEXT + INVALID_TYPE + " failed due to invalid type declaration: invalid"; + } + + private String getExpectedInvalidRequiredEntryError() { + return ERROR_TEXT + INVALID_REQUIRED_ENTRY + " failed due to invalid required entry: codecIdentifier(invalid)"; + } + + private String getExpectedNoEventDefinitionError() { + return ERROR_TEXT + NO_EVENT_PROPERTY + " failed due to schema not containing property: event"; + } + + private VesDataTypeDefinition buildFieldDefinition() { + Map<String, VesDataTypeDefinition> propsMap = new HashMap<>(); + VesDataTypeDefinition prop = buildVesDataType(null, VesSimpleTypesEnum.STRING.getType(), new ArrayList<>(), null, null); + propsMap.put("name", prop); + propsMap.put("value", prop); + return buildVesDataType("name value pair", VesSimpleTypesEnum.OBJECT.getType(), Arrays.asList("name", "value"), propsMap, null); + } + + private VesDataTypeDefinition buildStateChangeFieldsDefinition() { + + VesDataItemsDefinition items = new VesDataItemsDefinition(); + items.add(buildFieldDefinition()); + VesDataTypeDefinition prop = buildVesDataType("additional stateChange fields if needed", VesSimpleTypesEnum.ARRAY.getType(), new ArrayList<>(), null, null); + prop.setItems(items); + Map<String, VesDataTypeDefinition> propsMap = new HashMap<>(); + propsMap.put("additionalFields", prop); + prop = buildVesDataType("new state of the entity", VesSimpleTypesEnum.STRING.getType(), new ArrayList<>(), null, Arrays.asList("inService", "maintenance", "outOfService")); + propsMap.put("newState", prop); + prop = buildVesDataType("previous state of the entity", VesSimpleTypesEnum.STRING.getType(), new ArrayList<>(), null, Arrays.asList("inService", "maintenance", "outOfService")); + propsMap.put("oldState", prop); + prop = buildVesDataType("version of the stateChangeFields block", VesSimpleTypesEnum.NUMBER.getType(), new ArrayList<>(), null, null); + propsMap.put("stateChangeFieldsVersion", prop); + prop = buildVesDataType("card or port name of the entity that changed state", VesSimpleTypesEnum.STRING.getType(), new ArrayList<>(), null, null); + propsMap.put("stateInterface", prop); + VesDataTypeDefinition def = buildVesDataType("stateChange fields", VesSimpleTypesEnum.OBJECT.getType(), Arrays.asList("newState", "oldState", "stateChangeFieldsVersion", "stateInterface"), propsMap, null); + return def; + } + + private VesDataTypeDefinition buildVesDataType(String description, String type, List<String> required, Map<String, VesDataTypeDefinition> properties, List<String> enums) { + VesDataTypeDefinition def = new VesDataTypeDefinition(); + def.setDescription(description); + def.setType(type); + def.setRequired(required); + def.setEnums(enums); + def.setProperties(properties); + return def; + } + +}
\ No newline at end of file |