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 -------- 11 files changed, 642 insertions(+), 333 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 (limited to 'vid-app-common/src/test/java/org/onap/vid/job/command') 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); - } - } -} -- cgit 1.2.3-korg