From 86457ed120fc236b1485ad3251589aedad2401bd Mon Sep 17 00:00:00 2001 From: "Eran (ev672n), Vosk" Date: Mon, 6 Aug 2018 17:02:39 +0300 Subject: Changing the dcae dt main code Updating DCAE-dt-main code for Dockerizing the DCAE-CI code Change-Id: Ia50d24e60e9ddc9bbc58dd8651d7a4f7e0dc8270 Issue-ID: SDC-1605 Signed-off-by: Eran (ev672n), Vosk --- .../impl/CompositionCatalogBusinessLogicTest.java | 74 ++++--- .../impl/RuleEditorBusinessLogicTest.java | 131 ++++++------ .../rule/editor/impl/RulesBusinessLogicTest.java | 231 +++++++++++++++++---- 3 files changed, 298 insertions(+), 138 deletions(-) (limited to 'dcaedt_be/src/test/java') diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java index ac12f8d..25bf1f1 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/CompositionCatalogBusinessLogicTest.java @@ -7,68 +7,84 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.onap.sdc.dcae.catalog.asdc.ASDCCatalog; +import org.onap.sdc.dcae.catalog.asdc.ASDCException; import org.onap.sdc.dcae.catalog.engine.CatalogController; import org.onap.sdc.dcae.catalog.engine.CatalogError; import org.onap.sdc.dcae.catalog.engine.CatalogResponse; +import org.onap.sdc.dcae.client.ISdcClient; +import org.onap.sdc.dcae.composition.restmodels.canvas.DcaeComponentCatalog; +import org.onap.sdc.dcae.composition.restmodels.sdc.Resource; +import org.onap.sdc.dcae.composition.util.DcaeBeConstants; +import org.onap.sdc.dcae.errormng.ErrorConfigurationLoader; +import org.onap.sdc.dcae.errormng.RequestError; +import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.errormng.ServiceException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.context.request.async.DeferredResult; -import java.net.URI; +import java.util.Arrays; +import java.util.List; import java.util.UUID; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class CompositionCatalogBusinessLogicTest { + private final String REQUEST_ID = "123456"; + private ASDCCatalog asdcCatalog = new ASDCCatalog(); + @Mock private CatalogController catalogController; - private ASDCCatalog asdcCatalog = new ASDCCatalog(URI.create("https://mockUri:8888#mock")); + @Mock + private ISdcClient sdcRestClient; @InjectMocks - private CompositionCatalogBusinessLogic compositionCatalogBusinessLogic = new CompositionCatalogBusinessLogic(); + private CompositionCatalogBusinessLogic compositionCatalogBusinessLogic; @Before public void init() throws JSONException { MockitoAnnotations.initMocks(this); - when(catalogController.getCatalog(any())).thenReturn(asdcCatalog); + when(catalogController.getCatalog()).thenReturn(asdcCatalog); + new ErrorConfigurationLoader(System.getProperty("user.dir")+"/src/main/webapp/WEB-INF"); + mockCatalog(); } @Test - public void getItemsTest() { - compositionCatalogBusinessLogic.getItems(null).getResult(); - verify(catalogController, times(7)).patchData(any(), any()); + public void getCatalogTest() { + DcaeComponentCatalog catalog = compositionCatalogBusinessLogic.getCatalog(REQUEST_ID); + assertEquals(1, catalog.getElements().size()); + assertEquals(1, catalog.getElements().get(0).getItems().size()); } - @Test - public void getItemByIdNoSuchFolderFailureTest() { - DeferredResult result = compositionCatalogBusinessLogic.getItemById(null, "No Such Category"); - verify(catalogController).getCatalog(any()); - verify(catalogController, times(0)).patchData(any(), any()); - CatalogError error = (CatalogError)result.getResult(); - assertEquals("{\"exception\":\"java.lang.RuntimeException: No such folder No Such Category\",\"message\":\"Catalog API failed\"}", error.getError()); - } @Test public void getModelByIdInvalidUuidFailureTest() { - try { - compositionCatalogBusinessLogic.getModelById(null, "Invalid-UUID"); - } catch (IllegalArgumentException e) { - assertEquals("Invalid UUID string: Invalid-UUID", e.getMessage()); - verify(catalogController).getCatalog(any()); - verify(catalogController, times(0)).patchData(any(), any()); - } + ResponseEntity result = compositionCatalogBusinessLogic.getModelById(REQUEST_ID, "invalidId"); + assertEquals("Invalid UUID string: invalidId", ((ResponseFormat)result.getBody()).getNotes()); } @Test public void getTypeInfoModelNotLoadedFailureTest() { - // this is pretty awful. you cannot call 'getTypeInfo' unless it is preceded by a 'getModel' call of the containing model, so that the 'catalogs' item is populated by the container model id. String uuid = UUID.randomUUID().toString(); - DeferredResult result = compositionCatalogBusinessLogic.getTypeInfo(null, uuid, "tosca.nodes.Root"); - verify(catalogController).getCatalog(any()); - verify(catalogController, times(0)).patchData(any(), any()); - CatalogError error = (CatalogError)result.getResult(); - assertEquals("{\"exception\":\"java.lang.Exception: No catalog available for resource " + uuid + ". You might want to fetch the model first.\",\"message\":\"Catalog API failed\"}", error.getError()); + // this is pretty awful. you cannot call 'getTypeInfo' unless it is preceded by a 'getModel' call of the containing model, so that the 'catalogs' item is populated by the container model id. + ResponseEntity result = compositionCatalogBusinessLogic.getTypeInfo(uuid, "tosca.nodes.Root"); + assertEquals("No catalog available for resource " + uuid + ". You might want to fetch the model first.", ((ResponseFormat)result.getBody()).getNotes()); + } + + private void mockCatalog() { + String subcategory1 = "subcategory1"; + String subcategory2 = "subcategory2"; + List resources = Arrays.asList(buildVf(subcategory1, DcaeBeConstants.LifecycleStateEnum.CERTIFIED.name()), buildVf(subcategory1, DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name()), buildVf(subcategory2, DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())); + when(sdcRestClient.getResources(anyString(), anyString(), eq(null), anyString())).thenReturn(resources); + } + + private Resource buildVf(String subcategory, String lifecycleState) { + Resource vf = new Resource(); + vf.setLifecycleState(lifecycleState); + vf.setSubCategory(subcategory); + return vf; } } \ No newline at end of file diff --git a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java index d421113..3c6d1dd 100644 --- a/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java +++ b/dcaedt_be/src/test/java/org/onap/sdc/dcae/composition/impl/RuleEditorBusinessLogicTest.java @@ -1,31 +1,37 @@ package org.onap.sdc.dcae.composition.impl; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +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.composition.CompositionConfig; -import org.onap.sdc.dcae.composition.restmodels.ruleeditor.*; -import org.onap.sdc.dcae.composition.restmodels.sdc.*; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.MappingRules; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.Rule; +import org.onap.sdc.dcae.composition.restmodels.ruleeditor.SchemaInfo; +import org.onap.sdc.dcae.composition.restmodels.sdc.Artifact; +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.RequestError; import org.onap.sdc.dcae.errormng.ResponseFormat; +import org.onap.sdc.dcae.errormng.ServiceException; import org.onap.sdc.dcae.rule.editor.impl.RulesBusinessLogic; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.testng.Assert; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; public class RuleEditorBusinessLogicTest { // DEFAULT PROPERTIES - private String justAString = "aStringForAllSeasons"; + private String justAString = "aStringForAllSeasons"; private String userId = "gc786h"; private String vfcmtUuid = "26e8d4b5-f087-4821-a75a-0b9514b5a7ab"; private String dcaeCompLabel = "dMp.DockerMap"; @@ -34,12 +40,10 @@ public class RuleEditorBusinessLogicTest { private String artifactUuid = "9b00ba74-da02-4706-8db0-ac3c11d1d47b"; private String configParam = "aaf_username"; private String requestId = "9a89b5c7-33b2-4f7e-a404-66bf4115f510"; - private String flowTypeName = "SNMP MSE"; private String ruleUuid = "sadsads"; private String categoryName = "Template"; private String resourceType = "VFCMT"; private String saveRulesJsonRequest = "{\n\"version\":\"4.1\",\n\"eventType\":\"syslogFields\",\n\"uid\":\"\",\n\"description\":\"sfasfsaf\",\n\"actions\":[\n{\n\"id\":\"6e0175a0-581f-11e8-82eb-53bb060b790a\",\n\"actionType\":\"copy\",\n\"from\":{\n\"value\":\"asfsf\",\n\"regex\":\"\",\n\"state\":\"closed\",\n\"values\":[\n{\n" + "\"value\":\"\"\n" + "},\n" + "{\n\"value\":\"\"\n}\n]\n},\n\"target\":\"event.commonEventHeader.eventType\",\n\"map\":{\n\"values\":[\n{\n\"key\":\"\",\n\"value\":\"\"\n}\n],\n\"haveDefault\":false,\n\"default\":\"\"\n},\n\"dateFormatter\":{\n\"fromFormat\":\"\",\n\"toFormat\":\"\",\n\"fromTimezone\":\"\",\n\"toTimezone\":\"\"\n},\n\"replaceText\":{\n\"find\":\"\",\n\"replace\":\"\"\n},\n\"logText\":{\n\"name\":\"\",\n\"level\":\"\",\n\"text\":\"\"\n},\n\"logEvent\":{\n\"title\":\"\"\n}\n}\n],\n\"condition\":null\n}"; - private String artifactJson = "{\n \"artifactName\":\"composition.yml\",\n \"artifactType\":\"DCAE_TOSCA\",\n \"artifactURL\":\"/sdc/v1/catalog/resources/c2877686-616a-48ca-a37b-7e311bf83adc/artifacts/9b00ba74-da02-4706-8db0-ac3c11d1d47b\",\n \"artifactDescription\":\"createReferenceArtifact\",\n \"artifactTimeout\":null,\n \"artifactChecksum\":\"MjhhYTAwOTIxZGZkMGMyMmFjYmEzYjI1NTIwYjA3YzM=\",\n \"artifactUUID\":\"9b00ba74-da02-4706-8db0-ac3c11d1d47b\",\n \"artifactVersion\":\"1\",\n \"generatedFromUUID\":null,\n \"artifactLabel\":\"servicereference\",\n \"artifactGroupType\":\"DEPLOYMENT\",\n \"payloadData\":null,\n \"description\":null\n" + "}"; private String defaultPayload = "{eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'}}}"; @@ -47,9 +51,7 @@ public class RuleEditorBusinessLogicTest { private ISdcClient sdcClientMock = Mockito.mock(ISdcClient.class); private ResourceDetailed vfcmt = Mockito.mock(ResourceDetailed.class); private SchemaInfo schemaInfo = Mockito.mock(SchemaInfo.class); - private CompositionConfig compositionConfig = Mockito.mock(CompositionConfig.class); private RulesBusinessLogic rulesBusinessLogic = Mockito.mock(RulesBusinessLogic.class); - private CompositionConfig.FlowType flowType = Mockito.mock(CompositionConfig.FlowType.class); @InjectMocks private RuleEditorBusinessLogic ruleEditorBusinessLogic = new RuleEditorBusinessLogic(); @@ -67,11 +69,9 @@ public class RuleEditorBusinessLogicTest { when(vfcmt.getResourceType()).thenReturn(resourceType); when(vfcmt.getCategory()).thenReturn(categoryName); - when(ruleEditorBusinessLogic.getSdcRestClient().getResource(anyString(), anyString())).thenReturn(vfcmt); + when(sdcClientMock.getResource(anyString(), anyString())).thenReturn(vfcmt); when(schemaInfo.getVersion()).thenReturn("0.2"); - /* PowerMockito.doReturn(vs).when(VesStructureLoader.class); - when(vs.getEventListenerDefinitionByVersion(anyString())).thenReturn(null);*/ } @Test @@ -79,29 +79,55 @@ public class RuleEditorBusinessLogicTest { emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); - when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); - when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class))).thenReturn(true); + when(sdcClientMock.getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class), anyBoolean())).thenReturn(true); + when(rulesBusinessLogic.validateGroupDefinitions(any(MappingRules.class), anyBoolean())).thenReturn(true); ResponseEntity result = ruleEditorBusinessLogic.saveRule(saveRulesJsonRequest, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); assertEquals(200,result.getStatusCodeValue()); - Assert.assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); - verify(rulesBusinessLogic,times(1)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); + verify(rulesBusinessLogic,times(1)).addOrEditRule(any(MappingRules.class), any(Rule.class), anyBoolean()); } + @Test + public void test_exportRules_resourceNotFound() throws Exception { + RequestError requestError = new RequestError(); + requestError.setServiceException(new ServiceException("SVC4063", "", null)); + when(sdcClientMock.getResource(resourceUuid, requestId)).thenThrow(new ASDCException(HttpStatus.NOT_FOUND, requestError)); + + ResponseEntity result = ruleEditorBusinessLogic.downloadRules(vfcmtUuid, dcaeCompLabel, nId, configParam, requestId); + assertEquals(404,result.getStatusCodeValue()); + } + + + @Test + public void invalidRuleFormatImportRulesFailureTest() throws Exception { + String invalidInput = "{rules:[blahblahblah]}"; + String expectedError = "Error - Rule format is invalid: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 9 path $.rules[0]."; + ResponseEntity result = ruleEditorBusinessLogic.importRules(invalidInput, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); + assertEquals(400,result.getStatusCodeValue()); + assertEquals(expectedError, result.getBody().getRequestError().getServiceException().getFormattedErrorMessage()); + verify(rulesBusinessLogic, times(0)).validateImportedRules(any()); + verify(sdcClientMock, times(0)).getResource(anyString(), anyString()); + verify(sdcClientMock, times(0)).createResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(0)).updateResourceArtifact(anyString(), anyString(), any(), anyString()); + verify(sdcClientMock, times(0)).changeResourceLifecycleState(anyString(), anyString(), anyString(), anyString(), anyString()); + } + @Test public void test_saveRules_artifactNotFound() throws Exception { emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, false); - when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class))).thenReturn(true); + when(rulesBusinessLogic.addOrEditRule(any(MappingRules.class), any(Rule.class), anyBoolean())).thenReturn(true); String payload = "{eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'}},\"nid\":\"n.1525864440166.30}"; when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(anyString(),anyString(), anyString())).thenReturn(payload); ResponseEntity result = ruleEditorBusinessLogic.saveRule(saveRulesJsonRequest, requestId, userId, vfcmtUuid, dcaeCompLabel, nId, configParam); assertEquals(200,result.getStatusCodeValue()); - Assert.assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); - verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + assertTrue(result.getBody().toString().contains("6e0175a0-581f-11e8-82eb-53bb060b790a")); + verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class), anyBoolean()); } @@ -116,7 +142,7 @@ public class RuleEditorBusinessLogicTest { assertEquals(400,result.getStatusCodeValue()); assertEquals("SVC6114",result.getBody().getRequestError().getServiceException().getMessageId()); assertEquals("DCAE component %1 not found in composition",result.getBody().getRequestError().getServiceException().getText()); - verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class)); + verify(rulesBusinessLogic,times(0)).addOrEditRule(any(MappingRules.class), any(Rule.class), anyBoolean()); } @@ -125,12 +151,9 @@ public class RuleEditorBusinessLogicTest { emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); - when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)) - .thenReturn(defaultPayload); - - ResponseEntity result = ruleEditorBusinessLogic.getRules(vfcmtUuid, dcaeCompLabel, nId, configParam, requestId); + ResponseEntity result = ruleEditorBusinessLogic.getRulesAndSchema(vfcmtUuid, dcaeCompLabel, nId, configParam, requestId); assertEquals(200,result.getStatusCodeValue()); - Assert.assertTrue(result.getBody().toString().contains("eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'")); + assertTrue(result.getBody().toString().contains("eventType:syslogFields,version:4.1,rules:{'test':{'version':'4.1'")); } @@ -147,33 +170,13 @@ public class RuleEditorBusinessLogicTest { } - @Test - public void test_translate() throws Exception { - - emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); - - when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); - Map flowTypeMap = new HashMap<>(); - flowTypeMap.put("SNMP MSE", flowType); - when(compositionConfig.getFlowTypesMap()).thenReturn(flowTypeMap); - when(compositionConfig.getFlowTypesMap().get("SNMP MSE").getEntryPointPhaseName()).thenReturn("testName"); - when(compositionConfig.getFlowTypesMap().get("SNMP MSE").getLastPhaseName()).thenReturn("testLastName"); - - when(rulesBusinessLogic.translateRules(any(MappingRules.class), anyString(), anyString(), anyString())).thenReturn("testLastName"); - ResponseEntity result = ruleEditorBusinessLogic.translateRules(vfcmtUuid, requestId, dcaeCompLabel, nId, configParam, flowTypeName); - verify(compositionConfig,times(6)).getFlowTypesMap(); - verify(rulesBusinessLogic,times(1)).translateRules(any(MappingRules.class), anyString(), anyString(), anyString()); - - assertEquals(200,result.getStatusCodeValue()); - - } @Test public void test_deleteRule() throws Exception { emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); - when(ruleEditorBusinessLogic.getSdcRestClient().getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + when(sdcClientMock.getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); when(rulesBusinessLogic.deleteRule(any(MappingRules.class), anyString())).thenReturn(new Rule()); ResponseEntity result = ruleEditorBusinessLogic.deleteRule(userId, vfcmtUuid, dcaeCompLabel, nId, configParam, ruleUuid, requestId); @@ -181,18 +184,16 @@ public class RuleEditorBusinessLogicTest { } - @Test - public void test_getDefinition(){ - + @Test + public void test_deleteGroupOfRules() throws Exception { -/* - PowerMockito.mockStatic(VesStructureLoader.class); - when(VesStructureLoader.getEventListenerDefinitionByVersion(anyString())).thenReturn(null); -*/ + emulateMockListOfArtifacts(dcaeCompLabel, nId, configParam, true); + when(sdcClientMock.getResourceArtifact(resourceUuid, artifactUuid, requestId)).thenReturn(defaultPayload); + when(rulesBusinessLogic.deleteGroupOfRules(any(MappingRules.class), anyString())).thenReturn(Collections.singletonList(new Rule())); + ResponseEntity result = ruleEditorBusinessLogic.deleteGroupOfRules(userId, vfcmtUuid, dcaeCompLabel, nId, configParam, ruleUuid, requestId); + assertEquals(200,result.getStatusCodeValue()); + } - ResponseEntity res = ruleEditorBusinessLogic.getDefinition("4.1","syslogFields"); - - } private void emulateMockListOfArtifacts(String dcaeCompLabel, String nid, String configParam, boolean isApprovedArtifact) { List listOfArtifactCompositionYml = new ArrayList<>(); @@ -208,10 +209,10 @@ public class RuleEditorBusinessLogicTest { when(artifact.getArtifactType()).thenReturn("DCAE_TOSCA"); when(artifact.getArtifactUUID()).thenReturn(artifactUuid); when(artifact.getArtifactDescription()).thenReturn("createmapArtifact"); + when(artifact.getPayloadData()).thenReturn(defaultPayload); listOfArtifactCompositionYml.add(artifact); when(vfcmt.getArtifacts()).thenReturn(listOfArtifactCompositionYml); } - } 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 index bc03632..3b7181d 100644 --- 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 @@ -5,23 +5,30 @@ import com.google.gson.GsonBuilder; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; +import org.mockito.Mockito; 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 org.onap.sdc.dcae.rule.editor.validators.MappingRulesValidator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; public class RulesBusinessLogicTest { private static Gson gson = new GsonBuilder() .registerTypeAdapter(BaseAction.class, new ActionDeserializer()) .registerTypeAdapter(BaseCondition.class, new ConditionDeserializer()).create(); + private String mockUiInput = "mockUiInput"; + private MappingRulesValidator mappingRulesValidator = Mockito.mock(MappingRulesValidator.class); + @InjectMocks private RulesBusinessLogic rulesBusinessLogic = new RulesBusinessLogic(); private ResponseFormatManager responseFormatManager = null; @@ -36,33 +43,57 @@ public class RulesBusinessLogicTest { @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\"}]}]}"; + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\"},\"class\":\"Set\"},{\"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"); + rule.setPhase("phase_1"); MappingRules mr = new MappingRules(rule); - List errors = rulesBusinessLogic.validateRules(mr); + mr.setEntryPhase("snmp_map"); + mr.setPublishPhase("map_publish"); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); + } + + @Test + public void translateSingleRuleSingleCopyActionWithNotifyOidFilter() throws Exception { + String expectedTranslation = "{\"processing\":[{\"phase\":\"foi_map\",\"filter\":{\"string\":\"${notify OID}\",\"value\":\"someValue\",\"class\":\"StartsWith\"},\"processors\":[{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]}," + + "{\"phase\":\"phase_1\",\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\"},\"class\":\"Set\"},{\"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"); + rule.setPhase("phase_1"); + rule.setNotifyId("someValue"); + rule.setEntryPhase("foi_map"); + rule.setPublishPhase("map_publish"); + MappingRules mr = new MappingRules(rule); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); + assertTrue(errors.isEmpty()); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @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\"}]}]}"; + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"fromFormat\":\"fromFormat\",\"fromTz\":\"fromTZ\",\"toField\":\"targetField\",\"toFormat\":\"toFormat\",\"toTz\":\"toTz\",\"value\":\"fromField\",\"class\":\"DateFormatter\"},{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; Rule rule = new Rule(); rule.setActions(new ArrayList<>()); rule.getActions().add(buildDateFormatterAction()); rule.setDescription("description"); + rule.setPhase("phase_1"); + rule.setNotifyId(""); + rule.setEntryPhase("snmp_map"); + rule.setPublishPhase("map_publish"); MappingRules mr = new MappingRules(rule); - List errors = rulesBusinessLogic.validateRules(mr); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -70,12 +101,12 @@ public class RulesBusinessLogicTest { 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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); - List errors = rulesBusinessLogic.validateRules(mr); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -85,36 +116,36 @@ public class RulesBusinessLogicTest { + "\"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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); mr.addOrReplaceRule(buildRuleWithMultipleCopyActions()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @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:'\"\"'}}]}"; + + "{\"phase\":\"phase_1\",\"class\":\"RunPhase\"}]},{\"phase\":\"phase_1\",\"processors\":[{\"map\":{\"\":\"\"},\"field\":\"\",\"toField\":\"mapTargetField\",\"default\":\"\",\"class\":\"MapAlarmValues\"},{\"phase\":\"map_publish\",\"class\":\"RunPhase\"}]}]}"; + String ruleRequestBody = "{entryPhase:snmp_map,publishPhase:map_publish,phase:phase_1,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 errors = rulesBusinessLogic.validateRules(mr); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr, "snmp_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"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")); + mr.setEntryPhase("syslog_map"); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -122,12 +153,13 @@ public class RulesBusinessLogicTest { 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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"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")); + mr.setEntryPhase("foi_map"); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -135,12 +167,12 @@ public class RulesBusinessLogicTest { 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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"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")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -148,12 +180,12 @@ public class RulesBusinessLogicTest { 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\"}]}]}"; + + "{\"regex\":\"([^:]*):.*\",\"field\":\"targetField\",\"value\":\"extractFromHere\",\"class\":\"ExtractText\"},{\"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")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(mr)); } @Test @@ -172,6 +204,66 @@ public class RulesBusinessLogicTest { assertEquals(rule1, rule2); } + @Test + public void reorderRuleWithConditionalActionDuringValidationSuccessTest() { + Rule rule1 = buildValidRuleWithDependentSearchAndTransformActions(); + Rule rule2 = buildValidRuleWithDependentSearchAndTransformActions(); + assertEquals(rule1, rule2); + List errors = rulesBusinessLogic.validateRule(rule1); + assertTrue(errors.isEmpty()); + assertNotEquals(rule1, rule2); + //after validation actions are reordered: 5, 2, 4, 1, 3 + rule2.getActions().add(0, rule2.getActions().get(4)); // 1, 2, 3, 4, 5 -> 5, 1, 2, 3, 4, 5 + rule2.getActions().remove(5); // 5, 1, 2, 3, 4, 5 -> 5, 1, 2, 3, 4 + rule2.getActions().add(1, rule2.getActions().get(2)); // 5, 1, 2, 3, 4 -> 5, 2, 1, 2, 3, 4 + rule2.getActions().remove(3); // 5, 2, 1, 2, 3, 4 -> 5, 2, 1, 3, 4 + rule2.getActions().add(2, rule2.getActions().get(4)); // 5, 2, 1, 3, 4 -> 5, 2, 4, 1, 3, 4 + rule2.getActions().remove(5); // 5, 2, 4, 1, 3, 4 -> 5, 2, 4, 1, 3 + assertEquals(rule1, rule2); + } + + @Test + public void importMappingRulesAndReorderActionsDuringImportValidationSuccessTest() { + // as this top level validator uses external ves configuration it is mocked. + // dependency validations are conducted in the class under test and verified with the control rule + when(mappingRulesValidator.validate(any(), any())).thenReturn(true); + Rule importedRule = buildValidRuleWithDependentActions(); + Rule controlRule = buildValidRuleWithDependentActions(); + MappingRules mappingRules = new MappingRules(importedRule); + // copying the generated uuid to the control rule to sustain equality + controlRule.setUid(importedRule.getUid()); + assertEquals(importedRule, controlRule); + + List errors = rulesBusinessLogic.validateImportedRules(mappingRules); + assertTrue(errors.isEmpty()); + assertNotEquals(importedRule, controlRule); + //after validation actions are reordered: 1, 3, 4, 2, 5 + controlRule.getActions().add(1, controlRule.getActions().get(2)); // 1, 2, 3, 4, 5 -> 1, 3, 2, 3, 4, 5 + controlRule.getActions().remove(3); // 1, 3, 2, 3, 4, 5 -> 1, 3, 2, 4, 5 + controlRule.getActions().add(2, controlRule.getActions().get(3)); // 1, 3, 2, 4, 5 -> 1, 3, 4, 2, 4, 5 + controlRule.getActions().remove(4); // 1, 3, 4, 2, 4, 5 -> 1, 3, 4, 2, 5 + assertEquals(importedRule, controlRule); + } + + @Test + public void supportGroupDefinitionTest() { + + Rule rule = buildRuleWithMultipleCopyActions(); + List errors = rulesBusinessLogic.validateRule(rule); + assertTrue(errors.isEmpty()); + MappingRules mappingRules = new MappingRules(rule); + // first rule dictates whether or not user defined phases should be supported (supportGroups = false) + assertTrue(rulesBusinessLogic.validateGroupDefinitions(mappingRules, false)); + assertFalse(rulesBusinessLogic.validateGroupDefinitions(mappingRules, true)); + // add group definitions (supportGroups = true) + rule.setGroupId("mapPhaseId"); + errors = rulesBusinessLogic.validateRule(rule); + assertTrue(errors.isEmpty()); + assertTrue(rulesBusinessLogic.validateGroupDefinitions(mappingRules, true)); + assertFalse(rulesBusinessLogic.validateGroupDefinitions(mappingRules, false)); + } + + @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"; @@ -182,22 +274,39 @@ public class RulesBusinessLogicTest { @Test - public void reorderMappingRulesByDependencySuccessTest() { - MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); - Rule rule = new Rule(); - rule.setDescription("description"); - rule.setActions(new ArrayList<>()); + public void reorderMappingRulesByDependencyOnlyInSamePhaseSuccessTest() { + when(mappingRulesValidator.validateTranslationPhaseNames(any(), any())).thenReturn(true); + when(mappingRulesValidator.validate(any(), any())).thenReturn(true); + Rule rule1 = buildRuleWithMultipleCopyActions(); + MappingRules mr = new MappingRules(rule1); + Rule rule2 = new Rule(); + rule2.setDescription("description"); + rule2.setActions(new ArrayList<>()); // create a dependency between rules - rule.getActions().add(buildCopyAction("${event.commonEventHeader.someField}","event.commonEventHeader.sourceName")); - mr.addOrReplaceRule(rule); + rule2.getActions().add(buildCopyAction("${event.commonEventHeader.someField}","event.commonEventHeader.sourceName")); + rule2.setPhase("phase_1"); + mr.addOrReplaceRule(rule2); + mr.setPublishPhase("map_publish"); + mr.setEntryPhase("snmp_map"); List ruleUids = new ArrayList<>(mr.getRules().keySet()); - String translateBefore = rulesBusinessLogic.translateRules(mr,"snmp_map", "map_publish", "phase_1"); - List errors = rulesBusinessLogic.validateRules(mr); + String translateBefore = rulesBusinessLogic.translateRules(mr); + //separate the rules into two phases, call import validator and translate + rule1.setGroupId("group_1"); + rule2.setGroupId("group_2"); + List errors = rulesBusinessLogic.validateImportedRules(mr); + assertTrue(errors.isEmpty()); + errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); + assertTrue(errors.isEmpty()); + assertEquals(translateBefore, rulesBusinessLogic.translateRules(mr)); + //revert to single phase + rule1.setGroupId(""); + rule2.setGroupId(""); + errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); List 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")); + assertNotEquals(translateBefore, rulesBusinessLogic.translateRules(mr)); } @Test @@ -213,9 +322,9 @@ public class RulesBusinessLogicTest { @Test public void reorderMappingRulesCircularDependencyFailureTest() { - + when(mappingRulesValidator.validateTranslationPhaseNames(any(), any())).thenReturn(true); MappingRules mr = new MappingRules(buildRuleWithMultipleCopyActions()); - List errors = rulesBusinessLogic.validateRules(mr); + List errors = rulesBusinessLogic.validateRulesBeforeTranslate(mr); assertTrue(errors.isEmpty()); Rule rule = new Rule(); rule.setDescription("description"); @@ -224,8 +333,9 @@ public class RulesBusinessLogicTest { 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); + rule.setPhase("phase_1"); + assertTrue(rulesBusinessLogic.addOrEditRule(mr, rule, false)); + errors = rulesBusinessLogic.validateRulesBeforeTranslate(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()); @@ -238,18 +348,21 @@ public class RulesBusinessLogicTest { + "{\"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\"}]}]}"; + + "\"processors\":[{\"updates\":{\"event.commonEventHeader.version\":\"2.0\"},\"class\":\"Set\"},{\"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]}]}]}"; + String condition = "{id:123456,level:1,name:elvis,type:All,children:[{id:123456,level:1,name:elvis,operator:equals,left:\"${event.commonEventHeader.version}\",right:[\"${event.commonEventHeader.eventId}\"]}," + + "{id:123456,level:1,name:elvis,type:Any,children:[{id:123456,level:1,name:elvis,operator:contains,left:\"${XXX}\",right:[right1,right2]},{id:123456,level:1,name:elvis,operator:notEqual,left:left,right:[right]}]}]}"; rule.setCondition(gson.fromJson(condition, BaseCondition.class)); + rule.setPublishPhase("map_publish"); + rule.setEntryPhase("foi_map"); + rule.setPhase("phase_1"); List errors = rulesBusinessLogic.validateRule(rule); assertTrue(errors.isEmpty()); - assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(new MappingRules(rule),"foi_map", "map_publish", "phase_1")); + assertEquals(expectedTranslation, rulesBusinessLogic.translateRules(new MappingRules(rule))); } private Rule buildRuleWithMultipleCopyActions() { @@ -260,6 +373,9 @@ public class RulesBusinessLogicTest { actions.add(buildConcatAction(Arrays.asList("${event.commonEventHeader.sourceName}","_","${eventGroup}"), "event.commonEventHeader.eventId")); actions.add(buildRegexAction("extractFromHere", "targetField", "([^:]*):.*")); rule.setActions(actions); + rule.setPhase("phase_1"); + rule.setEntryPhase("snmp_map"); + rule.setPublishPhase("map_publish"); return rule; } @@ -270,6 +386,23 @@ public class RulesBusinessLogicTest { return rule; } + private Rule buildValidRuleWithDependentSearchAndTransformActions() { + Rule rule = buildRuleWithMultipleCopyActions(); + rule.getActions().add(0, buildStringTransformAction()); + rule.getActions().add(0, buildConditionalTopoSearchAction()); + return rule; + } + + private StringTransformAction buildStringTransformAction() { + String stringTransform = "{actionType:\"string Transform\",id:76,target:searchString,stringTransform:{targetCase:same,startValue:\"${event.otherFields.otherSiteId}${targetField}${event.commonEventHeader.sourceName}\"}}"; + return gson.fromJson(stringTransform, StringTransformAction.class); + } + + private TopoSearchAction buildConditionalTopoSearchAction() { + String topoSearch = "{actionType:\"Topology Search\",id:76,search:{searchField:sourceToSearch,searchValue:\"${searchString}\",radio:'',searchFilter:{left:\"${event.commonEventHeader.eventId}\",right:[rightO],operator:OneOf},enrich:{fields:[{value:e_field1},{value:e_field2}],prefix:e_prefix}}}"; + return gson.fromJson(topoSearch, TopoSearchAction.class); + } + private Rule buildRuleWithCircularActionDependencies() { Rule rule = buildValidRuleWithDependentActions(); rule.getActions().add(buildCopyAction("${invalidSelfDependency}", "invalidSelfDependency")); @@ -282,6 +415,7 @@ public class RulesBusinessLogicTest { action.setActionType("copy"); action.setFrom(from); action.setTarget(to); + mockUiGeneratedFields(action); return action; } @@ -289,6 +423,7 @@ public class RulesBusinessLogicTest { LogTextAction logTextAction = new LogTextAction(); logTextAction.setActionType("Log Text"); logTextAction.setLogText("a name", "a level", ""); + logTextAction.setId(mockUiInput); return logTextAction; } @@ -297,6 +432,7 @@ public class RulesBusinessLogicTest { action.setActionType("concat"); action.setFrom(from); action.setTarget(to); + mockUiGeneratedFields(action); return action; } @@ -305,6 +441,7 @@ public class RulesBusinessLogicTest { action.setActionType("copy"); action.setFrom(from, regex); action.setTarget(to); + mockUiGeneratedFields(action); return action; } @@ -317,6 +454,12 @@ public class RulesBusinessLogicTest { action.setToFormat("toFormat"); action.setFromTz("fromTZ"); action.setToTz("toTz"); + mockUiGeneratedFields(action); return action; } + + private void mockUiGeneratedFields(UnaryFieldAction action) { + action.setId(mockUiInput); + action.regexState(mockUiInput); + } } \ No newline at end of file -- cgit 1.2.3-korg