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