Update license headers
[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
62 public class ServiceInProgressStatusCommandTest {
63
64
65     @Mock
66     private AsyncInstantiationBusinessLogic asyncInstantiationBL;
67
68     @Mock
69     private JobsBrokerService jobsBrokerService;
70
71     @Mock
72     private JobAdapter jobAdapter;
73
74     @Mock
75     private FeatureManager featureManager;
76
77     @Mock
78     private JobSharedData sharedData;
79
80     @Mock
81     private Environment environment;
82
83     @Mock
84     private ServiceInstantiation request;
85
86     @Mock
87     private InProgressStatusService inProgressStatusService;
88
89     @InjectMocks
90     private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand();
91
92     @DataProvider
93     public static Object[][] isNeedToCreateChildJobsDataProvider() {
94         return new Object[][]{
95                 {new TreeMap<String,Vnf>() ,                 true, true, false},
96                 {null ,                                      true, true, false},
97                 {ImmutableMap.of("a",mock(Vnf.class)),   false, true, false},
98                 {ImmutableMap.of("a",mock(Vnf.class)),   true, false, false},
99                 {ImmutableMap.of("a",mock(Vnf.class)),   true, true, true},
100         };
101     }
102
103     @DataProvider
104     public static Object[][] processJobStatusData() {
105         return new Object[][]{
106                 /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */
107                 {IN_PROGRESS,           false, IN_PROGRESS},
108                 {FAILED,                false, FAILED},
109                 {PAUSE,                 false, IN_PROGRESS},
110                 {COMPLETED,             false, COMPLETED},
111                 {COMPLETED,             true,  IN_PROGRESS},
112                 {RESOURCE_IN_PROGRESS,  false, RESOURCE_IN_PROGRESS},
113                 {PENDING,               false, PENDING},
114                 {STOPPED,               false, STOPPED},
115                 {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS},
116                 {CREATING,              false, CREATING}
117         };
118     }
119
120     @DataProvider
121     public static Object[][] isExpiredJobStatusData() {
122         return new Object[][]{
123                 {ZonedDateTime.now(), "24", false},
124                 {getTimeNowMinus(2),  "1",  true},
125                 {getTimeNowMinus(24), "24",  true},
126                 {getTimeNowMinus(2),  "0",  false},
127                 {getTimeNowMinus(2),  "-1", false},
128                 {getTimeNowMinus(2),  "",   false},
129                 {getTimeNowMinus(2),  "a",  false}
130         };
131     }
132
133     private static ZonedDateTime getTimeNowMinus(int hoursAgo) {
134         return ZonedDateTime.ofInstant(Instant.now().minus(hoursAgo, ChronoUnit.HOURS), ZoneOffset.UTC);
135     }
136
137     @BeforeMethod
138     public void initMocks() {
139         MockitoAnnotations.initMocks(this);
140     }
141
142     @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" )
143     public void testIsNeedToCreateChildJobs(Map<String, Vnf> serviceVnfs, boolean isALaCarte,
144                                             boolean isFeatureEnabled, boolean expected) {
145         MockitoAnnotations.initMocks(this);
146         ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
147         when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs);
148         when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte);
149         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled);
150         assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected));
151     }
152
153     @Test
154     public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() {
155         UUID uuid = UUID.randomUUID();
156         String userId = "mockedUserID";
157         Vnf vnf1 = mock(Vnf.class);
158         Vnf vnf2 = mock(Vnf.class);
159         Network network1 = mock(Network.class);
160         ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
161         when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2));
162         when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1));
163         when(serviceInstantiation.isALaCarte()).thenReturn(true);
164         when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo());
165
166         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
167
168         UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012");
169         UUID uuid2 = UUID.fromString("12345678-1234-1234-1234-123456789013");
170         UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014");
171         when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3);
172
173         JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation);
174         command.init(sharedData, "", "");
175         when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED);
176         NextCommand nextCommand = command.call();
177
178         ArgumentCaptor<JobAdapter.AsyncJobRequest> argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class);
179         verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
180         verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any());
181         assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1));
182
183         verify(jobsBrokerService, times(3)).add(any());
184
185         //verify we don't update service info during this case, which shall stay in_progress
186         verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any());
187
188         assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS));
189         assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType()));
190         assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString())));
191         assertThat(nextCommand.getCommand().getData().get("isService"), is(true));
192     }
193
194     @Test(dataProvider = "processJobStatusData")
195     public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) {
196
197         when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
198         // All mocks under are used for isNeedToCreateChildJobs=true case
199         when(sharedData.getRequest()).thenReturn(request);
200         when(request.isALaCarte()).thenReturn(true);
201         Map vnfs = mock(Map.class);
202         ModelInfo modelInfo = mock(ModelInfo.class);
203       
204         // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false
205         when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs);
206       
207         when(request.getVnfs()).thenReturn(vnfs);
208         when(request.getModelInfo()).thenReturn(modelInfo);
209         command.instanceId = "MockInstId";
210
211         NextCommand nextCommand = command.processJobStatus(jobStatus);
212         Assert.assertEquals(nextCommand.getStatus(), expectedStatus);
213         if (isNeedToCreateChildJobs) {
214             Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class);
215         } else {
216             Assert.assertEquals(nextCommand.getCommand(), command);
217         }
218     }
219
220     @Test(dataProvider = "isExpiredJobStatusData")
221     public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) {
222         SystemProperties systemProperties = new SystemProperties();
223         systemProperties.setEnvironment(environment);
224         when(environment.getRequiredProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(configValue);
225         when(environment.containsProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS)).thenReturn(true);
226         Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult);
227     }
228 }