Catalog alignment
[sdc.git] / asdctool / src / test / java / org / openecomp / sdc / asdctool / migration / tasks / mig1710 / UpgradeMigration1710Test.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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  * Modifications copyright (c) 2019 Nokia
20  * ================================================================================
21  */
22 package org.openecomp.sdc.asdctool.migration.tasks.mig1710;
23
24 import com.google.common.collect.Lists;
25 import fj.data.Either;
26 import org.junit.AfterClass;
27 import org.junit.Before;
28 import org.junit.BeforeClass;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.InjectMocks;
32 import org.mockito.Mock;
33 import org.mockito.junit.MockitoJUnitRunner;
34 import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
35 import org.openecomp.sdc.asdctool.migration.tasks.handlers.XlsOutputHandler;
36 import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic;
37 import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic;
38 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
40 import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic;
41 import org.openecomp.sdc.be.config.Configuration;
42 import org.openecomp.sdc.be.config.ConfigurationManager;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
45 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
46 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
47 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
48 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
49 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
51 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
52 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
53 import org.openecomp.sdc.be.impl.ComponentsUtils;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.ComponentInstance;
56 import org.openecomp.sdc.be.model.ComponentParametersView;
57 import org.openecomp.sdc.be.model.LifecycleStateEnum;
58 import org.openecomp.sdc.be.model.Resource;
59 import org.openecomp.sdc.be.model.Service;
60 import org.openecomp.sdc.be.model.User;
61 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
62 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
63 import org.openecomp.sdc.be.model.operations.impl.CsarOperation;
64 import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
65 import org.openecomp.sdc.common.api.ConfigurationSource;
66 import org.openecomp.sdc.common.http.client.api.HttpRequestHandler;
67 import org.openecomp.sdc.exception.ResponseFormat;
68
69 import java.util.ArrayList;
70 import java.util.HashMap;
71 import java.util.List;
72 import java.util.Map;
73 import java.util.stream.Collectors;
74 import java.util.stream.Stream;
75
76 import static org.junit.Assert.assertEquals;
77 import static org.mockito.ArgumentMatchers.any;
78 import static org.mockito.ArgumentMatchers.anyString;
79 import static org.mockito.ArgumentMatchers.eq;
80 import static org.mockito.Mockito.doReturn;
81 import static org.mockito.Mockito.times;
82 import static org.mockito.Mockito.verify;
83 import static org.mockito.Mockito.when;
84
85 @RunWith(MockitoJUnitRunner.class)
86 public class UpgradeMigration1710Test {
87
88     private static final String USER = "jh0003";
89     private static final String CONF_LEVEL = "5.0";
90     private static final String COMPONENT_UNIQUE_ID = "12345";
91     private static final String OLD_VERSION = "1.0";
92     private static final String UPDATED_VERSION = "2.0";
93     private static final String CSAR_UUID = "1234578";
94     private static HttpRequestHandler originHandler;
95
96     private final User user = new User();
97
98     @InjectMocks
99     private UpgradeMigration1710 migration = new UpgradeMigration1710();
100     @Mock
101     private UserAdminOperation userAdminOperation;
102     @Mock
103     private ToscaOperationFacade toscaOperationFacade;
104     @Mock
105     private LifecycleBusinessLogic lifecycleBusinessLogic;
106     @Mock
107     private JanusGraphDao janusGraphDao;
108     @Mock
109     private ComponentsUtils componentUtils;
110     @Mock
111     private CsarOperation csarOperation;
112     @Mock
113     private ConfigurationSource configurationSource;
114     //don't remove - it is intended to avoid the xls file generating
115     @Mock
116     private XlsOutputHandler outputHandler;
117     @Mock
118     private ResourceBusinessLogic resourceBusinessLogic;
119     @Mock
120     private ServiceBusinessLogic serviceBusinessLogic;
121     @Mock
122     private ResponseFormat responseFormat;
123     @Mock
124     private ComponentsCleanBusinessLogic componentsCleanBusinessLogic;
125
126     private static ConfigurationManager configurationManager;
127     private static List<String> resources = Stream.of("org.openecomp.resource.cp.extCP").collect(Collectors.toList());
128     private static Map<String, List<String>> resourcesForUpgrade;
129     private static Configuration.EnvironmentContext environmentContext = new Configuration.EnvironmentContext();
130
131     private Resource resource;
132     private Service service;
133     private List<String> vfList = new ArrayList<>();
134
135     @BeforeClass
136     public static void setUpClass() {
137         resourcesForUpgrade = new HashMap<>();
138         resourcesForUpgrade.put(CONF_LEVEL, resources);
139         originHandler = HttpRequestHandler.get();
140     }
141
142     @AfterClass
143     public static void tearDownClass() {
144         //put the origin handler back
145         HttpRequestHandler.setTestInstance(originHandler);
146     }
147
148     @Before
149     public void setUp() {
150         user.setUserId(USER);
151         configurationManager = new ConfigurationManager(configurationSource);
152         configurationManager.setConfiguration(new Configuration());
153         configurationManager.getConfiguration().setSkipUpgradeVSPs(true);
154         configurationManager.getConfiguration().setSkipUpgradeFailedVfs(true);
155         configurationManager.getConfiguration().setAutoHealingOwner(USER);
156         configurationManager.getConfiguration().setSupportAllottedResourcesAndProxy(true);
157         configurationManager.getConfiguration().setDeleteLockTimeoutInSeconds(10);
158         configurationManager.getConfiguration().setMaxDeleteComponents(5);
159         configurationManager.getConfiguration().setEnableAutoHealing(true);
160         configurationManager.getConfiguration().setToscaConformanceLevel("5.0");
161         environmentContext.setDefaultValue("General_Revenue-Bearing");
162         configurationManager.getConfiguration().setEnvironmentContext(environmentContext);
163         HashMap<String, List<String>> resourcesForUpgrade = new HashMap();
164         resourcesForUpgrade.put("5.0", Lists.newArrayList("port"));
165         configurationManager.getConfiguration().setResourcesForUpgrade(resourcesForUpgrade);
166
167         migration.init();
168         migration.setNodeTypesSupportOnly(false);
169         when(componentsCleanBusinessLogic.lockDeleteOperation()).thenReturn(StorageOperationStatus.OK);
170
171         resource = new Resource();
172         resource.setCsarUUID(CSAR_UUID);
173         resource.setVersion(OLD_VERSION);
174         resource.setUniqueId(COMPONENT_UNIQUE_ID);
175
176         service = new Service();
177         service.setVersion(OLD_VERSION);
178         service.setUniqueId(COMPONENT_UNIQUE_ID);
179
180         vfList.add(COMPONENT_UNIQUE_ID);
181
182         when(responseFormat.getFormattedMessage())
183                 .thenReturn("");
184         when(componentUtils.convertFromStorageResponse(any(), any())).thenCallRealMethod();
185         mockChangeComponentState();
186     }
187
188     @Test
189     public void nodeTypesUpgradeFailed() {
190         migration.setNodeTypesSupportOnly(true);
191         resolveUserAndDefineUpgradeLevel();
192         when(janusGraphDao.getByCriteria(any(), any(), any(), any()))
193                 .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
194         assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
195     }
196
197     @Test
198     public void migrationDisabled() {
199         configurationManager.getConfiguration().setEnableAutoHealing(false);
200         migration.init();
201         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
202         verify(janusGraphDao, times(0)).commit();
203         verify(janusGraphDao, times(0)).rollback();
204     }
205
206     @Test
207     public void migrationFailedIfDeleteNodeLockFailed() {
208         when(componentsCleanBusinessLogic.lockDeleteOperation())
209                 .thenReturn(StorageOperationStatus.BAD_REQUEST);
210         assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
211     }
212
213     @Test
214     public void migrationFailedIfDeleteNodeLockRetryFailed() {
215         when(componentsCleanBusinessLogic.lockDeleteOperation())
216                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT)
217                 .thenReturn(StorageOperationStatus.BAD_REQUEST);
218         assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
219     }
220
221     @Test
222     public void nodeTypesOnlyUpgradePassed() {
223         migration.setNodeTypesSupportOnly(true);
224         upgradeAllScenario(false);
225         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
226         verify(janusGraphDao, times(2)).commit();
227         verify(janusGraphDao, times(0)).rollback();
228     }
229
230     @Test
231     public void nodeTypesUpgradePassedAndVFsUpgradeFailedWhenSkipFailedVFsIsNotSupported() {
232         final boolean failOnVfUpgrade = true;
233         final boolean upgradeServices = false;
234         final boolean exceptionOnVfUpgrade = false;
235         final boolean upgradeVFC = false;
236         final boolean isFailed = true;
237         configurationManager.getConfiguration().setSkipUpgradeFailedVfs(false);
238         migration.init();
239         migration.setNodeTypesSupportOnly(false);
240         resolveUserAndDefineUpgradeLevel();
241         upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC, isFailed);
242         assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
243         verify(janusGraphDao, times(1)).commit();
244         verify(janusGraphDao, times(2)).rollback();
245     }
246
247
248     @Test
249     public void upgradeAllVFsUpgradeFailedOnExceptionWhenSkipFailedVFsIsNotSupported() {
250         final boolean failOnVfUpgrade = false;
251         final boolean upgradeServices = false;
252         final boolean exceptionOnVfUpgrade = true;
253         final boolean upgradeVFC = false;
254         final boolean isFailed = true;
255         configurationManager.getConfiguration().setSkipUpgradeFailedVfs(false);
256         resolveUserAndDefineUpgradeLevel();
257         upgradeRules(failOnVfUpgrade, exceptionOnVfUpgrade, upgradeServices, upgradeVFC, isFailed);
258         migration.init();
259         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
260         verify(janusGraphDao, times(2)).commit();
261         verify(janusGraphDao, times(0)).rollback();
262     }
263
264     @Test
265     public void upgradeAllIfVFsUpgradeFailedOnExceptionWhenSkipFailedVFsIsSupported() {
266         final boolean failOnVfUpgrade = false;
267         final boolean upgradeServices = true;
268         final boolean exceptionOnFvUpgrade = true;
269         final boolean upgradeVFC = false;
270         final boolean isFailed = false;
271         configurationManager.getConfiguration().setSkipUpgradeFailedVfs(true);
272         resolveUserAndDefineUpgradeLevel();
273         upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC, isFailed);
274         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
275         verify(janusGraphDao, times(3)).commit();
276         verify(janusGraphDao, times(1)).rollback();
277     }
278
279
280     @Test
281     public void upgradeAll() {
282         upgradeAllScenario(true);
283         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
284         verify(janusGraphDao, times(4)).commit();
285         verify(janusGraphDao, times(0)).rollback();
286     }
287
288     @Test
289     public void upgradeAllWhenDeleteLockRetrySucceeded() {
290         when(componentsCleanBusinessLogic.lockDeleteOperation())
291                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT)
292                 .thenReturn(StorageOperationStatus.OK);
293         upgradeAllScenario(true);
294         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
295         verify(janusGraphDao, times(4)).commit();
296         verify(janusGraphDao, times(0)).rollback();
297     }
298
299     @Test
300     public void upgradeAllWhenVspUpgradeIsRequired() {
301         final boolean failOnVfUpgrade = false;
302         final boolean upgradeServices = true;
303         final boolean exceptionOnFvUpgrade = false;
304         final boolean upgradeVFC = true;
305         final boolean isFailed = true;
306         resolveUserAndDefineUpgradeLevel();
307         upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC, isFailed);
308         configurationManager.getConfiguration().setSkipUpgradeVSPs(false);
309         assertEquals(MigrationResult.MigrationStatus.COMPLETED, migration.migrate().getMigrationStatus());
310     }
311
312     @Test
313     public void migrationFailedWhenUserNotResolved() {
314         when(userAdminOperation.getUserData(anyString(), eq(false))).thenReturn(Either.right(ActionStatus.MISSING_INFORMATION));
315         when(janusGraphDao.rollback()).thenReturn(JanusGraphOperationStatus.OK);
316         assertEquals(MigrationResult.MigrationStatus.FAILED, migration.migrate().getMigrationStatus());
317     }
318
319     @Test
320     public void verifyThatCheckedOutResourcesMarkedAsDeletedIfUpgradeFailed() {
321         mockCheckoutFlow();
322         when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(Resource.class), any(), any(), any(),
323                 any()))
324                 .thenThrow(new ByResponseFormatComponentException(responseFormat));
325         when(resourceBusinessLogic.deleteResource(anyString(), any()))
326                 .thenReturn(responseFormat);
327         mockChangeComponentState();
328         migration.upgradeVFs(vfList, false);
329         verify(resourceBusinessLogic).deleteResource(anyString(), any());
330     }
331
332     @Test
333     public void verifyThatCheckedOutAllottedResourcesMarkedAsDeletedIfUpgradeFailed() {
334         mockCheckoutFlow();
335         when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(Resource.class), any(), any(), any(),
336                 any()))
337                 .thenThrow(new ByResponseFormatComponentException(responseFormat));
338         when(resourceBusinessLogic.deleteResource(anyString(), any()))
339                 .thenReturn(responseFormat);
340         mockChangeComponentState();
341         migration.upgradeVFs(vfList, true);
342         verify(resourceBusinessLogic).deleteResource(anyString(), any());
343     }
344
345     @Test
346     public void verifyThatCheckedOutResourceIsNotMarkedAsDeletedIfUpgradeSucceeded() {
347         mockCheckoutFlow();
348         resource.setVersion(UPDATED_VERSION);
349         when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(Resource.class), any(), any(), any(),
350                 any()))
351                 .thenReturn(resource);
352         mockChangeComponentState();
353         migration.upgradeVFs(vfList, true);
354         verify(resourceBusinessLogic, times(0)).deleteResource(anyString(), any());
355     }
356
357     @Test
358     public void verifyThatCheckedOutServicesMarkedAsDeletedIfUpgradeFailed() {
359         List<String> servicesForUpgrade = new ArrayList<>();
360         servicesForUpgrade.add(COMPONENT_UNIQUE_ID);
361
362         Either<Resource, StorageOperationStatus> foundServices = Either.left(resource);
363         mockCheckoutFlow();
364         when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class)))
365                 .thenReturn(Either.left(service));
366         when(toscaOperationFacade.getLatestCertifiedByToscaResourceName(any(), any(), any()))
367                 .thenReturn(foundServices);
368         migration.upgradeServices(servicesForUpgrade, component -> true, "services");
369         verify(serviceBusinessLogic, times(0)).deleteService(anyString(), any());
370     }
371
372     @Test
373     public void verifyThatCheckedOutServicesIsNotMarkedAsDeletedIfUpgradeSucceeded() {
374         List<String> servicesForUpgrade = new ArrayList<>();
375         servicesForUpgrade.add(COMPONENT_UNIQUE_ID);
376
377         mockCheckoutFlow();
378         when(toscaOperationFacade.getLatestCertifiedByToscaResourceName(anyString(), any(VertexTypeEnum.class), any(JsonParseFlagEnum.class)))
379                 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
380         when(serviceBusinessLogic.deleteService(anyString(), any()))
381                 .thenReturn(responseFormat);
382         migration.upgradeServices(servicesForUpgrade, component -> true, "services");
383         verify(serviceBusinessLogic).deleteService(anyString(), any());
384     }
385
386
387     @Test
388     public void unlockDeleteOperationIsPerformedIfItWasLocked() {
389         migration.isLockDeleteOperationSucceeded();
390         migration.unlockDeleteOperation();
391         verify(componentsCleanBusinessLogic).unlockDeleteOperation();
392     }
393
394     @Test
395     public void unlockDeleteOperationIsNotPerformedIfItWasNotLocked() {
396         when(componentsCleanBusinessLogic.lockDeleteOperation()).thenReturn(StorageOperationStatus.GENERAL_ERROR);
397         migration.isLockDeleteOperationSucceeded();
398         migration.unlockDeleteOperation();
399         verify(componentsCleanBusinessLogic, times(0)).unlockDeleteOperation();
400     }
401
402     @Test
403     public void deleteLockSucceededAfterRetry() {
404         when(componentsCleanBusinessLogic.lockDeleteOperation())
405                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT)
406                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT)
407                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT)
408                 .thenReturn(StorageOperationStatus.OK);
409         migration.isLockDeleteOperationSucceeded();
410         migration.unlockDeleteOperation();
411         verify(componentsCleanBusinessLogic).unlockDeleteOperation();
412     }
413
414     @Test
415     public void deleteLockFailedAfterRetry() {
416         when(componentsCleanBusinessLogic.lockDeleteOperation())
417                 .thenReturn(StorageOperationStatus.FAILED_TO_LOCK_ELEMENT);
418         migration.isLockDeleteOperationSucceeded();
419         migration.unlockDeleteOperation();
420         verify(componentsCleanBusinessLogic, times(0)).unlockDeleteOperation();
421     }
422
423     @Test
424     public void deleteMarkedResourcesWhenLimitIsReached() {
425         ArrayList<NodeTypeEnum> componentsToClean = new ArrayList<>();
426         componentsToClean.add(NodeTypeEnum.Resource);
427         migration.setUser(user);
428         migration.setMarkedAsDeletedResourcesCnt(5);
429         migration.deleteResourcesIfLimitIsReached();
430         verify(componentsCleanBusinessLogic).cleanComponents(componentsToClean, true);
431     }
432
433     @Test
434     public void deleteMarkedResourcesNotCalledWhenLimitIsNotReached() {
435         ArrayList<NodeTypeEnum> componentsToClean = new ArrayList<>();
436         componentsToClean.add(NodeTypeEnum.Resource);
437         migration.setUser(user);
438         migration.setMarkedAsDeletedResourcesCnt(3);
439         migration.deleteResourcesIfLimitIsReached();
440         verify(componentsCleanBusinessLogic, times(0)).cleanComponents(componentsToClean, true);
441     }
442
443     @Test
444     public void deleteMarkedServicesWhenLimitIsReached() {
445         ArrayList<NodeTypeEnum> componentsToClean = new ArrayList<>();
446         componentsToClean.add(NodeTypeEnum.Service);
447         migration.setUser(user);
448         migration.setMarkedAsDeletedServicesCnt(5);
449         migration.deleteServicesIfLimitIsReached();
450         verify(componentsCleanBusinessLogic).cleanComponents(componentsToClean, true);
451     }
452
453     @Test
454     public void deleteMarkedServicesNotCalledWhenLimitIsNotReached() {
455         ArrayList<NodeTypeEnum> componentsToClean = new ArrayList<>();
456         componentsToClean.add(NodeTypeEnum.Service);
457         migration.setUser(user);
458         migration.setMarkedAsDeletedServicesCnt(2);
459         migration.deleteServicesIfLimitIsReached();
460         verify(componentsCleanBusinessLogic, times(0)).cleanComponents(componentsToClean, true);
461     }
462
463     @Test
464     public void getVfUpgradeStatusWhenUpgradeFailedAndItIsInstance() {
465         assertEquals(UpgradeMigration1710.UpgradeStatus.NOT_UPGRADED, migration.getVfUpgradeStatus(false, true));
466     }
467
468     @Test
469     public void getVfUpgradeStatusWhenUpgradeFailedAndItIsNotInstance() {
470         assertEquals(UpgradeMigration1710.UpgradeStatus.NOT_UPGRADED, migration.getVfUpgradeStatus(false, false));
471     }
472
473     @Test
474     public void getVfUpgradeStatusWhenUpgradeSucceededAndItIsInstance() {
475         assertEquals(UpgradeMigration1710.UpgradeStatus.UPGRADED_AS_INSTANCE, migration.getVfUpgradeStatus(true, true));
476     }
477
478     @Test
479     public void getVfUpgradeStatusWhenUpgradeSucceededAndItIsNotInstance() {
480         assertEquals(UpgradeMigration1710.UpgradeStatus.UPGRADED, migration.getVfUpgradeStatus(true, false));
481     }
482
483     private void resolveUserAndDefineUpgradeLevel() {
484         when(userAdminOperation.getUserData(anyString(), eq(false))).thenReturn(Either.left(user));
485         configurationManager.getConfiguration().setToscaConformanceLevel(CONF_LEVEL);
486         configurationManager.getConfiguration().setResourcesForUpgrade(resourcesForUpgrade);
487     }
488
489     private void upgradeAllScenario(boolean upgradeServices) {
490         final boolean failOnVfUpgrade = false;
491         final boolean exceptionOnFvUpgrade = false;
492         final boolean upgradeVFC = false;
493         final boolean isFailed = false;
494         final boolean isProxy = true;
495
496         resolveUserAndDefineUpgradeLevel();
497         mockCheckoutFlow();
498         when(resourceBusinessLogic.validateAndUpdateResourceFromCsar(any(Resource.class), any(), any(), any(),
499                 any()))
500                 .thenReturn(resource);
501         upgradeRules(failOnVfUpgrade, exceptionOnFvUpgrade, upgradeServices, upgradeVFC, isFailed, isProxy);
502     }
503
504     private void upgradeRules(boolean failedVfUpgrade, boolean exceptionOnVfUpgrade, boolean upgradeService,
505                               boolean upgradeVFCs, boolean isFailed) {
506         upgradeRules(failedVfUpgrade, exceptionOnVfUpgrade, upgradeService, upgradeVFCs, isFailed, false);
507     }
508
509     private void upgradeRules(boolean failedVfUpgrade, boolean exceptionOnVfUpgrade, boolean upgradeService,
510                               boolean upgradeVFCs, boolean isFailed, boolean isProxy) {
511
512         mockNodeTypesUpgrade();
513         Either<Component, StorageOperationStatus> foundResource = Either.left(resource);
514
515         if (failedVfUpgrade) {
516             getToscaElementMockForVfUpgradeFailedScenario(foundResource);
517         } else {
518             if (exceptionOnVfUpgrade) {
519                 getToscaElementMockForExceptionOnUpgradeScenario(foundResource, upgradeService);
520             } else {
521                 when(toscaOperationFacade.getToscaElement(anyString()))
522                         .thenReturn(foundResource);
523             }
524         }
525         //happy flow
526         if (upgradeService) {
527             mockForUpgradeServiceScenario(foundResource, upgradeVFCs, isFailed);
528         }
529     }
530
531     private void mockNodeTypesUpgrade() {
532         GraphVertex component = createComponent();
533         List<GraphVertex> components = Lists.newArrayList();
534         components.add(component);
535
536         when(janusGraphDao.getByCriteria(any(), any(), any(), any()))
537                 .thenReturn(Either.left(components));
538         when(janusGraphDao.getParentVertices(any(GraphVertex.class), any(EdgeLabelEnum.class), any(JsonParseFlagEnum.class)))
539                 //1th node to upgrade
540                 .thenReturn(Either.left(components))
541                 //parent of the 1th node - stop recursion
542                 .thenReturn(Either.right(JanusGraphOperationStatus.NOT_FOUND));
543     }
544
545     private GraphVertex createComponent() {
546         GraphVertex component = new GraphVertex();
547         component.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE,LifecycleStateEnum.CERTIFIED.name());
548         component.setJsonMetadataField(JsonPresentationFields.UNIQUE_ID,COMPONENT_UNIQUE_ID);
549         component.setJsonMetadataField(JsonPresentationFields.CI_COMPONENT_VERSION,UPDATED_VERSION);
550         return component;
551     }
552
553     private void mockChangeComponentState() {
554         List<ComponentInstance> instances = Lists.newArrayList();
555         instances.add(createComponentInstance());
556
557         Resource checkedOutResource = new Resource();
558         checkedOutResource.setUniqueId("123400");
559         checkedOutResource.setComponentInstances(instances);
560         Either<Resource, ResponseFormat> fromLifeCycle = Either.left(checkedOutResource);
561         doReturn(fromLifeCycle).when(lifecycleBusinessLogic)
562                 .changeComponentState(any(), any(), any(), any(), any(),eq(true), eq(false));
563     }
564
565     private void getToscaElementMockForVfUpgradeFailedScenario(Either<Component, StorageOperationStatus> foundResource) {
566         when(toscaOperationFacade.getToscaElement(anyString()))
567                 .thenReturn(foundResource)
568                 .thenReturn(foundResource)
569                 .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
570     }
571
572     private void mockForUpgradeServiceScenario(Either<Component, StorageOperationStatus> foundResource, boolean upgradeVFC, boolean isFailed) {
573         Either<Resource, StorageOperationStatus> foundService = Either.left(resource);
574         if (upgradeVFC) {
575             when(toscaOperationFacade.getToscaElement(anyString()))
576                     .thenReturn(foundResource)
577                     .thenReturn(foundResource)
578                     .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
579         }
580         else if (!isFailed) {
581             when(toscaOperationFacade.getToscaElement(any(), any(ComponentParametersView.class)))
582                     .thenReturn(Either.left(resource));
583             when(toscaOperationFacade.getLatestCertifiedByToscaResourceName(any(), any(), any()))
584                     .thenReturn(foundService);
585         }
586     }
587
588     private void getToscaElementMockForExceptionOnUpgradeScenario(Either<Component, StorageOperationStatus> foundResource, boolean upgradeService) {
589         if (upgradeService) {
590             service.setVersion(UPDATED_VERSION);
591             Either<Component, StorageOperationStatus> foundService = Either.left(service);
592             when(toscaOperationFacade.getToscaElement(anyString()))
593                     .thenReturn(foundResource)
594                     .thenReturn(foundResource)
595                     .thenThrow(new RuntimeException())
596                     .thenReturn(foundService);
597         }
598         else {
599             when(toscaOperationFacade.getToscaElement(anyString()))
600                     .thenReturn(foundResource)
601                     .thenReturn(foundResource)
602                     .thenThrow(new RuntimeException());
603         }
604     }
605
606     private void mockCheckoutFlow() {
607         GraphVertex component = new GraphVertex();
608         component.setJsonMetadataField(JsonPresentationFields.LIFECYCLE_STATE, LifecycleStateEnum.CERTIFIED.name());
609         component.setJsonMetadataField(JsonPresentationFields.UNIQUE_ID, COMPONENT_UNIQUE_ID);
610         List<GraphVertex> components = Lists.newArrayList();
611         components.add(component);
612
613         when(toscaOperationFacade.getToscaElement(anyString())).thenReturn(Either.left(resource));
614         when(janusGraphDao.getByCriteria(any(), any(), any(), any()))
615                 .thenReturn(Either.left(components));
616         when(csarOperation.getCsarLatestVersion(anyString(), any()))
617                 .thenReturn(Either.left("2.0"));
618     }
619
620     private ComponentInstance createComponentInstance() {
621         ComponentInstance instance = new ComponentInstance();
622         instance.setIcon("");
623         instance.setUniqueId("");
624         instance.setName("");
625         instance.setComponentUid("");
626         instance.setCreationTime(1L);
627         instance.setModificationTime(2L);
628         instance.setDescription("");
629         instance.setPosX("");
630         instance.setPosY("");
631         instance.setPropertyValueCounter(1);
632         instance.setNormalizedName("");
633         instance.setOriginType(OriginTypeEnum.CVFC);
634         instance.setCustomizationUUID("");
635         instance.setComponentName("");
636         instance.setComponentVersion(OLD_VERSION);
637         instance.setToscaComponentName("");
638         instance.setInvariantName("");
639         instance.setSourceModelInvariant("");
640         instance.setSourceModelName("");
641         instance.setSourceModelUuid("");
642         instance.setSourceModelUid("");
643         instance.setIsProxy(false);
644         return instance;
645     }
646
647
648 }