diff options
Diffstat (limited to 'dcae-analytics-tca/src/test/java/org/onap')
8 files changed, 1021 insertions, 0 deletions
diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/BaseAnalyticsTCAUnitTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/BaseAnalyticsTCAUnitTest.java new file mode 100644 index 0000000..9b3762c --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/BaseAnalyticsTCAUnitTest.java @@ -0,0 +1,162 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Suppliers; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.ClosedLoopEventStatus; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.Direction; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.Threshold; +import org.onap.dcae.apod.analytics.model.util.AnalyticsModelIOUtils; +import org.onap.dcae.apod.analytics.model.util.json.AnalyticsModelObjectMapperSupplier; +import org.onap.dcae.apod.analytics.test.BaseDCAEAnalyticsUnitTest; + +import java.io.IOException; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * @author Rajiv Singla . Creation Date: 10/25/2016. + */ +public abstract class BaseAnalyticsTCAUnitTest extends BaseDCAEAnalyticsUnitTest { + + /** + * Object mapper to be used for all TCA Json Parsing + */ + protected static final ObjectMapper ANALYTICS_MODEL_OBJECT_MAPPER = + Suppliers.memoize(new AnalyticsModelObjectMapperSupplier()).get(); + + protected static final String TCA_POLICY_JSON_FILE_LOCATION = "data/json/policy/tca_policy.json"; + protected static final String CEF_MESSAGES_JSON_FILE_LOCATION = "data/json/cef/cef_messages.json"; + protected static final String CEF_MESSAGE_JSON_FILE_LOCATION = "data/json/cef/cef_message.json"; + protected static final String CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION = + "data/json/cef/cef_message_with_threshold_violation.json"; + + protected static final String TCA_CONTROLLER_POLICY_FILE_LOCATION = + "data/properties/tca_controller_policy.properties"; + + protected static final String TCA_AAI_VNF_ENRICHMENT_FILE_LOCATION = "data/json/aai/aai_vnf_enrichment.json"; + + protected static final String TCA_TEST_APP_CONFIG_NAME = "testTCAAppName"; + protected static final String TCA_TEST_APP_CONFIG_DESCRIPTION = "testTCAAppDescription"; + protected static final String TCA_TEST_APP_CONFIG_SUBSCRIBER_OUTPUT_STREAM_NAME = + "testTcaSubscriberOutputStreamName"; + protected static final String TCA_TEST_APP_CONFIG_VES_ALERT_TABLE_NAME = "testTcaVESAlertsTableName"; + protected static final String TCA_TEST_APP_CONFIG_VES_MESSAGE_STATUS_TABLE_NAME = + "testTcaVESMessageStatusTableName"; + + + /** + * Provides TCA Policy that can be used for testing + * + * @return test TCA Policy Object + */ + protected TCAPolicy getSampleTCAPolicy() { + try { + return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(fromStream(TCA_POLICY_JSON_FILE_LOCATION), TCAPolicy.class); + } catch (IOException e) { + LOG.error("Error while parsing policy: {}", e); + throw new RuntimeException("Error while parsing policy", e); + } + } + + /** + * Provides list containing 350 CEF messages + * + * @return CEF Test Message + * @throws Exception Exception + */ + protected List<EventListener> getCEFMessages() throws Exception { + final String cefMessageAsString = fromStream(CEF_MESSAGES_JSON_FILE_LOCATION); + final TypeReference<List<EventListener>> eventListenerListTypeReference = + new TypeReference<List<EventListener>>() { + }; + return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(cefMessageAsString, eventListenerListTypeReference); + } + + /** + * Provides 1 valid CEF messages which does not violate Threshold as String + * + * @return CEF Test Message String + * @throws Exception Exception + */ + protected String getValidCEFMessage() throws Exception { + return fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + } + + + /** + * Provides single CEF Test Message + * + * @return CEF Test Message + * @throws Exception Exception + */ + protected EventListener getCEFEventListener() throws Exception { + final String cefMessageAsString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + return ANALYTICS_MODEL_OBJECT_MAPPER.readValue(cefMessageAsString, EventListener.class); + } + + protected static List<Threshold> getThresholds() { + Threshold majorThreshold = new Threshold(); + majorThreshold.setClosedLoopControlName("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"); + majorThreshold.setFieldPath("$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn"); + majorThreshold.setVersion("Test Version"); + majorThreshold.setThresholdValue(500L); + majorThreshold.setClosedLoopEventStatus(ClosedLoopEventStatus.ONSET); + majorThreshold.setDirection(Direction.LESS_OR_EQUAL); + + Threshold criticalThreshold = new Threshold(); + criticalThreshold.setClosedLoopControlName("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"); + criticalThreshold.setThresholdValue(5000L); + criticalThreshold.setFieldPath("$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn"); + criticalThreshold.setClosedLoopEventStatus(ClosedLoopEventStatus.ONSET); + criticalThreshold.setDirection(Direction.GREATER_OR_EQUAL); + return Arrays.asList(majorThreshold, criticalThreshold); + } + + protected static Threshold getCriticalThreshold() { + Threshold criticalThreshold = new Threshold(); + criticalThreshold.setClosedLoopControlName("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A"); + criticalThreshold.setThresholdValue(5000L); + criticalThreshold.setFieldPath("$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn"); + criticalThreshold.setDirection(Direction.GREATER_OR_EQUAL); + return criticalThreshold; + } + + protected static Map<String, String> getControllerRuntimeArguments() { + final Properties controllerProperties = + AnalyticsModelIOUtils.loadPropertiesFile(TCA_CONTROLLER_POLICY_FILE_LOCATION, new Properties()); + + final Map<String, String> runtimeArgs = new LinkedHashMap<>(); + for (Map.Entry<Object, Object> property : controllerProperties.entrySet()) { + runtimeArgs.put(property.getKey().toString(), property.getValue().toString()); + } + + return runtimeArgs; + } + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/AbstractTCAECEFPolicyProcessorTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/AbstractTCAECEFPolicyProcessorTest.java new file mode 100644 index 0000000..1a0a2c4 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/AbstractTCAECEFPolicyProcessorTest.java @@ -0,0 +1,56 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Test; +import org.onap.dcae.apod.analytics.common.exception.MessageProcessingException; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +/** + * @author Rajiv Singla . Creation Date: 12/16/2016. + */ +public class AbstractTCAECEFPolicyProcessorTest extends BaseAnalyticsTCAUnitTest { + + private class DummyAbstractTCAECEFPolicyProcessor extends AbstractTCAECEFPolicyProcessor { + + @Override + public String getProcessorDescription() { + return "dummy"; + } + + @Override + public TCACEFProcessorContext processMessage(TCACEFProcessorContext processorContext) { + return processorContext; + } + } + + + @Test(expected = MessageProcessingException.class) + public void preProcessorWhenThereIsNoCEFMessage() throws Exception { + DummyAbstractTCAECEFPolicyProcessor dummyAbstractTCAECEFPolicyProcessor = new + DummyAbstractTCAECEFPolicyProcessor(); + + final TCACEFProcessorContext processorContext = new TCACEFProcessorContext(null, getSampleTCAPolicy()); + processorContext.setCEFEventListener(null); + dummyAbstractTCAECEFPolicyProcessor.preProcessor(processorContext); + } + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFJsonProcessorTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFJsonProcessorTest.java new file mode 100644 index 0000000..b3ae9eb --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFJsonProcessorTest.java @@ -0,0 +1,117 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Test; +import org.onap.dcae.apod.analytics.common.exception.MessageProcessingException; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; + +/** + * + * @author Rajiv Singla . Creation Date: 11/9/2016. + */ +public class TCACEFJsonProcessorTest extends BaseAnalyticsTCAUnitTest { + + + // A valid CEF Message + @Test + public void testCEFJsonProcessorWithValidCEFMessage() throws Exception { + + final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + final TCACEFProcessorContext tcacefProcessorContext = + new TCACEFProcessorContext(cefMessageString, getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + final TCACEFProcessorContext finalProcessorContext = tcacefJsonProcessor.apply(tcacefProcessorContext); + + final EventListener cefEventListener = finalProcessorContext.getCEFEventListener(); + + assertNotNull("CEF Event Listener must be present", cefEventListener); + + } + + // Even if message is not a valid CEF format but still a Json - Json Processor will parse it + @Test + public void testCEFJsonProcessorWithValidJson() throws Exception { + + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext( + " { \"key\" : \"value\" } ", getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + final TCACEFProcessorContext finalProcessorContext = tcacefJsonProcessor.apply(tcacefProcessorContext); + final EventListener cefEventListener = finalProcessorContext.getCEFEventListener(); + + assertNotNull("Even if message is not a valid CEF format but a valid Json.Json Processor must be able to " + + "parse it", + cefEventListener); + } + + @Test(expected = MessageProcessingException.class) + public void testCEFJsonProcessorWithCEFMessageAsNull() throws Exception { + + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(null, getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + tcacefJsonProcessor.apply(tcacefProcessorContext); + + } + + @Test + public void testCEFJsonProcessorWithCEFMessageIsBlank() throws Exception { + + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(" ", getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + final TCACEFProcessorContext finalProcessorContext = tcacefJsonProcessor.apply(tcacefProcessorContext); + assertFalse("Blank message must terminate processing of message chain", finalProcessorContext + .canProcessingContinue()); + } + + + @Test + public void testCEFJsonProcessorWithCEFMessageWhichIsNotValidMessage() throws Exception { + + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(" Invalid Message ", + getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + final TCACEFProcessorContext finalProcessorContext = tcacefJsonProcessor.apply(tcacefProcessorContext); + assertFalse("Invalid message must terminate processing of message chain", finalProcessorContext + .canProcessingContinue()); + } + + + @Test(expected = MessageProcessingException.class) + public void testCEFJsonProcessorWithCEFMessageWhichIsNotValidJson() throws Exception { + + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext( + " { \"Invalid Event Listener Json\" } ", getSampleTCAPolicy()); + + TCACEFJsonProcessor tcacefJsonProcessor = new TCACEFJsonProcessor(); + tcacefJsonProcessor.apply(tcacefProcessorContext); + } + + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyDomainFilterTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyDomainFilterTest.java new file mode 100644 index 0000000..6609128 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyDomainFilterTest.java @@ -0,0 +1,74 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.apod.analytics.common.service.processor.ProcessingState; +import org.onap.dcae.apod.analytics.model.domain.cef.Domain; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @author Rajiv Singla . Creation Date: 12/16/2016. + */ +public class TCACEFPolicyDomainFilterTest extends BaseAnalyticsTCAUnitTest { + + private TCACEFPolicyDomainFilter tcacefPolicyDomainFilter; + private TCACEFProcessorContext processorContext; + private EventListener cefEventListener; + + @Before + public void before() throws Exception { + tcacefPolicyDomainFilter = new TCACEFPolicyDomainFilter(); + processorContext = new TCACEFProcessorContext("", getSampleTCAPolicy()); + cefEventListener = getCEFEventListener(); + processorContext.setCEFEventListener(cefEventListener); + } + + @Test + public void testProcessMessageWhenMessageIsValid() throws Exception { + tcacefPolicyDomainFilter.processMessage(processorContext); + assertThat("Processing must finish successfully", + tcacefPolicyDomainFilter.getProcessingState(), is(ProcessingState.PROCESSING_FINISHED_SUCCESSFULLY)); + } + + @Test + public void testProcessMessageWhenCEFEventIsNull() throws Exception { + cefEventListener.setEvent(null); + processorContext.setCEFEventListener(cefEventListener); + tcacefPolicyDomainFilter.processMessage(processorContext); + assertThat("Processing must terminate early", + tcacefPolicyDomainFilter.getProcessingState(), is(ProcessingState.PROCESSING_TERMINATED_EARLY)); + } + + @Test + public void testProcessMessageWhenPolicyDomainDoesNotMatchMessageDomain() throws Exception { + cefEventListener.getEvent().getCommonEventHeader().setDomain(Domain.other); + tcacefPolicyDomainFilter.processMessage(processorContext); + assertThat("Processing must terminate early", + tcacefPolicyDomainFilter.getProcessingState(), is(ProcessingState.PROCESSING_TERMINATED_EARLY)); + } + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyEventNameFilterTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyEventNameFilterTest.java new file mode 100644 index 0000000..6f01ab3 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyEventNameFilterTest.java @@ -0,0 +1,75 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.apod.analytics.common.service.processor.ProcessingState; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +/** + * @author Rajiv Singla . Creation Date: 12/19/2016. + */ +public class TCACEFPolicyEventNameFilterTest extends BaseAnalyticsTCAUnitTest { + + private TCACEFPolicyEventNameFilter tcacefPolicyEventNameFilter; + private TCACEFProcessorContext processorContext; + private EventListener cefEventListener; + + @Before + public void before() throws Exception { + tcacefPolicyEventNameFilter = new TCACEFPolicyEventNameFilter(); + processorContext = new TCACEFProcessorContext("", getSampleTCAPolicy()); + cefEventListener = getCEFEventListener(); + processorContext.setCEFEventListener(cefEventListener); + } + + @Test + public void testProcessMessageWhenMessageIsValid() throws Exception { + tcacefPolicyEventNameFilter.processMessage(processorContext); + assertThat("Processing must finish successfully", + tcacefPolicyEventNameFilter.getProcessingState(), + is(ProcessingState.PROCESSING_FINISHED_SUCCESSFULLY)); + } + + @Test + public void testProcessMessageWhenCEFEventIsNull() throws Exception { + cefEventListener.setEvent(null); + processorContext.setCEFEventListener(cefEventListener); + tcacefPolicyEventNameFilter.processMessage(processorContext); + assertThat("Processing must terminate early", + tcacefPolicyEventNameFilter.getProcessingState(), is(ProcessingState.PROCESSING_TERMINATED_EARLY)); + } + + @Test + public void testProcessMessageWhenPolicyEventNameDoesNotMatchMessageEventName() throws Exception { + cefEventListener.getEvent().getCommonEventHeader().setEventName("someNonPolicyEventName"); + tcacefPolicyEventNameFilter.processMessage(processorContext); + assertThat("Processing must terminate early", + tcacefPolicyEventNameFilter.getProcessingState(), is(ProcessingState.PROCESSING_TERMINATED_EARLY)); + } + + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyThresholdsProcessorTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyThresholdsProcessorTest.java new file mode 100644 index 0000000..0cec690 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFPolicyThresholdsProcessorTest.java @@ -0,0 +1,81 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Test; +import org.onap.dcae.apod.analytics.common.service.processor.ProcessingState; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * + * @author Rajiv Singla . Creation Date: 11/9/2016. + */ +public class TCACEFPolicyThresholdsProcessorTest extends BaseAnalyticsTCAUnitTest { + + @Test + public void testCEFPolicyThresholdProcessorWithNoThresholdViolation() throws Exception { + + final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(cefMessageString, + getSampleTCAPolicy()); + tcacefProcessorContext.setCEFEventListener(getCEFEventListener()); + + AbstractTCAECEFPolicyProcessor policyThresholdsProcessor = new TCACEFPolicyThresholdsProcessor(); + final TCACEFProcessorContext finalProcessorContext = policyThresholdsProcessor.apply(tcacefProcessorContext); + + assertFalse("Process Context can Processing Continue flag should be false", finalProcessorContext + .canProcessingContinue()); + assertThat("Policy Threshold Processor State must be terminated early", + policyThresholdsProcessor.getProcessingState(), is(ProcessingState.PROCESSING_TERMINATED_EARLY)); + assertEquals("Policy must not change", getSampleTCAPolicy(), finalProcessorContext.getTCAPolicy()); + + } + + @Test + public void testCEFPolicyThresholdProcessorWithThresholdViolation() throws Exception { + + final String cefMessageString = fromStream(CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION); + final TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(cefMessageString, + getSampleTCAPolicy()); + + final EventListener eventListener = ANALYTICS_MODEL_OBJECT_MAPPER.readValue(cefMessageString, + EventListener.class); + tcacefProcessorContext.setCEFEventListener(eventListener); + + AbstractTCAECEFPolicyProcessor policyThresholdsProcessor = new TCACEFPolicyThresholdsProcessor(); + final TCACEFProcessorContext finalProcessorContext = policyThresholdsProcessor.apply(tcacefProcessorContext); + + assertTrue("Process Context can Processing Continue flag should be true", finalProcessorContext + .canProcessingContinue()); + assertThat("Policy Threshold Processor State must be successful", + policyThresholdsProcessor.getProcessingState(), is(ProcessingState.PROCESSING_FINISHED_SUCCESSFULLY)); + assertEquals("Policy must not change", getSampleTCAPolicy(), finalProcessorContext.getTCAPolicy()); + + } + +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFProcessorContextTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFProcessorContextTest.java new file mode 100644 index 0000000..1482565 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/processor/TCACEFProcessorContextTest.java @@ -0,0 +1,38 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.processor; + +import org.junit.Test; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; + +/** + * + * @author Rajiv Singla . Creation Date: 11/14/2016. + */ +public class TCACEFProcessorContextTest extends BaseAnalyticsTCAUnitTest { + + @Test + public void testProcessorContextSerialization() throws Exception { + TCACEFProcessorContext tcacefProcessorContext = new TCACEFProcessorContext(getValidCEFMessage(), + getSampleTCAPolicy()); + testSerialization(tcacefProcessorContext, TCACEFProcessorContextTest.class); + } +} diff --git a/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/utils/TCAUtilsTest.java b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/utils/TCAUtilsTest.java new file mode 100644 index 0000000..e6b64d4 --- /dev/null +++ b/dcae-analytics-tca/src/test/java/org/onap/dcae/apod/analytics/tca/utils/TCAUtilsTest.java @@ -0,0 +1,418 @@ +/* + * ===============================LICENSE_START====================================== + * dcae-analytics + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================LICENSE_END=========================================== + */ + +package org.onap.dcae.apod.analytics.tca.utils; + +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Table; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; +import org.onap.dcae.apod.analytics.common.AnalyticsConstants; +import org.onap.dcae.apod.analytics.common.exception.MessageProcessingException; +import org.onap.dcae.apod.analytics.model.domain.cef.CommonEventHeader; +import org.onap.dcae.apod.analytics.model.domain.cef.Domain; +import org.onap.dcae.apod.analytics.model.domain.cef.Event; +import org.onap.dcae.apod.analytics.model.domain.cef.EventListener; +import org.onap.dcae.apod.analytics.model.domain.cef.EventSeverity; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.ClosedLoopEventStatus; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.ControlLoopSchemaType; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.Direction; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.MetricsPerEventName; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.TCAPolicy; +import org.onap.dcae.apod.analytics.model.domain.policy.tca.Threshold; +import org.onap.dcae.apod.analytics.model.facade.tca.TCAVESResponse; +import org.onap.dcae.apod.analytics.tca.BaseAnalyticsTCAUnitTest; +import org.onap.dcae.apod.analytics.tca.processor.TCACEFProcessorContext; +import org.quartz.Job; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SimpleTrigger; +import org.quartz.impl.StdSchedulerFactory; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.isA; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * @author Rajiv Singla . Creation Date: 11/9/2016. + */ +public class TCAUtilsTest extends BaseAnalyticsTCAUnitTest { + + @Test + public void testGetPolicyEventNames() throws Exception { + + final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy(); + final List<String> eventNames = TCAUtils.getPolicyEventNames(sampleTCAPolicy); + + assertThat("Policy event names must contain vFirewall, vLoadBalancer, virtualVMEventName", eventNames, + containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer", "virtualVMEventName")); + } + + @Test + public void testGetPolicyEventNamesSupplier() throws Exception { + final TCAPolicy sampleTCAPolicy = getSampleTCAPolicy(); + final Supplier<List<String>> policyEventNamesSupplier = TCAUtils.getPolicyEventNamesSupplier + (sampleTCAPolicy); + final List<String> eventNames = policyEventNamesSupplier.get(); + assertThat("Policy event names must contain vFirewall and vLoadBalancer", eventNames, + containsInAnyOrder("Mfvs_eNodeB_RANKPI", "vLoadBalancer", "virtualVMEventName")); + } + + @Test + public void testProcessCEFMessage() throws Exception { + final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + final TCACEFProcessorContext tcacefProcessorContext = TCAUtils.filterCEFMessage(cefMessageString, + getSampleTCAPolicy()); + assertThat("TCAECEFProcessor Processor Context can continue flag is true", tcacefProcessorContext + .canProcessingContinue(), is(true)); + } + + @Test + public void testGetPolicyFRThresholdsTableSupplier() throws Exception { + final Table<String, String, List<Threshold>> policyFRThresholdPathTable = TCAUtils + .getPolicyEventNameThresholdsTableSupplier(getSampleTCAPolicy()).get(); + + final Map<String, List<Threshold>> eNodeBRankpi = policyFRThresholdPathTable.row("Mfvs_eNodeB_RANKPI"); + final Map<String, List<Threshold>> vLoadBalancer = policyFRThresholdPathTable.row("vLoadBalancer"); + + final Set<String> eNodeBRankpiFieldPaths = eNodeBRankpi.keySet(); + final Set<String> vLoadBalancerPaths = vLoadBalancer.keySet(); + + final String receivedBroadcastPacketsFieldPath = + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated"; + assertThat("eNodeBRankpi threshold field path size must be " + + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" + + ".receivedBroadcastPacketsAccumulated", + eNodeBRankpiFieldPaths.iterator().next(), + is(receivedBroadcastPacketsFieldPath)); + + assertThat("vLoadBalancer threshold field path size must be " + + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*]" + + ".receivedBroadcastPacketsAccumulated", + vLoadBalancerPaths.iterator().next(), + is(receivedBroadcastPacketsFieldPath)); + + final List<Threshold> eNodeBRankpiThresholds = policyFRThresholdPathTable.get("Mfvs_eNodeB_RANKPI", + receivedBroadcastPacketsFieldPath); + final List<Threshold> vLoadBalancerThresholds = policyFRThresholdPathTable.get("vLoadBalancer", + receivedBroadcastPacketsFieldPath); + + assertThat("eNodeBRankpi Threshold size must be 3", eNodeBRankpiThresholds.size(), is(3)); + assertThat("vLoadBalancer Threshold size must be 2", vLoadBalancerThresholds.size(), is(2)); + } + + @Test + public void testGetJsonPathValueWithValidMessageAndPolicy() throws Exception { + final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + final String jsonPath = + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated"; + final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath); + final Map<String, List<BigDecimal>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths); + assertThat("Json Path value must match", + jsonPathValueMap.get(jsonPath).get(0), is(new BigDecimal(5000))); + + } + + @Test + public void testGetJsonPathValueWithValidPath() throws Exception { + final String cefMessageString = fromStream(CEF_MESSAGE_JSON_FILE_LOCATION); + final String jsonPath = "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].invalid"; + final ImmutableSet<String> fieldPaths = ImmutableSet.of(jsonPath); + final Map<String, List<BigDecimal>> jsonPathValueMap = TCAUtils.getJsonPathValue(cefMessageString, fieldPaths); + assertThat("Json path value must be empty", jsonPathValueMap.size(), is(0)); + + } + + + @Test + public void testCreateNewTCAVESResponseWithVFControlLoopSchemaType() throws Exception { + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + + MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class); + when(metricsPerEventName.getThresholds()).thenReturn(getThresholds()); + when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope"); + when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName); + when(metricsPerEventName.getEventName()).thenReturn("testEventName"); + when(metricsPerEventName.getControlLoopSchemaType()).thenReturn(ControlLoopSchemaType.VM); + + when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME"); + + //TODO : Add proper assertions, as the usage is not clearly understood + assertThat(tcaVESResponse.getClosedLoopControlName(), + is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A")); + assertThat(tcaVESResponse.getVersion(), is("Test Version")); + assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope")); + assertNull(tcaVESResponse.getAai().getGenericVNFName()); + assertNotNull(tcaVESResponse.getAai().getGenericServerName()); + } + + @Test + public void testCreateNewTCAVESResponseWithFunctionalRolevFirewall() throws Exception { + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + + MetricsPerEventName metricsPerEventName = mock(MetricsPerEventName.class); + when(metricsPerEventName.getThresholds()).thenReturn(getThresholds()); + when(metricsPerEventName.getPolicyScope()).thenReturn("Test Policy scope"); + when(tcacefProcessorContext.getMetricsPerEventName()).thenReturn(metricsPerEventName); + when(metricsPerEventName.getEventName()).thenReturn("vFirewall"); + + when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME"); + + //TODO : Add proper assertions, as the usage is not clearly understood + assertThat(tcaVESResponse.getClosedLoopControlName(), + is("CL-LBAL-LOW-TRAFFIC-SIG-FB480F95-A453-6F24-B767-FD703241AB1A")); + assertThat(tcaVESResponse.getVersion(), is("Test Version")); + assertThat(tcaVESResponse.getPolicyScope(), is("Test Policy scope")); + assertNotNull(tcaVESResponse.getAai().getGenericVNFName()); + assertNull(tcaVESResponse.getAai().getGenericServerName()); + + } + + @Rule + public ExpectedException expectedIllegalArgumentException = ExpectedException.none(); + + @Test + public void testCreateNewTCAVESResponseNullFunctionalRole() throws Exception { + expectedIllegalArgumentException.expect(MessageProcessingException.class); + expectedIllegalArgumentException.expectCause(isA(IllegalArgumentException.class)); + expectedIllegalArgumentException.expectMessage("No violations metrics. Unable to create VES Response"); + + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + TCAVESResponse tcaVESResponse = TCAUtils.createNewTCAVESResponse(tcacefProcessorContext, "TCA_APP_NAME"); + assertNotNull(tcaVESResponse.getClosedLoopControlName()); + } + + @Test + public void testPrioritizeThresholdViolations() throws Exception { + + Map<String, Threshold> thresholdMap = new HashMap<>(); + Threshold majorThreshold = mock(Threshold.class); + when(majorThreshold.getSeverity()).thenReturn(EventSeverity.MAJOR); + thresholdMap.put("MAJOR", majorThreshold); + + Threshold result1 = TCAUtils.prioritizeThresholdViolations(thresholdMap); + assertEquals(result1.getSeverity(), EventSeverity.MAJOR); + + Threshold criticalThreshold = mock(Threshold.class); + when(criticalThreshold.getSeverity()).thenReturn(EventSeverity.CRITICAL); + thresholdMap.put("CRITICAL", criticalThreshold); + + Threshold result2 = TCAUtils.prioritizeThresholdViolations(thresholdMap); + assertEquals(result2.getSeverity(), EventSeverity.CRITICAL); + } + + @Test + public void testCreateViolatedMetrics() throws Exception { + TCAPolicy tcaPolicy = getSampleTCAPolicy(); + Threshold violatedThreshold = getCriticalThreshold(); + String functionalRole = "Mfvs_eNodeB_RANKPI"; + MetricsPerEventName result = TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, functionalRole); + assertThat(result.getPolicyScope(), is("resource=vFirewall;type=configuration")); + assertThat(result.getPolicyName(), is("configuration.dcae.microservice.tca.xml")); + } + + @Test + public void testCreateViolatedMetricsWrongEventName() throws Exception { + expectedIllegalArgumentException.expect(MessageProcessingException.class); + expectedIllegalArgumentException.expectCause(isA(IllegalStateException.class)); + String eventName = "badEventName"; + expectedIllegalArgumentException.expectMessage("TCA Policy must contain eventName: " + eventName); + TCAPolicy tcaPolicy = getSampleTCAPolicy(); + Threshold violatedThreshold = getCriticalThreshold(); + TCAUtils.createViolatedMetrics(tcaPolicy, violatedThreshold, eventName); + } + + @Test + public void testGetDomainAndEventName() { + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + EventListener eventListener = mock(EventListener.class); + Event event = mock(Event.class); + CommonEventHeader commonEventHeader = mock(CommonEventHeader.class); + + Pair<String, String> result = TCAUtils.getDomainAndEventName(tcacefProcessorContext); + assertNull(result.getLeft()); + assertNull(result.getRight()); + + when(tcacefProcessorContext.getCEFEventListener()).thenReturn(eventListener); + result = TCAUtils.getDomainAndEventName(tcacefProcessorContext); + assertNull(result.getLeft()); + assertNull(result.getRight()); + + when(eventListener.getEvent()).thenReturn(event); + result = TCAUtils.getDomainAndEventName(tcacefProcessorContext); + assertNull(result.getLeft()); + assertNull(result.getRight()); + + when(event.getCommonEventHeader()).thenReturn(commonEventHeader); + result = TCAUtils.getDomainAndEventName(tcacefProcessorContext); + assertNull(result.getLeft()); + assertNull(result.getRight()); + + when(commonEventHeader.getDomain()).thenReturn(Domain.other); + when(commonEventHeader.getEventName()).thenReturn("eventName"); + + result = TCAUtils.getDomainAndEventName(tcacefProcessorContext); + assertEquals(result.getLeft(), "other"); + assertEquals(result.getRight(), "eventName"); + + } + + @Test + public void testComputeThresholdViolationsNotPresent() throws Exception { + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true); + when(tcacefProcessorContext.getMessage()).thenReturn(getValidCEFMessage()); + + when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy()); + when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + + TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext); + assertNotNull(result); + verify(result, times(0)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class)); + assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy()); + } + + @Test + public void testComputeThresholdViolationsPresent() throws Exception { + TCACEFProcessorContext tcacefProcessorContext = mock(TCACEFProcessorContext.class); + when(tcacefProcessorContext.canProcessingContinue()).thenReturn(true); + final String cefMessageString = fromStream(CEF_MESSAGE_WITH_THRESHOLD_VIOLATION_JSON_FILE_LOCATION); + when(tcacefProcessorContext.getMessage()).thenReturn(cefMessageString); + + when(tcacefProcessorContext.getTCAPolicy()).thenReturn(getSampleTCAPolicy()); + when(tcacefProcessorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + + TCACEFProcessorContext result = TCAUtils.computeThresholdViolations(tcacefProcessorContext); + verify(result, times(1)).setMetricsPerEventName(Mockito.any(MetricsPerEventName.class)); + + assertEquals("Policy must not change", getSampleTCAPolicy(), result.getTCAPolicy()); + } + + + @Test + public void testCreateTCAPolicyMetricsPerKeyName() throws Exception { + + final Map<String, String> tcaPolicyMap = TCAUtils.filterMapByKeyNamePrefix(getControllerRuntimeArguments(), + AnalyticsConstants.TCA_POLICY_METRICS_PER_FUNCTIONAL_ROLE_PATH); + + // determine functional Roles + final Map<String, Map<String, String>> functionalRolesMap = + TCAUtils.extractSubTree(tcaPolicyMap, 2, 3, AnalyticsConstants.TCA_POLICY_DELIMITER); + + final List<MetricsPerEventName> tcaPolicyMetricsPerEventNameList = + TCAUtils.createTCAPolicyMetricsPerEventNameList(functionalRolesMap); + + assertThat("There are two Metrics per function role", 2, + is(tcaPolicyMetricsPerEventNameList.size())); + } + + + @Test + public void testCreateQuartzScheduler() throws Exception { + final Scheduler scheduler = Mockito.mock(Scheduler.class); + final StdSchedulerFactory stdSchedulerFactory = Mockito.mock(StdSchedulerFactory.class); + when(stdSchedulerFactory.getScheduler()).thenReturn(scheduler); + final JobDataMap jobDataMap = Mockito.mock(JobDataMap.class); + TCAUtils.createQuartzScheduler(1000, stdSchedulerFactory, + "data/properties/quartz-test.properties", jobDataMap, Job.class, + "testJob", "testTigger"); + verify(scheduler, times(1)) + .scheduleJob(Mockito.any(JobDetail.class), Mockito.any(SimpleTrigger.class)); + } + + + @Test + public void testCreateTCAAlertStringWhenCEFIsEnabled() throws Exception { + final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.CRITICAL); + TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class); + when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics); + when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", true); + assertTrue(alertString.contains("thresholdCrossingAlertFields")); + } + + @Test(expected = MessageProcessingException.class) + public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsEnabled() throws Exception { + TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class); + when(processorContext.getMetricsPerEventName()).thenReturn(null); + TCAUtils.createTCAAlertString(processorContext, "testApp", true); + } + + @Test + public void testCreateTCAAlertStringWhenCEFIsDisabled() throws Exception { + final MetricsPerEventName violatedMetrics = createViolatedMetricsPerEventName(EventSeverity.MAJOR); + TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class); + when(processorContext.getMetricsPerEventName()).thenReturn(violatedMetrics); + when(processorContext.getCEFEventListener()).thenReturn(getCEFEventListener()); + final String alertString = TCAUtils.createTCAAlertString(processorContext, "testApp", false); + assertFalse(alertString.contains("thresholdCrossingAlertFields")); + } + + @Test(expected = MessageProcessingException.class) + public void testCreateTCAAlertStringWhenViolatedMetricsNotPresentAndCEFIsDisabled() throws Exception { + TCACEFProcessorContext processorContext = mock(TCACEFProcessorContext.class); + when(processorContext.getMetricsPerEventName()).thenReturn(null); + TCAUtils.createTCAAlertString(processorContext, "testApp", false); + } + + private static MetricsPerEventName createViolatedMetricsPerEventName(EventSeverity severity) { + final Threshold violatedThreshold = new Threshold(); + violatedThreshold.setSeverity(severity); + violatedThreshold.setDirection(Direction.GREATER); + violatedThreshold.setClosedLoopControlName("violatedThresholdClosedLoopName"); + violatedThreshold.setActualFieldValue(new BigDecimal(100L)); + violatedThreshold.setFieldPath("violatedThresholdFieldPath"); + violatedThreshold.setVersion("violatedThresholdVersion"); + violatedThreshold.setClosedLoopEventStatus(ClosedLoopEventStatus.ONSET); + violatedThreshold.setThresholdValue(50L); + + final MetricsPerEventName violatedMetrics = new MetricsPerEventName(); + violatedMetrics.setPolicyName("violatePolicyName"); + violatedMetrics.setPolicyVersion("violatedPolicyVersion"); + violatedMetrics.setPolicyScope("violatedPolicyScope"); + violatedMetrics.setEventName("violatedEventName"); + violatedMetrics.setThresholds(Arrays.asList(violatedThreshold)); + return violatedMetrics; + } +} |