diff options
author | xg353y <xg353y@intl.att.com> | 2017-04-11 13:30:42 +0200 |
---|---|---|
committer | xg353y <xg353y@intl.att.com> | 2017-04-11 15:34:19 +0200 |
commit | b6b7bef8bdcad15af01ac88a038dd763ce59f68f (patch) | |
tree | 399d39da23aaa37701e487df064e3e0c27709ef3 /bpmn/MSOCommonBPMN/src/test/java/org/openecomp | |
parent | 19340cad94eeaa1b580f7c0c99531de499e8ca14 (diff) |
[MSO-8] Update the maven dependency
Update the maven depenency for sdc-distribution-client to cooperate with the sdc changes.
Change-Id: I2da936e5c40cb68c7181bb78307192dd5655b5dc
Signed-off-by: xg353y <xg353y@intl.att.com>
Diffstat (limited to 'bpmn/MSOCommonBPMN/src/test/java/org/openecomp')
23 files changed, 6673 insertions, 0 deletions
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java new file mode 100644 index 0000000000..4e2b1e121a --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/BPMNUtil.java @@ -0,0 +1,214 @@ +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.spy; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Set of utility methods used for Unit testing + * + */ +public class BPMNUtil { + + public static String getVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertProcessInstanceFinished(processEngineServices, pID); + HistoricVariableInstance responseData = processEngineServices.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(pID) + .variableName(name) + .singleResult(); + + if (responseData != null) { + return (responseData.getValue() != null ? responseData.getValue().toString(): null); + } + return null; + } + + @SuppressWarnings("unchecked") + public static <T extends Object> T getRawVariable(ProcessEngineServices processEngineServices, String processDefinitionID, String name) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertProcessInstanceFinished(processEngineServices, pID); + Object responseData = processEngineServices.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(pID) + .variableName(name) + .singleResult() + .getValue(); + return (T) responseData; + } + + + public static void assertProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { + assertEquals(1, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + + public static void assertProcessInstanceNotFinished(ProcessEngineServices processEngineServices, String processDefinitionID) { + String pID = getProcessInstanceId(processEngineServices, + processDefinitionID); + assertEquals(0, processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pID).finished().count()); + } + + private static String getProcessInstanceId( + ProcessEngineServices processEngineServices, String processDefinitionID) { + List<HistoricProcessInstance> historyList = processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().list(); + String pID = null; + for (HistoricProcessInstance hInstance: historyList) { + if (hInstance.getProcessDefinitionKey().equals(processDefinitionID)) { + pID = hInstance.getId(); + break; + } + } + return pID; + } + + public static boolean isProcessInstanceFinished(ProcessEngineServices processEngineServices, String pid) { + return processEngineServices.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count() == 1 ? true: false; + } + + + private static void buildVariable(String key, String value, Map<String,Object> variableValueType) { + Map<String, Object> host = new HashMap<String, Object>(); + host.put("value", value); + host.put("type", "String"); + variableValueType.put(key, host); + } + + public static WorkflowResponse executeWorkFlow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) { + WorkflowResource workflowResource = new WorkflowResource(); + VariableMapImpl variableMap = new VariableMapImpl(); + + Map<String, Object> variableValueType = new HashMap<String, Object>(); + for (String key : variables.keySet()) { + buildVariable(key, variables.get(key), variableValueType); + } + buildVariable("mso-service-request-timeout","600", variableValueType); + variableMap.put("variables", variableValueType); + + workflowResource.setProcessEngineServices4junit(processEngineServices); + Response response = workflowResource.startProcessInstanceByKey( + processKey, variableMap); + WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); + return workflowResponse; + } + + //Check the runtime service to see whether the process is completed + public static void waitForWorkflowToFinish(ProcessEngineServices processEngineServices, String pid) throws InterruptedException { + // Don't wait forever + long waitTime = 120000; + long endTime = System.currentTimeMillis() + waitTime; + + while (true) { + if (processEngineServices.getRuntimeService().createProcessInstanceQuery().processInstanceId(pid).singleResult() == null) { + break; + } + + if (System.currentTimeMillis() >= endTime) { + fail("Process " + pid + " did not finish in " + waitTime + "ms"); + } + + Thread.sleep(200); + } + } + + /** + * Executes the Asynchronous workflow in synchronous fashion and returns the WorkflowResponse object + * @param processEngineServices + * @param processKey + * @param variables + * @return + * @throws InterruptedException + */ + public static WorkflowResponse executeAsyncWorkflow(ProcessEngineServices processEngineServices, String processKey, Map<String,String> variables) throws InterruptedException { + ProcessThread pthread = new ProcessThread(processKey, processEngineServices, variables); + pthread.start(); + BPMNUtil.assertProcessInstanceNotFinished(processEngineServices, processKey); + String pid = getProcessInstanceId(processEngineServices, processKey); + //Caution: If there is a problem with workflow, this may wait for ever + while (true) { + pid = getProcessInstanceId(processEngineServices, processKey); + if (!isProcessInstanceFinished(processEngineServices,pid)) { + Thread.sleep(200); + } else{ + break; + } + } + //need to retrieve for second time ? + pid = getProcessInstanceId(processEngineServices, processKey); + waitForWorkflowToFinish(processEngineServices, pid); + return pthread.workflowResponse; + } + + /** + * Execute workflow using async resource + * @param processEngineServices + * @param processKey + * @param asyncResponse + * @param variables + */ + private static void executeAsyncFlow(ProcessEngineServices processEngineServices, String processKey, AsynchronousResponse asyncResponse, Map<String,String> variables) { + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + VariableMapImpl variableMap = new VariableMapImpl(); + + Map<String, Object> variableValueType = new HashMap<String, Object>(); + for (String key : variables.keySet()) { + buildVariable(key, variables.get(key), variableValueType); + } + buildVariable("mso-service-request-timeout","600", variableValueType); + variableMap.put("variables", variableValueType); + + workflowResource.setProcessEngineServices4junit(processEngineServices); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap); + } + + /** + * Helper class which executes workflow in a thread + * + */ + static class ProcessThread extends Thread { + + public WorkflowResponse workflowResponse = null; + public String processKey; + public AsynchronousResponse asyncResponse = spy(AsynchronousResponse.class); + public boolean started; + public ProcessEngineServices processEngineServices; + public Map<String,String> variables; + + public ProcessThread(String processKey, ProcessEngineServices processEngineServices, Map<String,String> variables) { + this.processKey = processKey; + this.processEngineServices = processEngineServices; + this.variables = variables; + } + + public void run() { + started = true; + doAnswer(new Answer<Void>() { + public Void answer(InvocationOnMock invocation) { + Response response = (Response) invocation.getArguments()[0]; + workflowResponse = (WorkflowResponse) response.getEntity(); + return null; + } + }).when(asyncResponse).setResponse(any(Response.class)); + executeAsyncFlow(processEngineServices, processKey, asyncResponse, variables); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java new file mode 100644 index 0000000000..5cd59f38dd --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CompleteMsoProcessTest.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Unit test for CompleteMsoProcess.bpmn. + */ +public class CompleteMsoProcessTest extends WorkflowTest { + + private void executeFlow(String inputRequestFile) throws InterruptedException { + mockUpdateRequestDB(200, "Database/DBUpdateResponse.xml"); + + //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); + Map<String, String> variables = new HashMap<String, String>(); + variables.put("CompleteMsoProcessRequest",inputRequestFile); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "CompleteMsoProcess", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) + public void msoCompletionRequestWithNotificationurl_200() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Ignore // BROKEN TEST + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) + public void msoCompletionRequestWithNotificationurl_500() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("500", CMSO_ResponseCode); + Assert.assertFalse((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) + public void msoCompletionRequestWithNoNotificationurl() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNoNotificationurl()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) + public void msoCompletionRequestWithNotificationurlNoRequestId() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNotificationurlNoRequestId()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + @Test + @Deployment(resources = {"subprocess/CompleteMsoProcess.bpmn"}) + public void msoCompletionRequestWithNoNotificationurlNoRequestId() throws Exception { + logStart(); + + //Execute Flow + executeFlow(gMsoCompletionRequestWithNoNotificationurlNoRequestId()); + + //Verify Error + String CMSO_ResponseCode = BPMNUtil.getVariable(processEngineRule, "CompleteMsoProcess", "CMSO_ResponseCode"); + Assert.assertEquals("200", CMSO_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "CompleteMsoProcess", "CMSO_SuccessIndicator")); + logEnd(); + } + + public String gMsoCompletionRequestWithNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://ecomp.openecomp.org.com/mso/workflow/schema/v1\">" + + " <ns:request-information>" + + " <ns:request-id>uCPE1020_STUW105_5002</ns:request-id>" + + " <ns:request-action>Layer3ServiceActivateRequest</ns:request-action>" + + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + + " <ns:source>OMX</ns:source>" + + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>" + + " <ns:order-number>10205000</ns:order-number>" + + " <ns:order-version>1</ns:order-version>" + + " </ns:request-information>" + + " <sdncadapterworkflow:mso-bpel-name>UCPELayer3ServiceActivateV1</sdncadapterworkflow:mso-bpel-name>" + + "</sdncadapterworkflow:MsoCompletionRequest>"; + + return xml; + } + + + + public String gMsoCompletionRequestWithNoNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">" + + " <ns:request-information>" + + " <ns:request-id>uCPE1020_STUW105_5002</ns:request-id>" + + " <ns:request-action>Layer3ServiceActivateRequest</ns:request-action>" + + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + + " <ns:source>OMX</ns:source>" + + " <ns:notification-url></ns:notification-url>" + + " <ns:order-number>10205000</ns:order-number>" + + " <ns:order-version>1</ns:order-version>" + + " </ns:request-information>" + + " <sdncadapterworkflow:mso-bpel-name>UCPELayer3ServiceActivateV1</sdncadapterworkflow:mso-bpel-name>" + + "</sdncadapterworkflow:MsoCompletionRequest>"; + + return xml; + } + + public String gMsoCompletionRequestWithNoNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">" + + " <ns:request-information>" + + " <ns:request-id></ns:request-id>" + + " <ns:request-action>Layer3ServiceActivateRequest</ns:request-action>" + + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + + " <ns:source>OMX</ns:source>" + + " <ns:notification-url></ns:notification-url>" + + " <ns:order-number>10205000</ns:order-number>" + + " <ns:order-version>1</ns:order-version>" + + " </ns:request-information>" + + " <sdncadapterworkflow:mso-bpel-name>UCPELayer3ServiceActivateV1</sdncadapterworkflow:mso-bpel-name>" + + "</sdncadapterworkflow:MsoCompletionRequest>"; + + return xml; + } + + public String gMsoCompletionRequestWithNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:MsoCompletionRequest xmlns:ns=\"http://openecomp.org/mso/request/types/v1\" xmlns:sdncadapterworkflow=\"http://openecomp.org/mso/workflow/schema/v1\">" + + " <ns:request-information>" + + " <ns:request-id></ns:request-id>" + + " <ns:request-action>Layer3ServiceActivateRequest</ns:request-action>" + + " <ns:request-sub-action>COMPLETE</ns:request-sub-action>" + + " <ns:source>OMX</ns:source>" + + " <ns:notification-url>https://t3nap1a1.snt.bst.bls.com:9004/sdncontroller-sdncontroller-inbound-ws-war/sdncontroller-sdncontroller-inbound-ws.wsdl</ns:notification-url>" + + " <ns:order-number>10205000</ns:order-number>" + + " <ns:order-version>1</ns:order-version>" + + " </ns:request-information>" + + " <sdncadapterworkflow:mso-bpel-name>UCPELayer3ServiceActivateV1</sdncadapterworkflow:mso-bpel-name>" + + "</sdncadapterworkflow:MsoCompletionRequest>"; + + return xml; + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupNameTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupNameTest.java new file mode 100644 index 0000000000..5b10b8b89e --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupNameTest.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; + +/** + * Unit test cases for ConfirmVolumeGroupName.bpmn + */ +public class ConfirmVolumeGroupNameTest extends WorkflowTest { + /** + * Sunny day scenario. + * + * @throws Exception + */ + @Test + @Deployment(resources = { + "subprocess/ConfirmVolumeGroupName.bpmn" + }) + public void sunnyDay() throws Exception { + + logStart(); + MockGetVolumeGroupById("MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml"); + + System.out.println("Before starting process"); + + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1"); + variables.put("ConfirmVolumeGroupName_volumeGroupName", "VOLUME_GROUP_ID_1_NAME"); + variables.put("ConfirmVolumeGroupName_aicCloudRegion", "MDTWNJ21"); + System.out.println("after setting variables"); + runtimeService.startProcessInstanceByKey("ConfirmVolumeGroupName", variables); + String response = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponse"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponseCode"); + + assertEquals("200", responseCode); + System.out.println(response); + logEnd(); + } + + /** + * Rainy day scenario - nonexisting volume group id. + * + * @throws Exception + */ + @Test + @Deployment(resources = { + "subprocess/ConfirmVolumeGroupName.bpmn" + }) + public void rainyDayNoVolumeGroupId() throws Exception { + + logStart(); + MockGetVolumeGroupById("MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml"); + + System.out.println("Before starting process"); + + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_THAT_DOES_NOT_EXIST"); + variables.put("ConfirmVolumeGroupName_volumeGroupName", "cee6d136-e378-4678-a024-2cd15f0ee0cg"); + System.out.println("after setting variables"); + runtimeService.startProcessInstanceByKey("ConfirmVolumeGroupName", variables); + String response = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponse"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponseCode"); + + assertEquals("404", responseCode); + System.out.println(response); + + logEnd(); + } + + /** + * Rainy day scenario - volume group name does not match the name in AAI + * + * + * @throws Exception + */ + @Test + @Deployment(resources = { + "subprocess/ConfirmVolumeGroupName.bpmn" + }) + public void rainyDayNameDoesNotMatch() throws Exception { + + logStart(); + MockGetVolumeGroupById("MDTWNJ21", "VOLUME_GROUP_ID_1", "aai-volume-group-id-info.xml"); + + System.out.println("Before starting process"); + + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("ConfirmVolumeGroupName_volumeGroupId", "VOLUME_GROUP_ID_1"); + variables.put("ConfirmVolumeGroupName_volumeGroupName", "BAD_VOLUME_GROUP_NAME"); + System.out.println("after setting variables"); + runtimeService.startProcessInstanceByKey("ConfirmVolumeGroupName", variables); + String response = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponse"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupName", "CVGN_queryVolumeGroupResponseCode"); + + assertEquals("404", responseCode); + System.out.println(response); + + logEnd(); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupTenantTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupTenantTest.java new file mode 100644 index 0000000000..e62742da30 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/ConfirmVolumeGroupTenantTest.java @@ -0,0 +1,91 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVolumeGroupById; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Please describe the ConfirmVolumeGroupTenantTest.java class + * + */ +public class ConfirmVolumeGroupTenantTest extends WorkflowTest { + + @Test + @Deployment(resources = {"subprocess/ConfirmVolumeGroupTenant.bpmn"}) + public void testRemoveLayer3Service_success() throws Exception{ + MockGetVolumeGroupById("MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58", "CRTGVNF_queryAAIResponseVolume.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "ConfirmVolumeGroupTenant", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String actualNameMatch = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "groupNamesMatch"); + String actualIdMatch = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "tenantIdsMatch"); + String actualResponse = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "volumeHeatStackId"); + + assertEquals("Response", "true", actualNameMatch); + assertEquals("Response", "true", actualIdMatch); + assertEquals("Response", "MoG_CinderVolumes_2/19387dc6-060f-446e-b41f-dcfd29c73845", actualResponse); + } + + @Test + @Deployment(resources = {"subprocess/ConfirmVolumeGroupTenant.bpmn"}) + public void testRemoveLayer3Service_idsNotMatch() throws Exception{ + MockGetVolumeGroupById("MDTWNJ21", "a8399879-31b3-4973-be26-0a0cbe776b58", "CRTGVNF_queryAAIResponseVolume_idsNotMatch.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "ConfirmVolumeGroupTenant", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String actualNameMatch = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "groupNamesMatch"); + String actualIdMatch = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "tenantIdsMatch"); + String actualResponse = BPMNUtil.getVariable(processEngineRule, "ConfirmVolumeGroupTenant", "WorkflowException"); + + assertEquals("Response", "true", actualNameMatch); + assertEquals("Response", "false", actualIdMatch); + assertEquals("Response", "WorkflowException[processKey=ConfirmVolumeGroupTenant,errorCode=1,errorMessage=Volume Group a8399879-31b3-4973-be26-0a0cbe776b58 does not belong to your tenant]", actualResponse); + + } + + private void setVariables(Map<String, String> variables) { + variables.put("isDebugLogEnabled", "true"); + variables.put("volumeGroupId","a8399879-31b3-4973-be26-0a0cbe776b58"); + variables.put("tenantId", "7dd5365547234ee8937416c65507d266"); + variables.put("aicCloudRegion", "MDTWNJ21"); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java new file mode 100644 index 0000000000..b41d2d2558 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleTest.java @@ -0,0 +1,277 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.openecomp.mso.bpmn.common.DeleteAAIVfModuleTest.MockAAIGenericVnfSearch; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for CreateAAIVfModule.bpmn. + */ +public class CreateAAIVfModuleTest extends WorkflowTest { + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfSuccess_200() { + + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC22"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + Assert.assertEquals("201", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateVfModuleSuccess_200() { + // create Add-on VF Module for existing Generic VNF + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC21-MMSC::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "CreateAAIVfModule", "CAAIVfMod_createVfModuleResponseCode"); + Assert.assertEquals("201", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC23"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC23-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateDupGenericVnfFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC21"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-MMSC::module-0-0"); + variables.put("vfModuleModelName", "MMSC::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Invalid request for new Generic VNF which already exists")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateDupVfModuleFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC20-MMSC::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC20-MMSC::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("already exists for Generic VNF")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfName", "STMTN5MMSC22"); + variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); + variables.put("vfModuleModelName", "PCRF::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateGenericVnfFailure_1002() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "768073c7-f41f-4822-9323-b75962763d74"); + variables.put("serviceId", "00000000-0000-0000-0000-000000000000"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC22-PCRF::module-1-0"); + variables.put("vfModuleModelName", "PCRF::module-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModule.bpmn" + }) + public void TestCreateVfModuleFailure_5000() { + MockAAIGenericVnfSearch(); + MockAAICreateGenericVnf(); + MockAAIVfModulePUT(true); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("isVidRequest", "false"); + variables.put("vnfId", "a27ce5a9-29c4-4c22-a017-6615ac73c721"); + variables.put("serviceId", "99999999-9999-9999-9999-999999999999"); + variables.put("personaModelId", "973ed047-d251-4fb9-bf1a-65b8949e0a73"); + variables.put("personaModelVersion", "1.0"); + variables.put("vfModuleName", "STMTN5MMSC21-PCRF::module-1-0"); + variables.put("vfModuleModelName", "STMTN5MMSC21-PCRF::model-1-0"); + runtimeService.startProcessInstanceByKey("CreateAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "CreateAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + public static void MockAAICreateGenericVnf(){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) + .withRequestBody(containing("<service-id>00000000-0000-0000-0000-000000000000</service-id>")) + .willReturn(aResponse() + .withStatus(201))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*")) + .withRequestBody(containing("<service-id>99999999-9999-9999-9999-999999999999</service-id>")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + } + + // start of mocks used locally and by other VF Module unit tests + public static void MockAAIVfModulePUT(boolean isCreate){ + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("MMSC")) + .willReturn(aResponse() + .withStatus(isCreate ? 201 : 200))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/.*/vf-modules/vf-module/.*")) + .withRequestBody(containing("PCRF")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(put(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721")) + .willReturn(aResponse() + .withStatus(200))); + } + +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleVolumeGroupTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleVolumeGroupTest.java new file mode 100644 index 0000000000..f1a2d7b4e2 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/CreateAAIVfModuleVolumeGroupTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVfModuleId; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVfModuleIdNoResponse; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for CreateAAIVfModuleVolumeGroup.bpmn. + */ +public class CreateAAIVfModuleVolumeGroupTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModuleVolumeGroup.bpmn" + }) + public void happyPath() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml"); + MockGetGenericVnfByIdWithPriority("skask", "lukewarm", 200, "VfModularity/VfModule-lukewarm.xml", 2); + MockPutVfModuleIdNoResponse("skask", "PCRF", "lukewarm"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest); + invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModuleVolumeGroup.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml"); + MockGetVfModuleId("skask", ".*", "VfModularity/VfModule-supercool.xml", 404); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest); + invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_getVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/CreateAAIVfModuleVolumeGroup.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/CreateAAIVfModuleVolumeGroupRequest.xml"); + MockGetVfModuleId("skask", "lukewarm", "VfModularity/VfModule-lukewarm.xml", 200); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("CreateAAIVfModuleVolumeGroupRequest", updateAAIVfModuleRequest); + invokeSubProcess("CreateAAIVfModuleVolumeGroup", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "CAAIVfModVG_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java new file mode 100644 index 0000000000..0136b675dd --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/DeleteAAIVfModuleTest.java @@ -0,0 +1,643 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit test for DeleteAAIVfModule.bpmn. + */ +public class DeleteAAIVfModuleTest extends WorkflowTest { + private static final String EOL = "\n"; + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteGenericVnfSuccess_200() { + // delete the Base Module and Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c721, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a73 + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest","<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id> <vnf-name>STMTN5MMSC21</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id> <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>"); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteGenericVnfResponseCode"); + Assert.assertEquals("200", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleSuccess_200() { + // delete Add-on Vf Module for existing Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a75 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + String response = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); + String responseCode = BPMNUtil.getVariable(processEngineRule, "DeleteAAIVfModule", "DAAIVfMod_deleteVfModuleResponseCode"); + Assert.assertEquals("200", responseCode); + System.out.println(response); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_5000() { + // query Generic Vnf failure (non-404) with A&AI + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c723, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a71 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c723</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC23</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a71</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestQueryGenericVnfFailure_1002() { + // attempt to delete Vf Module for Generic Vnf that does not exist (A&AI returns 404) + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c722, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a72 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c722</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC22</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a72</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC22-MMSC::module-1-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("Generic VNF Not Found")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteGenericVnfFailure_5000() { + // A&AI failure (non-200) when attempting to delete a Generic Vnf + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c718, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a78 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_5000() { + // A&AI failure (non-200) when attempting to delete a Vf Module + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c719, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a77 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(5000, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("<messageId>SVC3002</messageId>")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_1002_1() { + // failure attempting to delete Base Module when not the last Vf Module + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a74 + String request = + "<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\">" + EOL + + " <request-info>" + EOL + + " <action>DELETE_VF_MODULE</action>" + EOL + + " <source>PORTAL</source>" + EOL + + " </request-info>" + EOL + + " <vnf-inputs>" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL + + " </vnf-inputs>" + EOL + + " <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/>" + EOL + + "</vnf-request>" + EOL; + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest",request); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("is Base Module, not Last Module")); + System.out.println(exception.getErrorMessage()); + } + + @Test + @Deployment(resources = { + "subprocess/DeleteAAIVfModule.bpmn" + }) + public void TestDeleteVfModuleFailure_1002_2() { + // failure attempting to delete a Vf Module that does not exist (A&AI returns 404) + // vnf-id=a27ce5a9-29c4-4c22-a017-6615ac73c720, vf-module-id=973ed047-d251-4fb9-bf1a-65b8949e0a76 + MockAAIGenericVnfSearch(); + MockAAIDeleteGenericVnf(); + MockAAIDeleteVfModule(); + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("isDebugLogEnabled","true"); + variables.put("DeleteAAIVfModuleRequest","<vnf-request xmlns=\"http://openecomp.org/mso/infra/vnf-request/v1\"> <request-info> <action>DELETE_VF_MODULE</action> <source>PORTAL</source> </request-info> <vnf-inputs> <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id> <vnf-name>STMTN5MMSC20</vnf-name> <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id> <vf-module-name>STMTN5MMSC20-MMSC::module-2-0</vf-module-name> </vnf-inputs> <vnf-params xmlns:tns=\"http://openecomp.org/mso/infra/vnf-request/v1\"/> </vnf-request>"); + runtimeService.startProcessInstanceByKey("DeleteAAIVfModule", variables); + WorkflowException exception = BPMNUtil.getRawVariable(processEngineRule, "DeleteAAIVfModule", "WorkflowException"); + Assert.assertEquals(1002, exception.getErrorCode()); + Assert.assertEquals(true, exception.getErrorMessage().contains("does not exist for Generic Vnf Id")); + System.out.println(exception.getErrorMessage()); + } + + // Start of VF Modularization A&AI mocks + + public static void MockAAIGenericVnfSearch(){ + String body; + + // The following stubs are for CreateAAIVfModule and UpdateAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC23&depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC22&depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/768073c7-f41f-4822-9323-b75962763d74[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>1508691</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>1508692</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC21&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>1508691</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>1508692</resource-version>" + EOL + + " </vf-module>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>false</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>1508692</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/[?]vnf-name=STMTN5MMSC20&depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/2f6aee38-1e2a-11e6-82d1-ffc7d9ee8aa4[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + // The following stubs are for DeleteAAIVfModule + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c723[?]depth=1")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c722[?]depth=1")) + .willReturn(aResponse() + .withStatus(404) + .withHeader("Content-Type", "text/xml") + .withBody("Generic VNF Not Found"))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>0000021</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000073</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c720</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC20</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>0000020</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a74</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000074</resource-version>" + EOL + + " </vf-module>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC20-MMSC::module-1-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a75</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>false</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000075</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c719</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC19</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>0000019</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC19-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a76</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000076</resource-version>" + EOL + + " </vf-module>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC19-MMSC::module-1-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a77</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>false</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000077</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c718</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC18</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>0000018</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC18-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a78</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000078</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + + body = + "<generic-vnf xmlns=\"http://com.att.aai.inventory/v7\">" + EOL + + " <vnf-id>a27ce5a9-29c4-4c22-a017-6615ac73c721</vnf-id>" + EOL + + " <vnf-name>STMTN5MMSC21</vnf-name>" + EOL + + " <vnf-type>mmsc-capacity</vnf-type>" + EOL + + " <service-id>SDN-MOBILITY</service-id>" + EOL + + " <equipment-role>vMMSC</equipment-role>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <in-maint>false</in-maint>" + EOL + + " <is-closed-loop-disabled>false</is-closed-loop-disabled>" + EOL + + " <resource-version>0000021</resource-version>" + EOL + + " <vf-modules>" + EOL + + " <vf-module>" + EOL + + " <vf-module-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</vf-module-id>" + EOL + + " <vf-module-name>STMTN5MMSC21-MMSC::module-0-0</vf-module-name>" + EOL + + " <persona-model-id>973ed047-d251-4fb9-bf1a-65b8949e0a73</persona-model-id>" + EOL + + " <persona-model-version>1.0</persona-model-version>" + EOL + + " <is-base-vf-module>true</is-base-vf-module>" + EOL + + " <heat-stack-id>FILLED-IN-BY-MSO</heat-stack-id>" + EOL + + " <orchestration-status>pending-create</orchestration-status>" + EOL + + " <resource-version>0000073</resource-version>" + EOL + + " </vf-module>" + EOL + + " </vf-modules>" + EOL + + " <relationship-list/>" + EOL + + " <l-interfaces/>" + EOL + + " <lag-interfaces/>" + EOL + + "</generic-vnf>" + EOL; + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(body))); + } + public static void MockAAIDeleteGenericVnf(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/[?]resource-version=0000021")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/[?]resource-version=0000018")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + } + + public static void MockAAIDeleteVfModule(){ + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c721/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a73/[?]resource-version=0000073")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c720/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a75/[?]resource-version=0000075")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c718/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a78/[?]resource-version=0000078")) + .willReturn(aResponse() + .withStatus(200))); + stubFor(delete(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/a27ce5a9-29c4-4c22-a017-6615ac73c719/vf-modules/vf-module/973ed047-d251-4fb9-bf1a-65b8949e0a77/[?]resource-version=0000077")) + .willReturn(aResponse() + .withStatus(500) + .withHeader("Content-Type", "text/xml") + .withBodyFile("aaiFault.xml"))); + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))); + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java new file mode 100644 index 0000000000..77320751ee --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/FalloutHandlerTest.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Unit test for FalloutHandler.bpmn. + */ +public class FalloutHandlerTest extends WorkflowTest { + private void setupMocks() { + stubFor(post(urlEqualTo("/dbadapters/RequestsDbAdapter")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody("<DbTag>Notified</DbTag>"))); + } + + private void executeFlow(String inputRequestFile) throws InterruptedException { + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + + //String changeFeatureActivateRequest = FileUtil.readResourceFile("__files/SDN-ETHERNET-INTERNET/ChangeFeatureActivateV1/" + inputRequestFile); + Map<String, String> variables = new HashMap<String, String>(); + variables.put("FalloutHandlerRequest",inputRequestFile); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "FalloutHandler", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + System.out.println("ENDED TEST: " + method); + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNotificationurl_200() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNotificationurl()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns7=\"http://org.openecomp/mso/request/types/v1\">" + + " <ns7:request-information>" + + " <ns7:request-id>uCPE1020_STUW105_5002</ns7:request-id>" + + " <ns7:request-action>Layer3ServiceActivateRequest</ns7:request-action>" + + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>" + + " <ns7:source>OMX</ns7:source>" + + " <ns7:notification-url>http://localhost:28090/CCD/StatusNotification</ns7:notification-url>" + + " <ns7:order-number>10205000</ns7:order-number>" + + " <ns7:order-version>1</ns7:order-version>" + + " </ns7:request-information>" + + " <sdncadapterworkflow:WorkflowException>" + + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>" + + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>" + + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>" + + " </sdncadapterworkflow:WorkflowException>" + + "</sdncadapterworkflow:FalloutHandlerRequest>"; + + return xml; + + } + + + + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNoNotificationurl() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNoNotificationurl()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNoNotificationurl() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns7=\"http://org.openecomp/mso/request/types/v1\">" + + " <ns7:request-information>" + + " <ns7:request-id>uCPE1020_STUW105_5002</ns7:request-id>" + + " <ns7:request-action>Layer3ServiceActivateRequest</ns7:request-action>" + + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>" + + " <ns7:source>OMX</ns7:source>" + + " <ns7:notification-url></ns7:notification-url>" + + " <ns7:order-number>10205000</ns7:order-number>" + + " <ns7:order-version>1</ns7:order-version>" + + " </ns7:request-information>" + + " <sdncadapterworkflow:WorkflowException>" + + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>" + + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>" + + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>" + + " </sdncadapterworkflow:WorkflowException>" + + "</sdncadapterworkflow:FalloutHandlerRequest>"; + + return xml; + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNotificationurlNoRequestId() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNotificationurlNoRequestId()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns7=\"http://org.openecomp/mso/request/types/v1\">" + + " <ns7:request-information>" + + " <ns7:request-id></ns7:request-id>" + + " <ns7:request-action>Layer3ServiceActivateRequest</ns7:request-action>" + + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>" + + " <ns7:source>OMX</ns7:source>" + + " <ns7:notification-url>www.att.com</ns7:notification-url>" + + " <ns7:order-number>10205000</ns7:order-number>" + + " <ns7:order-version>1</ns7:order-version>" + + " </ns7:request-information>" + + " <sdncadapterworkflow:WorkflowException>" + + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>" + + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>" + + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>" + + " </sdncadapterworkflow:WorkflowException>" + + "</sdncadapterworkflow:FalloutHandlerRequest>"; + + return xml; + } + + @Test + @Deployment(resources = {"subprocess/FalloutHandler.bpmn"}) + public void msoFalloutHandlerWithNoNotificationurlNoRequestId() throws Exception{ + String method = getClass().getSimpleName() + "." + new Object() { + }.getClass().getEnclosingMethod().getName(); + System.out.println("STARTED TEST: " + method); + //Setup Mocks + setupMocks(); + //Execute Flow + executeFlow(gMsoFalloutHandlerWithNoNotificationurlNoRequestId()); + //Verify Error + String FH_ResponseCode = BPMNUtil.getVariable(processEngineRule, "FalloutHandler", "FH_ResponseCode"); + Assert.assertEquals("200", FH_ResponseCode); + Assert.assertTrue((boolean) BPMNUtil.getRawVariable(processEngineRule, "FalloutHandler", "FH_SuccessIndicator")); + } + + public String gMsoFalloutHandlerWithNoNotificationurlNoRequestId() { + //Generated the below XML from ActiveVOS moduler ... Using the generate sample XML feature in ActiveVOS + String xml = "" + + "<sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns7=\"http://org.openecomp/mso/request/types/v1\">" + + " <ns7:request-information>" + + " <ns7:request-id></ns7:request-id>" + + " <ns7:request-action>Layer3ServiceActivateRequest</ns7:request-action>" + + " <ns7:request-sub-action>CANCEL</ns7:request-sub-action>" + + " <ns7:source>OMX</ns7:source>" + + " <ns7:notification-url></ns7:notification-url>" + + " <ns7:order-number>10205000</ns7:order-number>" + + " <ns7:order-version>1</ns7:order-version>" + + " </ns7:request-information>" + + " <sdncadapterworkflow:WorkflowException>" + + " <sdncadapterworkflow:ErrorMessage>Some Error Message - Fallout Handler</sdncadapterworkflow:ErrorMessage>" + + " <sdncadapterworkflow:ErrorCode>Some Error Code - Fallout Handler</sdncadapterworkflow:ErrorCode>" + + " <sdncadapterworkflow:SourceSystemErrorCode>Some Source System Error Code- Fallout Handler</sdncadapterworkflow:SourceSystemErrorCode>" + + " </sdncadapterworkflow:WorkflowException>" + + "</sdncadapterworkflow:FalloutHandlerRequest>"; + + return xml; + } + +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteServiceTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteServiceTest.java new file mode 100644 index 0000000000..e83a644914 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteServiceTest.java @@ -0,0 +1,279 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteServiceInstance; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteServiceInstance_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance_500; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceSubscription; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + + + +/** + * Please describe the GenericDeleteServiceTest.java class + * + */ +public class GenericDeleteServiceTest extends WorkflowTest { + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_serviceInstance() throws Exception{ + MockDeleteServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "1234"); + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234"); + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + assertEquals("true", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("true", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + } + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_serviceSubscription() throws Exception{ + + MockDeleteServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234", 204); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, "", "1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("true", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("true", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_instanceNoResourceVersion() throws Exception { + MockGetServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceSubscription.xml"); + MockDeleteServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "1234"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("true", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("false", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_subscriptionNoResourceVersion() throws Exception{ + MockGetServiceSubscription("1604-MVM-26", "SDN-ETHERNET-INTERNET", "GenericFlows/getServiceSubscription.xml"); + MockDeleteServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234", 204); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, null, "1604-MVM-26", "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("true", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("false", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_get404Response() throws Exception{ + + MockGetServiceInstance_404("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("false", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("false", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_subscriptionGetEmpty200() throws Exception{ + MockGetServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234", 200); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, "", "1604-MVM-26", "SDN-ETHERNET-INTERNET", ""); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("false", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("false", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_success_delete404Response() throws Exception{ + + MockGetServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "GENDSI_getServiceInstanceResponse.xml"); + MockDeleteServiceInstance_404("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "1234"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", "1234"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + assertEquals("false", foundIndicator); + assertEquals("true", successIndicator); + assertEquals("true", resourceVersionProvidedFlag); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_error_invalidVariables() throws Exception{ + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, "SDN-ETHERNET-INTERNET", "1234"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + String expectedResponse = "WorkflowException[processKey=GenericDeleteService,errorCode=500,errorMessage=Incoming Required Variable is Missing or Null!]"; + + assertEquals("false", foundIndicator); + assertEquals("false", successIndicator); + assertEquals("true", resourceVersionProvidedFlag); + assertEquals(expectedResponse, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteService.bpmn"}) + public void testGenericDeleteService_error_getBadAAIResponse() throws Exception{ + + MockGetServiceInstance_500("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", "aaiFault.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_SuccessIndicator"); + String foundIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_FoundIndicator"); + String resourceVersionProvidedFlag = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "GENDS_resourceVersionProvidedFlag"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteService", "WorkflowException"); + + String expectedResponse = "WorkflowException[processKey=GenericDeleteService,errorCode=500,errorMessage=<requestError><serviceException><messageId>SVC3002</messageId><text>Error writing output performing %1 on %2 (msg=%3) (ec=%4)</text><variables><variable>PUTcustomer</variable><variable>SubName01</variable><variable>Unexpected error reading/updating database:Adding this property for key [service-instance-id] and value [USSTU2CFCNC0101UJZZ01] violates a uniqueness constraint [service-instance-id]</variable><variable>ERR.5.4.5105</variable></variables></serviceException></requestError>" + "\n" + + "]"; + + assertEquals("false", foundIndicator); + assertEquals("false", successIndicator); + assertEquals("false", resourceVersionProvidedFlag); + assertEquals(expectedResponse, workflowException); + } + + + private void setVariablesInstance(Map<String, String> variables, String siId, String globalCustId, String serviceType, String reVersion) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENDS_serviceInstanceId", siId); + variables.put("GENDS_globalCustomerId",globalCustId); + variables.put("GENDS_serviceType", serviceType); + variables.put("GENDS_resourceVersion", reVersion); + variables.put("GENDS_type", "service-instance"); + } + + private void setVariablesSubscription(Map<String, String> variables, String siId, String globalCustId, String serviceType, String reVersion) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENDS_serviceInstanceId", siId); + variables.put("GENDS_globalCustomerId",globalCustId); + variables.put("GENDS_serviceType", serviceType); + variables.put("GENDS_resourceVersion", reVersion); + variables.put("GENDS_type", "service-subscription"); + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteVnfTest.java new file mode 100644 index 0000000000..dd3fd73afe --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericDeleteVnfTest.java @@ -0,0 +1,221 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteGenericVnf_500; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockDeleteVce; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVceById; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Please describe the GenericDeleteVnfTest.java class + * + */ +public class GenericDeleteVnfTest extends WorkflowTest { + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_genericVnf() throws Exception{ + MockDeleteGenericVnf("testVnfId123", "testReVer123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "true", "true", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_vce() throws Exception{ + MockDeleteVce("testVnfId123", "testReVer123", 204); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "vce", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "true", "true", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_genericVnfNoResourceVersion() throws Exception{ + + MockGetGenericVnfById("/testVnfId123", "GenericFlows/getGenericVnfByNameResponse.xml", 200); + MockDeleteGenericVnf("testVnfId123", "testReVer123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", ""); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "true", "false", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_vceNoResourceVersion() throws Exception{ + MockDeleteVce("testVnfId123", "testReVer123", 204); + MockGetVceById("testVnfId123", "GenericFlows/getVceResponse.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "vce", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "true", "false", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_genericVnf404() throws Exception{ + MockDeleteGenericVnf("testVnfId123", "testReVer123", 404); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "false", "true", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_vce404() throws Exception{ + MockDeleteVce("testVnfId123", "testReVer123", 404); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "vce", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "false", "true", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_success_genericVnfNoResourceVersion404() throws Exception{ + MockGetGenericVnfById_404("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", ""); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("true", "false", "false", null); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_error_missingVariables() throws Exception{ + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("false", "false", "true", "WorkflowException[processKey=GenericDeleteVnf,errorCode=500,errorMessage=Incoming Required Variable is Missing or Null!]"); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_error_genericVnf500() throws Exception{ + + MockDeleteGenericVnf_500("testVnfId123", "testReVer123"); + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("false", "false", "true", "WorkflowException[processKey=GenericDeleteVnf,errorCode=500,errorMessage=Received a bad response from AAI]"); + + } + + @Test + @Deployment(resources = {"subprocess/GenericDeleteVnf.bpmn"}) + public void testGenericDeleteVnf_error_genericVnf412() throws Exception{ + MockDeleteGenericVnf("testVnfId123", "testReVer123", 412); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "generic-vnf", "testReVer123"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericDeleteVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + assertVariables("false", "false", "true", "WorkflowException[processKey=GenericDeleteVnf,errorCode=412,errorMessage=Delete Vnf Received a resource-version Mismatch Error Response from AAI]"); + + } + + private void assertVariables(String exSuccessIndicator, String exFound, String exRVProvided, String exWorkflowException) { + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericDeleteVnf", "GENDV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericDeleteVnf", "GENDV_FoundIndicator"); + String rvProvided = BPMNUtil.getVariable(processEngineRule, "GenericDeleteVnf", "GENDV_resourceVersionProvided"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericDeleteVnf", "WorkflowException"); + + assertEquals(exSuccessIndicator, successIndicator); + assertEquals(exFound, found); + assertEquals(exRVProvided, rvProvided); + assertEquals(exWorkflowException, workflowException); + } + + private void setVariables(Map<String, String> variables, String vnfId, String type, String resourceVer) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENDV_vnfId", vnfId); + variables.put("GENDV_type", type); + variables.put("GENDV_resourceVersion", resourceVer); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java new file mode 100644 index 0000000000..2af42db574 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java @@ -0,0 +1,505 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceInstance_500; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetServiceSubscription; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceById_500; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceByName; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceByName_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockNodeQueryServiceInstanceByName_500; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + + +/** + * Unit Test for the GenericGetService Sub Flow + */ +public class GenericGetServiceTest extends WorkflowTest { + + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstance() throws Exception{ + MockGetServiceInstance("SDN-ETHERNET-INTERNET", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml"); + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, "SDN-ETHERNET-INTERNET", "123456789"); + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertNotNull(response); + assertEquals(null, workflowException); + } + + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceSubscription() throws Exception{ + + MockGetServiceSubscription("1604-MVM-26", "SDN-ETHERNET-INTERNET", "GenericFlows/getServiceSubscription.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, "", null , "1604-MVM-26", "SDN-ETHERNET-INTERNET"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertNotNull(response); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstance_byName() throws Exception{ + + MockNodeQueryServiceInstanceByName("1604-MVM-26", "GenericFlows/getSIUrlByName.xml"); + MockGetServiceInstance("SDN-ETHERNET-INTERNET", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, null, "1604-MVM-26", null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("true", obtainUrl); + assertEquals("true", byName); + assertNotNull(response); + assertEquals("200", siUrlResponseCode); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstance_byId() throws Exception{ + + MockNodeQueryServiceInstanceById("MIS%2F1604%2F0026%2FSW_INTERNET", "GenericFlows/getSIUrlById.xml"); + MockGetServiceInstance("SDN-ETHERNET-INTERNET", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("true", obtainUrl); + assertEquals("false", byName); + assertNotNull(response); + assertEquals("200", siUrlResponseCode); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstance_404Response() throws Exception{ + + MockGetServiceInstance_404("SDN-ETHERNET-INTERNET", "123456789", "MIS%2F1604%2F0026%2FSW_INTERNET"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, "SDN-ETHERNET-INTERNET", "123456789"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceSubscription404() throws Exception{ + MockGetServiceSubscription("1604-MVM-26", "SDN-ETHERNET-INTERNET", 404); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, "", "", "SDN-ETHERNET-INTERNET", "1604-MVM-26"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertNotNull(response); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstanceByName404() throws Exception{ + + MockNodeQueryServiceInstanceByName_404("1604-MVM-26"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "", "1604-MVM-26", null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("true", byName); + assertEquals("404", siUrlResponseCode); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstanceById404() throws Exception{ + + MockNodeQueryServiceInstanceById_404("MIS%2F1604%2F0026%2FSW_INTERNET"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("false", byName); + assertEquals("404", siUrlResponseCode); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstanceEmptyResponse() throws Exception{ + + MockGetServiceInstance("1604-MVM-26", "SDN-ETHERNET-INTERNET", "MIS%252F1604%252F0026%252FSW_INTERNET", " "); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, "SDN-ETHERNET-INTERNET", "123456789"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstanceByNameEmpty() throws Exception{ + MockNodeQueryServiceInstanceByName("1604-MVM-26", ""); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "", "1604-MVM-26", null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("true", byName); + assertEquals("200", siUrlResponseCode); + assertEquals(null, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceInstanceByIdEmpty() throws Exception{ + + MockNodeQueryServiceInstanceById("MIS[%]2F1604[%]2F0026[%]2FSW_INTERNET", ""); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + assertEquals("true", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("false", byName); + assertEquals("200", siUrlResponseCode); + assertEquals(null, workflowException); + } + + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_error_serviceInstanceInvalidVariables() throws Exception{ + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, null, null, "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetService,errorCode=500,errorMessage=Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.]"; + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertEquals(expectedWorkflowException, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_success_serviceSubscriptionInvalidVariables() throws Exception{ + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesSubscription(variables, "", "", "SDN-ETHERNET-INTERNET", null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetService,errorCode=500,errorMessage=Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.]"; + + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertEquals(expectedWorkflowException, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_error_serviceInstance_getSIBadResponse() throws Exception{ + + MockGetServiceInstance_500("SDN-ETHERNET-INTERNET", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", "1604-MVM-26", "SDN-ETHERNET-INTERNET", "123456789"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetService,errorCode=500,errorMessage=Received a bad response from AAI]"; + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("false", obtainUrl); + assertEquals("false", byName); + assertEquals(expectedWorkflowException, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_error_serviceInstance_getUrlByIdBadResponse() throws Exception{ + + MockNodeQueryServiceInstanceById_500("MIS%2F1604%2F0026%2FSW_INTERNET"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, "MIS%2F1604%2F0026%2FSW_INTERNET", null, null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetService,errorCode=500,errorMessage=Received a bad response from AAI]"; + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("false", byName); + assertEquals("500", siUrlResponseCode); + assertEquals(expectedWorkflowException, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericGetService.bpmn"}) + public void testGenericGetService_error_serviceInstance_getUrlByNameBadResponse() throws Exception{ + + MockNodeQueryServiceInstanceByName_500("1604-MVM-26"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariablesInstance(variables, null, "1604-MVM-26", null, null); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException"); + String obtainUrl = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrl"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainServiceInstanceUrlByName"); + String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetService,errorCode=500,errorMessage=Received a bad response from AAI]"; + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("true", obtainUrl); + assertEquals("true", byName); + assertEquals("500", siUrlResponseCode); + assertEquals(expectedWorkflowException, workflowException); + } + + + private void setVariablesInstance(Map<String, String> variables, String siId, String siName, String globalCustId, String serviceType) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENGS_serviceInstanceId", siId); + variables.put("GENGS_serviceInstanceName", siName); + variables.put("GENGS_globalCustomerId",globalCustId); + variables.put("GENGS_serviceType", serviceType); + variables.put("GENGS_type", "service-instance"); + } + + private void setVariablesSubscription(Map<String, String> variables, String siId, String siName, String globalCustId, String serviceType) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENGS_serviceInstanceId", siId); + variables.put("GENGS_serviceInstanceName", siName); + variables.put("GENGS_globalCustomerId",globalCustId); + variables.put("GENGS_serviceType", serviceType); + variables.put("GENGS_type", "service-subscription"); + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetVnfTest.java new file mode 100644 index 0000000000..80105bbb99 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetVnfTest.java @@ -0,0 +1,191 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_500; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByNameWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVceByNameWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetVceById; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Please describe the GenericGetVnfTest.java class + * + */ +public class GenericGetVnfTest extends WorkflowTest { + + @Test + @Deployment(resources = {"subprocess/GenericGetVnf.bpmn"}) + public void testGenericGetVnf_success_genericVnf() throws Exception{ + MockGetGenericVnfByIdWithDepth("testVnfId123", 1, "GenericFlows/getGenericVnfByNameResponse.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "testVnfName123", "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_FoundIndicator"); + String vnf = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_vnf"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_getVnfByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("false", byName); + assertNotNull(response); + assertNotNull(vnf); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericGetVnf.bpmn"}) + public void testGenericGetVnf_success_vce() throws Exception{ + MockGetVceById("testVnfId123[?]depth=1", "GenericFlows/getVceResponse.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "testVnfName123", "vce"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_FoundIndicator"); + String vnf = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_vnf"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_getVnfByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("false", byName); + assertNotNull(response); + assertNotNull(vnf); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericGetVnf.bpmn"}) + public void testGenericGetVnf_success_genericVnfByName() throws Exception{ + MockGetGenericVnfByNameWithDepth("testVnfName123", 1, "GenericFlows/getGenericVnfResponse.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "", "testVnfName123", "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_FoundIndicator"); + String vnf = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_vnf"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_getVnfByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("true", byName); + assertNotNull(response); + assertNotNull(vnf); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericGetVnf.bpmn"}) + public void testGenericGetVnf_success_vceByName() throws Exception{ + MockGetGenericVceByNameWithDepth("testVnfName123", 1, "GenericFlows/getVceByNameResponse.xml"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, null, "testVnfName123", "vce"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_FoundIndicator"); + String vnf = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_vnf"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_getVnfByName"); + String response = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowResponse"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals("true", found); + assertEquals("true", byName); + assertNotNull(response); + assertNotNull(vnf); + assertEquals(null, workflowException); + + } + + @Test + @Ignore // BROKEN TEST (previously ignored) + @Deployment(resources = {"subprocess/GenericGetVnf.bpmn"}) + public void testGenericGetVnf_error_genericVnf500() throws Exception{ + + MockGetGenericVnfById_500("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", "testVnfName123", "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_SuccessIndicator"); + String found = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_FoundIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "WorkflowException"); + String byName = BPMNUtil.getVariable(processEngineRule, "GenericGetVnf", "GENGV_getVnfByName"); + + String expectedWorkflowException = "WorkflowException[processKey=GenericGetVnf,errorCode=500,errorMessage=Incoming VnfId and VnfName are null. VnfId or VnfName is required!]"; + + assertEquals("false", successIndicator); + assertEquals("false", found); + assertEquals("false", byName); + + assertEquals(expectedWorkflowException, workflowException); + } + + private void setVariables(Map<String, String> variables, String vnfId, String vnfName, String type) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENGV_vnfId", vnfId); + variables.put("GENGV_vnfName",vnfName); + variables.put("GENGV_type", type); + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericPutVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericPutVnfTest.java new file mode 100644 index 0000000000..248cb978dc --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericPutVnfTest.java @@ -0,0 +1,182 @@ +/* + * © 2014 AT&T Intellectual Property. All rights reserved. Used under license from AT&T Intellectual Property. + */ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.openecomp.mso.bpmn.common.BPMNUtil.executeWorkFlow; +import static org.openecomp.mso.bpmn.common.BPMNUtil.waitForWorkflowToFinish; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutVce; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +/** + * Please describe the GenericPutVnf.java class + * + */ +public class GenericPutVnfTest extends WorkflowTest { + + private String genericVnfPayload = "<generic-vnf><vnf-id>testId</vnf-id></generic-vnf>"; + private String vcePayload = "<vce><vnf-id>testId</vnf-id></vce>"; + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_success_genericVnf() throws Exception{ + + MockPutGenericVnf("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", genericVnfPayload, "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_success_vce() throws Exception{ + + MockPutVce("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", vcePayload, "vce"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + assertEquals("true", successIndicator); + assertEquals(null, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_error_missingType() throws Exception{ + + MockPutGenericVnf("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", genericVnfPayload, ""); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + String expectedWFEX = "WorkflowException[processKey=GenericPutVnf,errorCode=500,errorMessage=Incoming Vnf Payload and/or Type is null. These Variables are required!]"; + + assertEquals("false", successIndicator); + assertEquals(expectedWFEX, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_error_missingPayload() throws Exception{ + + MockPutGenericVnf("testVnfId123"); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", genericVnfPayload, ""); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + String expectedWFEX = "WorkflowException[processKey=GenericPutVnf,errorCode=500,errorMessage=Incoming Vnf Payload and/or Type is null. These Variables are required!]"; + + assertEquals("false", successIndicator); + assertEquals(expectedWFEX, workflowException); + + } + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_error_404() throws Exception{ + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", genericVnfPayload, "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + String expectedWFEX = "WorkflowException[processKey=GenericPutVnf,errorCode=404,errorMessage=Received a bad response from AAI]"; + + assertEquals("false", successIndicator); + assertEquals(expectedWFEX, workflowException); + } + + @Test + @Deployment(resources = {"subprocess/GenericPutVnf.bpmn"}) + public void testGenericPutVnf_error_400() throws Exception{ + + MockPutGenericVnf("/testVnfId123", 400); + + Map<String, String> variables = new HashMap<String, String>(); + setVariables(variables, "testVnfId123", genericVnfPayload, "generic-vnf"); + + WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericPutVnf", variables); + waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID()); + + String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "GENPV_SuccessIndicator"); + String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericPutVnf", "WorkflowException"); + + String expectedWFEX = "WorkflowException[processKey=GenericPutVnf,errorCode=400,errorMessage=Received a bad response from AAI]"; + + assertEquals("false", successIndicator); + assertEquals(expectedWFEX, workflowException); + + + } + + private void setVariables(Map<String, String> variables, String vnfId, String payload, String type) { + variables.put("isDebugLogEnabled", "true"); + variables.put("GENPV_vnfId", vnfId); + variables.put("GENPV_vnfPayload",payload); + variables.put("GENPV_type", type); + } + + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java new file mode 100644 index 0000000000..cb5f722a42 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/PrepareUpdateAAIVfModuleTest.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for PrepareUpdateAAIVfModule.bpmn. + */ +public class PrepareUpdateAAIVfModuleTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void happyPath() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + String heatStackId = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_heatStackId"); + System.out.println("Ouput heat-stack-id:" + heatStackId); + Assert.assertEquals("slowburn", heatStackId); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById_404("skask[?]depth=1"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_getVnfResponseCode"); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + + logEnd(); + } + + /** + * Test the case where the validation of the VF Module fails. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void failValidation1() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "lukewarm"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: Orchestration")); + + logEnd(); + } + + /** + * Test the case where the validation of the VF Module fails. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void failValidation2() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml").replaceFirst("supercool", "notsocool"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + Assert.assertTrue(workflowException.getErrorMessage().startsWith("VF Module validation error: VF Module")); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but the subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/PrepareUpdateAAIVfModule.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String prepareUpdateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/PrepareUpdateAAIVfModuleRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("PrepareUpdateAAIVfModuleRequest", prepareUpdateAAIVfModuleRequest); + invokeSubProcess("PrepareUpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "PUAAIVfMod_updateVfModuleResponseCode"); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + Assert.assertNotNull(workflowException); + System.out.println("Subflow WorkflowException error message: " + workflowException.getErrorMessage()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterCallbackRule.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterCallbackRule.java new file mode 100644 index 0000000000..f3c3b84d18 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterCallbackRule.java @@ -0,0 +1,64 @@ +package org.openecomp.mso.bpmn.common; + +import javax.xml.ws.Endpoint; + +import org.camunda.bpm.engine.ProcessEngineServices; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.Statement; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; + +/** + * A JUnit rule that starts the SDNC Adapter Callback Service before + * every test, and tears it down after every test. Example: + * <pre> + * @Rule + * public final SDNCAdapterCallbackRule sdncAdapterCallbackRule = + * new SDNCAdapterCallbackRule(processEngineRule); + * </pre> + */ +public class SDNCAdapterCallbackRule implements TestRule { + public static final String DEFAULT_ENDPOINT_URL = + "http://localhost:28080/mso/SDNCAdapterCallbackService"; + + private final ProcessEngineServices processEngineServices; + private final String endpointUrl; + + public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices) { + this(processEngineServices, DEFAULT_ENDPOINT_URL); + } + + public SDNCAdapterCallbackRule(ProcessEngineServices processEngineServices, + String endpointUrl) { + this.processEngineServices = processEngineServices; + this.endpointUrl = endpointUrl; + } + + @Override + public Statement apply(final Statement baseStmt, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + Endpoint endpoint = null; + + try { + SDNCAdapterCallbackServiceImpl sdncCallbackService = new SDNCAdapterCallbackServiceImpl(); + sdncCallbackService.setProcessEngineServices4junit(processEngineServices); + + System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true"); + System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true"); + + System.out.println("Publishing Endpoint - " + endpointUrl); + endpoint = Endpoint.publish(endpointUrl, sdncCallbackService); + + baseStmt.evaluate(); + } finally { + if (endpoint != null) { + System.out.println("Stopping Endpoint - " + endpointUrl); + endpoint.stop(); + } + } + } + }; + } +}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java new file mode 100644 index 0000000000..b0e1dc9afc --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/SDNCAdapterV1Test.java @@ -0,0 +1,389 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.openecomp.mso.bpmn.mock.StubResponseDatabase.mockUpdateRequestDB; +import static org.openecomp.mso.bpmn.mock.StubResponseSDNCAdapter.mockSDNCAdapter; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.MismatchingMessageCorrelationException; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl.SDNCAdapterExceptionResponse; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit test cases for SDNCAdapterV1.bpmn + */ +public class SDNCAdapterV1Test extends WorkflowTest { + + private String sdncAdapterWorkflowRequest; + private String sdncAdapterWorkflowRequestAct; + private String sdncAdapterCallbackRequestData; + private String sdncAdapterCallbackRequestDataNonfinal; + + public SDNCAdapterV1Test() throws IOException { + sdncAdapterWorkflowRequest = FileUtil.readResourceFile("sdncadapterworkflowrequest.xml"); + sdncAdapterWorkflowRequestAct = FileUtil.readResourceFile("sdncadapterworkflowrequest-act.xml"); + sdncAdapterCallbackRequestData = FileUtil.readResourceFile("sdncadaptercallbackrequestdata.text"); + sdncAdapterCallbackRequestDataNonfinal = FileUtil.readResourceFile("sdncadaptercallbackrequestdata-nonfinal.text"); + } + + /** + * End-to-End flow - Unit test for SDNCAdapterV1.bpmn + * - String input & String response + */ + + private WorkflowResponse invokeFlow(String workflowRequest) { + + Map<String, Object>valueMap = new HashMap<String, Object>(); + valueMap.put("value", workflowRequest); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("sdncAdapterWorkflowRequest", valueMap); + + Map<String, Object> valueMap2 = new HashMap<String, Object>(); + valueMap2.put("value", "true"); + variables.put("isDebugLogEnabled", valueMap2); + + VariableMapImpl varMap = new VariableMapImpl(); + varMap.put("variables", variables); + + //System.out.println("Invoking the flow"); + + WorkflowResource workflowResource = new WorkflowResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + Response response = workflowResource.startProcessInstanceByKey("sdncAdapter", varMap); + WorkflowResponse workflowResponse = (WorkflowResponse) response.getEntity(); + + //String pid = workflowResponse.getProcessInstanceID(); + //System.out.println("Back from executing process instance with pid=" + pid); + return workflowResponse; + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void sunnyDay() throws InterruptedException { + + mockSDNCAdapter(200); + + //System.out.println("SDNCAdapter sunny day flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceFinished(pid); + + //System.out.println("SDNCAdapter sunny day flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void nonFinalWithTimeout() throws InterruptedException { + + mockSDNCAdapter(200); + mockUpdateRequestDB(200, "Database/DBAdapter.xml"); + + //System.out.println("SDNCAdapter interim status processing flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceNotFinished(pid); + + checkForTimeout(pid); + + assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); + + + //System.out.println("SDNCAdapter interim status processing flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void nonFinalThenFinal() throws InterruptedException { + + mockSDNCAdapter(200); + mockUpdateRequestDB(200, "Database/DBAdapter.xml"); + + //System.out.println("SDNCAdapter non-final then final processing flow Started!"); + + // Start the flow + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequestAct); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + assertProcessInstanceNotFinished(pid); + + // Inject a "non-final" SDNC Adapter asynchronous callback message + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestDataNonfinal); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceNotFinished(pid); + assertEquals(true, (Boolean) (getVariable(pid, "continueListening"))); + + // Inject a "final" SDNC Adapter asynchronous callback message + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertFalse(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertProcessInstanceFinished(pid); + assertEquals(false, (Boolean) (getVariable(pid, "continueListening"))); + + //System.out.println("SDNCAdapter non-final then final processing flow Completed!"); + } + + + + private void waitForExecutionToStart(String processDefintion, int count) throws InterruptedException { + //System.out.println(processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count()); + while (processEngineRule.getRuntimeService().createExecutionQuery().processDefinitionKey(processDefintion).count() != count) { + Thread.sleep(200); + } + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void badCorrelationIdTest() throws InterruptedException { + + mockSDNCAdapter(200); + + //System.out.println("SDNCAdapter bad RequestId test Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + assertProcessInstanceNotFinished(pid); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String badRequestId = "This is not the RequestId that was used"; + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(badRequestId); + callbackHeader.setResponseCode("200"); + callbackHeader.setResponseMessage("OK"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(sdncAdapterCallbackRequestData); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertTrue(sdncAdapterResponse instanceof SDNCAdapterExceptionResponse); + assertTrue(((SDNCAdapterExceptionResponse) sdncAdapterResponse).getException() instanceof MismatchingMessageCorrelationException); + assertProcessInstanceNotFinished(pid); + + //System.out.println("SDNCAdapter bad RequestId test Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void badSynchronousResponse() throws IOException, InterruptedException { + + mockSDNCAdapter(404); + + //System.out.println("SDNCAdapter bad synchronous response flow Started!"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + while (thread.isAlive()) { + Thread.sleep(200); + } + WorkflowResponse response = thread.workflowResponse; + Assert.assertNotNull(response); + Assert.assertEquals("404 error", response.getMessageCode(),7000); +// assertProcessInstanceFinished(response.getProcessInstanceID()); + //System.out.println("SDNCAdapter bad synchronous response flow Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void sdncNotFound() throws IOException, InterruptedException { + mockSDNCAdapter(200); + mockSDNCAdapter("/sdncAdapterMock/404", 400, "sdncCallbackErrorResponse.xml"); + + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + String pid = getPid(); + + //System.out.println("Injecting SDNC Adapter asynchronous callback message to continue processing"); + String generatedRequestId = (String) processEngineRule.getRuntimeService().getVariable(pid, "SDNCA_requestId"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(generatedRequestId); + callbackHeader.setResponseCode("404"); + callbackHeader.setResponseMessage("Error processing request to SDNC. Not Found. https://sdncodl.it.us.aic.cip.att.com:8443/restconf/config/L3SDN-API:services/layer3-service-list/AS%2FVLXM%2F000199%2F%2FSB_INTERNET. SDNC Returned-[error-type:application, error-tag:data-missing, error-message:Request could not be completed because the relevant data model content does not exist.]"); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + //System.out.println("Back from executing process again"); + + assertProcessInstanceFinished(pid); + assertNotNull(sdncAdapterResponse); + //TODO query history to see SDNCA_ResponseCode, SDNCA_ErrorResponse + //System.out.println("SDNCAdapter SDNC Notfound test Completed!"); + } + + @Test + @Deployment(resources = {"subprocess/SDNCAdapterV1.bpmn"}) + public void asynchronousMessageTimeout() throws IOException, InterruptedException { + mockSDNCAdapter(200); + //System.out.println("SDNCAdapter asynchronous message timeout flow Started!"); + ProcessExecutionThread thread = new ProcessExecutionThread(sdncAdapterWorkflowRequest); + thread.start(); + waitForExecutionToStart("sdncAdapter", 3); + checkForTimeout(getPid()); + } + + private void checkForTimeout(String pid) throws InterruptedException { + + assertProcessInstanceNotFinished(pid); + + ProcessEngineConfigurationImpl processEngineConfiguration = + (ProcessEngineConfigurationImpl) processEngineRule.getProcessEngine().getProcessEngineConfiguration(); + assertTrue(processEngineConfiguration.getJobExecutor().isActive()); + + Job timerJob = processEngineRule.getManagementService().createJobQuery().processInstanceId(pid).singleResult(); + assertNotNull(timerJob); + + processEngineRule.getManagementService().executeJob(timerJob.getId()); + + assertProcessInstanceFinished(pid); + + //System.out.println("SDNCAdapter asynchronous message timeout flow Completed!"); + } + + class ProcessExecutionThread extends Thread { + + private String workflowRequest; + private WorkflowResponse workflowResponse; + + public ProcessExecutionThread(String workflowRequest) { + this.workflowRequest = workflowRequest; + } + + public void run() { + workflowResponse = invokeFlow(workflowRequest); + workflowResponse.getProcessInstanceID(); + } + } + + private String getPid() { + return processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().list().get(0).getId(); + } + + private Object getVariable(String pid, String variableName) { + try { + return + processEngineRule + .getHistoryService() + .createHistoricVariableInstanceQuery() + .processInstanceId(pid).variableName(variableName) + .singleResult() + .getValue(); + } catch(Exception ex) { + return null; + } + } + + private void assertProcessInstanceFinished(String pid) { + assertEquals(1, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + + private void assertProcessInstanceNotFinished(String pid) { + assertEquals(0, processEngineRule.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(pid).finished().count()); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java new file mode 100644 index 0000000000..4ae76206cc --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIGenericVnfTest.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithDepth; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf_Bad; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for UpdateAAIGenericVnf bpmn. + */ +public class UpdateAAIGenericVnfTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void happyPath() throws IOException { + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf("/skask", 200); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void personaMismatch() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + updateAAIGenericVnfRequest = updateAAIGenericVnfRequest.replaceFirst("introvert", "extrovert"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + WorkflowException workflowException = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + System.out.println("Workflow Exception: " + workflowException); + Assert.assertNotNull(workflowException); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + + MockGetGenericVnfById_404("skask[?]depth=1"); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_getGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIGenericVnf.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String updateAAIGenericVnfRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIGenericVnfRequest.xml"); + + MockGetGenericVnfByIdWithDepth("skask", 1, "VfModularity/GenericVnf.xml"); + MockPutGenericVnf_Bad("skask", 404); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIGenericVnfRequest", updateAAIGenericVnfRequest); + invokeSubProcess("UpdateAAIGenericVnf", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIGenVnf_updateGenericVnfResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java new file mode 100644 index 0000000000..8691ae8e61 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/UpdateAAIVfModuleTest.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfByIdWithPriority; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockGetGenericVnfById_404; +import static org.openecomp.mso.bpmn.mock.StubResponseAAI.MockPutGenericVnf; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Assert; +import org.junit.Test; +import org.openecomp.mso.bpmn.mock.FileUtil; + +/** + * Unit tests for UpdateAAIVfModuleTest.bpmn. + */ +public class UpdateAAIVfModuleTest extends WorkflowTest { + + /** + * Test the happy path through the flow. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void happyPath() throws IOException { + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfByIdWithPriority("/skask/vf-modules/vf-module/supercool", 200, "VfModularity/VfModule-supercool.xml"); + MockPutGenericVnf("/skask/vf-modules/vf-module/supercool", "PCRF", 200); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(200, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI returns a 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void badGet() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById("/skask/vf-modules/vf-module/.*", "VfModularity/VfModule-supercool.xml", 404); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_getVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } + + /** + * Test the case where the GET to AAI is successful, but he subsequent PUT returns 404. + */ + @Test + @Deployment(resources = { + "subprocess/UpdateAAIVfModule.bpmn" + }) + public void badPut() throws IOException { + + logStart(); + + String updateAAIVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/UpdateAAIVfModuleRequest.xml"); + MockGetGenericVnfById_404("/skask/vf-modules/vf-module/supercool"); + MockGetGenericVnfById("/skask/vf-modules/vf-module/supercool", "VfModularity/VfModule-supercool.xml", 200); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", "999-99-9999"); + variables.put("isDebugLogEnabled","true"); + variables.put("UpdateAAIVfModuleRequest", updateAAIVfModuleRequest); + invokeSubProcess("UpdateAAIVfModule", businessKey, variables); + + Assert.assertTrue(isProcessEnded(businessKey)); + String response = (String) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponse"); + Integer responseCode = (Integer) getVariableFromHistory(businessKey, "UAAIVfMod_updateVfModuleResponseCode"); + System.out.println("Subflow response code: " + responseCode); + System.out.println("Subflow response: " + response); + Assert.assertEquals(404, responseCode.intValue()); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/VnfAdapterRestV1Test.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/VnfAdapterRestV1Test.java new file mode 100644 index 0000000000..d2b0e274e9 --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/VnfAdapterRestV1Test.java @@ -0,0 +1,389 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFDelete; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPost; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFPut; +import static org.openecomp.mso.bpmn.mock.StubResponseVNFAdapter.mockVNFRollbackDelete; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.junit.Test; +import org.openecomp.mso.bpmn.core.WorkflowException; + +/** + * Unit tests for VnfAdapterRestV1. + */ +public class VnfAdapterRestV1Test extends WorkflowTest { + + private static final String EOL = "\n"; + + private final CallbackSet callbacks = new CallbackSet(); + + private final String CREATE_VF_MODULE_REQUEST = + "<createVfModuleRequest>" + EOL + + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + + " <tenantId>tenantId</tenantId>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleName>vfModuleName</vfModuleName>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vnfType>vnfType</vnfType>" + EOL + + " <vnfVersion>vnfVersion</vnfVersion>" + EOL + + " <vfModuleType>vfModuleType</vfModuleType>" + EOL + + " <volumeGroupId>volumeGroupId</volumeGroupId>" + EOL + + " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL + + " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL + + " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL + + " <skipAAI>true</skipAAI>" + EOL + + " <backout>false</backout>" + EOL + + " <failIfExists>true</failIfExists>" + EOL + + " <vfModuleParams>" + EOL + + " <entry>" + EOL + + " <key>key1</key>" + EOL + + " <value>value1</value>" + EOL + + " </entry>" + EOL + + " <entry>" + EOL + + " <key>key2</key>" + EOL + + " <value>value2</value>" + EOL + + " </entry>" + EOL + + " </vfModuleParams>" + EOL + + " <msoRequest>" + EOL + + " <requestId>requestId</requestId>" + EOL + + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + + " </msoRequest>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL + + "</createVfModuleRequest>" + EOL; + + private final String UPDATE_VF_MODULE_REQUEST = + "<updateVfModuleRequest>" + EOL + + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + + " <tenantId>tenantId</tenantId>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleName>vfModuleName</vfModuleName>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <vnfType>vnfType</vnfType>" + EOL + + " <vnfVersion>vnfVersion</vnfVersion>" + EOL + + " <vfModuleType>vfModuleType</vfModuleType>" + EOL + + " <volumeGroupId>volumeGroupId</volumeGroupId>" + EOL + + " <volumeGroupStackId>volumeGroupStackId</volumeGroupStackId>" + EOL + + " <baseVfModuleId>baseVfModuleId</baseVfModuleId>" + EOL + + " <baseVfModuleStackId>baseVfModuleStackId</baseVfModuleStackId>" + EOL + + " <skipAAI>true</skipAAI>" + EOL + + " <backout>false</backout>" + EOL + + " <failIfExists>true</failIfExists>" + EOL + + " <vfModuleParams>" + EOL + + " <entry>" + EOL + + " <key>key1</key>" + EOL + + " <value>value1</value>" + EOL + + " </entry>" + EOL + + " <entry>" + EOL + + " <key>key2</key>" + EOL + + " <value>value2</value>" + EOL + + " </entry>" + EOL + + " </vfModuleParams>" + EOL + + " <msoRequest>" + EOL + + " <requestId>requestId</requestId>" + EOL + + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + + " </msoRequest>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL + + "</updateVfModuleRequest>" + EOL; + + private final String DELETE_VF_MODULE_REQUEST = + "<deleteVfModuleRequest>" + EOL + + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + + " <tenantId>tenantId</tenantId>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <skipAAI>true</skipAAI>" + EOL + + " <msoRequest>" + EOL + + " <requestId>requestId</requestId>" + EOL + + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + + " </msoRequest>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL + + "</deleteVfModuleRequest>" + EOL; + + private final String ROLLBACK_VF_MODULE_REQUEST = + "<rollbackVfModuleRequest>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <notificationUrl>http://localhost:28080/mso/WorkflowMessage</notificationUrl>" + EOL + + " <skipAAI>true</skipAAI>" + EOL + + " <vfModuleRollback>" + EOL + + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + + " <tenantId>tenantId</tenantId>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <msoRequest>" + EOL + + " <requestId>requestId</requestId>" + EOL + + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + + " </msoRequest>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <vfModuleCreated>true</vfModuleCreated>" + EOL + + " </vfModuleRollback>" + EOL + + "</rollbackVfModuleRequest>" + EOL; + + public VnfAdapterRestV1Test() throws IOException { + callbacks.put("createVfModule", + "<createVfModuleResponse>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <vfModuleCreated>true</vfModuleCreated>" + EOL + + " <vfModuleOutputs>" + EOL + + " <entry>" + EOL + + " <key>key1</key>" + EOL + + " <value>value1</value>" + EOL + + " </entry>" + EOL + + " <entry>" + EOL + + " <key>key2</key>" + EOL + + " <value>value2</value>" + EOL + + " </entry>" + EOL + + " </vfModuleOutputs>" + EOL + + " <rollback>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <vfModuleCreated>true</vfModuleCreated>" + EOL + + " <tenantId>tenantId</tenantId>" + EOL + + " <cloudSiteId>cloudSiteId</cloudSiteId>" + EOL + + " <msoRequest>" + EOL + + " <requestId>requestId</requestId>" + EOL + + " <serviceInstanceId>serviceInstanceId</serviceInstanceId>" + EOL + + " </msoRequest>" + EOL + + " <messageId>messageId</messageId>" + EOL + + " </rollback>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + "</createVfModuleResponse>" + EOL); + + callbacks.put("updateVfModule", + "<updateVfModuleResponse>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleStackId>vfModuleStackId</vfModuleStackId>" + EOL + + " <vfModuleOutputs>" + EOL + + " <entry>" + EOL + + " <key>key1</key>" + EOL + + " <value>value1</value>" + EOL + + " </entry>" + EOL + + " <entry>" + EOL + + " <key>key2</key>" + EOL + + " <value>value2</value>" + EOL + + " </entry>" + EOL + + " </vfModuleOutputs>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + "</updateVfModuleResponse>" + EOL); + + callbacks.put("deleteVfModule", + "<deleteVfModuleResponse>" + EOL + + " <vnfId>vnfId</vnfId>" + EOL + + " <vfModuleId>vfModuleId</vfModuleId>" + EOL + + " <vfModuleDeleted>true</vfModuleDeleted>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + "</deleteVfModuleResponse>" + EOL); + + callbacks.put("rollbackVfModule", + "<rollbackVfModuleResponse>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + " <vfModuleRolledback>true</vfModuleRolledback>" + EOL + + "</rollbackVfModuleResponse>" + EOL); + + callbacks.put("vfModuleException", + "<vfModuleException>" + EOL + + " <message>message</message>" + EOL + + " <category>category</category>" + EOL + + " <rolledBack>false</rolledBack>" + EOL + + " <messageId>{{MESSAGE-ID}}</messageId>" + EOL + + "</vfModuleException>" + EOL); + } + + @Test + @Deployment(resources = { + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void testCreateVfModuleSuccess() throws Exception { + logStart(); + + mockVNFPost("", 202, "vnfId"); + + String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312"; + String messageId = requestId + "-" + System.currentTimeMillis(); + String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", requestId); + variables.put("isDebugLogEnabled", "true"); + variables.put("vnfAdapterRestV1Request", request); + + invokeSubProcess("vnfAdapterRestV1", businessKey, variables); + injectVNFRestCallbacks(callbacks, "createVfModule"); + waitForProcessEnd(businessKey, 10000); + + String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response"); + System.out.println("Response:\n" + response); + assertTrue(response.contains("<createVfModuleResponse>")); + assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator")); + + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void testUpdateVfModuleSuccess() throws Exception { + logStart(); + + mockVNFPut("/vfModuleId", 202); + + String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312"; + String messageId = requestId + "-" + System.currentTimeMillis(); + String request = UPDATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", requestId); + variables.put("isDebugLogEnabled", "true"); + variables.put("vnfAdapterRestV1Request", request); + + invokeSubProcess("vnfAdapterRestV1", businessKey, variables); + injectVNFRestCallbacks(callbacks, "updateVfModule"); + waitForProcessEnd(businessKey, 10000); + + String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response"); + System.out.println("Response:\n" + response); + assertTrue(response.contains("<updateVfModuleResponse>")); + assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator")); + + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void testDeleteVfModuleSuccess() throws Exception { + logStart(); + + mockVNFDelete("vnfId", "/vfModuleId", 202); + + String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312"; + String messageId = requestId + "-" + System.currentTimeMillis(); + String request = DELETE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", requestId); + variables.put("isDebugLogEnabled", "true"); + variables.put("vnfAdapterRestV1Request", request); + + invokeSubProcess("vnfAdapterRestV1", businessKey, variables); + injectVNFRestCallbacks(callbacks, "deleteVfModule"); + waitForProcessEnd(businessKey, 10000); + + String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response"); + System.out.println("Response:\n" + response); + assertTrue(response.contains("<deleteVfModuleResponse>")); + assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator")); + + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void testRollbackVfModuleSuccess() throws Exception { + logStart(); + + mockVNFRollbackDelete("/vfModuleId", 202); + + String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312"; + String messageId = requestId + "-" + System.currentTimeMillis(); + String request = ROLLBACK_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", requestId); + variables.put("isDebugLogEnabled", "true"); + variables.put("vnfAdapterRestV1Request", request); + + invokeSubProcess("vnfAdapterRestV1", businessKey, variables); + injectVNFRestCallbacks(callbacks, "rollbackVfModule"); + waitForProcessEnd(businessKey, 10000); + + String response = (String) getVariableFromHistory(businessKey, "vnfAdapterRestV1Response"); + System.out.println("Response:\n" + response); + assertTrue(response.contains("<rollbackVfModuleResponse>")); + assertTrue((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator")); + + logEnd(); + } + + @Test + @Deployment(resources = { + "subprocess/VnfAdapterRestV1.bpmn" + }) + public void testCreateVfModuleException() throws Exception { + logStart(); + + mockVNFPost("", 202, "vnfId"); + + String requestId = "dffbae0e-5588-4bd6-9749-b0f0adb52312"; + String messageId = requestId + "-" + System.currentTimeMillis(); + String request = CREATE_VF_MODULE_REQUEST.replace("{{MESSAGE-ID}}", messageId); + + String businessKey = UUID.randomUUID().toString(); + Map<String, Object> variables = new HashMap<String, Object>(); + variables.put("mso-request-id", requestId); + variables.put("isDebugLogEnabled", "true"); + variables.put("vnfAdapterRestV1Request", request); + + invokeSubProcess("vnfAdapterRestV1", businessKey, variables); + injectVNFRestCallbacks(callbacks, "vfModuleException"); + waitForProcessEnd(businessKey, 10000); + + WorkflowException wfe = (WorkflowException) getVariableFromHistory(businessKey, "WorkflowException"); + assertNotNull(wfe); + System.out.println(wfe.toString()); + + String response = (String) getVariableFromHistory(businessKey, "WorkflowResponse"); + System.out.println("Response:\n" + response); + assertTrue(response.contains("<vfModuleException>")); + assertFalse((boolean) getVariableFromHistory(businessKey, "VNFREST_SuccessIndicator")); + + logEnd(); + } +} + diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowAsyncResourceTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowAsyncResourceTest.java new file mode 100644 index 0000000000..4ac885fd9d --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowAsyncResourceTest.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +public class WorkflowAsyncResourceTest extends WorkflowTest { + + @Test + @Deployment(resources = { "testAsyncResource.bpmn" }) + public void asyncRequestSuccess() throws InterruptedException { + //it can be any request which asynchronously processed by the workflow + String request = "<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns5=\"http://org.openecomp/mso/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.openecomp/mso/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>"; + + Map<String,String> variables = new HashMap<String,String>(); + variables.put("testAsyncRequestMsg", request); + variables.put("mso-request-id", UUID.randomUUID().toString()); + variables.put("mso-service-request-timeout", "5"); + + WorkflowResponse workflowResponse = BPMNUtil.executeAsyncWorkflow(processEngineRule, "testAsyncProcess", variables); + assertEquals("Received the request, the process is getting executed, request message<aetgt:CreateTenantRequest xmlns:aetgt=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:sdncadapterworkflow=\"http://org.openecomp/mso/workflow/schema/v1\" xmlns:ns5=\"http://org.openecomp/mso/request/types/v1\"> <msoservtypes:service-information xmlns:msoservtypes=\"http://org.openecomp/mso/request/types/v1\"> <msoservtypes:service-type>SDN-ETHERNET-INTERNET</msoservtypes:service-type> <msoservtypes:service-instance-id>HI/VLXM/950604//SW_INTERNET</msoservtypes:service-instance-id> <msoservtypes:subscriber-name>SubName01</msoservtypes:subscriber-name> </msoservtypes:service-information> </aetgt:CreateTenantRequest>", workflowResponse.getResponse()); + assertEquals(200, workflowResponse.getMessageCode()); + } + + private void executeWorkflow(String request, String requestId, AsynchronousResponse asyncResponse, String processKey) { + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + VariableMapImpl variableMap = new VariableMapImpl(); + + Map<String, Object> variableValueType = new HashMap<String, Object>(); + + Map<String, Object> requestMsg = new HashMap<String, Object>(); + requestMsg.put("value", request); + requestMsg.put("type", "String"); + + Map<String, Object> msorequestId = new HashMap<String, Object>(); + msorequestId.put("type", "String"); + msorequestId.put("value",requestId); + + Map<String, Object> timeout = new HashMap<String, Object>(); + timeout.put("type", "String"); + timeout.put("value","5"); + + variableValueType.put("testAsyncRequestMsg", requestMsg); + variableValueType.put("mso-request-id", msorequestId); + variableValueType.put("mso-service-request-timeout", timeout); + + variableMap.put("variables", variableValueType); + + workflowResource.setProcessEngineServices4junit(processEngineRule); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMap); + } + + class ProcessThread extends Thread { + + public WorkflowResponse workflowResponse; + public String requestId; + public String processKey; + public AsynchronousResponse asyncResponse = mock(AsynchronousResponse.class); + public String request; + public boolean started; + public void run() { + started = true; + executeWorkflow(request, requestId, asyncResponse, processKey); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowContextHolderTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowContextHolderTest.java new file mode 100644 index 0000000000..bff193ffdd --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowContextHolderTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.util.UUID; + +import javax.ws.rs.core.Response; + +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowCallbackResponse; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowContext; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowContextHolder; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; + +public class WorkflowContextHolderTest { + + private WorkflowContext createContext(AsynchronousResponse asyncResponse) { + WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance(); + String requestId = UUID.randomUUID().toString(); + WorkflowContext workflowContext = new WorkflowContext("testAsyncProcess", + requestId, asyncResponse, 1000L); + contextHolder.put(workflowContext); + return workflowContext; + } + + @Test + @Ignore // BROKEN TEST (previously ignored) + public void testContextExpiry() throws InterruptedException { + + WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance(); + AsynchronousResponse asyncResponse = mock(AsynchronousResponse.class); + WorkflowContext workflowContext = createContext(asyncResponse); + String requestId = workflowContext.getRequestId(); + WorkflowContext context1 = contextHolder.getWorkflowContext(requestId); + + Assert.assertNotNull(context1); + Assert.assertEquals(requestId, context1.getRequestId()); + Assert.assertEquals(workflowContext.getProcessKey(), context1.getProcessKey()); + Assert.assertEquals(workflowContext.getStartTime(), context1.getStartTime()); + + Thread.sleep(1000); + //context should not be available after a second + WorkflowContext context2 = contextHolder.getWorkflowContext(requestId); + Assert.assertNull(context2); + } + + @Test + public void testProcessCallback() { + WorkflowContextHolder contextHolder = WorkflowContextHolder.getInstance(); + AsynchronousResponse asyncResponse = mock(AsynchronousResponse.class); + WorkflowContext workflowContext = createContext(asyncResponse); + + WorkflowCallbackResponse callbackResponse = new WorkflowCallbackResponse(); + callbackResponse.setMessage("Success"); + callbackResponse.setResponse("Successfully processed request"); + callbackResponse.setStatusCode(200); + + Response response = contextHolder.processCallback("testAsyncProcess", + "process-instance-id", workflowContext.getRequestId(), + callbackResponse); + WorkflowResponse response1 = (WorkflowResponse) response.getEntity(); + Assert.assertNotNull(response1.getMessage()); + Assert.assertEquals(200,response1.getMessageCode()); + Assert.assertEquals("Success", response1.getMessage()); + Assert.assertEquals("Successfully processed request", response1.getResponse()); + verify(asyncResponse).setResponse(any(Response.class)); + + WorkflowContext context1 = contextHolder.getWorkflowContext(workflowContext.getRequestId()); + Assert.assertNull(context1); + } + +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java new file mode 100644 index 0000000000..c47521384b --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java @@ -0,0 +1,1796 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - MSO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.management.ManagementFactory; +import java.lang.management.RuntimeMXBean; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.ws.rs.core.Response; +import javax.xml.bind.JAXBException; +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.custommonkey.xmlunit.DetailedDiff; +import org.custommonkey.xmlunit.XMLUnit; +import org.jboss.resteasy.spi.AsynchronousResponse; +import org.junit.Before; +import org.junit.Rule; +import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterCallbackRequest; +import org.openecomp.mso.bpmn.common.adapter.sdnc.SDNCAdapterResponse; +import org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.DeleteVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.MsoExceptionCategory; +import org.openecomp.mso.bpmn.common.adapter.vnf.MsoRequest; +import org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification; +import org.openecomp.mso.bpmn.common.adapter.vnf.VnfRollback; +import org.openecomp.mso.bpmn.common.workflow.service.SDNCAdapterCallbackServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.VnfAdapterNotifyServiceImpl; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncCommonResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource; +import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse; +import org.openecomp.mso.bpmn.core.CamundaDBSetup; +import org.openecomp.mso.bpmn.core.PropertyConfigurationSetup; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.extension.ResponseTransformer; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + + + +/** + * A base class for Workflow tests. + * <p> + * WireMock response transformers may be specified by declaring public + * static fields with the @WorkflowTestTransformer annotation. For example: + * <pre> + * @WorkflowTestTransformer + * public static final ResponseTransformer sdncAdapterMockTransformer = + * new SDNCAdapterMockTransformer(); + * </pre> + */ +public class WorkflowTest { + @Rule + public final ProcessEngineRule processEngineRule = new ProcessEngineRule(); + + @Rule + public final WireMockRule wireMockRule; + + /** + * Constructor. + */ + public WorkflowTest() throws RuntimeException { + // Process WorkflowTestTransformer annotations + List<ResponseTransformer> transformerList = new ArrayList<ResponseTransformer>(); + + for (Field field : getClass().getFields()) { + WorkflowTestTransformer annotation = (WorkflowTestTransformer) + field.getAnnotation(WorkflowTestTransformer.class); + + if (annotation == null) { + continue; + } + + if (!Modifier.isStatic(field.getModifiers())) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " has a @WorkflowTestTransformer " + + " annotation but it is not declared static"); + } + + ResponseTransformer transformer; + + try { + transformer = (ResponseTransformer) field.get(null); + } catch (IllegalAccessException e) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " is not accessible", e); + } catch (ClassCastException e) { + throw new RuntimeException(field.getDeclaringClass().getName() + + "#" + field.getName() + " is not a ResponseTransformer", e); + } + + if (transformer == null) { + continue; + } + + transformerList.add(transformer); + } + + ResponseTransformer[] transformerArray = + transformerList.toArray(new ResponseTransformer[transformerList.size()]); + + wireMockRule = new WireMockRule(WireMockConfiguration.wireMockConfig() + .port(28090).extensions(transformerArray)); + } + + @Before + public void testSetup() throws Exception { + CamundaDBSetup.configure(); + PropertyConfigurationSetup.init(); + } + + /** + * The current request ID. Normally set when an "invoke" method is called. + */ + protected volatile String msoRequestId = null; + + /** + * The current service instance ID. Normally set when an "invoke" method + * is called. + */ + protected volatile String msoServiceInstanceId = null; + + /** + * Logs a test start method. + */ + protected void logStart() { + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + String method = st[2].getMethodName(); + System.out.println("STARTED TEST: " + method); + } + + /** + * Logs a test end method. + */ + protected void logEnd() { + StackTraceElement[] st = Thread.currentThread().getStackTrace(); + String method = st[2].getMethodName(); + System.out.println("ENDED TEST: " + method); + } + + /** + * Invokes a subprocess. + * @param processKey the process key + * @param businessKey a unique key that will identify the process instance + * @param injectedVariables variables to inject into the process + */ + protected void invokeSubProcess(String processKey, String businessKey, + Map<String, Object> injectedVariables) { + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List<String> arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + msoRequestId = (String) injectedVariables.get("mso-request-id"); + + if (msoRequestId == null) { + String msg = "mso-request-id variable was not provided"; + System.out.println(msg); + fail(msg); + } + + // Note: some scenarios don't have a service-instance-id, may be null + msoServiceInstanceId = (String) injectedVariables.get("mso-service-instance-id"); + + RuntimeService runtimeService = processEngineRule.getRuntimeService(); + runtimeService.startProcessInstanceByKey(processKey, businessKey, injectedVariables); + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @return a TestAsyncResponse object associated with the test + */ + protected TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request) { + return invokeAsyncProcess(processKey, schemaVersion, businessKey, request, null); + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @return a TestAsyncResponse object associated with the test + */ + public TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request, + Map<String, Object> injectedVariables) { + + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List<String> arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + Map<String, Object> variables = createVariables(schemaVersion, businessKey, + request, injectedVariables, false); + VariableMapImpl variableMapImpl = createVariableMapImpl(variables); + + System.out.println("Sending " + request + " to " + processKey + " process"); + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + TestAsyncResponse asyncResponse = new TestAsyncResponse(); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); + return asyncResponse; + } + + /** + * Invokes an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param processKey the process key + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @param serviceInstantiationModel indicates whether this method is being + * invoked for a flow that is designed using the service instantiation model + * @return a TestAsyncResponse object associated with the test + */ + protected TestAsyncResponse invokeAsyncProcess(String processKey, + String schemaVersion, String businessKey, String request, + Map<String, Object> injectedVariables, boolean serviceInstantiationModel) { + + RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); + List<String> arguments = runtimeMxBean.getInputArguments(); + System.out.println("JVM args = " + arguments); + + Map<String, Object> variables = createVariables(schemaVersion, businessKey, + request, injectedVariables, serviceInstantiationModel); + VariableMapImpl variableMapImpl = createVariableMapImpl(variables); + + System.out.println("Sending " + request + " to " + processKey + " process"); + WorkflowAsyncCommonResource workflowResource = new WorkflowAsyncCommonResource(); + workflowResource.setProcessEngineServices4junit(processEngineRule); + + TestAsyncResponse asyncResponse = new TestAsyncResponse(); + workflowResource.startProcessInstanceByKey(asyncResponse, processKey, variableMapImpl); + return asyncResponse; + } + + /** + * Private helper method that creates a variable map for a request. + * Errors are handled with junit assertions and will cause the test to fail. + * @param schemaVersion the API schema version, e.g. "v1" + * @param businessKey a unique key that will identify the process instance + * @param request the request + * @param injectedVariables optional variables to inject into the process + * @param serviceInstantiationModel indicates whether this method is being + * invoked for a flow that is designed using the service instantiation model + * @return a variable map + */ + private Map<String, Object> createVariables(String schemaVersion, + String businessKey, String request, Map<String, Object> injectedVariables, + boolean serviceInstantiationModel) { + + Map<String, Object> variables = new HashMap<String, Object>(); + + // These variables may be overridded by injected variables. + variables.put("mso-service-request-timeout", "180"); + variables.put("isDebugLogEnabled", "true"); + + // These variables may not be overridded by injected variables. + String[] notAllowed = new String[] { + "mso-schema-version", + "mso-business-key", + "bpmnRequest", + "mso-request-id", + "mso-service-instance-id" + }; + + if (injectedVariables != null) { + for (String key : injectedVariables.keySet()) { + for (String var : notAllowed) { + if (var.equals(key)) { + String msg = "Cannot specify " + var + " in injected variables"; + System.out.println(msg); + fail(msg); + } + } + + variables.put(key, injectedVariables.get(key)); + } + } + + variables.put("mso-schema-version", schemaVersion); + variables.put("mso-business-key", businessKey); + variables.put("bpmnRequest", request); + + if (serviceInstantiationModel) { + + /* + * The request ID and the service instance ID are generated for flows + * that follow the service instantiation model unless "requestId" and + * "serviceInstanceId" are injected variables. + */ + + try { + msoRequestId = (String) injectedVariables.get("requestId"); + variables.put("mso-request-id", msoRequestId); + msoServiceInstanceId = (String) injectedVariables.get("serviceInstanceId"); + variables.put("mso-service-instance-id", msoServiceInstanceId); + } + catch(Exception e) { + } + if (msoRequestId == null || msoRequestId.trim().equals("")) { + System.out.println("No requestId element in injectedVariables"); + variables.put("mso-request-id", UUID.randomUUID().toString()); + } + if (msoServiceInstanceId == null || msoServiceInstanceId.trim().equals("")) { + System.out.println("No seviceInstanceId element in injectedVariables"); + variables.put("mso-service-instance-id", UUID.randomUUID().toString()); + } + + } else { + msoRequestId = getXMLTextElement(request, "request-id"); + + if (msoRequestId == null) { + //check in injected variables + try { + msoRequestId = (String) injectedVariables.get("requestId"); + } + catch(Exception e) { + } + if (msoRequestId == null || msoRequestId.trim().equals("")) { + String msg = "No request-id element in " + request; + System.out.println(msg); + fail(msg); + } + } + + variables.put("mso-request-id", msoRequestId); + + // Note: some request types don't have a service-instance-id + msoServiceInstanceId = getXMLTextElement(request, "service-instance-id"); + + if (msoServiceInstanceId != null) { + variables.put("mso-service-instance-id", msoServiceInstanceId); + } + } + + return variables; + } + + /** + * Private helper method that creates a camunda VariableMapImpl from a simple + * variable map. + * @param variables the simple variable map + * @return a VariableMap + */ + private VariableMapImpl createVariableMapImpl(Map<String, Object> variables) { + Map<String, Object> wrappedVariables = new HashMap<String, Object>(); + + for (String key : variables.keySet()) { + Object value = variables.get(key); + wrappedVariables.put(key, wrapVariableValue(value)); + } + + VariableMapImpl variableMapImpl = new VariableMapImpl(); + variableMapImpl.put("variables", wrappedVariables); + return variableMapImpl; + } + + /** + * Private helper method that wraps a variable value for inclusion in a + * camunda VariableMapImpl. + * @param value the variable value + * @return the wrapped variable + */ + private Map<String, Object> wrapVariableValue(Object value) { + HashMap<String, Object> valueMap = new HashMap<String, Object>(); + valueMap.put("value", value); + return valueMap; + } + + /** + * Receives a response from an asynchronous process. + * Errors are handled with junit assertions and will cause the test to fail. + * @param businessKey the process business key + * @param asyncResponse the TestAsyncResponse object associated with the test + * @param timeout the timeout in milliseconds + * @return the WorkflowResponse + */ + public WorkflowResponse receiveResponse(String businessKey, + TestAsyncResponse asyncResponse, long timeout) { + System.out.println("Waiting " + timeout + "ms for process with business key " + businessKey + + " to send a response"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + while (now <= endTime) { + Response response = asyncResponse.getResponse(); + + if (response != null) { + System.out.println("Received a response from process with business key " + businessKey); + + Object entity = response.getEntity(); + + if (!(entity instanceof WorkflowResponse)) { + String msg = "Response entity is " + + (entity == null ? "null" : entity.getClass().getName()) + + ", expected WorkflowResponse"; + System.out.println(msg); + fail(msg); + return null; // unreachable + } + + return (WorkflowResponse) entity; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for a response from process with business key " + + businessKey; + System.out.println(msg); + fail(msg); + return null; // unreachable + } + + now = System.currentTimeMillis(); + } + + String msg = "No response received from process with business key " + businessKey + + " within " + timeout + "ms"; + System.out.println(msg); + fail("Process with business key " + businessKey + " did not end within 10000ms"); + return null; // unreachable + } + + /** + * Runs a program to inject SDNC callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + * <pre> + * reserve, assign, delete:ERR + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + protected void injectSDNCRestCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' SDNC request"; + System.out.println(msg); + fail(msg); + } + } else if ("ERR".equals(modifier)) { + content = "{\"SDNCServiceError\":{\"sdncRequestId\":\"((REQUEST-ID))\",\"responseCode\":\"500\",\"responseMessage\":\"SIMULATED ERROR FROM SDNC ADAPTER\",\"ackFinalIndicator\":\"Y\"}}"; + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectSDNCRestCallback(content, 10000)) { + fail("Failed to inject SDNC '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject SDNC events into the test environment. + * A program is essentially just a list of keys that identify event data + * to be injected, in sequence. An example program: + * <pre> + * event1, event2 + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * Defaults the Event Type to "SDNCAEvent" for backward compatibility. + * @param callbacks an object containing event data for the program + * @param program the program to execute + */ + protected void injectSDNCEvents(CallbackSet callbacks, String program) { + injectSDNCEvents(callbacks, program, "SDNCAEvent"); + } + + /** + * Runs a program to inject SDNC events into the test environment. + * A program is essentially just a list of keys that identify event data + * to be injected, in sequence. An example program: + * <pre> + * event1, event2 + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing event data for the program + * @param program the program to execute + * @param eventType (i.e. "SDNCAEvent", "SNIROResponse", etc.) + */ + protected void injectSDNCEvents(CallbackSet callbacks, String program, String eventType) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No SDNC event callback defined for '" + action + "'"; + System.out.println(msg); + fail(msg); + } + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectWorkflowMessage(eventType, content, 10000)) { + fail("Failed to inject SDNC '" + action + "' event"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' event"); + } + } + } + + /** + * Runs a program to inject SDNC callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + * <pre> + * reserve, assign, delete:ERR + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + public void injectSDNCCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + int respCode = 200; + String respMsg = "OK"; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' SDNC request"; + System.out.println(msg); + fail(msg); + } + + respCode = 200; + respMsg = "OK"; + } else if ("ERR".equals(modifier)) { + content = "<svc-request-id>((REQUEST-ID))</svc-request-id><response-code>500</response-code><response-message>SIMULATED ERROR FROM SDNC ADAPTER</response-message>"; + respCode = 500; + respMsg = "SERVER ERROR"; + } else { + String msg = "Invalid SDNC program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectSDNCCallback(respCode, respMsg, content, 10000)) { + fail("Failed to inject SDNC '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of SDNC '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject VNF adapter REST callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + * <pre> + * create, rollback + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + public void injectVNFRestCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' VNF REST request"; + System.out.println(msg); + fail(msg); + } + } else if ("ERR".equals(modifier)) { + content = "SIMULATED ERROR FROM VNF ADAPTER"; + } else { + String msg = "Invalid VNF REST program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + if (!injectVnfAdapterRestCallback(content, 10000)) { + fail("Failed to inject VNF REST '" + action + "' callback"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of VNF REST '" + action + "' callback"); + } + } + } + + /** + * Runs a program to inject VNF callback data into the test environment. + * A program is essentially just a list of keys that identify callback data + * to be injected, in sequence. An example program: + * <pre> + * createVnf, deleteVnf + * </pre> + * Errors are handled with junit assertions and will cause the test to fail. + * @param callbacks an object containing callback data for the program + * @param program the program to execute + */ + protected void injectVNFCallbacks(CallbackSet callbacks, String program) { + + String[] cmds = program.replaceAll("\\s+", "").split(","); + + for (String cmd : cmds) { + String action = cmd; + String modifier = "STD"; + + if (cmd.contains(":")) { + String[] parts = cmd.split(":"); + action = parts[0]; + modifier = parts[1]; + } + + String content = null; + + if ("STD".equals(modifier)) { + content = callbacks.get(action); + + if (content == null) { + String msg = "No callback defined for '" + action + "' VNF request"; + System.out.println(msg); + fail(msg); + } + + } else if ("ERR".equals(modifier)) { + String msg = "Currently unsupported VNF program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } else { + String msg = "Invalid VNF program modifier: '" + modifier + "'"; + System.out.println(msg); + fail(msg); + } + + boolean injected = false; + + if (content.contains("createVnfNotification")) { + injected = injectCreateVNFCallback(content, 10000); + } else if (content.contains("deleteVnfNotification")) { + injected = injectDeleteVNFCallback(content, 10000); + } else if (content.contains("updateVnfNotification")) { + injected = injectUpdateVNFCallback(content, 10000); + } + + if (!injected) { + String msg = "Failed to inject VNF '" + action + "' callback"; + System.out.println(msg); + fail(msg); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + fail("Interrupted after injection of VNF '" + action + "' callback"); + } + } + } + + /** + * Waits for the number of running processes with the specified process + * definition key to equal a particular count. + * @param processKey the process definition key + * @param count the desired count + * @param timeout the timeout in milliseconds + */ + public void waitForRunningProcessCount(String processKey, int count, long timeout) { + System.out.println("Waiting " + timeout + "ms for there to be " + count + " " + + processKey + " instances"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + int last = -1; + + while (now <= endTime) { + int actual = processEngineRule.getRuntimeService() + .createProcessInstanceQuery() + .processDefinitionKey(processKey) + .list().size(); + + if (actual != last) { + System.out.println("There are now " + actual + " " + + processKey + " instances"); + last = actual; + } + + if (actual == count) { + return; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for there to be " + count + " " + + processKey + " instances"; + System.out.println(msg); + fail(msg); + } + + now = System.currentTimeMillis(); + } + + String msg = "Timed out waiting for there to be " + count + " " + + processKey + " instances"; + System.out.println(msg); + fail(msg); + } + + /** + * Waits for the specified process variable to be set. + * @param processKey the process definition key + * @param variable the variable name + * @param timeout the timeout in milliseconds + * @return the variable value, or null if it cannot be obtained + * in the specified time + */ + protected Object getProcessVariable(String processKey, String variable, + long timeout) { + + System.out.println("Waiting " + timeout + "ms for " + + processKey + "." + variable + " to be set"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + ProcessInstance processInstance = null; + Object value = null; + + while (value == null) { + if (now > endTime) { + if (processInstance == null) { + System.out.println("Timed out waiting for " + + processKey + " to start"); + } else { + System.out.println("Timed out waiting for " + + processKey + "[" + processInstance.getId() + + "]." + variable + " to be set"); + } + + return null; + } + + if (processInstance == null) { + processInstance = processEngineRule.getRuntimeService() + .createProcessInstanceQuery() + .processDefinitionKey(processKey) + .singleResult(); + } + + if (processInstance != null) { + value = processEngineRule.getRuntimeService() + .getVariable(processInstance.getId(), variable); + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + System.out.println("Interrupted waiting for " + + processKey + "." + variable + " to be set"); + return null; + } + + now = System.currentTimeMillis(); + } + + System.out.println(processKey + "[" + + processInstance.getId() + "]." + variable + "=" + + value); + + return value; + } + + /** + * Injects a single SDNC adapter callback request. The specified callback data + * may contain the placeholder string ((REQUEST-ID)) which is replaced with + * the actual SDNC request ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectSDNCRestCallback(String content, long timeout) { + String sdncRequestId = (String) getProcessVariable("SDNCAdapterRestV1", + "SDNCAResponse_CORRELATOR", timeout); + + if (sdncRequestId == null) { + return false; + } + + content = content.replace("((REQUEST-ID))", sdncRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", sdncRequestId); + + System.out.println("Injecting SDNC adapter callback"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver("SDNCAResponse", sdncRequestId, content); + System.out.println("Workflow response to SDNC adapter callback: " + response); + return true; + } + + /** + * Injects a single SDNC adapter callback request. The specified callback data + * may contain the placeholder string ((REQUEST-ID)) which is replaced with + * the actual SDNC request ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param respCode the response code (normally 200) + * @param respMsg the response message (normally "OK") + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectSDNCCallback(int respCode, String respMsg, + String content, long timeout) { + + String sdncRequestId = (String) getProcessVariable("sdncAdapter", + "SDNCA_requestId", timeout); + + if (sdncRequestId == null) { + return false; + } + + content = content.replace("((REQUEST-ID))", sdncRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", sdncRequestId); + + System.out.println("Injecting SDNC adapter callback"); + CallbackHeader callbackHeader = new CallbackHeader(); + callbackHeader.setRequestId(sdncRequestId); + callbackHeader.setResponseCode(String.valueOf(respCode)); + callbackHeader.setResponseMessage(respMsg); + SDNCAdapterCallbackRequest sdncAdapterCallbackRequest = new SDNCAdapterCallbackRequest(); + sdncAdapterCallbackRequest.setCallbackHeader(callbackHeader); + sdncAdapterCallbackRequest.setRequestData(content); + SDNCAdapterCallbackServiceImpl callbackService = new SDNCAdapterCallbackServiceImpl(); + callbackService.setProcessEngineServices4junit(processEngineRule); + SDNCAdapterResponse sdncAdapterResponse = callbackService.sdncAdapterCallback(sdncAdapterCallbackRequest); + System.out.println("Workflow response to SDNC adapter callback: " + sdncAdapterResponse); + + return true; + } + + /** + * Injects a single VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. Note: this is not the requestId in the original + * MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + */ + protected boolean injectVnfAdapterRestCallback(String content, long timeout) { + String messageId = (String) getProcessVariable("vnfAdapterRestV1", + "VNFAResponse_CORRELATOR", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + System.out.println("Injecting VNF adapter callback"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver("VNFAResponse", messageId, content); + System.out.println("Workflow response to VNF adapter callback: " + response); + return true; + } + + /** + * Injects a Create VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectCreateVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterCreateV1", + "VNFC_messageId", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + if(content.contains("((REQUEST-ID))")){ + content = content.replace("((REQUEST-ID))", msoRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", msoRequestId); + } + + System.out.println("Injecting VNF adapter callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + CreateVnfNotification createVnfNotification = new CreateVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:createVnfNotification/tns:completed/text()"); + createVnfNotification.setCompleted("true".equals(completed)); + + String vnfId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:vnfId/text()"); + createVnfNotification.setVnfId(vnfId); + + NodeList entries = (NodeList) xpathTool.evaluate( + "/tns:createVnfNotification/tns:outputs/tns:entry", + XPathConstants.NODESET); + + CreateVnfNotificationOutputs outputs = new CreateVnfNotificationOutputs(); + + for (int i = 0; i < entries.getLength(); i++) { + Node node = entries.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element entry = (Element) node; + String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); + String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); + outputs.add(key, value); + } + } + + createVnfNotification.setOutputs(outputs); + + VnfRollback rollback = new VnfRollback(); + + String cloudSiteId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:cloudSiteId/text()"); + rollback.setCloudSiteId(cloudSiteId); + + String requestId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); + String serviceInstanceId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); + + if (requestId != null || serviceInstanceId != null) { + MsoRequest msoRequest = new MsoRequest(); + msoRequest.setRequestId(requestId); + msoRequest.setServiceInstanceId(serviceInstanceId); + rollback.setMsoRequest(msoRequest); + } + + String tenantCreated = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:tenantCreated/text()"); + rollback.setTenantCreated("true".equals(tenantCreated)); + + String tenantId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:tenantId/text()"); + rollback.setTenantId(tenantId); + + String vnfCreated = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:vnfCreated/text()"); + rollback.setVnfCreated("true".equals(vnfCreated)); + + String rollbackVnfId = xpathTool.evaluate( + "/tns:createVnfNotification/tns:rollback/tns:vnfId/text()"); + rollback.setVnfId(rollbackVnfId); + + createVnfNotification.setRollback(rollback); + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.createVnfNotification( + messageId, + createVnfNotification.isCompleted(), + createVnfNotification.getException(), + createVnfNotification.getErrorMessage(), + createVnfNotification.getVnfId(), + createVnfNotification.getOutputs(), + createVnfNotification.getRollback()); + + return true; + } + + /** + * Injects a Delete VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectDeleteVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterDeleteV1", + "VNFDEL_uuid", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + System.out.println("Injecting VNF adapter delete callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + DeleteVnfNotification deleteVnfNotification = new DeleteVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:deleteVnfNotification/tns:completed/text()"); + deleteVnfNotification.setCompleted("true".equals(completed)); + // if notification failure, set the exception and error message + if (deleteVnfNotification.isCompleted() == false) { + deleteVnfNotification.setException(MsoExceptionCategory.INTERNAL); + deleteVnfNotification.setErrorMessage(xpathTool.evaluate( + "/tns:deleteVnfNotification/tns:errorMessage/text()")) ; + } + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF Delete callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.deleteVnfNotification( + messageId, + deleteVnfNotification.isCompleted(), + deleteVnfNotification.getException(), + deleteVnfNotification.getErrorMessage()); + + return true; + } + + /** + * Injects a Update VNF adapter callback request. The specified callback data + * may contain the placeholder string ((MESSAGE-ID)) which is replaced with + * the actual message ID. It may also contain the placeholder string + * ((REQUEST-ID)) which is replaced request ID of the original MSO request. + * @param content the content of the callback + * @param timeout the timeout in milliseconds + * @return true if the callback could be injected, false otherwise + * @throws JAXBException if the content does not adhere to the schema + */ + protected boolean injectUpdateVNFCallback(String content, long timeout) { + + String messageId = (String) getProcessVariable("vnfAdapterUpdate", + "VNFU_messageId", timeout); + + if (messageId == null) { + return false; + } + + content = content.replace("((MESSAGE-ID))", messageId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{MESSAGE-ID}}", messageId); + + content = content.replace("((REQUEST-ID))", msoRequestId); + // Deprecated usage. All test code should switch to the (( ... )) syntax. + content = content.replace("{{REQUEST-ID}}", msoRequestId); + + System.out.println("Injecting VNF adapter callback"); + + // Is it possible to unmarshal this with JAXB? I couldn't. + + UpdateVnfNotification updateVnfNotification = new UpdateVnfNotification(); + XPathTool xpathTool = new VnfNotifyXPathTool(); + xpathTool.setXML(content); + + try { + String completed = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:completed/text()"); + updateVnfNotification.setCompleted("true".equals(completed)); + + NodeList entries = (NodeList) xpathTool.evaluate( + "/tns:updateVnfNotification/tns:outputs/tns:entry", + XPathConstants.NODESET); + + UpdateVnfNotificationOutputs outputs = new UpdateVnfNotificationOutputs(); + + for (int i = 0; i < entries.getLength(); i++) { + Node node = entries.item(i); + + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element entry = (Element) node; + String key = entry.getElementsByTagNameNS("*", "key").item(0).getTextContent(); + String value = entry.getElementsByTagNameNS("*", "value").item(0).getTextContent(); + outputs.add(key, value); + } + } + + updateVnfNotification.setOutputs(outputs); + + VnfRollback rollback = new VnfRollback(); + + String cloudSiteId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:cloudSiteId/text()"); + rollback.setCloudSiteId(cloudSiteId); + + String requestId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:requestId/text()"); + String serviceInstanceId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:msoRequest/tns:serviceInstanceId/text()"); + + if (requestId != null || serviceInstanceId != null) { + MsoRequest msoRequest = new MsoRequest(); + msoRequest.setRequestId(requestId); + msoRequest.setServiceInstanceId(serviceInstanceId); + rollback.setMsoRequest(msoRequest); + } + + String tenantCreated = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:tenantCreated/text()"); + rollback.setTenantCreated("true".equals(tenantCreated)); + + String tenantId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:tenantId/text()"); + rollback.setTenantId(tenantId); + + String vnfCreated = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:vnfCreated/text()"); + rollback.setVnfCreated("true".equals(vnfCreated)); + + String rollbackVnfId = xpathTool.evaluate( + "/tns:updateVnfNotification/tns:rollback/tns:vnfId/text()"); + rollback.setVnfId(rollbackVnfId); + + updateVnfNotification.setRollback(rollback); + + } catch (Exception e) { + System.out.println("Failed to unmarshal VNF callback content:"); + System.out.println(content); + return false; + } + + VnfAdapterNotifyServiceImpl notifyService = new VnfAdapterNotifyServiceImpl(); + notifyService.setProcessEngineServices4junit(processEngineRule); + + notifyService.updateVnfNotification( + messageId, + updateVnfNotification.isCompleted(), + updateVnfNotification.getException(), + updateVnfNotification.getErrorMessage(), + updateVnfNotification.getOutputs(), + updateVnfNotification.getRollback()); + + return true; + } + + /** + * Injects a workflow message. The specified callback data may contain the + * placeholder string ((CORRELATOR)) which is replaced with the actual + * correlator value. + * @param content the message type + * @param content the message content + * @param timeout the timeout in milliseconds + * @return true if the event could be injected, false otherwise + */ + protected boolean injectWorkflowMessage(String messageType, String content, long timeout) { + String correlator = (String) getProcessVariable("ReceiveWorkflowMessage", + messageType + "_CORRELATOR", timeout); + + if (correlator == null) { + return false; + } + + content = content.replace("((CORRELATOR))", correlator); + + System.out.println("Injecting " + messageType + " message"); + WorkflowMessageResource workflowMessageResource = new WorkflowMessageResource(); + workflowMessageResource.setProcessEngineServices4junit(processEngineRule); + Response response = workflowMessageResource.deliver(messageType, correlator, content); + System.out.println("Workflow response to " + messageType + " message: " + response); + return true; + } + + /** + * Wait for the process to end. + * @param businessKey the process business key + * @param timeout the amount of time to wait, in milliseconds + */ + public void waitForProcessEnd(String businessKey, long timeout) { + System.out.println("Waiting " + timeout + "ms for process with business key " + + businessKey + " to end"); + + long now = System.currentTimeMillis() + timeout; + long endTime = now + timeout; + + while (now <= endTime) { + if (isProcessEnded(businessKey)) { + System.out.println("Process with business key " + businessKey + " has ended"); + return; + } + + try { + Thread.sleep(200); + } catch (InterruptedException e) { + String msg = "Interrupted waiting for process with business key " + + businessKey + " to end"; + System.out.println(msg); + fail(msg); + } + + now = System.currentTimeMillis(); + } + + String msg = "Process with business key " + businessKey + + " did not end within " + timeout + "ms"; + System.out.println(msg); + fail(msg); + } + + /** + * Verifies that the specified historic process variable has the specified value. + * If the variable does not have the specified value, the test is failed. + * @param businessKey the process business key + * @param variable the variable name + * @param value the expected variable value + */ + public void checkVariable(String businessKey, String variable, Object value) { + if (!isProcessEnded(businessKey)) { + fail("Cannot get historic variable " + variable + " because process with business key " + + businessKey + " has not ended"); + } + + Object variableValue = getVariableFromHistory(businessKey, variable); + assertEquals(value, variableValue); + } + + /** + * Checks to see if the specified process is ended. + * @param businessKey the process business Key + * @return true if the process is ended + */ + protected boolean isProcessEnded(String businessKey) { + HistoricProcessInstance processInstance = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); + return processInstance != null && processInstance.getEndTime() != null; + } + + /** + * Gets a variable value from a historical process instance. + * @param businessKey the process business key + * @param variableName the variable name + * @return the variable value, or null if the variable could not be + * obtained + */ + public Object getVariableFromHistory(String businessKey, String variableName) { + try { + HistoricProcessInstance processInstance = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult(); + + if (processInstance == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from historical process with business key " + businessKey + ": " + e); + return null; + } + } + + /** + * Gets the value of a subflow variable from the specified subflow's + * historical process instance. + * + * @param subflowName - the name of the subflow that contains the variable + * @param variableName the variable name + * + * @return the variable value, or null if the variable could not be obtained + * + */ + protected Object getVariableFromSubflowHistory(String subflowName, String variableName) { + try { + List<HistoricProcessInstance> processInstanceList = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); + + Collections.sort(processInstanceList, new Comparator<HistoricProcessInstance>() { + public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { + return m1.getStartTime().compareTo(m2.getStartTime()); + } + }); + + HistoricProcessInstance processInstance = processInstanceList.get(0); + + if (processInstanceList == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from sub flow: " + subflowName + ", Exception is: " + e); + return null; + } + } + + /** + * Gets the value of a subflow variable from the subflow's + * historical process x instance. + * + * @param subflowName - the name of the subflow that contains the variable + * @param variableName the variable name + * @param subflowInstanceIndex - the instance of the subflow (use when same subflow is called more than once from mainflow) + * + * @return the variable value, or null if the variable could not be obtained + */ + protected Object getVariableFromSubflowHistory(int subflowInstanceIndex, String subflowName, String variableName) { + try { + List<HistoricProcessInstance> processInstanceList = processEngineRule.getHistoryService() + .createHistoricProcessInstanceQuery().processDefinitionName(subflowName).list(); + + Collections.sort(processInstanceList, new Comparator<HistoricProcessInstance>() { + public int compare(HistoricProcessInstance m1, HistoricProcessInstance m2) { + return m1.getStartTime().compareTo(m2.getStartTime()); + } + }); + + HistoricProcessInstance processInstance = processInstanceList.get(subflowInstanceIndex); + + if (processInstanceList == null) { + return null; + } + + HistoricVariableInstance v = processEngineRule.getHistoryService() + .createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()) + .variableName(variableName).singleResult(); + return v == null ? null : v.getValue(); + } catch (Exception e) { + System.out.println("Error retrieving variable " + variableName + + " from " + subflowInstanceIndex + " instance index of sub flow: " + subflowName + ", Exception is: " + e); + return null; + } + } + + + /** + * Extracts text from an XML element. This method is not namespace aware + * (namespaces are ignored). The first matching element is selected. + * @param xml the XML document or fragment + * @param tag the desired element, e.g. "<name>" + * @return the element text, or null if the element was not found + */ + protected String getXMLTextElement(String xml, String tag) { + xml = removeXMLNamespaces(xml); + + if (!tag.startsWith("<")) { + tag = "<" + tag + ">"; + } + + int start = xml.indexOf(tag); + + if (start == -1) { + return null; + } + + int end = xml.indexOf('<', start + tag.length()); + + if (end == -1) { + return null; + } + + return xml.substring(start + tag.length(), end); + } + + /** + * Removes namespace definitions and prefixes from XML, if any. + */ + private String removeXMLNamespaces(String xml) { + // remove xmlns declaration + xml = xml.replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""); + + // remove opening tag prefix + xml = xml.replaceAll("(<)(\\w+:)(.*?>)", "$1$3"); + + // remove closing tags prefix + xml = xml.replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); + + // remove extra spaces left when xmlns declarations are removed + xml = xml.replaceAll("\\s+>", ">"); + + return xml; + } + + /** + * Asserts that two XML documents are semantically equivalent. Differences + * in whitespace or in namespace usage do not affect the comparison. + * @param expected the expected XML + * @param actual the XML to test + * @throws SAXException + * @throws IOException + */ + public static void assertXMLEquals(String expected, String actual) + throws SAXException, IOException { + XMLUnit.setIgnoreWhitespace(true); + XMLUnit.setIgnoreAttributeOrder(true); + DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expected, actual)); + List<?> allDifferences = diff.getAllDifferences(); + assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size()); + } + + /** + * A test implementation of AsynchronousResponse. + */ + public class TestAsyncResponse implements AsynchronousResponse { + Response response = null; + + /** + * {@inheritDoc} + */ + @Override + public synchronized void setResponse(Response response) { + this.response = response; + } + + /** + * Gets the response. + * @return the response, or null if none has been produced yet + */ + public synchronized Response getResponse() { + return response; + } + } + + /** + * An object that contains callback data for a "program". + */ + public class CallbackSet { + private final Map<String, String> map = new HashMap<String, String>(); + + /** + * Add callback data to the set. + * @param action the action with which the data is associated + * @param content the callback data + */ + public void put(String action, String content) { + map.put(action, content); + } + + /** + * Retrieve callback data from the set. + * @param action the action with which the data is associated + * @return the callback data, or null if there is none for the specified operation + */ + public String get(String action) { + return map.get(action); + } + } + + /** + * A tool for evaluating XPath expressions. + */ + protected class XPathTool { + private final DocumentBuilderFactory factory; + private final SimpleNamespaceContext context = new SimpleNamespaceContext(); + private final XPath xpath = XPathFactory.newInstance().newXPath(); + private String xml = null; + private Document doc = null; + + /** + * Constructor. + */ + public XPathTool() { + factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + xpath.setNamespaceContext(context); + } + + /** + * Adds a namespace. + * @param prefix the namespace prefix + * @param uri the namespace uri + */ + public synchronized void addNamespace(String prefix, String uri) { + context.add(prefix, uri); + } + + /** + * Sets the XML content to be operated on. + * @param xml the XML content + */ + public synchronized void setXML(String xml) { + this.xml = xml; + this.doc = null; + } + + /** + * Returns the document object. + * @return the document object, or null if XML has not been set + * @throws SAXException + * @throws IOException + * @throws ParserConfigurationException + */ + public synchronized Document getDocument() + throws ParserConfigurationException, IOException, SAXException { + if (xml == null) { + return null; + } + + buildDocument(); + return doc; + } + + /** + * Evaluates the specified XPath expression and returns a string result. + * This method throws exceptions on error. + * @param expression the expression + * @return the result object + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws XPathExpressionException on error + */ + public synchronized String evaluate(String expression) + throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException { + return (String) evaluate(expression, XPathConstants.STRING); + } + + /** + * Evaluates the specified XPath expression. + * This method throws exceptions on error. + * @param expression the expression + * @param returnType the return type + * @return the result object + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws XPathExpressionException on error + */ + public synchronized Object evaluate(String expression, QName returnType) + throws ParserConfigurationException, SAXException, + IOException, XPathExpressionException { + + buildDocument(); + XPathExpression expr = xpath.compile(expression); + return expr.evaluate(doc, returnType); + } + + /** + * Private helper method that builds the document object. + * Assumes the calling method is synchronized. + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void buildDocument() throws ParserConfigurationException, + IOException, SAXException { + if (doc == null) { + if (xml == null) { + throw new IOException("XML input is null"); + } + + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource source = new InputSource(new StringReader(xml)); + doc = builder.parse(source); + } + } + } + + /** + * A NamespaceContext class based on a Map. + */ + private class SimpleNamespaceContext implements NamespaceContext { + private Map<String, String> prefixMap = new HashMap<String, String>(); + private Map<String, String> uriMap = new HashMap<String, String>(); + + public synchronized void add(String prefix, String uri) { + prefixMap.put(prefix, uri); + uriMap.put(uri, prefix); + } + + @Override + public synchronized String getNamespaceURI(String prefix) { + return prefixMap.get(prefix); + } + + @Override + public Iterator<String> getPrefixes(String uri) { + List<String> list = new ArrayList<String>(); + String prefix = uriMap.get(uri); + if (prefix != null) { + list.add(prefix); + } + return list.iterator(); + } + + @Override + public String getPrefix(String uri) { + return uriMap.get(uri); + } + } + + /** + * A VnfNotify XPathTool. + */ + protected class VnfNotifyXPathTool extends XPathTool { + public VnfNotifyXPathTool() { + addNamespace("tns", "http://org.openecomp.mso/vnfNotify"); + } + } + + /** + * Helper class to make it easier to create this type. + */ + private static class CreateVnfNotificationOutputs + extends org.openecomp.mso.bpmn.common.adapter.vnf.CreateVnfNotification.Outputs { + public void add(String key, String value) { + Entry entry = new Entry(); + entry.setKey(key); + entry.setValue(value); + getEntry().add(entry); + } + } + + /** + * Helper class to make it easier to create this type. + */ + private static class UpdateVnfNotificationOutputs + extends org.openecomp.mso.bpmn.common.adapter.vnf.UpdateVnfNotification.Outputs { + public void add(String key, String value) { + Entry entry = new Entry(); + entry.setKey(key); + entry.setValue(value); + getEntry().add(entry); + } + } +} diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java new file mode 100644 index 0000000000..4aa6fbe0bb --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTestTransformer.java @@ -0,0 +1,21 @@ +package org.openecomp.mso.bpmn.common; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Allows a subclass of WorkflowTest to specify one or more WireMock + * response transformers. A transformer must be declared as a public + * static field in the subclass. For example: + * <pre> + * @WorkflowTestTransformer + * public static final ResponseTransformer sdncAdapterMockTransformer = + * new SDNCAdapterMockTransformer(); + * </pre> + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface WorkflowTestTransformer { +}
\ No newline at end of file |