diff options
Diffstat (limited to 'src/test/java')
10 files changed, 585 insertions, 35 deletions
diff --git a/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDelegateTest.java new file mode 100644 index 000000000..75be799b7 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDelegateTest.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.clamp.clds.client; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.exception.ModelBpmnException; +import org.onap.policy.controlloop.policy.builder.BuilderException; + +@RunWith(MockitoJUnitRunner.class) +public class OperationalPolicyDelegateTest { + + private static final String TEST_KEY = "isTest"; + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String RECIPE_TOPIC_KEY = "op.recipeTopic"; + private static final String MESSAGE_KEY = "operationalPolicyResponseMessage"; + private static final String SERVICE_NAME = "service.name"; + private static final String POLICY_ID_FROM_JSON = "{policy:[{id:Oper12,from:''}]}"; + private static final String ID_WITH_CHAIN_JSON = "{Oper12:{ab:[" + + "{name:timeout,value:500}," + + "{policyConfigurations:[" + + "[{name:maxRetries,value:5}," + + "{name:retryTimeLimit,value:1000}," + + "{name:recipe,value:go}," + + "{name:targetResourceId," + + "value:resid234}]]}]}," + + "global:[{name:service,value:" + SERVICE_NAME + "}]}"; + private static final String SIMPLE_JSON = "{}"; + private static final String NOT_JSON = "not json"; + private static final String MESSAGE_VALUE = "message"; + private static final String RECIPE_TOPIC_VALUE = "recipe.topic"; + + @Mock + private Exchange exchange; + + @Mock + private PolicyClient policyClient; + + @Mock + private ClampProperties refProp; + + @InjectMocks + private OperationalPolicyDelegate operationalPolicyDelegate; + + @Test + public void shouldExecuteSuccessfully() throws BuilderException, UnsupportedEncodingException { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(POLICY_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_WITH_CHAIN_JSON); + when(policyClient.sendBrmsPolicy(any(), any(), any())).thenReturn(MESSAGE_VALUE); + when(refProp.getStringValue(eq(RECIPE_TOPIC_KEY), eq(SERVICE_NAME))).thenReturn(RECIPE_TOPIC_VALUE); + + // when + operationalPolicyDelegate.execute(exchange); + + // then + verify(exchange).setProperty(eq(MESSAGE_KEY), eq(MESSAGE_VALUE.getBytes())); + } + + @Test + public void shouldExecutePolicyNotFound() throws BuilderException, UnsupportedEncodingException { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(SIMPLE_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(SIMPLE_JSON); + + // when + operationalPolicyDelegate.execute(exchange); + + // then + verify(policyClient, never()).sendBrmsPolicy(any(), any(), any()); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() throws BuilderException, UnsupportedEncodingException { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + + // when + operationalPolicyDelegate.execute(exchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() throws BuilderException, UnsupportedEncodingException { + // when + operationalPolicyDelegate.execute(exchange); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegateTest.java new file mode 100644 index 000000000..9d87e7e97 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegateTest.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.clamp.clds.client; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.exception.ModelBpmnException; +import org.onap.clamp.clds.model.properties.ModelProperties; + +@RunWith(MockitoJUnitRunner.class) +public class OperationalPolicyDeleteDelegateTest { + + private static final String TEST_KEY = "isTest"; + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String EVENT_ACTION_KEY = "eventAction"; + private static final String POLICY_ID_FROM_JSON = "{policy:[{id:Poli2,from:''}]}"; + private static final String ID_WITH_CHAIN_JSON = "{Poli2:{ab:c,xy:z}}"; + private static final String ID_NO_CHAIN_JSON = "{Poli2:{}}"; + private static final String EVENT_ACTION_VALUE = "still"; + private static final String NOT_JSON = "23e"; + + @Mock + private Exchange exchange; + + @Mock + private PolicyClient policyClient; + + @InjectMocks + private OperationalPolicyDeleteDelegate operationalPolicyDeleteDelegate; + + @Test + public void shouldExecuteSuccessfully() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(POLICY_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_WITH_CHAIN_JSON); + when(exchange.getProperty(eq(EVENT_ACTION_KEY))).thenReturn(EVENT_ACTION_VALUE); + + // when + operationalPolicyDeleteDelegate.execute(exchange); + + // then + verify(policyClient, times(2)).deleteBrms(any(ModelProperties.class)); + } + + @Test + public void shouldExecuteTcaNotFound() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(POLICY_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_NO_CHAIN_JSON); + + // when + operationalPolicyDeleteDelegate.execute(exchange); + + // then + verify(policyClient, never()).deleteBrms(any(ModelProperties.class)); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + + // when + operationalPolicyDeleteDelegate.execute(exchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() { + // when + operationalPolicyDeleteDelegate.execute(exchange); + } +} diff --git a/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java b/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java index a32a60351..549c91321 100644 --- a/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java +++ b/src/test/java/org/onap/clamp/clds/config/CldsUserJsonDecoderTest.java @@ -5,6 +5,8 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -25,10 +27,11 @@ package org.onap.clamp.clds.config; import static org.assertj.core.api.Assertions.assertThat; - import org.junit.Test; +import org.onap.clamp.clds.exception.CldsUsersException; import org.onap.clamp.clds.service.CldsUser; + public class CldsUserJsonDecoderTest { private String user1 = "admin1"; @@ -92,4 +95,12 @@ public class CldsUserJsonDecoderTest { assertThat(user.getPassword()).isEqualTo(password); assertThat(user.getPermissionsString()).isEqualTo(incompletePermissionsArray); } + + @Test(expected = CldsUsersException.class) + public void shouldThrowCldsUsersException() { + //when + CldsUserJsonDecoder + .decodeJson(this.getClass().getResourceAsStream("/clds/clds-parse-exception.json")); + } + } diff --git a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java index 36d4eb829..e1b963cc4 100644 --- a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java @@ -179,10 +179,9 @@ public class CsarInstallerItCase { ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca-2.json"), StandardCharsets.UTF_8), cldsModel2.getPropText(), true); CldsModel cldsModel3 = verifyClosedLoopModelLoadedInDb(csar, "tca_3.yaml"); - JSONAssert.assertEquals( - IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca.json"), - StandardCharsets.UTF_8), - cldsModel3.getPropText(), true); + JSONAssert.assertEquals(IOUtils.toString( + ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca-3.json"), + StandardCharsets.UTF_8), cldsModel3.getPropText(), true); } private CldsModel verifyClosedLoopModelLoadedInDb(CsarHandler csar, String artifactName) diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java index 211bb3906..7a1f9f0ac 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParserTest.java @@ -142,18 +142,18 @@ public class BlueprintParserTest { public void getNodeRepresentationFromCompleteYaml() { final JsonObject jsonObject = jsonObjectBlueprintValid; - MicroService expected = new MicroService(SECOND_APPP, MODEL_TYPE1, FIRST_APPP, "", SECOND_APPP); + MicroService expected = new MicroService(SECOND_APPP, MODEL_TYPE1, FIRST_APPP, ""); Entry<String, JsonElement> entry = jsonObject.entrySet().iterator().next(); - MicroService actual = new BlueprintParser().getNodeRepresentation(entry); + MicroService actual = new BlueprintParser().getNodeRepresentation(entry, jsonObject); Assert.assertEquals(expected, actual); } @Test public void getMicroServicesFromBlueprintTest() { - MicroService thirdApp = new MicroService(THIRD_APPP, MODEL_TYPE3, "", "", THIRD_APPP); - MicroService firstApp = new MicroService(FIRST_APPP, MODEL_TYPE1, THIRD_APPP, "", FIRST_APPP); - MicroService secondApp = new MicroService(SECOND_APPP, MODEL_TYPE2, FIRST_APPP, "", SECOND_APPP); + MicroService thirdApp = new MicroService(THIRD_APPP, MODEL_TYPE3, "", ""); + MicroService firstApp = new MicroService(FIRST_APPP, MODEL_TYPE1, THIRD_APPP, ""); + MicroService secondApp = new MicroService(SECOND_APPP, MODEL_TYPE2, FIRST_APPP, ""); Set<MicroService> expected = new HashSet<>(Arrays.asList(firstApp, secondApp, thirdApp)); Set<MicroService> actual = new BlueprintParser().getMicroServices(microServiceTheWholeBlueprintValid); @@ -164,7 +164,7 @@ public class BlueprintParserTest { @Test public void fallBackToOneMicroServiceTCATest() { MicroService tcaMS = new MicroService(BlueprintParser.TCA, "onap.policies.monitoring.cdap.tca.hi.lo.app", "", - "", ""); + ""); List<MicroService> expected = Collections.singletonList(tcaMS); List<MicroService> actual = new BlueprintParser().fallbackToOneMicroService(microServiceBlueprintOldStyleTCA); @@ -175,7 +175,7 @@ public class BlueprintParserTest { @Test public void fallBackToOneMicroServiceHolmesTest() { MicroService holmesMS = new MicroService(BlueprintParser.HOLMES, "onap.policies.monitoring.cdap.tca.hi.lo.app", - "", "", ""); + "", ""); List<MicroService> expected = Collections.singletonList(holmesMS); List<MicroService> actual = new BlueprintParser() diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java index 1eb66eadd..4b41ee818 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/ChainGeneratorTest.java @@ -38,10 +38,10 @@ public class ChainGeneratorTest { @Test public void getChainOfMicroServicesTest() { - MicroService ms1 = new MicroService(FIRST_APPP, "", "", "", ""); - MicroService ms2 = new MicroService(SECOND_APPP, "", FIRST_APPP, "", ""); - MicroService ms3 = new MicroService(THIRD_APPP, "", SECOND_APPP, "", ""); - MicroService ms4 = new MicroService(FOURTH_APPP, "", THIRD_APPP, "", ""); + MicroService ms1 = new MicroService(FIRST_APPP, "", "", ""); + MicroService ms2 = new MicroService(SECOND_APPP, "", FIRST_APPP, ""); + MicroService ms3 = new MicroService(THIRD_APPP, "", SECOND_APPP, ""); + MicroService ms4 = new MicroService(FOURTH_APPP, "", THIRD_APPP, ""); List<MicroService> expectedList = Arrays.asList(ms1, ms2, ms3, ms4); Set<MicroService> inputSet = new HashSet<>(expectedList); @@ -52,10 +52,10 @@ public class ChainGeneratorTest { @Test public void getChainOfMicroServicesTwiceNoInputTest() { - MicroService ms1 = new MicroService(FIRST_APPP, "", "", "", ""); - MicroService ms2 = new MicroService(SECOND_APPP, "", "", "", ""); - MicroService ms3 = new MicroService(THIRD_APPP, "", SECOND_APPP, "", ""); - MicroService ms4 = new MicroService(FOURTH_APPP, "", FIRST_APPP, "", ""); + MicroService ms1 = new MicroService(FIRST_APPP, "", "", ""); + MicroService ms2 = new MicroService(SECOND_APPP, "", "", ""); + MicroService ms3 = new MicroService(THIRD_APPP, "", SECOND_APPP, ""); + MicroService ms4 = new MicroService(FOURTH_APPP, "", FIRST_APPP, ""); Set<MicroService> inputSet = new HashSet<>(Arrays.asList(ms1, ms2, ms3, ms4)); List<MicroService> actualList = new ChainGenerator().getChainOfMicroServices(inputSet); @@ -64,10 +64,10 @@ public class ChainGeneratorTest { @Test public void getChainOfMicroServicesBranchingTest() { - MicroService ms1 = new MicroService(FIRST_APPP, "", "", "", ""); - MicroService ms2 = new MicroService(SECOND_APPP, "", FIRST_APPP, "", ""); - MicroService ms3 = new MicroService(THIRD_APPP, "", FIRST_APPP, "", ""); - MicroService ms4 = new MicroService(FOURTH_APPP, "", FIRST_APPP, "", ""); + MicroService ms1 = new MicroService(FIRST_APPP, "", "", ""); + MicroService ms2 = new MicroService(SECOND_APPP, "", FIRST_APPP, ""); + MicroService ms3 = new MicroService(THIRD_APPP, "", FIRST_APPP, ""); + MicroService ms4 = new MicroService(FOURTH_APPP, "", FIRST_APPP, ""); Set<MicroService> inputSet = new HashSet<>(Arrays.asList(ms1, ms2, ms3, ms4)); List<MicroService> actualList = new ChainGenerator().getChainOfMicroServices(inputSet); diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java index 5eb664fe7..ff6e1b5d4 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/ClampGraphBuilderTest.java @@ -56,8 +56,8 @@ public class ClampGraphBuilderTest { @Test public void clampGraphBuilderCompleteChainTest() { String collector = "VES"; - MicroService ms1 = new MicroService("ms1", "", "", "ms1_jpa_id", ""); - MicroService ms2 = new MicroService("ms2", "", "", "ms2_jpa_id", ""); + MicroService ms1 = new MicroService("ms1", "", "", "ms1_jpa_id"); + MicroService ms2 = new MicroService("ms2", "", "", "ms2_jpa_id"); String policy = "OperationalPolicy"; List<MicroService> microServices = Arrays.asList(ms1, ms2); @@ -76,8 +76,8 @@ public class ClampGraphBuilderTest { @Test(expected = InvalidStateException.class) public void clampGraphBuilderNoPolicyGivenTest() { String collector = "VES"; - MicroService ms1 = new MicroService("ms1", "", "", "ms1_jpa_id", ""); - MicroService ms2 = new MicroService("ms2", "", "", "ms2_jpa_id", ""); + MicroService ms1 = new MicroService("ms1", "", "", "ms1_jpa_id"); + MicroService ms2 = new MicroService("ms2", "", "", "ms2_jpa_id"); ClampGraphBuilder clampGraphBuilder = new ClampGraphBuilder(mockPainter); clampGraphBuilder.collector(collector).addMicroService(ms1).addMicroService(ms2).build(); diff --git a/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java b/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java new file mode 100644 index 000000000..1abeb104c --- /dev/null +++ b/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java @@ -0,0 +1,41 @@ +package org.onap.clamp.flow; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.clds.util.ONAPLogConstants; +import org.onap.clamp.flow.log.FlowLogOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.util.ReflectionTestUtils; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + + +public class FlowLogOperationTestItCase { + + @Autowired + CamelContext camelContext; + + @Test + public void testStratLog() { + //given + FlowLogOperation flowLogOperation = new FlowLogOperation(); + Exchange exchange = new DefaultExchange(camelContext); + LoggingUtils loggingUtils = mock(LoggingUtils.class); + ReflectionTestUtils.setField(flowLogOperation, "util", loggingUtils); + + //when + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)).thenReturn("MockRequestId"); + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)).thenReturn("MockInvocationId"); + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)).thenReturn("MockPartnerName"); + flowLogOperation.startLog(exchange, "serviceName"); + + //then + assertThat(exchange.getProperty(ONAPLogConstants.Headers.REQUEST_ID)).isEqualTo("MockRequestId"); + assertThat(exchange.getProperty(ONAPLogConstants.Headers.INVOCATION_ID)).isEqualTo("MockInvocationId"); + assertThat(exchange.getProperty(ONAPLogConstants.Headers.PARTNER_NAME)).isEqualTo("MockPartnerName"); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java index 883945ebc..cd6db68db 100644 --- a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java @@ -49,7 +49,9 @@ import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerExceptio import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact; import org.onap.clamp.clds.sdc.controller.installer.CsarHandler; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; +import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.ResourceFileUtil; +import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.api.notification.INotificationData; import org.onap.sdc.api.notification.IResourceInstance; @@ -57,6 +59,7 @@ import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.test.context.SpringBootTest; @@ -69,7 +72,7 @@ import org.springframework.test.context.junit4.SpringRunner; @ActiveProfiles(profiles = "clamp-default,clamp-default-user,clamp-sdc-controller-new") public class CsarInstallerItCase { - private static final String CSAR_ARTIFACT_NAME = "example/sdc/service-Vloadbalancerms-csar.csar"; + private static final String CSAR_ARTIFACT_NAME = "example/sdc/service_Vloadbalancerms_csar.csar"; private static final String INVARIANT_SERVICE_UUID = "4cc5b45a-1f63-4194-8100-cd8e14248c92"; private static final String INVARIANT_RESOURCE1_UUID = "07e266fc-49ab-4cd7-8378-ca4676f1b9ec"; private static final String INVARIANT_RESOURCE2_UUID = "023a3f0d-1161-45ff-b4cf-8918a8ccf3ad"; @@ -137,8 +140,7 @@ public class CsarInstallerItCase { // set SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); String path = Thread.currentThread().getContextClassLoader().getResource(CSAR_ARTIFACT_NAME).getFile(); - ISdcCsarHelper sdcHelper = factory - .getSdcCsarHelper(path); + ISdcCsarHelper sdcHelper = factory.getSdcCsarHelper(path); Mockito.when(csarHandler.getSdcCsarHelper()).thenReturn(sdcHelper); // Mockito.when(csarHandler.getSdcCsarHelper()).thenReturn(csarHelper); @@ -158,11 +160,11 @@ public class CsarInstallerItCase { Mockito.when(notificationData.getServiceArtifacts()).thenReturn(serviceArtifactsList); CsarHandler csarHandler = new CsarHandler(notificationData, "", ""); - csarHandler.setFilePath(Thread.currentThread().getContextClassLoader() - .getResource(CSAR_ARTIFACT_NAME).getFile()); + csarHandler + .setFilePath(Thread.currentThread().getContextClassLoader().getResource(CSAR_ARTIFACT_NAME).getFile()); Optional<String> testyaml = csarHandler.getPolicyModelYaml(); - Assert.assertEquals(testyaml, Optional.ofNullable(ResourceFileUtil - .getResourceAsString("example/sdc/expected-result/policy-data.yaml"))); + Assert.assertEquals(testyaml, + Optional.ofNullable(ResourceFileUtil.getResourceAsString("example/sdc/expected-result/policy-data.yaml"))); } @Test @@ -178,6 +180,7 @@ public class CsarInstallerItCase { @Test @Transactional + @Rollback(value = false) public void testInstallTheCsarTca() throws SdcArtifactInstallerException, SdcToscaParserException, CsarHandlerException, IOException, JSONException, InterruptedException, PolicyModelException { String generatedName = RandomStringUtils.randomAlphanumeric(5); @@ -202,6 +205,19 @@ public class CsarInstallerItCase { assertThat(loop.getOperationalPolicies()).hasSize(1); assertThat(loop.getModelPropertiesJson().get("serviceDetails")).isNotNull(); assertThat(loop.getModelPropertiesJson().get("resourceDetails")).isNotNull(); + JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/model-properties.json"), + JsonUtils.GSON.toJson(loop.getModelPropertiesJson()), true); + assertThat(((MicroServicePolicy) (loop.getMicroServicePolicies().toArray()[0])).getModelType()).isNotEmpty(); + + loop = loopsRepo + .findById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE1, "tca_3.yaml")) + .get(); + assertThat(((MicroServicePolicy) (loop.getMicroServicePolicies().toArray()[0])).getModelType()).isNotEmpty(); + + loop = loopsRepo + .findById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE2, "tca_2.yaml")) + .get(); + assertThat(((MicroServicePolicy) (loop.getMicroServicePolicies().toArray()[0])).getModelType()).isNotEmpty(); } } diff --git a/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java b/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java new file mode 100644 index 000000000..e71b4982d --- /dev/null +++ b/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java @@ -0,0 +1,250 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Nokia 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.clamp.loop; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.util.HashSet; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.json.simple.parser.ParseException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.clamp.clds.Application; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.loop.LoopOperation.TempLoopState; +import org.onap.clamp.policy.microservice.MicroServicePolicy; +import org.onap.clamp.policy.operational.OperationalPolicy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class) +public class LoopOperationTestItCase { + + private Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); + @Autowired + LoopService loopService; + + @Autowired + ClampProperties property; + + private Loop createTestLoop() { + String yaml = "imports:\n" + + " - \"http://www.getcloudify.org/spec/cloudify/3.4/types.yaml\"\n" + + "node_templates:\n" + + " docker_service_host:\n" + + " type: dcae.nodes.SelectedDockerHost"; + + Loop loopTest = new Loop("ControlLoopTest", yaml, "<xml></xml>"); + loopTest.setGlobalPropertiesJson(new Gson().fromJson("{\"testname\":\"testvalue\"}", JsonObject.class)); + loopTest.setLastComputedState(LoopState.DESIGN); + loopTest.setDcaeDeploymentId("123456789"); + loopTest.setDcaeDeploymentStatusUrl("http4://localhost:8085"); + loopTest.setDcaeBlueprintId("UUID-blueprint"); + + MicroServicePolicy microServicePolicy = new MicroServicePolicy("configPolicyTest", "", + "tosca_definitions_version: tosca_simple_yaml_1_0_0", true, + gson.fromJson("{\"configtype\":\"json\"}", JsonObject.class), new HashSet<>()); + microServicePolicy.setProperties(new Gson().fromJson("{\"param1\":\"value1\"}", JsonObject.class)); + + loopTest.addMicroServicePolicy(microServicePolicy); + return loopTest; + } + + + @Test + public void testAnalysePolicyResponse() { + LoopOperation loopOp = new LoopOperation(loopService, property); + String status1 = loopOp.analysePolicyResponse(200); + String status2 = loopOp.analysePolicyResponse(404); + String status3 = loopOp.analysePolicyResponse(500); + String status4 = loopOp.analysePolicyResponse(503); + + // then + assertThat(status1).isEqualTo("SUBMITTED"); + assertThat(status2).isEqualTo("NOT_SUBMITTED"); + assertThat(status3).isEqualTo("IN_ERROR"); + assertThat(status4).isEqualTo("IN_ERROR"); + } + + @Test + public void testGetOperationalPolicyName() { + LoopOperation loopOp = new LoopOperation(loopService, property); + Loop loop = this.createTestLoop(); + String opName1 = loopOp.getOperationalPolicyName(loop); + assertThat(opName1).isNull(); + + OperationalPolicy opPolicy1 = new OperationalPolicy("OperationalPolicyTest1", null, + gson.fromJson("{\"type\":\"Operational\"}", JsonObject.class)); + loop.addOperationalPolicy(opPolicy1); + String opName2 = loopOp.getOperationalPolicyName(loop); + assertThat(opName2).isEqualTo("OperationalPolicyTest1"); + } + + @Test + public void testAnalyseDcaeResponse() throws ParseException { + LoopOperation loopOp = new LoopOperation(loopService, property); + String dcaeStatus1 = loopOp.analyseDcaeResponse(null, null); + assertThat(dcaeStatus1).isEqualTo("NOT_DEPLOYED"); + + String dcaeStatus2 = loopOp.analyseDcaeResponse(null, 500); + assertThat(dcaeStatus2).isEqualTo("IN_ERROR"); + + String dcaeStatus3 = loopOp.analyseDcaeResponse(null, 404); + assertThat(dcaeStatus3).isEqualTo("NOT_DEPLOYED"); + + Exchange camelExchange = Mockito.mock(Exchange.class); + Message mockMessage = Mockito.mock(Message.class); + Mockito.when(camelExchange.getIn()).thenReturn(mockMessage); + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"install\",\"status\":\"succeeded\"}"); + String dcaeStatus4 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus4).isEqualTo("DEPLOYED"); + + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"install\",\"status\":\"processing\"}"); + String dcaeStatus5 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus5).isEqualTo("PROCESSING"); + + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"install\",\"status\":\"failed\"}"); + String dcaeStatus6 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus6).isEqualTo("IN_ERROR"); + + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"succeeded\"}"); + String dcaeStatus7 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus7).isEqualTo("NOT_DEPLOYED"); + + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"processing\"}"); + String dcaeStatus8 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus8).isEqualTo("PROCESSING"); + + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"failed\"}"); + String dcaeStatus9 = loopOp.analyseDcaeResponse(camelExchange, 200); + assertThat(dcaeStatus9).isEqualTo("IN_ERROR"); + } + + @Test + public void testUpdateLoopStatus() { + LoopOperation loopOp = new LoopOperation(loopService, property); + Loop loop = this.createTestLoop(); + loopService.saveOrUpdateLoop(loop); + LoopState newState1 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.DEPLOYED); + LoopState dbState1 = loopService.getLoop(loop.getName()).getLastComputedState(); + assertThat(newState1).isEqualTo(LoopState.DEPLOYED); + assertThat(dbState1).isEqualTo(LoopState.DEPLOYED); + + LoopState newState2 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.NOT_DEPLOYED); + LoopState dbState2 = loopService.getLoop(loop.getName()).getLastComputedState(); + assertThat(newState2).isEqualTo(LoopState.SUBMITTED); + assertThat(dbState2).isEqualTo(LoopState.SUBMITTED); + + LoopState newState3 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.PROCESSING); + assertThat(newState3).isEqualTo(LoopState.WAITING); + + LoopState newState4 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.IN_ERROR); + assertThat(newState4).isEqualTo(LoopState.IN_ERROR); + + LoopState newState5 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.DEPLOYED); + assertThat(newState5).isEqualTo(LoopState.IN_ERROR); + + LoopState newState6 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.PROCESSING); + assertThat(newState6).isEqualTo(LoopState.IN_ERROR); + + LoopState newState7 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.NOT_DEPLOYED); + assertThat(newState7).isEqualTo(LoopState.DESIGN); + + LoopState newState8 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.DEPLOYED); + assertThat(newState8).isEqualTo(LoopState.IN_ERROR); + + LoopState newState9 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.NOT_DEPLOYED); + assertThat(newState9).isEqualTo(LoopState.IN_ERROR); + + LoopState newState10 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.PROCESSING); + assertThat(newState10).isEqualTo(LoopState.IN_ERROR); + + LoopState newState11 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.IN_ERROR); + assertThat(newState11).isEqualTo(LoopState.IN_ERROR); + } + + @Test + public void testUpdateLoopInfo() throws ParseException { + Loop loop = this.createTestLoop(); + loopService.saveOrUpdateLoop(loop); + + Exchange camelExchange = Mockito.mock(Exchange.class); + Message mockMessage = Mockito.mock(Message.class); + Mockito.when(camelExchange.getIn()).thenReturn(mockMessage); + Mockito.when(mockMessage.getBody(String.class)) + .thenReturn("{\"links\":{\"status\":\"http://testhost/dcae-operationstatus\",\"test2\":\"test2\"}}"); + + LoopOperation loopOp = new LoopOperation(loopService, property); + loopOp.updateLoopInfo(camelExchange, loop, "testNewId"); + + Loop newLoop = loopService.getLoop(loop.getName()); + String newDeployId = newLoop.getDcaeDeploymentId(); + String newDeploymentStatusUrl = newLoop.getDcaeDeploymentStatusUrl(); + + assertThat(newDeployId).isEqualTo("testNewId"); + assertThat(newDeploymentStatusUrl).isEqualTo("http4://testhost/dcae-operationstatus"); + } + + @Test + public void testGetDeploymentId() { + Loop loop = this.createTestLoop(); + LoopOperation loopOp = new LoopOperation(loopService, property); + String deploymentId1 = loopOp.getDeploymentId(loop); + assertThat(deploymentId1).isEqualTo("123456789"); + + loop.setDcaeDeploymentId(null); + String deploymentId2 = loopOp.getDeploymentId(loop); + assertThat(deploymentId2).isEqualTo("closedLoop_ControlLoopTest_deploymentId"); + + loop.setDcaeDeploymentId(""); + String deploymentId3 = loopOp.getDeploymentId(loop); + assertThat(deploymentId3).isEqualTo("closedLoop_ControlLoopTest_deploymentId"); + } + + @Test + public void testGetDeployPayload() throws IOException { + Loop loop = this.createTestLoop(); + LoopOperation loopOp = new LoopOperation(loopService, property); + String deploymentPayload = loopOp.getDeployPayload(loop); + + String expectedPayload = "{\"serviceTypeId\":\"UUID-blueprint\",\"inputs\":{\"imports\":[\"http://www.getcloudify.org/spec/cloudify/3.4/types.yaml\"],\"node_templates\":{\"docker_service_host\":{\"type\":\"dcae.nodes.SelectedDockerHost\"}}}}"; + assertThat(deploymentPayload).isEqualTo(expectedPayload); + } +}
\ No newline at end of file |