catalog-be servlets refactoring
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / servlets / AutomatedUpgradeEndpointTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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.openecomp.sdc.be.servlets;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import fj.data.Either;
25 import org.glassfish.jersey.client.ClientConfig;
26 import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJaxbJsonProvider;
27 import org.glassfish.jersey.jackson.internal.jackson.jaxrs.json.JacksonJsonProvider;
28 import org.glassfish.jersey.server.ResourceConfig;
29 import org.junit.Before;
30 import org.junit.BeforeClass;
31 import org.junit.Test;
32 import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic;
33 import org.openecomp.sdc.be.components.impl.GroupBusinessLogic;
34 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
35 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
36 import org.openecomp.sdc.be.components.upgrade.ServiceInfo;
37 import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic;
38 import org.openecomp.sdc.be.components.upgrade.UpgradeRequest;
39 import org.openecomp.sdc.be.components.upgrade.UpgradeStatus;
40 import org.openecomp.sdc.be.components.validation.UserValidations;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.dao.api.ActionStatus;
43 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
44 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
45 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
46 import org.openecomp.sdc.be.impl.ComponentsUtils;
47 import org.openecomp.sdc.be.model.*;
48 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
49 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.UpgradeOperation;
50 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
51 import org.openecomp.sdc.be.user.UserBusinessLogic;
52 import org.openecomp.sdc.common.api.ConfigurationSource;
53 import org.openecomp.sdc.common.api.Constants;
54 import org.openecomp.sdc.common.impl.ExternalConfiguration;
55 import org.openecomp.sdc.common.impl.FSConfigurationSource;
56 import org.openecomp.sdc.exception.ResponseFormat;
57 import org.openecomp.sdc.exception.ServiceException;
58 import org.springframework.context.annotation.Bean;
59 import org.springframework.context.annotation.Import;
60 import org.springframework.http.HttpStatus;
61
62 import javax.ws.rs.client.Entity;
63 import javax.ws.rs.client.Invocation;
64 import javax.ws.rs.core.MediaType;
65 import javax.ws.rs.core.Response;
66 import java.util.ArrayList;
67 import java.util.List;
68
69 import static org.assertj.core.api.Assertions.assertThat;
70 import static org.mockito.ArgumentMatchers.any;
71 import static org.mockito.ArgumentMatchers.anyBoolean;
72 import static org.mockito.ArgumentMatchers.anyString;
73 import static org.mockito.ArgumentMatchers.eq;
74 import static org.mockito.Mockito.*;
75
76 public class AutomatedUpgradeEndpointTest extends JerseySpringBaseTest {
77     static ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), "src/test/resources/config/catalog-be");
78     static ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
79
80     private static final String RESOURCE_ID_PREV = "prevVF";
81     private static final String RESOURCE_ID_NEW = "newVF";
82     private static final String SERVICE_ID_PREV = "prevSer";
83     private static final String SERVICE_ID_NEW = "newSer";
84     private static final String SERVICE_ID_PROXY = "serProxy";
85     private static final String SERVICE_ID_PROXY_PREV = "serProxyContainerPrev";
86     private static final String SERVICE_ID_PROXY_NEW = "serProxyContainerNew";
87     private static final String INVARIANT_ID = "invariantUUID";
88     private static final String USER_ID = "userId";
89
90     private static LifecycleBusinessLogic lifecycleBusinessLogic;
91     private static ComponentInstanceBusinessLogic componentInstanceBusinessLogic;
92     private static UserValidations userValidations;
93     private static ToscaOperationFacade toscaOperationFacade;
94     private static ComponentsUtils componentsUtils;
95     private static UpgradeOperation upgradeOperation;
96     private static JanusGraphDao janusGraphDao;
97
98     private static User user;
99     private static Resource vfPrev;
100     private static Resource vfNew;
101     private static Service servicePrev;
102     private static Service serviceNew;
103     private static Service serviceNewCheckIn;
104     private static ComponentInstance istanceNew;
105
106     private static Service serviceProxy;
107     private static Service serviceProxyContainerPrev;
108     private static Service serviceProxyContainerNew;
109
110     @org.springframework.context.annotation.Configuration
111     @Import(BaseTestConfig.class)
112     static class AutomatedUpgradeTestConfig {
113
114         @Bean
115         AutomatedUpgradeEndpoint automatedUpgradeEndpoint() {
116
117             UserBusinessLogic userBusinessLogic = mock(UserBusinessLogic.class);
118             ComponentsUtils componentsUtils = mock(ComponentsUtils.class);
119
120             return new AutomatedUpgradeEndpoint(userBusinessLogic, componentsUtils,
121                 upgradeBusinessLogic());
122         }
123
124         @Bean
125         UpgradeBusinessLogic upgradeBusinessLogic() {
126             return new UpgradeBusinessLogic(lifecycleBusinessLogic, componentInstanceBusinessLogic, userValidations, toscaOperationFacade, componentsUtils, upgradeOperation,
127                 janusGraphDao);
128         }
129     }
130
131     @BeforeClass
132     public static void initClass() {
133         lifecycleBusinessLogic = mock(LifecycleBusinessLogic.class);
134         componentInstanceBusinessLogic = mock(ComponentInstanceBusinessLogic.class);
135         userValidations = mock(UserValidations.class);
136         toscaOperationFacade = mock(ToscaOperationFacade.class);
137         componentsUtils = mock(ComponentsUtils.class);
138         upgradeOperation = mock(UpgradeOperation.class);
139         janusGraphDao = mock(JanusGraphDao.class);
140         user = mock(User.class);
141     }
142
143     @Before
144     public void init() {
145         prepareComponents();
146         when(userValidations.validateUserExists(eq(USER_ID), anyString(), anyBoolean())).thenReturn(user);
147         when(toscaOperationFacade.getToscaFullElement(eq(RESOURCE_ID_PREV))).thenReturn(Either.left(vfPrev));
148         when(toscaOperationFacade.getToscaFullElement(eq(RESOURCE_ID_NEW))).thenReturn(Either.left(vfNew));
149         when(toscaOperationFacade.getToscaFullElement(eq(SERVICE_ID_PREV))).thenReturn(Either.left(servicePrev));
150         when(toscaOperationFacade.getToscaFullElement(eq(SERVICE_ID_NEW))).thenReturn(Either.left(serviceNew));
151
152         Either<Service, ResponseFormat> fromLifeCycle = Either.left(serviceNew);
153         doReturn(fromLifeCycle).when(lifecycleBusinessLogic).changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_PREV), any(User.class), eq(LifeCycleTransitionEnum.CHECKOUT), any(LifecycleChangeInfoWithAction.class), eq(false),
154                 eq(true));
155
156         when(toscaOperationFacade.getToscaElement(eq(RESOURCE_ID_PREV), any(ComponentParametersView.class))).thenReturn(Either.left(vfPrev));
157         when(componentInstanceBusinessLogic.changeInstanceVersion(any(Service.class), any(ComponentInstance.class), any(ComponentInstance.class), any(User.class), eq(ComponentTypeEnum.SERVICE))).thenReturn(Either.left(istanceNew));
158
159         doReturn(Either.left(serviceNewCheckIn)).when(lifecycleBusinessLogic).changeComponentState(eq(ComponentTypeEnum.SERVICE), eq(SERVICE_ID_NEW), any(User.class), eq(LifeCycleTransitionEnum.CHECKIN), any(LifecycleChangeInfoWithAction.class),
160                 eq(false), eq(true));
161
162     }
163
164     @Override
165     protected void configureClient(ClientConfig config) {
166         final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
167         config.register(jacksonJsonProvider);
168     }
169
170     @Override
171     protected ResourceConfig configure() {
172         return super.configure(AutomatedUpgradeTestConfig.class).register(AutomatedUpgradeEndpoint.class);
173     }
174
175     @Test
176     public void upgradeVfInService_success() {
177         List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
178         UpgradeRequest request = new UpgradeRequest(SERVICE_ID_PREV);
179         inputsToUpdate.add(request);
180
181         Invocation.Builder builder = buildAutomatedUpgradeCall(RESOURCE_ID_NEW);
182         UpgradeStatus status = builder.post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), UpgradeStatus.class);
183
184         assertThat(status.getStatus()).isEqualTo(ActionStatus.OK);
185         List<ServiceInfo> expected = new ArrayList<>();
186         ServiceInfo serviceInfo = new ServiceInfo(serviceNewCheckIn.getUniqueId(), ActionStatus.OK);
187         serviceInfo.setName(serviceNewCheckIn.getName());
188         serviceInfo.setVersion(serviceNewCheckIn.getVersion());
189         expected.add(serviceInfo);
190         assertThat(status.getComponentToUpgradeStatus()).hasSameSizeAs(expected);
191         assertThat(status.getComponentToUpgradeStatus()).hasSameElementsAs(expected);
192
193     }
194
195     @Test
196     public void upgradeVfInService_IdNotExist() {
197         List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
198         UpgradeRequest request = new UpgradeRequest(SERVICE_ID_PREV);
199         inputsToUpdate.add(request);
200         String wrongId = "1234";
201         when(toscaOperationFacade.getToscaFullElement(eq(wrongId))).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
202         when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
203         String[] variables = { wrongId };
204         ServiceException serviceException = new ServiceException("SVC4063", "Error: Requested '%1' resource was not found.", variables);
205         ResponseFormat expected = new ResponseFormat(HttpStatus.NOT_FOUND.value());
206         expected.setServiceException(serviceException);
207         when(componentsUtils.getResponseFormatByResource(eq(ActionStatus.RESOURCE_NOT_FOUND), eq(wrongId))).thenReturn(expected);
208
209         Response response = buildAutomatedUpgradeCall(wrongId).post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
210         assertThat(response.getStatus()).isEqualTo(HttpStatus.NOT_FOUND.value());
211
212         ResponseFormat actual = response.readEntity(ResponseFormat.class);
213         assertThat(actual.getMessageId()).isEqualTo(expected.getMessageId());
214         assertThat(actual.getFormattedMessage()).isEqualTo(expected.getFormattedMessage());
215
216     }
217
218     @Test
219     public void upgradeVfInService_NotHihgestCertified() {
220         List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
221         UpgradeRequest request = new UpgradeRequest(RESOURCE_ID_PREV);
222         inputsToUpdate.add(request);
223
224         when(componentsUtils.convertFromStorageResponse(eq(StorageOperationStatus.NOT_FOUND))).thenReturn(ActionStatus.RESOURCE_NOT_FOUND);
225         String[] variables = { vfPrev.getName() };
226         ServiceException serviceException = new ServiceException("SVC4699", "Error: Component %1 is not highest certified", variables);
227         ResponseFormat expected = new ResponseFormat(HttpStatus.BAD_REQUEST.value());
228         expected.setServiceException(serviceException);
229         when(componentsUtils.getResponseFormat(eq(ActionStatus.COMPONENT_IS_NOT_HIHGEST_CERTIFIED), eq(vfPrev.getName()))).thenReturn(expected);
230
231         Response response = buildAutomatedUpgradeCall(RESOURCE_ID_PREV).post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), Response.class);
232         assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value());
233
234         ResponseFormat actual = response.readEntity(ResponseFormat.class);
235         assertThat(actual.getMessageId()).isEqualTo(expected.getMessageId());
236         assertThat(actual.getFormattedMessage()).isEqualTo(expected.getFormattedMessage());
237     }
238
239 //    @Test
240 //    public void upgradeProxyInService_successful() {
241 //        List<UpgradeRequest> inputsToUpdate = new ArrayList<>();
242 //        UpgradeRequest request = new UpgradeRequest(SERVICE_ID_PROXY_PREV);
243 //        inputsToUpdate.add(request);
244 //
245 //        when(toscaOperationFacade.getToscaElement(eq(SERVICE_ID_PROXY))).thenReturn(Either.left(serviceProxy));
246 //        
247 //        UpgradeStatus status = buildAutomatedUpgradeCall(SERVICE_ID_PROXY).post(Entity.entity(inputsToUpdate, MediaType.APPLICATION_JSON), UpgradeStatus.class);
248 //        assertThat(status.getStatus()).isEqualTo(ActionStatus.OK);
249 //    }
250
251     private Invocation.Builder buildAutomatedUpgradeCall(String id) {
252         return target("/v1/catalog/resources/{id}/automatedupgrade").resolveTemplate("id", id).request(MediaType.APPLICATION_JSON).header(Constants.USER_ID_HEADER, USER_ID);
253     }
254
255     private void prepareComponents() {
256         createVF();
257
258         createService();
259     }
260
261     private void createService() {
262         servicePrev = createService("service1", SERVICE_ID_PREV, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
263         
264         ComponentInstance ci = new ComponentInstance();
265         ci.setComponentUid(RESOURCE_ID_PREV);
266         ci.setName("inst 1");
267         List<ComponentInstance> resourceInstances = new ArrayList<>();
268         resourceInstances.add(ci);
269         servicePrev.setComponentInstances(resourceInstances);
270
271         serviceNew = createService("service1", SERVICE_ID_NEW, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
272         serviceNew.setComponentInstances(resourceInstances);
273
274         serviceNewCheckIn = createService("service1", SERVICE_ID_NEW, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
275         
276         serviceNewCheckIn.setComponentInstances(resourceInstances);
277
278         istanceNew = new ComponentInstance();
279         istanceNew.setComponentUid(RESOURCE_ID_NEW);
280         istanceNew.setName("inst 1");
281
282         serviceProxy = createService("serviceProxy", SERVICE_ID_PROXY, LifecycleStateEnum.CERTIFIED);
283         serviceProxyContainerPrev = createService("serviceProxyContainer", SERVICE_ID_PROXY_PREV, LifecycleStateEnum.NOT_CERTIFIED_CHECKIN);
284         serviceProxyContainerNew = createService("serviceProxyContainer", SERVICE_ID_PROXY_NEW, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
285        
286         
287
288     }
289
290     private Service createService(String name, String id, LifecycleStateEnum state){
291         Service service = new Service();
292         service.setName(name);
293         service.setUniqueId(id);
294         service.setLifecycleState(state);
295         service.setHighestVersion(true);
296         return service;
297     }
298     private void createVF() {
299         vfPrev = new Resource();
300         vfPrev.setName("vf1");
301         vfPrev.setUniqueId(RESOURCE_ID_PREV);
302         vfPrev.setLifecycleState(LifecycleStateEnum.CERTIFIED);
303         vfPrev.setHighestVersion(false);
304         vfPrev.setResourceType(ResourceTypeEnum.VF);
305         vfPrev.setVersion("1.0");
306         vfPrev.setInvariantUUID(INVARIANT_ID);
307         vfPrev.setComponentType(ComponentTypeEnum.RESOURCE);
308
309         vfNew = new Resource();
310         vfNew.setName("vf1");
311         vfNew.setUniqueId(RESOURCE_ID_PREV);
312         vfNew.setLifecycleState(LifecycleStateEnum.CERTIFIED);
313         vfNew.setHighestVersion(true);
314         vfNew.setResourceType(ResourceTypeEnum.VF);
315         vfNew.setVersion("2.0");
316         vfNew.setInvariantUUID(INVARIANT_ID);
317         vfNew.setComponentType(ComponentTypeEnum.RESOURCE);
318
319     }
320 }