31dbc9f6d2d28ee79da52e9fe19a527d2892c5f2
[vid.git] / vid-app-common / src / test / java / org / onap / vid / job / command / ServiceInProgressStatusCommandTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.job.command;
22
23 import com.google.common.collect.ImmutableMap;
24 import org.mockito.ArgumentCaptor;
25 import org.mockito.InjectMocks;
26 import org.mockito.Mock;
27 import org.mockito.MockitoAnnotations;
28 import org.onap.portalsdk.core.util.SystemProperties;
29 import org.onap.vid.job.*;
30 import org.onap.vid.job.impl.JobSharedData;
31 import org.onap.vid.model.serviceInstantiation.Network;
32 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
33 import org.onap.vid.model.serviceInstantiation.Vnf;
34 import org.onap.vid.mso.model.ModelInfo;
35 import org.onap.vid.properties.Features;
36 import org.onap.vid.properties.VidProperties;
37 import org.onap.vid.services.AsyncInstantiationBusinessLogic;
38 import org.springframework.core.env.Environment;
39 import org.testng.Assert;
40 import org.testng.annotations.BeforeMethod;
41 import org.testng.annotations.DataProvider;
42 import org.testng.annotations.Test;
43 import org.togglz.core.manager.FeatureManager;
44
45 import java.time.Instant;
46 import java.time.ZoneOffset;
47 import java.time.ZonedDateTime;
48 import java.time.temporal.ChronoUnit;
49 import java.util.Arrays;
50 import java.util.Map;
51 import java.util.TreeMap;
52 import java.util.UUID;
53
54 import static org.hamcrest.MatcherAssert.assertThat;
55 import static org.hamcrest.Matchers.containsInAnyOrder;
56 import static org.hamcrest.core.Is.is;
57 import static org.mockito.Matchers.any;
58 import static org.mockito.Matchers.eq;
59 import static org.mockito.Mockito.*;
60 import static org.onap.vid.job.Job.JobStatus.*;
61 import static org.onap.vid.testUtils.TestUtils.testWithSystemProperty;
62
63 public class ServiceInProgressStatusCommandTest {
64
65
66     @Mock
67     private AsyncInstantiationBusinessLogic asyncInstantiationBL;
68
69     @Mock
70     private JobsBrokerService jobsBrokerService;
71
72     @Mock
73     private JobAdapter jobAdapter;
74
75     @Mock
76     private FeatureManager featureManager;
77
78     @Mock
79     private JobSharedData sharedData;
80
81     @Mock
82     private Environment environment;
83
84     @Mock
85     private ServiceInstantiation request;
86
87     @Mock
88     private InProgressStatusService inProgressStatusService;
89
90     @InjectMocks
91     private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand();
92
93     @DataProvider
94     public static Object[][] isNeedToCreateChildJobsDataProvider() {
95         return new Object[][]{
96                 {new TreeMap<String,Vnf>() ,                 true, true, false},
97                 {null ,                                      true, true, false},
98                 {ImmutableMap.of("a",mock(Vnf.class)),   false, true, false},
99                 {ImmutableMap.of("a",mock(Vnf.class)),   true, false, false},
100                 {ImmutableMap.of("a",mock(Vnf.class)),   true, true, true},
101         };
102     }
103
104     @DataProvider
105     public static Object[][] processJobStatusData() {
106         return new Object[][]{
107                 /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */
108                 {IN_PROGRESS,           false, IN_PROGRESS},
109                 {FAILED,                false, FAILED},
110                 {PAUSE,                 false, IN_PROGRESS},
111                 {COMPLETED,             false, COMPLETED},
112                 {COMPLETED,             true,  IN_PROGRESS},
113                 {RESOURCE_IN_PROGRESS,  false, RESOURCE_IN_PROGRESS},
114                 {PENDING,               false, PENDING},
115                 {STOPPED,               false, STOPPED},
116                 {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS},
117                 {CREATING,              false, CREATING}
118         };
119     }
120
121     @DataProvider
122     public static Object[][] isExpiredJobStatusData() {
123         return new Object[][]{
124                 {ZonedDateTime.now(), "24", false},
125                 {getTimeNowMinus(2),  "1",  true},
126                 {getTimeNowMinus(24), "24",  true},
127                 {getTimeNowMinus(2),  "0",  false},
128                 {getTimeNowMinus(2),  "-1", false},
129                 {getTimeNowMinus(2),  "",   false},
130                 {getTimeNowMinus(2),  "a",  false}
131         };
132     }
133
134     private static ZonedDateTime getTimeNowMinus(int hoursAgo) {
135         return ZonedDateTime.ofInstant(Instant.now().minus(hoursAgo, ChronoUnit.HOURS), ZoneOffset.UTC);
136     }
137
138     @BeforeMethod
139     public void initMocks() {
140         MockitoAnnotations.initMocks(this);
141     }
142
143     @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" )
144     public void testIsNeedToCreateChildJobs(Map<String, Vnf> serviceVnfs, boolean isALaCarte,
145                                             boolean isFeatureEnabled, boolean expected) {
146         MockitoAnnotations.initMocks(this);
147         ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
148         when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs);
149         when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte);
150         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled);
151         assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected));
152     }
153
154     @Test
155     public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() {
156         UUID uuid = UUID.randomUUID();
157         String userId = "mockedUserID";
158         Vnf vnf1 = mock(Vnf.class);
159         Vnf vnf2 = mock(Vnf.class);
160         Network network1 = mock(Network.class);
161         ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
162         when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2));
163         when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1));
164         when(serviceInstantiation.isALaCarte()).thenReturn(true);
165         when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo());
166
167         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
168
169         UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012");
170         UUID uuid2 = UUID.fromString("12345678-1234-1234-1234-123456789013");
171         UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014");
172         when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3);
173
174         JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation);
175         command.init(sharedData, "", "");
176         when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED);
177         NextCommand nextCommand = command.call();
178
179         ArgumentCaptor<JobAdapter.AsyncJobRequest> argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class);
180         verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
181         verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
182         assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1));
183
184         verify(jobsBrokerService, times(3)).add(any());
185
186         //verify we don't update service info during this case, which shall stay in_progress
187         verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any());
188
189         assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS));
190         assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType()));
191         assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString())));
192         assertThat(nextCommand.getCommand().getData().get("isService"), is(true));
193     }
194
195     @Test(dataProvider = "processJobStatusData")
196     public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) {
197
198         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
199         // All mocks under are used for isNeedToCreateChildJobs=true case
200         when(sharedData.getRequest()).thenReturn(request);
201         when(request.isALaCarte()).thenReturn(true);
202         Map vnfs = mock(Map.class);
203         ModelInfo modelInfo = mock(ModelInfo.class);
204       
205         // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false
206         when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs);
207       
208         when(request.getVnfs()).thenReturn(vnfs);
209         when(request.getModelInfo()).thenReturn(modelInfo);
210         command.instanceId = "MockInstId";
211
212         NextCommand nextCommand = command.processJobStatus(jobStatus);
213         Assert.assertEquals(nextCommand.getStatus(), expectedStatus);
214         if (isNeedToCreateChildJobs) {
215             Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class);
216         } else {
217             Assert.assertEquals(nextCommand.getCommand(), command);
218         }
219     }
220
221     @Test(dataProvider = "isExpiredJobStatusData")
222     public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) throws Exception {
223         testWithSystemProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS, configValue, ()->
224             Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult)
225         );
226     }
227 }