From e601bbdc43bae9a08e2e10c5139a6f76b47860d7 Mon Sep 17 00:00:00 2001 From: Einat Vinouze Date: Tue, 16 Jul 2019 17:17:36 +0300 Subject: Implant vid-app-common org.onap.vid.job (main and test) Issue-ID: VID-378 Change-Id: I41b0bdc2c4e3635f3f3319b1cd63cefc61912dfc Signed-off-by: Einat Vinouze Signed-off-by: Ittay Stern --- .../org/onap/vid/job/command/CommandUtilsTest.java | 4 +- .../job/command/InProgressStatusServiceTest.java | 83 +- .../vid/job/command/InstanceGroupCommandTest.java | 71 +- .../vid/job/command/JobCommandFactoryTest.java | 8 +- .../vid/job/command/MacroServiceCommandTest.java | 136 +++ .../job/command/MsoResultHandlerServiceTest.java | 95 ++ .../onap/vid/job/command/ResourceCommandTest.java | 258 ++++- .../ResourceInProgressStatusCommandTest.java | 60 -- .../ServiceInProgressStatusCommandTest.java | 157 ++- .../vid/job/command/WatchChildrenJobsBLTest.java | 6 +- .../onap/vid/job/command/WatchingCommandTest.java | 97 -- .../impl/AsyncInstantiationIntegrationTest.java | 1020 +++++++++++++------- .../DeleteOldJobsSchedulerInitializerTest.java | 55 ++ .../onap/vid/job/impl/DeleteOldJobsWorkerTest.java | 43 + .../java/org/onap/vid/job/impl/JobAdapterTest.java | 43 +- .../java/org/onap/vid/job/impl/JobWorkerTest.java | 13 +- 16 files changed, 1437 insertions(+), 712 deletions(-) create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java (limited to 'vid-app-common/src/test/java/org/onap/vid/job') diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java index da300bf3e..ee43d1f72 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java @@ -7,9 +7,9 @@ * 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. diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java index c8772ee76..125d2ed4c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,8 +20,10 @@ package org.onap.vid.job.command; +import org.jetbrains.annotations.NotNull; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.vid.job.Job; import org.onap.vid.job.impl.JobSharedData; @@ -29,11 +31,16 @@ import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.rest.AsyncRequestStatus; -import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.properties.Features; import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.UUID; import java.util.stream.Stream; @@ -51,6 +58,12 @@ public class InProgressStatusServiceTest { @Mock private AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Mock + private AuditService auditService; + + @Mock + private FeatureManager featureManager; + @InjectMocks private InProgressStatusService inProgressStatusService; @@ -59,10 +72,16 @@ public class InProgressStatusServiceTest { MockitoAnnotations.initMocks(this); } + @BeforeMethod + public void resetMocks() { + Mockito.reset(restMso); + Mockito.reset(asyncInstantiationBL); + } + @DataProvider public static Object[][] jobStatuses() { return Stream.of(Job.JobStatus.values()) - .map(student -> new Object[] { student }) + .map(status -> new Object[] { status }) .toArray(Object[][]::new); } @@ -71,16 +90,14 @@ public class InProgressStatusServiceTest { UUID jobUuid = UUID.randomUUID(); String userId = "mockedUserID"; + String testApi = "mockedTestApi"; String requestId = UUID.randomUUID().toString(); ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(""); - RestObject msoResponse = mock(RestObject.class); AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse(""); - - when(msoResponse.getStatusCode()).thenReturn(200); - when(msoResponse.get()).thenReturn(requestStatus); + RestObject msoResponse = createMockedAsyncRequestStatus(requestStatus, 200); when(restMso.GetForObject(contains(requestId), eq(AsyncRequestStatus.class))).thenReturn(msoResponse); when(asyncInstantiationBL.calcStatus(any())).thenReturn(expectedJobStatus); @@ -88,16 +105,60 @@ public class InProgressStatusServiceTest { ExpiryChecker expiryChecker = mock(ExpiryChecker.class); when(expiryChecker.isExpired(any())).thenReturn(false); - JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation); + JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation, testApi); Job.JobStatus actualJobStatus = inProgressStatusService.call(expiryChecker, sharedData, requestId); assertEquals(expectedJobStatus, actualJobStatus); - verify(asyncInstantiationBL).auditMsoStatus(eq(jobUuid), same(requestStatus.request)); - + verify(auditService).auditMsoStatus(eq(jobUuid), same(requestStatus.request)); + verify(asyncInstantiationBL).updateResourceInfo(eq(sharedData), eq(expectedJobStatus), eq(requestStatus)); //verify we don't update service info during this case, which shall stay in_progress verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); + } + + @NotNull + protected RestObject createMockedAsyncRequestStatus(AsyncRequestStatus requestStatus, int statusCode) { + RestObject msoResponse = mock(RestObject.class); + when(msoResponse.getStatusCode()).thenReturn(statusCode); + when(msoResponse.get()).thenReturn(requestStatus); + return msoResponse; + } + + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void whenGetAsyncRequestStatus_thenRightResponseReturned(boolean isResumeFlagActive) { + String requestId = "abcRequest"; + String baseMso = "/fakeBase/v15"; + + when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(baseMso); + when(featureManager.isActive(Features.FLAG_1908_RESUME_MACRO_SERVICE)).thenReturn(isResumeFlagActive); + + AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse(""); + RestObject mockedResponse = createMockedAsyncRequestStatus(requestStatus, 399); + String path = baseMso + "/" + requestId + (isResumeFlagActive ? "?format=detail" : ""); + when(restMso.GetForObject(eq(path), eq(AsyncRequestStatus.class))).thenReturn(mockedResponse); + + assertEquals(mockedResponse, inProgressStatusService.getAsyncRequestStatus(requestId)); + } + + @DataProvider + public static Object[][] getAsyncReturnErrorDataProvider() { + return new Object[][]{ + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 400}, + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 401}, + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 500}, + {null, 200}, + }; + } + + @Test(dataProvider = "getAsyncReturnErrorDataProvider", expectedExceptions = InProgressStatusService.BadResponseFromMso.class) + public void whenGetAsyncReturnError_thenExceptionIsThrown(AsyncRequestStatus requestStatus, int statusCode) { + String requestId = "abcRequest"; + String baseMso = "/fakeBase/v15"; + when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(baseMso); + RestObject mockedResponse = createMockedAsyncRequestStatus(requestStatus, statusCode); + when(restMso.GetForObject(eq(baseMso + "/" + requestId), eq(AsyncRequestStatus.class))).thenReturn(mockedResponse); + inProgressStatusService.getAsyncRequestStatus(requestId); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java index b4a5c64f5..c68c5f754 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,29 +20,35 @@ package org.onap.vid.job.command; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.only; -import static org.mockito.Mockito.same; -import static org.mockito.Mockito.verify; - import com.google.common.collect.ImmutableMap; -import java.util.Optional; +import org.apache.commons.beanutils.BeanUtils; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.model.serviceInstantiation.InstanceGroup; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.testUtils.TestUtils; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.util.Optional; +import java.util.Set; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + public class InstanceGroupCommandTest { @Mock(answer = Answers.RETURNS_MOCKS) @@ -53,11 +59,20 @@ public class InstanceGroupCommandTest { @Mock(answer = Answers.RETURNS_MOCKS) MsoResultHandlerService msoResultHandlerService; + @Mock(answer = Answers.RETURNS_MOCKS) + MsoRequestBuilder msoRequestBuilder; + @Mock WatchChildrenJobsBL watchChildrenJobsBL; @Mock(answer = Answers.RETURNS_MOCKS) AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Mock(answer = Answers.RETURNS_MOCKS) + JobsBrokerService jobsBrokerService; + + @Mock(answer = Answers.RETURNS_MOCKS) + JobAdapter jobAdapter; + @Mock InProgressStatusService inProgressStatusService; @InjectMocks @@ -68,29 +83,41 @@ public class InstanceGroupCommandTest { command = null; MockitoAnnotations.initMocks(this); } - - @Test - public void createMyself_callsMso() { - final ModelInfo serviceModelInfo = setStrings(new ModelInfo()); + @DataProvider + public static Object[][] testApis() { + return new Object[][]{ + {"VNF_API"}, {null}}; + } + @Test(dataProvider = "testApis") + public void createMyself_callsMso(String testApi) { + final ModelInfo serviceModelInfo = setRandomStrings(new ModelInfo()); final String serviceInstanceId = "service-instance-id"; final String userId = "ff3223"; - command.init(new JobSharedData( - null, userId, instanceGroupRequest - ), ImmutableMap.of( + when(instanceGroupRequest.getAction()).thenReturn(Action.Delete); + + JobSharedData sharedData = new JobSharedData( + null, userId, instanceGroupRequest, testApi); + command.init(sharedData, ImmutableMap.of( "resourceModelInfos", ImmutableMap.of("SERVICE_MODEL_INFO", serviceModelInfo), "resourceInstancesIds", ImmutableMap.of("SERVICE_INSTANCE_ID", serviceInstanceId) )); command.createMyself(); - verify(asyncInstantiationBL).generateInstanceGroupInstantiationRequest( - same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId)); + verify(msoRequestBuilder).generateInstanceGroupInstantiationRequest( + same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId), eq(testApi)); verify(restMso, only()).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty())); - } - private ModelInfo setStrings(ModelInfo object) { - return TestUtils.setStringsInStringProperties(object); + private ModelInfo setRandomStrings(ModelInfo object) { + try { + Set fields = BeanUtils.describe(object).keySet(); + BeanUtils.populate(object, + fields.stream().collect(toMap(identity(), s -> randomAlphanumeric(4)))); + return object; + } catch (Exception e) { + throw new RuntimeException(e); + } } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java index d7389ad0a..72336e5a9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java @@ -7,9 +7,9 @@ * 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. @@ -105,7 +105,7 @@ public class JobCommandFactoryTest { final UUID uuid = UUID.randomUUID(); final Map data = ImmutableMap.of("foo", "bar"); - final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a")); + final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a"), "testApi"); when(job.getType()).thenReturn(jobType); when(job.getUuid()).thenReturn(uuid); @@ -119,4 +119,4 @@ public class JobCommandFactoryTest { assertThat(command, equalTo(mockCommand)); } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java new file mode 100644 index 000000000..e4771611c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.command; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.model.VidNotions.ModelCategory.INFRASTRUCTURE_VPN; +import static org.onap.vid.model.VidNotions.ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL; +import static org.onap.vid.model.VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL; +import static org.onap.vid.model.VidNotions.ModelCategory.OTHER; +import static org.onap.vid.model.VidNotions.ModelCategory.SERVICE_WITH_COLLECTION_RESOURCE; +import static org.onap.vid.model.VidNotions.ModelCategory.Transport; +import static org.testng.AssertJUnit.assertEquals; + +import com.google.common.collect.ImmutableList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class MacroServiceCommandTest { + + @Mock + private InProgressStatusService inProgressStatusService; + + @Mock + private WatchChildrenJobsBL watchChildrenJobsB; + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Mock + private JobsBrokerService jobsBrokerService; + + @Mock + private MsoRequestBuilder msoRequestBuilder; + + @Mock + private MsoResultHandlerService msoResultHandlerService; + + @Mock + private JobAdapter jobAdapter; + + @Mock + private RestMsoImplementation restMso; + + @Mock + private AuditService auditService; + + @InjectMocks + private MacroServiceCommand macroServiceCommand; + + @DataProvider + public static Object[][] modelCategoryPre1806DataProvider() { + return new Object[][]{ + {IS_5G_PROVIDER_NETWORK_MODEL, false}, + {IS_5G_FABRIC_CONFIGURATION_MODEL, false}, + {Transport, true}, + {SERVICE_WITH_COLLECTION_RESOURCE, true}, + {INFRASTRUCTURE_VPN, true}, + {OTHER, false}, + }; + } + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test(dataProvider = "modelCategoryPre1806DataProvider") + public void testShouldUsePre1806Request(VidNotions.ModelCategory modelCategory, boolean expectedResult) { + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + VidNotions vidNotions = mock(VidNotions.class); + when(serviceInstantiation.getVidNotions()).thenReturn(vidNotions); + when(vidNotions.getModelCategory()).thenReturn(modelCategory); + assertEquals(macroServiceCommand.shouldUsePre1806Request(serviceInstantiation), expectedResult); + } + + @DataProvider + public static Object[][] MsoFilteredRequestsDataProvider() { + return new Object[][]{ + {Collections.EMPTY_LIST}, + {ImmutableList.of(new AsyncRequestStatus.Request())} + }; + } + + @Test(dataProvider = "MsoFilteredRequestsDataProvider") + public void givenResumeAction_whenCantRetrieveRequestIdFromMSO_thenJobIsFailed(List requests) { + String instanceId = UUID.randomUUID().toString(); + BaseResource baseResource = mock(BaseResource.class); + when(baseResource.getInstanceId()).thenReturn(instanceId); + when(baseResource.getAction()).thenReturn(Action.Resume); + macroServiceCommand.init(new JobSharedData(null, null, baseResource, null)); + when(auditService.retrieveRequestsFromMsoByServiceIdAndRequestTypeAndScope(eq(instanceId), any(), any())) + .thenReturn(requests); + assertEquals(macroServiceCommand.resumeMyself(), Job.JobStatus.FAILED); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java new file mode 100644 index 000000000..5f958016b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.command; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.onap.vid.job.impl.AsyncInstantiationIntegrationTest.createResponse; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.UUID; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.RestObject; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class MsoResultHandlerServiceTest { + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; + + @Mock + private AuditService auditService; + + @InjectMocks + private MsoResultHandlerService underTest; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @DataProvider + public static Object[][] okStatusCodes() { + return new Object[][]{ + {200}, {202} , {300}, {399} + }; + } + + @Test(dataProvider = "okStatusCodes") + public void whenOkResponseFromMso_getResultsWithIdsAndCompleteWithNoAction(int statusCode) { + String instanceId = UUID.randomUUID().toString(); + String requestId = UUID.randomUUID().toString(); + JobSharedData sharedData = new JobSharedData(); + RestObject msoResponse = createResponse(statusCode, instanceId, requestId); + MsoResult expectedResult = new MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, new MsoResourceIds(requestId, instanceId)); + MsoResult actualMsoResult = underTest.handleResponse(sharedData, msoResponse, "test desc"); + assertEquals(expectedResult, actualMsoResult); + verify(asyncInstantiationBusinessLogic).addResourceInfo(eq(sharedData), eq(Job.JobStatus.IN_PROGRESS), eq(instanceId)); + } + + @DataProvider + public static Object[][] notOkStatusCodes() { + return new Object[][]{ + {199}, {400} , {404}, {500} + }; + } + + @Test(dataProvider = "notOkStatusCodes") + public void whenNotOkFromMso_getResultsWithFailedStatus(int statusCode) { + Mockito.reset(asyncInstantiationBusinessLogic); + JobSharedData sharedData = new JobSharedData(); + RestObject msoResponse = createResponse(statusCode); + MsoResult expectedResult = new MsoResult(Job.JobStatus.FAILED); + MsoResult actualMsoResult = underTest.handleResponse(new JobSharedData(), msoResponse, "test desc"); + assertEquals(expectedResult, actualMsoResult); + verify(asyncInstantiationBusinessLogic).addFailedResourceInfo(eq(sharedData), eq(msoResponse)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java index 9f252c5e8..2780e1515 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,29 +20,38 @@ package org.onap.vid.job.command; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.jetbrains.annotations.NotNull; +import org.onap.vid.exceptions.AbortingException; import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.TryAgainException; import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.NextCommand; import org.onap.vid.job.impl.JobSharedData; import org.onap.vid.model.Action; -import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.*; import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.model.ModelInfo; import org.springframework.http.HttpMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import javax.ws.rs.ProcessingException; -import java.util.Collections; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; import java.util.stream.Stream; +import static java.util.Collections.emptyList; +import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE; import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE; +import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.*; +import static org.onap.vid.model.Action.*; import static org.onap.vid.utils.Logging.getMethodCallerName; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; @@ -54,18 +63,32 @@ public class ResourceCommandTest { public static class MockCommand extends ResourceCommand { public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus) { - super(mock(RestMsoImplementation.class, RETURNS_MOCKS), mock(InProgressStatusService.class), mock(MsoResultHandlerService.class, RETURNS_MOCKS), mock(WatchChildrenJobsBL.class)); + this(mockState, mockPhase, mockedJobStatus, false); + } + public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean lateInit) { + super( + mock(RestMsoImplementation.class, RETURNS_MOCKS), + mock(InProgressStatusService.class), + mock(MsoResultHandlerService.class, RETURNS_MOCKS), + mock(WatchChildrenJobsBL.class), + mock(JobsBrokerService.class, RETURNS_MOCKS), + mock(JobAdapter.class, RETURNS_MOCKS)); this.mockedJobStatus = mockedJobStatus; this.mockState = mockState; this.mockPhase = mockPhase; - if (mockState==InternalState.INITIAL) { - init(mock(JobSharedData.class), Collections.emptyMap()); + if (!lateInit) { + init(); } - else { + when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus); + } + + protected void init() { + if (mockState == InternalState.INITIAL) { + init(mock(JobSharedData.class), Collections.emptyMap()); + } else { init(mock(JobSharedData.class), ImmutableMap.of(INTERNAL_STATE, mockState.name(), ACTION_PHASE, mockPhase.name())); } - when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus); } private final Job.JobStatus mockedJobStatus; @@ -76,7 +99,7 @@ public class ResourceCommandTest { @NotNull @Override public Job.JobStatus createChildren() { - if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Action.Delete)) + if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Delete)) return mockedJobStatus; throw (new RuntimeException("Not expected to call "+getMethodCallerName())); } @@ -95,7 +118,7 @@ public class ResourceCommandTest { @NotNull @Override - public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) { + public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId, String testApi) { return mockedPlanOrThrow(InternalState.CREATE_MYSELF); } @@ -109,16 +132,19 @@ public class ResourceCommandTest { public static class MockCommandTestingStateMachine extends MockCommand { private final JobSharedData sharedData; + private final boolean isDescendantHasAction; public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf) { - this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false); + this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false, true); } - public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService) { - super(mockState, mockPhase, mockedJobStatus); + public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService, boolean isDescendantHasAction) { + super(mockState, mockPhase, mockedJobStatus, true); this.mockedNeedToDeleteMySelf = mockedNeedToDeleteMySelf; this.isService = isService; this.sharedData = mock(JobSharedData.class, RETURNS_MOCKS); + this.isDescendantHasAction = isDescendantHasAction; + init(); } protected final boolean mockedNeedToDeleteMySelf; @@ -150,6 +176,11 @@ public class ResourceCommandTest { public JobSharedData getSharedData() { return sharedData; } + + @Override + protected boolean isDescendantHasAction(@NotNull Action phase) { + return isDescendantHasAction; + } } @DataProvider @@ -171,28 +202,28 @@ public class ResourceCommandTest { InternalState internalState, Job.JobStatus jobStatus, InternalState expectedState) { //there is no meaning to the constructor inputs here - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.FAILED, true); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Delete, Job.JobStatus.FAILED, true); assertEquals(expectedState, underTest.calcNextStateDeletePhase(jobStatus, internalState)); } @Test public void whenNoNeedToDeleteMyself_internalStateMovesFromWatchingToTerminal() { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED, false); assertEquals(InternalState.TERMINAL, underTest.calcNextStateDeletePhase(Job.JobStatus.COMPLETED, InternalState.WATCHING)); } @DataProvider public static Object[][] testShallStopJobDataProvider() { return new Object[][]{ - {Job.JobStatus.IN_PROGRESS, Action.None, false, false}, - {Job.JobStatus.COMPLETED_WITH_NO_ACTION, Action.None, false, false}, - {Job.JobStatus.COMPLETED, Action.None, false, false}, - {Job.JobStatus.FAILED, Action.None, false, true}, - {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, false, true}, - {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, true, false}, - {Job.JobStatus.FAILED, Action.None, true, false}, - {Job.JobStatus.FAILED, Action.Delete, true, true}, - {Job.JobStatus.FAILED, Action.Create, true, true}, + {Job.JobStatus.IN_PROGRESS, None, false, false}, + {Job.JobStatus.COMPLETED_WITH_NO_ACTION, None, false, false}, + {Job.JobStatus.COMPLETED, None, false, false}, + {Job.JobStatus.FAILED, None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, None, true, false}, + {Job.JobStatus.FAILED, None, true, false}, + {Job.JobStatus.FAILED, Delete, true, true}, + {Job.JobStatus.FAILED, Create, true, true}, }; } @@ -200,7 +231,7 @@ public class ResourceCommandTest { @Test(dataProvider = "testShallStopJobDataProvider") public void testShallStopJob(Job.JobStatus jobStatus, Action action, boolean isService, boolean expectedResult) { //in this test, there is no meaning to constructor parameters besides isService - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false, isService); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED, false, isService, true); BaseResource mockedRequest = mock(BaseResource.class); when(underTest.getSharedData().getRequest()).thenReturn(mockedRequest); @@ -209,6 +240,94 @@ public class ResourceCommandTest { assertEquals(expectedResult, underTest.shallStopJob(jobStatus)); } + public static class FakeResourceCreator { + + public static Map convertToMap(List list) { + if (list==null) { + return null; + } + return list.stream().collect(Collectors.toMap(x-> UUID.randomUUID().toString(), x->x)); + } + + static ServiceInstantiation createService(List vnfs, List networks, List vnfGroups) { + return new ServiceInstantiation(mock(ModelInfo.class), null, null, null, null, null, null, null, null, null, null, null, null, null, null, + convertToMap(vnfs), + convertToMap(networks), + convertToMap(vnfGroups), + null, + null, false, 1, false,false,null, null, null, null, null, null, null); + } + + public static ServiceInstantiation createServiceWith2InstancesInEachLevel(Action action) { + return createService( + ImmutableList.of( + createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action), + createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action)), + ImmutableList.of( + createNetwork(action), + createNetwork(action)), + ImmutableList.of( + createGroup(ImmutableList.of(createMember(action), createMember(action)), action), + createGroup(ImmutableList.of(createMember(action), createMember(action)), action)) + ); + } + + static InstanceGroup createGroup(List groupMembers, Action action) { + return new InstanceGroup(mock(ModelInfo.class), null, action.name(), false, null, convertToMap(groupMembers), null, null, null); + } + + static InstanceGroupMember createMember(Action action) { + return new InstanceGroupMember(null, action.toString(), null, null, null); + } + + static Vnf createVnf(List vfModules, Action action) { + Map> vfModulesMap = new HashMap<>(); + vfModulesMap.put("abc",convertToMap(vfModules)); + + return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, vfModulesMap, null, null, null); + } + + static Vnf createVnf(Action action) { + return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null,null, null, null, null); + } + + static VfModule createVfModule(Action action) { + return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, false, false, null, null, null, null); + } + + static Network createNetwork(Action action) { + return new Network(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, null, null, null); + } + } + + @DataProvider + public static Object[][] testIsDescendantHasActionDataProvider() { + return new Object[][]{ + {"empty service", Create, false, createService(emptyList(), emptyList(), emptyList())}, + {"instance group with None", Create, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), None)))}, + {"instance group with Create", Create, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), Create)))}, + {"instance group None + member Delete", Delete, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Delete)), None)))}, + {"instance group None + member Create", Delete, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create)), None)))}, + {"instance group None + member Create + member Delete", Delete, true, + createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create), createMember(Delete)), None)))}, + {"vnf Create", Delete, false, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())}, + {"vnf Create", Create, true, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())}, + {"vnf Create null VfModules internal map", Create, false, createService(ImmutableList.of(createVnf(null, Delete)), emptyList(),emptyList())}, + {"vnf Delete with null VfModules", Create, false, createService(ImmutableList.of(createVnf(Delete)), emptyList(),emptyList())}, + {"vnf None + VfModule Create", Create, true, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(Create)), None)), emptyList(),emptyList())}, + {"vnf None + VfModule None", Create, false, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(None)), None)), emptyList(),emptyList())}, + {"network Create", Create, true, createService(emptyList(), ImmutableList.of(createNetwork(Create)), emptyList())}, + {"network Delete", Create, false, createService(emptyList(), ImmutableList.of(createNetwork(Delete)), emptyList())}, + }; + } + + @Test(dataProvider = "testIsDescendantHasActionDataProvider") + public void testIsDescendantHasAction(String desc, Action action, boolean expectedResult, BaseResource request) { + //in this test, there is no meaning to constructor parameters + MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED); + assertEquals(expectedResult, underTest.isDescendantHasAction(request, action)); + } + @DataProvider public static Object[][] testCallDataProvider() { return new Object[][]{ @@ -235,7 +354,7 @@ public class ResourceCommandTest { String description, InternalState internalState, Job.JobStatus currentStateResult, InternalState expectedNextState, Job.JobStatus expectedNextStatus) { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Action.Delete, currentStateResult, true); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Delete, currentStateResult, true); NextCommand nextCommand = underTest.call(); assertEquals(expectedNextStatus, nextCommand.getStatus()); @@ -250,12 +369,6 @@ public class ResourceCommandTest { } } - @Test(expectedExceptions = IllegalStateException.class) - public void whenCommandInUnMappedState_exceptionIsThrown() { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.COMPLETED, true); - underTest.call(); - } - @DataProvider public static Object[][] InProgressDataProvider() { return Stream.of(Job.JobStatus.values()) @@ -266,7 +379,7 @@ public class ResourceCommandTest { @Test(dataProvider = "InProgressDataProvider") public void whenGetResultFromMso_InProgressReturnThem(Job.JobStatus mockedJobStatus) { Job.JobStatus expectedJobStatus = (mockedJobStatus== Job.JobStatus.PAUSE) ? Job.JobStatus.IN_PROGRESS : mockedJobStatus; - MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, mockedJobStatus); + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, mockedJobStatus); when(underTest.getInProgressStatusService().call(any(), any(), any())).thenReturn(mockedJobStatus); assertEquals(expectedJobStatus, underTest.inProgress()); } @@ -282,22 +395,22 @@ public class ResourceCommandTest { @Test(dataProvider = "InProgressExceptionsDataProvider") public void whenInProgressStatusServiceThrowException_InProgressReturnStatus(Exception exception, Job.JobStatus expectedJobStatus) { - MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, expectedJobStatus); + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, expectedJobStatus); when(underTest.getInProgressStatusService().call(any(), any(), any())).thenThrow(exception); assertEquals(expectedJobStatus, underTest.inProgress()); } @DataProvider public static Object[][] testIsNeedToDeleteMySelfDataProvider() { - return Stream.of(Action.values()) + return Stream.of(values()) .map(status -> new Object[] { status }) .toArray(Object[][]::new); } @Test(dataProvider = "testIsNeedToDeleteMySelfDataProvider") public void testIsNeedToDeleteMySelf(Action action) { - boolean expectedResult = (action== Action.Delete); - MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Action.Delete, Job.JobStatus.IN_PROGRESS); + boolean expectedResult = (action== Delete); + MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Delete, Job.JobStatus.IN_PROGRESS); BaseResource mockedBaseResource = mock(BaseResource.class); when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource); when(mockedBaseResource.getAction()).thenReturn(action); @@ -315,9 +428,74 @@ public class ResourceCommandTest { @Test(dataProvider = "testWatchingDataProvider") public void testWatching(String desc, Job.JobStatus childrenJobsStatus, Job.JobStatus expectedJobStatus) { - MockCommand underTest = new MockCommand(InternalState.WATCHING, Action.Delete, Job.JobStatus.IN_PROGRESS); + MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, Job.JobStatus.IN_PROGRESS); when(underTest.getWatchChildrenJobsBL().retrieveChildrenJobsStatus(any())).thenReturn(childrenJobsStatus); assertEquals(expectedJobStatus, underTest.watchChildren()); } + @DataProvider + public static Object[][] testCalcInitialStateDataProvider() { + return new Object[][]{ + {Delete, true, Delete, InternalState.CREATING_CHILDREN}, + {Delete, false, Delete, InternalState.DELETE_MYSELF}, + {Delete, false, Create, InternalState.TERMINAL}, + {Delete, true, Create, InternalState.CREATING_CHILDREN}, + {Create, true, Create, InternalState.CREATE_MYSELF}, + {Create, false, Create, InternalState.CREATE_MYSELF}, + {Create, false, Delete, InternalState.TERMINAL}, + {Create, true, Delete, InternalState.CREATING_CHILDREN}, + {Create, true, Resume, InternalState.RESUME_MYSELF}, + {Delete, false, Resume, InternalState.TERMINAL}, + }; + } + + @Test(dataProvider = "testCalcInitialStateDataProvider") + public void testCalcInitialState(Action phase, boolean isDescendantHasAction, Action action, InternalState expectedState) { + ResourceCommand underTest = mock(ResourceCommand.class); + when(underTest.calcInitialState(any(), any())).thenCallRealMethod(); + when(underTest.isDescendantHasAction(eq(phase))).thenReturn(isDescendantHasAction); + when(underTest.getActionType()).thenReturn(action); + when(underTest.isNeedToDeleteMyself()).thenCallRealMethod(); + when(underTest.isNeedToCreateMyself()).thenCallRealMethod(); + when(underTest.isNeedToResumeMySelf()).thenCallRealMethod(); + + Map commandData = ImmutableMap.of(INTERNAL_STATE, InternalState.INITIAL.name()); + assertEquals(expectedState, underTest.calcInitialState(commandData, phase)); + } + + + //throw exception when call to create children + //create children is just example, it could be any other method that called by ResourceCommand.invokeCommand + public static class MockCommandThrowExceptionOnCreateChildren extends MockCommandTestingStateMachine { + + private final RuntimeException exceptionToThrow; + + public MockCommandThrowExceptionOnCreateChildren(RuntimeException exceptionToThrow) { + super(InternalState.CREATING_CHILDREN, Delete, Job.JobStatus.COMPLETED, true); + this.exceptionToThrow = exceptionToThrow; + doAnswer(returnsFirstArg()).when(this.getWatchChildrenJobsBL()).cumulateJobStatus(any(), any()); + } + + @NotNull + @Override + public Job.JobStatus createChildren() { + throw exceptionToThrow; + } + } + + @DataProvider + public static Object[][] exceptionAndStateProvider() { + return new Object[][]{ + {new TryAgainException(new Exception()), Job.JobStatus.RESOURCE_IN_PROGRESS}, + {new AbortingException(new Exception()), Job.JobStatus.FAILED}, + }; + } + + @Test(dataProvider = "exceptionAndStateProvider") + public void whenKnownExceptionThrownInCommandInvocation_thenStateIsAsExpected(RuntimeException exception, Job.JobStatus expectedNextStatus) { + MockCommandTestingStateMachine underTest = new MockCommandThrowExceptionOnCreateChildren(exception); + NextCommand nextCommand = underTest.call(); + assertEquals(expectedNextStatus, nextCommand.getStatus()); + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java deleted file mode 100644 index 5b036f587..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - -import org.mockito.InjectMocks; -import org.mockito.MockitoAnnotations; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - - -public class ResourceInProgressStatusCommandTest { - - @InjectMocks - private ResourceInProgressStatusCommand commandUnderTest = new ResourceInProgressStatusCommand(); - - @BeforeMethod - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @DataProvider - public static Object[][] givenStatusToExpectedStatus() { - return new Object[][]{ - {Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS}, - {Job.JobStatus.FAILED, Job.JobStatus.FAILED}, - {Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED} - }; - } - - @Test(dataProvider = "givenStatusToExpectedStatus") - public void whenGetStatusFromMso_returnExpectedNextCommand(Job.JobStatus jobStatus, Job.JobStatus expectedNextStatus) { - NextCommand nextCommand = commandUnderTest.processJobStatus(jobStatus); - assertThat(nextCommand.getStatus(), is(expectedNextStatus)); - assertThat(nextCommand.getCommand(), is(commandUnderTest)); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java index 31dbc9f6d..787ff608d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,22 +20,22 @@ package org.onap.vid.job.command; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.job.*; import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; import org.onap.vid.model.serviceInstantiation.Network; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.model.serviceInstantiation.Vnf; -import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.properties.Features; import org.onap.vid.properties.VidProperties; import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.springframework.core.env.Environment; +import org.onap.vid.services.AuditService; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -47,10 +47,9 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Arrays; -import java.util.Map; -import java.util.TreeMap; import java.util.UUID; +import static java.util.Collections.emptyList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.core.Is.is; @@ -58,7 +57,11 @@ import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.job.command.ResourceCommandKt.*; +import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.*; +import static org.onap.vid.model.Action.Create; import static org.onap.vid.testUtils.TestUtils.testWithSystemProperty; +import static org.testng.AssertJUnit.assertEquals; public class ServiceInProgressStatusCommandTest { @@ -78,45 +81,29 @@ public class ServiceInProgressStatusCommandTest { @Mock private JobSharedData sharedData; - @Mock - private Environment environment; - @Mock private ServiceInstantiation request; @Mock private InProgressStatusService inProgressStatusService; - @InjectMocks - private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand(); + @Mock + private WatchChildrenJobsBL watchChildrenJobsBL; - @DataProvider - public static Object[][] isNeedToCreateChildJobsDataProvider() { - return new Object[][]{ - {new TreeMap() , true, true, false}, - {null , true, true, false}, - {ImmutableMap.of("a",mock(Vnf.class)), false, true, false}, - {ImmutableMap.of("a",mock(Vnf.class)), true, false, false}, - {ImmutableMap.of("a",mock(Vnf.class)), true, true, true}, - }; - } + @Mock + private MsoResultHandlerService msoResultHandlerService; + + @Mock + private MsoRequestBuilder msoRequestBuilder; + + @Mock + private RestMsoImplementation restMsoImplementation; + + @Mock + private AuditService auditService; + + private ALaCarteServiceCommand command; - @DataProvider - public static Object[][] processJobStatusData() { - return new Object[][]{ - /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */ - {IN_PROGRESS, false, IN_PROGRESS}, - {FAILED, false, FAILED}, - {PAUSE, false, IN_PROGRESS}, - {COMPLETED, false, COMPLETED}, - {COMPLETED, true, IN_PROGRESS}, - {RESOURCE_IN_PROGRESS, false, RESOURCE_IN_PROGRESS}, - {PENDING, false, PENDING}, - {STOPPED, false, STOPPED}, - {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS}, - {CREATING, false, CREATING} - }; - } @DataProvider public static Object[][] isExpiredJobStatusData() { @@ -138,32 +125,31 @@ public class ServiceInProgressStatusCommandTest { @BeforeMethod public void initMocks() { MockitoAnnotations.initMocks(this); - } - - @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" ) - public void testIsNeedToCreateChildJobs(Map serviceVnfs, boolean isALaCarte, - boolean isFeatureEnabled, boolean expected) { - MockitoAnnotations.initMocks(this); - ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); - when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs); - when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte); - when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled); - assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected)); + command = new ALaCarteServiceCommand( + inProgressStatusService, + watchChildrenJobsBL, + asyncInstantiationBL, + jobsBrokerService, + msoRequestBuilder, + msoResultHandlerService, + jobAdapter, + restMsoImplementation, + auditService + ); } @Test public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() { UUID uuid = UUID.randomUUID(); String userId = "mockedUserID"; - Vnf vnf1 = mock(Vnf.class); - Vnf vnf2 = mock(Vnf.class); - Network network1 = mock(Network.class); - ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); - when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2)); - when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1)); - when(serviceInstantiation.isALaCarte()).thenReturn(true); - when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo()); - + String testApi = "VNF_API"; + Vnf vnf1 = createVnf(emptyList(), Create); + Vnf vnf2 = createVnf(emptyList(), Create); + Network network = createNetwork(Create); + ServiceInstantiation serviceInstantiation = createService( + ImmutableList.of(vnf1, vnf2), + ImmutableList.of(network), + emptyList()); when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012"); @@ -171,15 +157,25 @@ public class ServiceInProgressStatusCommandTest { UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014"); when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3); - JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation); - command.init(sharedData, "", ""); + JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation, testApi); + command.init(sharedData, ImmutableMap.of( + ACTION_PHASE, Action.Create.name(), + INTERNAL_STATE, InternalState.IN_PROGRESS.name() + )); when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED); + when(watchChildrenJobsBL.cumulateJobStatus(Job.JobStatus.COMPLETED, COMPLETED_WITH_NO_ACTION)).thenReturn(COMPLETED); + when(watchChildrenJobsBL.cumulateJobStatus(Job.JobStatus.COMPLETED_WITH_NO_ACTION, COMPLETED)).thenReturn(COMPLETED); + when(msoResultHandlerService.getRequest(eq(sharedData))).thenReturn(serviceInstantiation); NextCommand nextCommand = command.call(); + assertEquals(IN_PROGRESS, nextCommand.getStatus()); + nextCommand = nextCommand.getCommand().call(); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class); - verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); - verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); - assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(0)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.VnfInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(1)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.VnfInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(2)); + + assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network)); verify(jobsBrokerService, times(3)).add(any()); @@ -187,41 +183,14 @@ public class ServiceInProgressStatusCommandTest { verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS)); - assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType())); - assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString()))); - assertThat(nextCommand.getCommand().getData().get("isService"), is(true)); - } - - @Test(dataProvider = "processJobStatusData") - public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) { - - when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); - // All mocks under are used for isNeedToCreateChildJobs=true case - when(sharedData.getRequest()).thenReturn(request); - when(request.isALaCarte()).thenReturn(true); - Map vnfs = mock(Map.class); - ModelInfo modelInfo = mock(ModelInfo.class); - - // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false - when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs); - - when(request.getVnfs()).thenReturn(vnfs); - when(request.getModelInfo()).thenReturn(modelInfo); - command.instanceId = "MockInstId"; - - NextCommand nextCommand = command.processJobStatus(jobStatus); - Assert.assertEquals(nextCommand.getStatus(), expectedStatus); - if (isNeedToCreateChildJobs) { - Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class); - } else { - Assert.assertEquals(nextCommand.getCommand(), command); - } + assertThat(nextCommand.getCommand().getType(), is(JobType.ALaCarteService)); + assertThat(nextCommand.getCommand().getData().get(CHILD_JOBS), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString()))); } @Test(dataProvider = "isExpiredJobStatusData") public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) throws Exception { testWithSystemProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS, configValue, ()-> - Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult) + Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult) ); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java index 630c46438..a9a961db8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java @@ -7,9 +7,9 @@ * 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. @@ -23,10 +23,10 @@ package org.onap.vid.job.command; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.impl.JobDaoImpl; import org.onap.vid.utils.DaoUtils; +import org.onap.portalsdk.core.service.DataAccessService; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java deleted file mode 100644 index cc0e66007..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.onap.vid.job.impl.JobSharedData; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.UUID; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; - -public class WatchingCommandTest { - - @Mock - private AsyncInstantiationBusinessLogic asyncInstantiationBL; - - @Mock - private DataAccessService dataAccessService; - - @Mock - private WatchChildrenJobsBL watchChildrenJobsBL; - - @InjectMocks - private WatchingCommand watchingCommand = new WatchingCommand(); - - - - @BeforeClass - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @DataProvider - public static Object[][] testWatchingDataProvider() { - return new Object[][]{ - {"all children final, no failed child, is service", Job.JobStatus.COMPLETED, true, Job.JobStatus.COMPLETED}, - {"all children final, there is failed child, is service", Job.JobStatus.COMPLETED_WITH_ERRORS, true, Job.JobStatus.COMPLETED_WITH_ERRORS}, - {"not all children final, is service", Job.JobStatus.IN_PROGRESS, true, Job.JobStatus.IN_PROGRESS}, - {"all children final, no failed child, not service", Job.JobStatus.COMPLETED, false, Job.JobStatus.COMPLETED}, - {"all children final, there is failed child, not service", Job.JobStatus.COMPLETED_WITH_ERRORS, false, Job.JobStatus.COMPLETED_WITH_ERRORS}, - {"not all children final, not service", Job.JobStatus.IN_PROGRESS, false, Job.JobStatus.RESOURCE_IN_PROGRESS}, - }; - } - - - - @Test(dataProvider = "testWatchingDataProvider") - public void whenGetChildrenStatus_thenJobStatusAsExpected(String desc, Job.JobStatus childrenComulativeStatus, boolean isService, Job.JobStatus expectedCommandStatus) { - UUID jobUUID = UUID.randomUUID(); - JobSharedData sharedData = new JobSharedData(jobUUID, "mockedUserID", mock(ServiceInstantiation.class)); - List uuids = mock(List.class); - watchingCommand.init(sharedData, uuids, isService); - when(watchChildrenJobsBL.retrieveChildrenJobsStatus(eq(uuids))).thenReturn(childrenComulativeStatus); - when(watchChildrenJobsBL.cumulateJobStatus(eq(childrenComulativeStatus),eq(Job.JobStatus.COMPLETED))).thenReturn(childrenComulativeStatus); - - //execute command and verify - NextCommand nextCommand = watchingCommand.call(); - assertThat(nextCommand.getStatus(), is(expectedCommandStatus)); - if (!expectedCommandStatus.equals(Job.JobStatus.IN_PROGRESS) && isService) { - verify(asyncInstantiationBL).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); - } else { - verify(asyncInstantiationBL, never()).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); - } - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java index 0b1fff3b2..498708d06 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,43 +20,55 @@ package org.onap.vid.job.impl; +import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.jetbrains.annotations.NotNull; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.mockito.hamcrest.MockitoHamcrest; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.config.DataSourceConfig; -import org.onap.vid.config.JobCommandsConfigWithMockedMso; -import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.job.Job; import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.JobType; import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.command.CommandUtils; import org.onap.vid.job.command.InternalState; -import org.onap.vid.model.Action; -import org.onap.vid.model.NameCounter; -import org.onap.vid.model.RequestReferencesContainer; -import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.*; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.InstanceGroup; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.RequestReferences; import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.AsyncRequestStatusList; import org.onap.vid.properties.Features; -import org.onap.vid.services.AsyncInstantiationBaseTest; import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.onap.vid.services.VersionService; import org.onap.vid.utils.DaoUtils; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.JobCommandsConfigWithMockedMso; +import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.testUtils.TestUtils; +import org.springframework.http.HttpMethod; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; import org.togglz.core.manager.FeatureManager; import javax.inject.Inject; import javax.ws.rs.ProcessingException; +import java.io.IOException; import java.lang.reflect.Method; import java.util.*; import java.util.function.BiConsumer; @@ -66,7 +78,8 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.*; -import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals; +import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; +import static net.javacrumbs.jsonunit.JsonMatchers.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasProperty; @@ -77,7 +90,7 @@ import static org.mockito.ArgumentMatchers.endsWith; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import static org.onap.vid.job.Job.JobStatus.*; -import static org.onap.vid.model.JobAuditStatus.SourceStatus.MSO; +import static org.onap.vid.job.impl.JobSchedulerInitializer.WORKERS_TOPICS; import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID; import static org.testng.AssertJUnit.*; @@ -96,6 +109,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes public static String REQUEST_ID = UUID.randomUUID().toString(); public static String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + @Inject + private VersionService versionService; + @Inject private JobsBrokerService jobsBrokerService; @@ -108,6 +124,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @Inject private AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Inject + private AuditService auditService; + @Inject private RestMsoImplementation restMso; @@ -120,6 +139,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @BeforeClass void initServicesInfoService() { createInstanceParamsMaps(); + when(versionService.retrieveBuildNumber()).thenReturn("fakeBuild"); } @BeforeMethod @@ -131,10 +151,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @BeforeMethod void defineMocks() { + Mockito.reset(restMso); + Mockito.reset(aaiClient); mockAaiClientAnyNameFree(); } - //@Test + @Test public void whenPushNewBulk_thenAllServicesAreInPending() { pushMacroBulk(); @@ -144,8 +166,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private List pushMacroBulk() { ServiceInstantiation serviceInstantiation = generateMockMacroServiceInstantiationPayload(false, - createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), - 3, true,PROJECT_NAME, true); + createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), + 3, true,PROJECT_NAME, true); return asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID); } @@ -167,6 +189,10 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return createResponse(statusCode, SERVICE_INSTANCE_ID, REQUEST_ID); } + public static RestObject createResponseRandomIds(int statusCode) { + return createResponse(statusCode, UUID.randomUUID().toString(), UUID.randomUUID().toString()); + } + public static RestObject createResponse(int statusCode, String instanceId, String requestId) { RequestReferences requestReferences = new RequestReferences(); requestReferences.setRequestId(requestId); @@ -180,7 +206,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes ImmutableList statusesToStrings(JobStatus... jobStatuses) { return Stream.of(jobStatuses).map( - Enum::toString).collect(ImmutableList.toImmutableList()); + Enum::toString).collect(ImmutableList.toImmutableList()); } /* @@ -190,81 +216,85 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes Make sure service state is Completed successfully once we got from MSO complete, and that next job is peeked. Once a service in the bulk is failed, other services moved to Stopped, and no other jobs from the bulk are peeked. */ - //@Test + @Test public void testStatusesOfMacroServiceInBulkDuringBulkLifeCycle() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE2_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE2_INSTANCE_ID = UUID.randomUUID().toString(); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); + ImmutableList> expectedStatusesForVid = ImmutableList.of( - statusesToStrings(PENDING, IN_PROGRESS, COMPLETED), - statusesToStrings(PENDING, IN_PROGRESS, FAILED), - statusesToStrings(PENDING, STOPPED) + statusesToStrings(PENDING, IN_PROGRESS, COMPLETED), + statusesToStrings(PENDING, IN_PROGRESS, FAILED), + statusesToStrings(PENDING, STOPPED) ); ImmutableList> expectedStatusesForMso = ImmutableList.of( - ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR), - ImmutableList.of(REQUESTED, FAILED_STR), - ImmutableList.of() + ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR), + ImmutableList.of(REQUESTED, FAILED_STR), + ImmutableList.of() ); List uuids = pushMacroBulk(); - pullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); - + UUID firstJobUuid = uuids.get(0); + UUID secondJobUuid = uuids.get(1); //assert that when get ProcessingException from restMso, status remain the same - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message")); - Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - UUID firstHandledJobUUID = job.getUuid(); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message")); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get IN_PROGRESS status from restMso, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get unrecognized status from restMso, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state")); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state")); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get non 200 status code during IN_PROGRESS, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404)); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //when get job COMPLETE from MSO, service status become COMPLETED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - List serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, job); - - + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); + List serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, firstJobUuid); + + //for use later in the test Map expectedJobStatusMap = serviceInfoList.stream().collect( - Collectors.toMap(ServiceInfo::getJobId, x-> PENDING)); - expectedJobStatusMap.put(job.getUuid(), COMPLETED); + Collectors.toMap(ServiceInfo::getJobId, x-> PENDING)); + expectedJobStatusMap.put(firstJobUuid, COMPLETED); //when handling another PENDING job, statuses are : COMPLETED, IN_PROGRESS, PENDING - job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS); - assertThat(job.getUuid(), not(equalTo(firstHandledJobUUID))); //assert different job was handled now - expectedJobStatusMap.put(job.getUuid(), JobStatus.IN_PROGRESS); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE2_INSTANCE_ID, SERVICE2_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimes(10); + + expectedJobStatusMap.put(secondJobUuid, JobStatus.IN_PROGRESS); listServicesAndAssertStatus(expectedJobStatusMap); + //when get FAILED status from MSO statuses are : COMPLETED, FAILED, STOPPED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED); - expectedJobStatusMap.put(job.getUuid(), JobStatus.FAILED); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED); + expectedJobStatusMap.put(secondJobUuid, JobStatus.FAILED); expectedJobStatusMap = expectedJobStatusMap.entrySet().stream().collect(Collectors.toMap( - e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue() + e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue() )); listServicesAndAssertStatus(expectedJobStatusMap); IntStream.range(0, uuids.size()).forEach(i -> { UUID uuid = uuids.get(i); - List msoStatuses = asyncInstantiationBL.getAuditStatuses(uuid, MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - List vidStatuses = asyncInstantiationBL.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - assertThat(msoStatuses, is(expectedStatusesForMso.get(i))); + List vidStatuses = auditService.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); assertThat(vidStatuses, is(expectedStatusesForVid.get(i))); }); - // + + //assert no more jobs to pull assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); } @@ -273,8 +303,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @DataProvider public static Object[][] AlaCarteStatuses(Method test) { return new Object[][]{ - {COMPLETE_STR, JobStatus.COMPLETED, JobStatus.COMPLETED}, - {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED}, + {COMPLETE_STR, JobStatus.COMPLETED}, + {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS}, }; } @@ -285,8 +315,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes Make sure service state is Completed successfully once we got from MSO complete for the vnf job. status Creating */ - //@Test(dataProvider = "AlaCarteStatuses") - public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus, JobStatus expectedVnfStatus) { + @Test(dataProvider = "AlaCarteStatuses") + public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus) { /* [v] + push alacarte with 1 vnf [v] verify STATUS pending @@ -305,6 +335,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes * not looking on audit (yet) */ + reset(restMso); when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false); final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); @@ -315,39 +346,22 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes //push alacarte with 1 vnf, verify STATUS pending UUID uuid = pushALaCarteWithVnf(); singleServicesAndAssertStatus(JobStatus.PENDING, uuid); - //mock mso to answer 200 of create service instance request, verify STATUS in progress - when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn( + createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching - reset(restMso); when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); - - //verify service job STATUS in progress - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - - //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, - //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) - reset(restMso); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID)); when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - pullJobProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, expectedVnfStatus, false); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, expectedServiceStatus, true); - singleServicesAndAssertStatus(expectedServiceStatus, uuid); + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); + + processJobsCountTimesAndAssertStatus(uuid, 100, expectedServiceStatus); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any()); + verify(restMso, times(2)).GetForObject(any(), any()); } @@ -361,13 +375,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes And union these tests to single one. */ - //@Test + @Test public void testALaCarteLifeCycle1Vnf2VfModules() { String msoVnfStatus = COMPLETE_STR; - JobStatus expectedServiceStatus = IN_PROGRESS; - JobStatus expectedVnfStatus = RESOURCE_IN_PROGRESS; when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true); final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); @@ -383,39 +395,27 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes //push alacarte with 1 vnf, verify STATUS pending UUID uuid = pushALaCarteWithVnf(); singleServicesAndAssertStatus(JobStatus.PENDING, uuid); + reset(restMso); /*---------- service -----------*/ //mock mso to answer 200 of create service instance request, verify STATUS in progress - when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn( + createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - //mock mso to answer COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching - reset(restMso); + //mock mso to answer COMPLETE for service instance create when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); /*---------- vnf -----------*/ - //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); - - //verify service job STATUS in progress - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + //mock mso to answer 200 of create vnf instance request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any())).thenReturn( + createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID)); //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, - //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) - reset(restMso); when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); try { reset(commandUtils); @@ -425,113 +425,164 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes } - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - /*---------- vf Module without volume group name (base) -----------*/ - //vg name not exist, so vf module created immediately - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VG_REQUEST_ID)); + //mock mso to answer for vf module orchestration request + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), any())).thenReturn( + createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID)); + //mock mso to answer for volume group orchestration request + when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - //verify vnf/volumeGroup job STATUS still watching with resource in progress - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + /*---------- vfModule -----------*/ //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2)); //mock mso to answer for vf module orchestration request - reset(restMso); - when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); - - //verify volume group become completed - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.COMPLETED, JobType.Watching); + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + processJobsCountTimesAndAssertStatus(uuid, 200, COMPLETED); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), any()); + verify(restMso, times(2)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any()); + verify(restMso, times(5)).GetForObject(any(), any()); + } - //vnf become watching after volume group completed, and new volume group created - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + @Test + public void testALaCarteLifeCycle2Networks() { - /*---------- volume group & vf module (non base) -----------*/ + //Create Service with 2 networks, and make sure they created in sequence (and not in parallel) + //Config MSO to response 200 only to first network creation. And answer 500 for second one. + //Then MSO return in_progress some times (like 10 times), and then return COMPLETE. + //Only when MSO return COMPLETE for first network, config MSO to return 200 for second network creation - /*---------- volume group -----------*/ + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String NETWORK_REQUEST_ID1 = UUID.randomUUID().toString(); + final String NETWORK_INSTANCE_ID1 = UUID.randomUUID().toString(); + //TODO use them later for different networks + final String NETWORK_REQUEST_ID2 = UUID.randomUUID().toString(); + final String NETWORK_INSTANCE_ID2 = UUID.randomUUID().toString(); - //mock mso to answer 200 of create volumeGroup instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus); - //verify vnf job STATUS still watching with resource in progress - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + NetworkDetails networkDetails1 = new NetworkDetails("LukaDoncic", "1"); + NetworkDetails networkDetails2 = new NetworkDetails("KevinDurant", "2"); - //mock mso to answer for volume group orchestration request reset(restMso); - when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); - /*---------- vfModule -----------*/ + /*---------- service -----------*/ - //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + //mock mso to answer 200 of create service instance request, verify STATUS in progress + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn( + createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - //mock mso to answer for vf module orchestration request - reset(restMso); - when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); + //mock mso to answer COMPLETE for service instance create + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + final MutableInt secondNetworkCode = new MutableInt(500); + final MutableInt inProgressCount = new MutableInt(0); + + /*---------- network 1-----------*/ + + //mock mso to answer 200 of first create network instance request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), + MockitoHamcrest.argThat(jsonPartMatches("requestDetails.requestInfo.instanceName", equalTo(networkDetails1.name))) , + endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenReturn( + createResponse(200, NETWORK_INSTANCE_ID1, NETWORK_REQUEST_ID1)); + + //mock mso to answer IN_PROGRESS 10 times, and only then COMPLETE for first network + //Once COMPLETE, second network creation will return 200 + when(restMso.GetForObject(endsWith(NETWORK_REQUEST_ID1), eq(AsyncRequestStatus.class))). + thenAnswer(x->{ + String status; + if (inProgressCount.getValue()<10) { + status = IN_PROGRESS_STR; + } else { + secondNetworkCode.setValue(200); + status = COMPLETE_STR; + } + inProgressCount.add(1); + return asyncRequestStatusResponseAsRestObject(status); + }); + + /*---------- network 2-----------*/ + + //mock MSO to return status code of secondNetworkCode (500 and 200 after first one COMPLETED) + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), + MockitoHamcrest.argThat(jsonPartMatches("requestDetails.requestInfo.instanceName", equalTo(networkDetails2.name))) , + endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenAnswer(x-> + createResponse(secondNetworkCode.intValue(), NETWORK_INSTANCE_ID2, NETWORK_REQUEST_ID2)); + +// when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any() , endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenReturn( +// createResponse(200, NETWORK_INSTANCE_ID1, NETWORK_REQUEST_ID1)); + //mock mso to answer COMPLETE for network creation status, + + when(restMso.GetForObject(endsWith(NETWORK_REQUEST_ID2), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + + /*---------- Create request and process it -----------*/ + //push alacarte with 2 networks, verify STATUS pending + when(featureManager.isActive(Features.FLAG_EXP_CREATE_RESOURCES_IN_PARALLEL)).thenReturn(false); + ServiceInstantiation serviceInstantiation = generateALaCarteWithNetworksPayload(ImmutableList.of(networkDetails1, networkDetails2)); + UUID uuid = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID).get(0); + singleServicesAndAssertStatus(JobStatus.PENDING, uuid); - //execute twice - 1 for parent volume group, 1 for parent vnf - pullAllJobProcessAndPushBackByType(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching , JobStatus.COMPLETED); + processJobsCountTimesAndAssertStatus(uuid, 200, COMPLETED); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.COMPLETED, true); - singleServicesAndAssertStatus(JobStatus.COMPLETED, uuid); + //validate the mso request id is the right one + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + ServiceInfo serviceInfo = serviceInfoList.get(0); + assertThat(serviceInfo.getMsoRequestId(), is(UUID.fromString(SERVICE_REQUEST_ID))); + + /*---------- verify -----------*/ + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(2)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/networks"), any()); + //get status + verify(restMso, times(1)).GetForObject(endsWith(SERVICE_REQUEST_ID), any()); + verify(restMso, times(11)).GetForObject(endsWith(NETWORK_REQUEST_ID1), any()); + verify(restMso, times(1)).GetForObject(endsWith(NETWORK_REQUEST_ID2), any()); } - //@Test + @Test public void testBadAaiResponseForSearchNamesAndBackToNormal() { when(aaiClient.isNodeTypeExistsByName(any(), any())).thenThrow(aaiNodeQueryBadResponseException()); - pushMacroBulk(); //JOB shall become IN_PROGRESS but service info is still pending - Job job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, true); - listServicesAndAssertStatus(PENDING, PENDING, job); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - //JOB shall remain in IN_PROGRESS - job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - //make sure the job command is still ServiceInstantiation - assertThat(job.getType(), is(JobType.MacroServiceInstantiation)); - listServicesAndAssertStatus(PENDING, PENDING, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 5, IN_PROGRESS, PENDING); //JOB shall become IN_PROGRESS but service info is still pending //simulate AAI back to normal, AAI return name is free, and MSO return good response Mockito.reset(aaiClient); // must forget the "thenThrow" when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false); - when(restMso.PostForObject(any(),any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, COMPLETED, COMPLETED); - //when get job COMPLETE from MSO, service status become COMPLETED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - listServicesAndAssertStatus(COMPLETED, PENDING, job); } - //@Test + @Test public void testAaiResponseNameUsedTillMaxRetries() { when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(true); + //simulate MSO to return good result, for making sure we failed because of AAI error + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10); - pushMacroBulk(); - //JOB shall become IN_PROGRESS but service info is still pending - Job job = pullJobProcessAndPushBack(PENDING, JobStatus.FAILED, true); - listServicesAndAssertStatus(JobStatus.FAILED, JobStatus.STOPPED, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 20, FAILED, STOPPED); } private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus) { @@ -559,22 +610,23 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return job.get(); } + private void simplePullJobProcessAndPushBack(JobStatus topic) { + Optional optionalJob = jobsBrokerService.pull(topic, randomUuid()); + optionalJob.ifPresent(job->{ + Job nextJob = jobWorker.executeJobAndGetNext(job); + jobsBrokerService.pushBack(nextJob); + }); + } + private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType) { + JobType expectedNextJobType) { Job job = pullJobProcessAndPushBack(topic, expectedNextJobStatus, false); assertThat("job not ok: " + job.getData(), job.getType(), is(expectedNextJobType)); return job; } private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType, int retries) { - return retryWithAssertionsLimit(retries, () -> { - return pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); - }); - } - - private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) { + JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) { return retryWithAssertionsLimit(retries, () -> { Job job = pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("actionPhase", actionPhase.name()))); @@ -598,49 +650,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes // No success: throw new AssertionError("No luck while all of these assertion errors: " + history.stream() - .map(Throwable::getMessage) - .map(s -> s.replace('\n', ' ')) - .map(s -> s.replaceAll("\\s{2,}"," ")) - .distinct() - .collect(joining("\n ", "\n ", "")), history.peek()); - } - - private Job pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus topic, JobType expectedCurrentJobType, JobStatus expectedNextJobStatus, - JobType expectedNextJobType) { - List pulledJobs = new ArrayList<>(); - Job lastJob = null; - while (lastJob == null || lastJob.getType() != expectedCurrentJobType) { - lastJob = pullJob(topic, false).get(); - if (lastJob.getType() != expectedCurrentJobType) { - pulledJobs.add(lastJob); - } - } - - Job nextJob = jobWorker.executeJobAndGetNext(lastJob); - assertThat(nextJob.getStatus(), is(expectedNextJobStatus)); - assertThat(nextJob.getType(), is(expectedNextJobType)); - - jobsBrokerService.pushBack(nextJob); - assertThat(jobsBrokerService.peek(nextJob.getUuid()).getStatus(), is(expectedNextJobStatus)); - - pulledJobs.forEach(job -> - jobsBrokerService.pushBack(job) - ); - - return nextJob; - } - - private void pullAllJobProcessAndPushBackByType(JobStatus topic, JobType commandType, JobStatus expectedFinalStatus) { - Map jobStatusMap = new HashMap<>(); - Optional job = pullJob(topic, false); - for (int i=0; i<1000 && job.isPresent() && job.get().getType() == commandType; i++) { - Job nextJob = jobWorker.executeJobAndGetNext(job.get()); - jobStatusMap.put(nextJob.getUuid(), nextJob.getStatus()); - jobsBrokerService.pushBack(nextJob); - job = jobsBrokerService.pull(topic, UUID.randomUUID().toString()); - } - assertThat(jobStatusMap.values(), everyItem(is(expectedFinalStatus))); - + .map(Throwable::getMessage) + .map(s -> s.replace('\n', ' ')) + .map(s -> s.replaceAll("\\s{2,}"," ")) + .distinct() + .collect(joining("\n ", "\n ", "")), history.peek()); } private Optional pullJob(JobStatus topic, boolean pullingAssertion) { @@ -665,49 +679,37 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes } - //@Test + @Test public void whenPushNewBulk_andGetNoResponseFromMsoOnCreation_thenServiceMoveToFailedAndOtherToStopped() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(500)); - pushBulkPullPendingJobAndAssertJobStatus(JobStatus.FAILED, JobStatus.STOPPED); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(500)); + //assert that when get ProcessingException from restMso, status remain the same + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, JobStatus.FAILED, JobStatus.STOPPED); } - //@Test + @Test public void whenMsoStatusIsPendingManualTask_ThenJobStatusIsPaused() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - - Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK)); //assert that when get ProcessingException from restMso, status remain the same - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK)); - Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(PAUSE, PENDING, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, PAUSE, PENDING); - //The paused job is pulled and remain in pause state. Other jobs from bulk remain pending - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(PAUSE, PENDING, job); //the job get IN_PROGRESS response (simulate activate operation) and status changed to IN_PROGRESS when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, IN_PROGRESS, PENDING); + //the job get COMPLETE response this job is copmpleted and then also other jobs when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - listServicesAndAssertStatus(COMPLETED, PENDING, job); - - //Pulling PENDING job return another job - assertThat(jobsBrokerService.pull(PENDING, randomUuid()).get().getUuid(), not(equalTo(job.getUuid()))); - - - ImmutableList expectedStatusesForMso = ImmutableList.of(REQUESTED, PENDING_MANUAL_TASK, IN_PROGRESS_STR, COMPLETE_STR); - List msoStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - assertThat(msoStatuses, is(expectedStatusesForMso)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + processJobsCountTimesAndAssertStatus(uuids.get(0), 200, COMPLETED, COMPLETED); ImmutableList expectedStatusesForVid = statusesToStrings(PENDING, IN_PROGRESS, PAUSE, IN_PROGRESS, COMPLETED); - List vidStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + List vidStatuses = auditService.getAuditStatuses(uuids.get(0), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); assertThat(vidStatuses, is(expectedStatusesForVid)); } @@ -718,65 +720,76 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private Job pullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) { Job job = pullJobProcessAndPushBack(PENDING, pulledJobStatus, false); - listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job); + listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job.getUuid()); return job; } - //@Test + @Test public void test2BulksLifeCyclesAreIndependent() { - pushMacroBulk(); - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - //push 2nd job, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending - Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); - //assert we can pull another job from pending from other template id - Job secondJob = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - assertThat(firstJob.getTemplateId(), not(equalTo(secondJob.getTemplateId()))); - - //assert no more PENDING jobs to pull - assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); - - //when get FAILED status from MSO statuses for failed bulk are: FAILED, STOPPED, for other bulk: IN_PROGRESS, 2 pending - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); - Job failedJob = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED, false); + final String SERVICE1_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE1_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE2_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE2_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE3_4_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE3_4_INSTANCE_ID = UUID.randomUUID().toString(); + + + //create first bulk and make one job in progress + List firstBulksIDs = pushMacroBulk(); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE1_INSTANCE_ID, SERVICE1_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE1_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(firstBulksIDs.get(0), 30, IN_PROGRESS, PENDING); + + //create 2nd bulk, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE2_INSTANCE_ID, SERVICE2_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + List secondBulksIDs = pushMacroBulk(); + processJobsCountTimes(30); + Map statusCount = getJobStatusesCount(); + assertThat(statusCount.get(IN_PROGRESS), is(2L)); + assertThat(statusCount.get(PENDING), is(4L)); + + //return failed to first job + //first bulk statuses shall be: FAILED, STOPPED, STOPPED + //second bulk statuses shall be: IN_PROGRESS, PENDING, PENDING + when(restMso.GetForObject(endsWith(SERVICE1_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + processJobsCountTimes(30); Map> servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - Job successJob = failedJob.getUuid().equals(firstJob.getUuid()) ? secondJob : firstJob; - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob); - - //yet no more PENDING jobs to pull - assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); - - //assert that job from non failed bulk can progress. - //When completed, failed bulk statuses: FAILED, STOPPED. Succeeded bulk statuses are : COMPLETED, 2 pending - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, PENDING, successJob); - - //advance other jobs of succeeded bulk till al of them reach to COMPLETED - pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob); - + asyncInstantiationBL.getAllServicesInfo() + .stream().collect(groupingBy(ServiceInfo::getTemplateId)); + ServiceInfo failedJob = asyncInstantiationBL.getAllServicesInfo().stream().filter(x->x.getJobId().equals(firstBulksIDs.get(0))).findFirst().get(); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob.getJobId()); + ServiceInfo successJob = asyncInstantiationBL.getAllServicesInfo().stream().filter(x->x.getJobId().equals(secondBulksIDs.get(0))).findFirst().get(); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob.getJobId()); + + //return completed to all other jobs + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE3_4_INSTANCE_ID, SERVICE3_4_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + when(restMso.GetForObject(endsWith(SERVICE3_4_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + processJobsCountTimes(30); + servicesByTemplateId = asyncInstantiationBL.getAllServicesInfo().stream().collect(groupingBy(ServiceInfo::getTemplateId)); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob.getJobId()); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob.getJobId()); //assert no more PENDING jobs nor IN_PROGRESS jobs to pull assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); } + protected Map getJobStatusesCount() { + return asyncInstantiationBL.getAllServicesInfo().stream().collect(groupingBy(ServiceInfo::getJobStatus, counting())); + } + + @Test public void deploy2NewGroupsToServiceWith1ExistingGroup() { /* @@ -795,18 +808,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes [v] + pull+execute (should NOT post to MSO) [v] verify STATUS in progress; TYPE watching ... - [v] verify job#2 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] verify job#3 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] verify job#4 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] + pull+execute job#1 (should NOT post to MSO) - [v] verify STATUS in progress; TYPE watching - [v] verify job#5 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - [v] verify job#6 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - [v] verify job#7 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - - [v] + pull+execute job#5 (should NOT post to MSO) - [v] verify job#5 STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE create [v] + pull+execute job#1 [v] verify job#1 STATUS in progress; TYPE watching @@ -845,70 +847,265 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes singleServicesAndAssertStatus(PENDING, uuid); // take from pending, put in-progress -> 3 delete-child were born - pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Delete, InternalState.WATCHING, 1); - verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, CREATING, 3 - )); - - Stream.of(1, 2, 3).forEach(i -> { - // take each child creating, put in-progress - verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Delete, null, 1); - - // execute each in-progress -> job is completed - verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED/*_WITH_NO_ACTION*/, JobType.InstanceGroup,1); - }); + pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Create, InternalState.INITIAL, 1); verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, COMPLETED, 3 + IN_PROGRESS, 1 )); // take job #1 from phase delete to phase create -> 3 create-child were born verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, CREATING, 3, COMPLETED, 3 + IN_PROGRESS, 1, PENDING_RESOURCE, 3 )); // prepare MSO mock - when(restMso.PostForObject(any(), endsWith("instanceGroups"), eq(RequestReferencesContainer.class))) - .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID)) - .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID)) - .thenReturn(null); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("instanceGroups"), eq(Optional.empty()))) + .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID)) + .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID)) + .thenReturn(null); when(restMso.GetForObject(argThat(uri -> StringUtils.endsWithAny(uri, GROUP1_REQUEST_ID, GROUP2_REQUEST_ID)), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - // take first "none" child from creating to completed + // take first "none" child from creating to COMPLETED_WITH_NO_ACTION // note there's no concrete mechanism that makes the first child be - // the "action=None" case, but that's what happens, and following line + // the "action=None" case, but that's what happens, and following lines // relies on that fact. - pullJobProcessAndPushBackWithTypeAssertion(CREATING, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroupInstantiation, 1); + pullJobProcessAndPushBackWithTypeAssertion(PENDING_RESOURCE, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroup, Action.Create, null, 1); // take each of next two children from creating to in-progress, then to completed // verify job #1 is watching, and MSO is getting requests Stream.of(1, 2).forEach(i -> { verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); - verify(restMso, times(i)).PostForObject(any(), any(), any()); + pullJobProcessAndPushBackWithTypeAssertion(PENDING_RESOURCE, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Create, InternalState.IN_PROGRESS, 1); + verify(restMso, times(i)).restCall(any(), any(), any(), any(), any()); verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.ResourceInProgressStatus); + pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.InstanceGroup, Action.Create, null, 3); verify(restMso, times(i)).GetForObject(any(), any()); }); // job #1 is done as all children are done verify_Job1InProgress.accept(Action.Create, COMPLETED); - verifyQueueSizes(ImmutableMap.of(COMPLETED, 7)); + verifyQueueSizes(ImmutableMap.of(COMPLETED, 3, COMPLETED_WITH_NO_ACTION, 1)); + } + + @DataProvider + public static Object[][] createAndDeleteIntegrationTestDataProvider(Method test) { + return new Object[][]{ + {"create and delete both bad http code", createResponse(400), createResponse(500), null, null, FAILED, 0}, + {"create and delete success and status is success ", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR), asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED, 2}, + {"create and delete success, create status FAILED, delete status COMPLETED", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(FAILED_STR), asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED_WITH_ERRORS, 2}, + {"create and delete success, create status FAILED, delete status FAILED", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(FAILED_STR), asyncRequestStatusResponseAsRestObject(FAILED_STR), FAILED, 2}, + {"create success but delete failed and status is success ", createResponseRandomIds(202), createResponseRandomIds(400), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR), null, COMPLETED_WITH_ERRORS, 1}, + {"delete success but create failed and status is success ", createResponseRandomIds(400), createResponseRandomIds(202), + null, asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED_WITH_ERRORS, 1}, + {"delete success but create failed and status of delete is FAILED ", createResponseRandomIds(400), createResponseRandomIds(202), + null, asyncRequestStatusResponseAsRestObject(FAILED_STR), FAILED, 1} + }; + } + + //this test is going along with AsyncInstantiationALaCarteApiTest.viewEditVnfGroup__verifyStatusAndAudit API test + //The API test has only the happy flow scenario, while this test also test additional MSO responses (mostly non happy) + @Test(dataProvider="createAndDeleteIntegrationTestDataProvider") + public void vnfGropingIntegrationTest( + String desc, + RestObject createGroupResponse, + RestObject deleteGroupResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + UUID jobUUID = createAndDeleteIntegrationTest("/payload_jsons/VnfGroupCreate1Delete1None1Request.json", + "/serviceInstantiation/v7/instanceGroups", + createGroupResponse, + "/serviceInstantiation/v7/instanceGroups/VNF_GROUP1_INSTANCE_ID", + deleteGroupResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + + ServiceInstantiation bulkForRetry = asyncInstantiationBL.getBulkForRetry(jobUUID); + InstanceGroup vnfGroupShouldBeDeleted = bulkForRetry.getVnfGroups().get("groupingservicefortest..ResourceInstanceGroup..0:001"); + InstanceGroup vnfGroupShouldBeCreated = bulkForRetry.getVnfGroups().get("groupingservicefortest..ResourceInstanceGroup..0"); + + if (deleteStatusResponse == null || deleteStatusResponse.get().request.requestStatus.getRequestState().equals(FAILED_STR)) { + assertThat(vnfGroupShouldBeDeleted.getAction(), equalTo(Action.Delete)); + assertErrorForResource(vnfGroupShouldBeDeleted, deleteGroupResponse, deleteStatusResponse); + } + + if (createStatusResponse == null || createStatusResponse.get().request.requestStatus.getRequestState().equals(FAILED_STR)) { + assertThat(vnfGroupShouldBeCreated.getAction(), equalTo(Action.Create)); + assertErrorForResource(vnfGroupShouldBeCreated, createGroupResponse, createStatusResponse); + } + } + + //this test is going along with AsyncInstantiationALaCarteApiTest3.delete1Create1VnfFromService API test + //The API test has only the happy flow scenario, while this test also test additional MSO responses (mostly non happy) + @Test(dataProvider="createAndDeleteIntegrationTestDataProvider") + public void vnfsIntegrationTest( + String desc, + RestObject createVnfResponse, + RestObject deleteVnfResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + createAndDeleteIntegrationTest("/payload_jsons/vnfDelete1Create1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs", + createVnfResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID", + deleteVnfResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + } + + @Test(dataProvider="createAndDeleteIntegrationTestDataProvider") + public void vfModulesIntegrationTest( + String desc, + RestObject createVfModuleResponse, + RestObject deleteVfModuleResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException, AsdcCatalogException { + + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true); + reset(commandUtils); + when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "f8360508-3f17-4414-a2ed-6bc71161e8db")).thenReturn(true); + when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "25284168-24bb-4698-8cb4-3f509146eca5")).thenReturn(false); + + createAndDeleteIntegrationTest("/payload_jsons/vfModuleDelete1Create1None1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules", + createVfModuleResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules/VF_MODULE_INSTANCE_ID", + deleteVfModuleResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + } + + //this test is going along with AsyncInstantiationALaCarteApiTest.delete1Create1NetworkFromService API test + //The API test has only the happy flow scenario, while this test also test additional MSO responses (mostly non happy) + @Test(dataProvider="createAndDeleteIntegrationTestDataProvider") + public void networksIntegrationTest( + String desc, + RestObject createNetworkResponse, + RestObject deleteNetworkResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + createAndDeleteIntegrationTest("/payload_jsons/networkDelete1Create1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/networks", + createNetworkResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/networks/NETWORK_INSTANCE_ID", + deleteNetworkResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); } + private UUID createAndDeleteIntegrationTest(String payload, + String createPath, + RestObject createResponse, + String deletePath, + RestObject deleteResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + UUID jobUUID = asyncInstantiationBL.pushBulkJob( + TestUtils.readJsonResourceFileAsObject(payload, ServiceInstantiation.class), "userId") + .get(0); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq(createPath), any())).thenReturn(createResponse); + when(restMso.restCall(eq(HttpMethod.DELETE), eq(RequestReferencesContainer.class), any(), eq(deletePath), any())).thenReturn(deleteResponse); + if (createStatusResponse!=null) { + when(restMso.GetForObject(endsWith(createResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))).thenReturn(createStatusResponse); + } + if (deleteStatusResponse!=null) { + when(restMso.GetForObject(endsWith(deleteResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))).thenReturn(deleteStatusResponse); + } + + processJobsCountTimesAndAssertStatus(jobUUID, 40, expectedJobStatus); + + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq(createPath), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.DELETE), any(), any(), eq(deletePath), any()); + verify(restMso, times(getStatusCounter)).GetForObject(any(), any()); + + return jobUUID; + } + + @Test + public void whenCreateTransportService_thanExpectedPre1806MacroRequestSent() throws IOException { + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generatePre1806MacroTransportServiceInstantiationPayload(null, null),"az2016").get(0); + RestObject createResponse = createResponseRandomIds(202); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq("/serviceInstantiation/v7/serviceInstances"), any())) + .thenReturn(createResponse); + when(restMso.GetForObject(endsWith(createResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))) + .thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + + JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/pre_1806_macro_without_cloudConfiguration.json", JsonNode.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class); + verify(restMso).restCall(any(), any(), requestCaptor.capture(), any(), any()); + requestCaptor.getAllValues().forEach(x->assertJsonEquals(expectedJson, x)); + } + + private void assertErrorForResource(BaseResource resource, + RestObject deleteOrCreateResponse, + RestObject statusResponse) { + JobAuditStatus auditStatus = auditService.getResourceAuditStatus(resource.getTrackById()); + assertThat(auditStatus, is(notNullValue())); + assertThat(auditStatus.getJobStatus(), equalTo(FAILED_STR)); + if (statusResponse == null) { + String errorMessage = "Http Code:" + deleteOrCreateResponse.getStatusCode() + ", " + RAW_DATA_FROM_MSO; + assertThat(auditStatus.getAdditionalInfo(), equalTo(errorMessage)); + assertThat(auditStatus.getRequestId(), is(nullValue())); + } else { + assertThat(auditStatus.getRequestId().toString(), equalTo(statusResponse.get().request.requestId)); + } + } + + protected void processJobsCountTimesAndAssertStatus(UUID serviceJobId, int times, JobStatus expectedStatus) { + processJobsCountTimes(times); + singleServicesAndAssertStatus(expectedStatus, serviceJobId); + } + + private void processJobsCountTimes(int times) { + for (int i = 0; i < times; i++) { + WORKERS_TOPICS.forEach(this::simplePullJobProcessAndPushBack); + } + } + + protected void processJobsCountTimesAndAssertStatus(UUID serviceJobId, int times, JobStatus expectedStatus, JobStatus otherJobsStatus) { + processJobsCountTimes(times); + listServicesAndAssertStatus(expectedStatus, otherJobsStatus, serviceJobId); + } + + private void verifyQueueSizes(ImmutableMap expected) { final Collection peek = jobsBrokerService.peek(); final Map jobTypes = peek.stream().collect(groupingBy(Job::getStatus, counting())); - assertThat(jobTypes, is(expected)); + assertThat(jobTypes, jsonEquals(expected)); } - private List listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + private List listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, UUID jobUUID) { List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); - assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, job); + assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, jobUUID); return serviceInfoList; } @@ -922,9 +1119,15 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return serviceInfo; } - private void assertServicesStatus(List serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + private boolean isServiceOnStatus(JobStatus expectedStatus) { + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + assertEquals(1, serviceInfoList.size()); + return serviceInfoList.get(0).getJobStatus()==expectedStatus; + } + + private void assertServicesStatus(List serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, UUID jobUUID) { serviceInfoList.forEach(si->{ - if (si.getJobId().equals(job.getUuid())) { + if (si.getJobId().equals(jobUUID)) { assertThat(si.getJobStatus(), is(pulledJobStatus)); } else { @@ -935,11 +1138,104 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private void listServicesAndAssertStatus(Map expectedJobStatusMap) { Map actualStatuses = asyncInstantiationBL.getAllServicesInfo() - .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus)); + .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus)); assertThat(actualStatuses.entrySet(), equalTo(expectedJobStatusMap.entrySet())); } private String randomUuid() { return UUID.randomUUID().toString(); } + + @Test + public void whenResumeService_thanExpectedResumeRequestSent() throws IOException { + String instanceId = "a565e6ad-75d1-4493-98f1-33234b5c17e2"; //from feRequestResumeMacroService.json + String originalRequestId = "894089b8-f7f4-418d-81da-34186fd32670"; //from msoResponseGetRequestsOfServiceInstance.json + String resumeRequestId = randomUuid(); + String userId = TestUtils.generateRandomAlphaNumeric(6); + + //prepare mocks for get all requests for instance id + RestObject getRequestByIdResponse = createAsyncRequestStatusListByInstanceId(); + when(restMso.GetForObject( + eq("/orchestrationRequests/v7?filter=serviceInstanceId:EQUALS:" + instanceId), + eq(AsyncRequestStatusList.class))) + .thenReturn(getRequestByIdResponse); + + //prepare mocks resume request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), isNull(), eq(String.format("/orchestrationRequests/v7/%s/resume", originalRequestId)), eq(Optional.of(userId)))) + .thenReturn(createResponse(202, instanceId, resumeRequestId)); + + //prepare mocks for get resume status + when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + resumeRequestId), eq(AsyncRequestStatus.class))) + .thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateResumeMacroPayload(), userId).get(0); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + verify(restMso).GetForObject( + eq("/orchestrationRequests/v7?filter=serviceInstanceId:EQUALS:" + instanceId), + eq(AsyncRequestStatusList.class)); + verify(restMso).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), isNull(), eq(String.format("/orchestrationRequests/v7/%s/resume", originalRequestId)), eq(Optional.of(userId))); + verify(restMso, times(3)).GetForObject(eq("/orchestrationRequests/v7/" + resumeRequestId), eq(AsyncRequestStatus.class)); + } + + @Test + public void givenResumeRequest_whenMsoReturnBadResponse_thanJobIsFailed() throws IOException { + //there is no mocks for restMSO which means restMso return bad response... + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateResumeMacroPayload(), "abc").get(0); + processJobsCountTimesAndAssertStatus(jobUUID, 20, FAILED); + } + + @NotNull + private RestObject createAsyncRequestStatusListByInstanceId() throws IOException { + AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject( + "/payload_jsons/resume/msoResponseGetRequestsOfServiceInstance.json", + AsyncRequestStatusList.class); + RestObject getRequestByIdResponse = new RestObject<>(); + getRequestByIdResponse.set(asyncRequestStatusList); + getRequestByIdResponse.setStatusCode(200); + return getRequestByIdResponse; + } + + private ServiceInstantiation generateResumeMacroPayload() throws IOException { + return TestUtils.readJsonResourceFileAsObject("/payload_jsons/resume/feRequestResumeMacroService.json", ServiceInstantiation.class); + } + + @Test + public void whenUpgradingAvfModule_thanExpectedReplaceRequestSent() throws IOException { + String instanceId = "5d49c3b1-fc90-4762-8c98-e800170baa55"; //from feRequestResumeMacroService.json + String replaceRequestId = randomUuid(); + String userId = "az2016"; + + + //prepare mocks resume request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq("/serviceInstantiation/v7/serviceInstances/e9993045-cc96-4f3f-bf9a-71b2a400a956/vnfs/5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5/vfModules/5d49c3b1-fc90-4762-8c98-e800170baa55/replace"), eq(Optional.of(userId)))) + .thenReturn(createResponse(202, instanceId, replaceRequestId)); + + + when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + replaceRequestId), eq(AsyncRequestStatus.class))) + .thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + ///orchestrationRequests/v7/0174b25a-dd81-45b7-b4af-0057bcc30857 + + when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true); + enableAddCloudOwnerOnMsoRequest(); + + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateReplaceVfModulePayload(), userId).get(0); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + + + + JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule.json", JsonNode.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class); + verify(restMso).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), requestCaptor.capture(), eq("/serviceInstantiation/v7/serviceInstances/e9993045-cc96-4f3f-bf9a-71b2a400a956/vnfs/5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5/vfModules/5d49c3b1-fc90-4762-8c98-e800170baa55/replace"), eq(Optional.of(userId))); + requestCaptor.getAllValues().forEach(x->assertJsonEquals(expectedJson, x)); + } + + private ServiceInstantiation generateReplaceVfModulePayload() throws IOException { + return TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule_fe_input.json", ServiceInstantiation.class); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java new file mode 100644 index 000000000..4944efa69 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.impl; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; +import static org.mockito.Mockito.mock; +import static org.onap.vid.testUtils.TestUtils.testWithSystemProperty; +import static org.testng.Assert.assertEquals; + +import org.onap.vid.job.JobsBrokerService; +import org.quartz.JobDetail; +import org.quartz.impl.triggers.CronTriggerImpl; +import org.testng.annotations.Test; + +public class DeleteOldJobsSchedulerInitializerTest { + + @Test + public void testCreateJobDetail() throws Exception { + testWithSystemProperty("vid.asyncJob.howLongToKeepOldJobsInDays", "7", ()-> { + JobsBrokerService mockBroker = mock(JobsBrokerService.class); + DeleteOldJobsSchedulerInitializer underTest = new DeleteOldJobsSchedulerInitializer(mockBroker, null); + JobDetail jobDetail = underTest.createJobDetail(); + assertEquals(DeleteOldJobsWorker.class, jobDetail.getJobClass()); + assertEquals(mockBroker, jobDetail.getJobDataMap().get("jobsBrokerService")); + assertEquals(604800L, jobDetail.getJobDataMap().get("secondsAgo")); + }); + } + + @Test + public void testCreateTrigger() { + DeleteOldJobsSchedulerInitializer underTest = new DeleteOldJobsSchedulerInitializer(null, null); + CronTriggerImpl trigger = (CronTriggerImpl) underTest.createTrigger(); + assertThat(trigger.getCronExpression(), matchesPattern("0 [1-5]?[0-9] 6 \\? \\* \\*")); + } + +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java new file mode 100644 index 000000000..229e0cab1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.impl; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.onap.vid.job.JobsBrokerService; +import org.quartz.JobExecutionException; +import org.testng.annotations.Test; + +public class DeleteOldJobsWorkerTest { + + @Test + public void whenExecuteInternal_thenCallToDeleteOldFinalJobs() throws JobExecutionException { + JobsBrokerService mockBroker = mock(JobsBrokerService.class); + long secondsAgo = 42L; + DeleteOldJobsWorker underTest = new DeleteOldJobsWorker(); + underTest.setJobsBrokerService(mockBroker); + underTest.setSecondsAgo(secondsAgo); + underTest.executeInternal(null); + verify(mockBroker).deleteOldFinalJobs(secondsAgo); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java index f6785c37d..4e11b7e8b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java @@ -7,9 +7,9 @@ * 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. @@ -26,10 +26,15 @@ import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; import org.onap.vid.job.command.JobCommandFactoryTest; +import org.onap.vid.properties.Features; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.UUID; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertNotNull; @@ -38,12 +43,14 @@ public class JobAdapterTest { @Test public void testCreateServiceInstantiationJob() { - JobAdapter jobAdapter = new JobAdapterImpl(); + FeatureManager featureManager = mock(FeatureManager.class); + JobAdapter jobAdapter = new JobAdapterImpl(featureManager); JobType jobType = JobType.NoOp; JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); UUID templateId = UUID.randomUUID(); String userId = "ou012t"; + String testApi = "VNF_API"; String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; int indexInBulk = RandomUtils.nextInt(); Job job = jobAdapter.createServiceInstantiationJob( @@ -51,6 +58,7 @@ public class JobAdapterTest { request, templateId, userId, + testApi, optimisticUniqueServiceInstanceName, indexInBulk ); @@ -59,6 +67,7 @@ public class JobAdapterTest { assertEquals(job.getSharedData().getRequest(), request); assertEquals(job.getSharedData().getRequestType(), request.getClass()); assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getTestApi(), testApi); assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); assertEquals(job.getSharedData().getRootJobId(), job.getUuid()); assertNotNull(job.getUuid()); @@ -68,13 +77,16 @@ public class JobAdapterTest { assertEquals(job.getStatus(), Job.JobStatus.PENDING); } - @Test - public void testCreateChildJob() { - - JobAdapter jobAdapter = new JobAdapterImpl(); + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void testCreateChildJob(boolean isFlagExpCreateResourcesInParallel) { + FeatureManager featureManager = mock(FeatureManager.class); + when(featureManager.isActive(Features.FLAG_EXP_CREATE_RESOURCES_IN_PARALLEL)).thenReturn(isFlagExpCreateResourcesInParallel); + Job.JobStatus expectedJobStatus = isFlagExpCreateResourcesInParallel ? Job.JobStatus.CREATING : Job.JobStatus.PENDING_RESOURCE; + JobAdapter jobAdapter = new JobAdapterImpl(featureManager); UUID templateId = UUID.randomUUID(); String userId = "ou012t"; + String testApi = "VNF_API"; String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; int indexInBulk = RandomUtils.nextInt(); Job grandJob = jobAdapter.createServiceInstantiationJob( @@ -82,39 +94,44 @@ public class JobAdapterTest { new JobCommandFactoryTest.MockedRequest(99, "anything"), templateId, userId, + testApi, optimisticUniqueServiceInstanceName, indexInBulk ); - Job.JobStatus jobStatus = Job.JobStatus.PAUSE; JobType jobType = JobType.NoOp; JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); - Job parentJob = jobAdapter.createChildJob(jobType, jobStatus, request, grandJob.getSharedData(), ImmutableMap.of()); + Job parentJob = jobAdapter.createChildJob(jobType, request, grandJob.getSharedData(), ImmutableMap.of(), 1); assertEquals(parentJob.getType(), jobType); assertEquals(parentJob.getSharedData().getRequest(), request); assertEquals(parentJob.getSharedData().getRequestType(), request.getClass()); assertEquals(parentJob.getSharedData().getUserId(), userId); + assertEquals(parentJob.getSharedData().getTestApi(), testApi); assertEquals(parentJob.getSharedData().getJobUuid(), parentJob.getUuid()); assertNotNull(parentJob.getUuid()); assertNotEquals(parentJob.getUuid(), grandJob.getUuid()); - assertEquals(parentJob.getStatus(), jobStatus); + assertEquals(parentJob.getStatus(), expectedJobStatus); + assertEquals(parentJob.getTemplateId(), grandJob.getUuid()); + assertEquals(parentJob.getIndexInBulk().intValue(), 1); assertEquals(parentJob.getSharedData().getRootJobId(), grandJob.getUuid()); - Job.JobStatus jobStatus2 = Job.JobStatus.IN_PROGRESS; JobType jobType2 = JobType.AggregateState; JobAdapter.AsyncJobRequest request2 = new JobCommandFactoryTest.MockedRequest(66,"abc"); - Job job = jobAdapter.createChildJob(jobType2, jobStatus2, request2, parentJob.getSharedData(), ImmutableMap.of()); + Job job = jobAdapter.createChildJob(jobType2, request2, parentJob.getSharedData(), ImmutableMap.of(), 0); assertEquals(job.getType(), jobType2); assertEquals(job.getSharedData().getRequest(), request2); assertEquals(job.getSharedData().getRequestType(), request2.getClass()); assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getTestApi(), testApi); assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); assertNotNull(job.getUuid()); assertNotEquals(job.getUuid(), parentJob.getUuid()); - assertEquals(job.getStatus(), jobStatus2); + assertEquals(job.getStatus(), expectedJobStatus); assertEquals(job.getSharedData().getRootJobId(), grandJob.getUuid()); + assertEquals(job.getTemplateId(), parentJob.getUuid()); + assertEquals(job.getIndexInBulk().intValue(), 0); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java index dc44d1520..e234ee969 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java @@ -7,9 +7,9 @@ * 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. @@ -33,6 +33,7 @@ import org.onap.vid.job.command.HttpCallCommand; import org.onap.vid.job.command.JobCommandFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.Map; import java.util.UUID; @@ -51,6 +52,9 @@ public class JobWorkerTest { @Mock private JobCommandFactory jobCommandFactory; + @Mock + private FeatureManager featureManager; + private final JobCommand jobCommand = mock(JobCommand.class); private Job jobUnderTest; private JobAdapter.AsyncJobRequest originalData; @@ -68,11 +72,12 @@ public class JobWorkerTest { }; originalType = JobType.MacroServiceInstantiation; - jobUnderTest = new JobAdapterImpl().createServiceInstantiationJob( + jobUnderTest = new JobAdapterImpl(featureManager).createServiceInstantiationJob( originalType, originalData, UUID.randomUUID(), "my user id", + "VNF_API", "optimisticUniqueServiceInstanceName", RandomUtils.nextInt() ); @@ -119,4 +124,4 @@ public class JobWorkerTest { assertThat(nextJob, jobMatcher); assertThat(jobAfter, equalTo(jobBefore)); } -} +} \ No newline at end of file -- cgit 1.2.3-korg