Backend support for operation milestones with activities
[sdc.git] / catalog-be / src / test / java / org / openecomp / sdc / be / components / impl / ServiceBusinessLogicTest.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  */
20
21 package org.openecomp.sdc.be.components.impl;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.hamcrest.Matchers.is;
25 import static org.hamcrest.Matchers.notNullValue;
26 import static org.hamcrest.Matchers.nullValue;
27 import static org.junit.jupiter.api.Assertions.assertEquals;
28 import static org.junit.jupiter.api.Assertions.assertFalse;
29 import static org.junit.jupiter.api.Assertions.assertNotEquals;
30 import static org.junit.jupiter.api.Assertions.assertNotNull;
31 import static org.junit.jupiter.api.Assertions.assertNull;
32 import static org.junit.jupiter.api.Assertions.assertThrows;
33 import static org.junit.jupiter.api.Assertions.assertTrue;
34 import static org.junit.jupiter.api.Assertions.fail;
35 import static org.mockito.Mockito.when;
36
37 import com.google.common.collect.Lists;
38 import com.google.common.collect.Maps;
39 import fj.data.Either;
40 import java.lang.reflect.Method;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Optional;
48 import java.util.Set;
49 import java.util.UUID;
50 import org.apache.commons.lang3.tuple.ImmutablePair;
51 import org.hamcrest.MatcherAssert;
52 import org.junit.Assert;
53 import org.junit.jupiter.api.Test;
54 import org.mockito.Mockito;
55 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
56 import org.openecomp.sdc.be.dao.api.ActionStatus;
57 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
59 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.MilestoneDataDefinition;
61 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
62 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.ModelTypeEnum;
64 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.Component;
67 import org.openecomp.sdc.be.model.ComponentInstance;
68 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
69 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
70 import org.openecomp.sdc.be.model.GroupInstance;
71 import org.openecomp.sdc.be.model.InputDefinition;
72 import org.openecomp.sdc.be.model.Model;
73 import org.openecomp.sdc.be.model.Operation;
74 import org.openecomp.sdc.be.model.PropertyDefinition;
75 import org.openecomp.sdc.be.model.Resource;
76 import org.openecomp.sdc.be.model.Service;
77 import org.openecomp.sdc.be.model.category.CategoryDefinition;
78 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
79 import org.openecomp.sdc.be.model.operations.StorageException;
80 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
81 import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
82 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
83 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
84 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
85 import org.openecomp.sdc.be.types.ServiceConsumptionData;
86 import org.openecomp.sdc.be.user.Role;
87 import org.openecomp.sdc.common.util.ValidationUtils;
88 import org.openecomp.sdc.exception.ResponseFormat;
89 import org.springframework.http.HttpStatus;
90
91 class ServiceBusinessLogicTest extends ServiceBusinessLogicBaseTestSetup {
92
93     private final static String DEFAULT_ICON = "defaulticon";
94     private static final String ALREADY_EXIST = "alreadyExist";
95     private static final boolean MULTITENANCY_ENABLED = true;
96     private static final String TEST_TENANT = "test_tenant";
97
98     @Test
99     void testGetComponentAuditRecordsCertifiedVersion() {
100         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords =
101             bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
102         assertTrue(componentAuditRecords.isLeft());
103         assertEquals(3, componentAuditRecords.left().value().size());
104     }
105
106     @Test
107     void testGetComponentAuditRecordsUnCertifiedVersion() {
108         Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords =
109             bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
110         assertTrue(componentAuditRecords.isLeft());
111         assertEquals(4, componentAuditRecords.left().value().size());
112     }
113
114     @Test
115     void testHappyScenario() {
116         Service service = createServiceObject(false);
117         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
118         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
119
120         if (createResponse.isRight()) {
121             assertEquals(new Integer(200), createResponse.right().value().getStatus());
122         }
123         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
124     }
125
126     @Test
127     void testServiceCreationPluginCall() {
128         final Service service = createServiceObject(false);
129         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
130         final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
131         serviceCreationPlugins.add(new ServiceCreationPlugin() {
132             @Override
133             public void beforeCreate(Service service) {
134                 //do nothing
135             }
136
137             @Override
138             public int getOrder() {
139                 return 0;
140             }
141         });
142         serviceCreationPlugins.add(new ServiceCreationPlugin() {
143             @Override
144             public void beforeCreate(Service service) {
145                 throw new RuntimeException();
146             }
147
148             @Override
149             public int getOrder() {
150                 return 0;
151             }
152         });
153         bl.setServiceCreationPluginList(serviceCreationPlugins);
154         final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
155         assertTrue(createResponse.isLeft());
156     }
157
158     @Test
159     void testCreateServiceWhenGenericTypeHasProperties() {
160         final Service service = createServiceObject(false);
161
162         final Resource genericTypeResource = mockGenericTypeResource();
163
164         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
165         final Service expectedService = createServiceObject(true);
166         expectedService.setProperties(mockPropertyList());
167         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
168         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
169
170         org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
171             createResponse.isLeft(), is(true));
172         final Service actualService = createResponse.left().value();
173         org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
174
175         assertEqualsServiceObject(expectedService, actualService);
176     }
177
178     @Test
179     void testCreateServiceWhenGenericTypeAndServiceHasProperties() {
180         final Service service = createServiceObject(false);
181         service.setProperties(mockPropertyList());
182         service.getProperties().remove(0);
183         final PropertyDefinition serviceProperty = new PropertyDefinition();
184         serviceProperty.setName("aServiceProperty");
185         service.getProperties().add(serviceProperty);
186
187         final Resource genericTypeResource = mockGenericTypeResource();
188
189         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
190         final Service expectedService = createServiceObject(true);
191         expectedService.setProperties(mockPropertyList());
192         expectedService.getProperties().add(serviceProperty);
193         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
194         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
195
196         org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
197             createResponse.isLeft(), is(true));
198         final Service actualService = createResponse.left().value();
199         org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
200
201
202         assertEqualsServiceObject(expectedService, actualService);
203     }
204
205     @Test
206     void testHappyScenarioCRNullProjectCode() {
207         Service service = createServiceObject(false);
208         service.setProjectCode(null);
209         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
210         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
211
212         if (createResponse.isRight()) {
213             assertEquals(new Integer(200), createResponse.right().value().getStatus());
214         }
215         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
216     }
217
218     @Test
219     void testHappyScenarioCREmptyStringProjectCode() {
220         createServiceValidator();
221         Service service = createServiceObject(false);
222         service.setProjectCode("");
223         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
224         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
225
226         if (createResponse.isRight()) {
227             assertEquals(new Integer(200), createResponse.right().value().getStatus());
228         }
229         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
230     }
231
232     private void assertEqualsServiceObject(final Service expectedService, final Service actualService) {
233         assertEquals(expectedService.getContactId(), actualService.getContactId());
234         assertEquals(expectedService.getCategories(), actualService.getCategories());
235         assertEquals(expectedService.getCreatorUserId(), actualService.getCreatorUserId());
236         assertEquals(expectedService.getCreatorFullName(), actualService.getCreatorFullName());
237         assertEquals(expectedService.getDescription(), actualService.getDescription());
238         assertEquals(expectedService.getIcon(), actualService.getIcon());
239         assertEquals(expectedService.getLastUpdaterUserId(), actualService.getLastUpdaterUserId());
240         assertEquals(expectedService.getLastUpdaterFullName(), actualService.getLastUpdaterFullName());
241         assertEquals(expectedService.getName(), actualService.getName());
242         assertEquals(expectedService.getUniqueId(), actualService.getUniqueId());
243         assertEquals(expectedService.getVersion(), actualService.getVersion());
244         assertEquals(expectedService.getArtifacts(), actualService.getArtifacts());
245         assertEquals(expectedService.getCreationDate(), actualService.getCreationDate());
246         assertEquals(expectedService.getLastUpdateDate(), actualService.getLastUpdateDate());
247         assertEquals(expectedService.getLifecycleState(), actualService.getLifecycleState());
248         assertEquals(expectedService.getTags(), actualService.getTags());
249         if (expectedService.getProperties() == null) {
250             org.hamcrest.MatcherAssert.assertThat("Service properties should be null",
251                 actualService.getProperties(), is(nullValue()));
252             return;
253         }
254         org.hamcrest.MatcherAssert.assertThat("Service properties should be as expected",
255             actualService.getProperties(), is(expectedService.getProperties()));
256     }
257
258     /* CREATE validations - start ***********************/
259     // Service name - start
260
261     @Test
262     void testFailedServiceValidations() {
263
264         testServiceNameAlreadyExists();
265         testServiceNameEmpty();
266         testServiceNameWrongFormat();
267         testServiceDescriptionEmpty();
268         testServiceDescriptionMissing();
269         testServiceDescExceedsLimitCreate();
270         testServiceDescNotEnglish();
271         testServiceIconEmpty();
272         testServiceIconMissing();
273         testResourceIconInvalid();
274         testTagsNoServiceName();
275         testInvalidTag();
276         testServiceTagNotExist();
277         testServiceTagEmpty();
278
279         testContactIdTooLong();
280         testContactIdWrongFormatCreate();
281         testInvalidProjectCode();
282         testProjectCodeTooLong();
283         testProjectCodeTooShort();
284
285         testResourceContactIdMissing();
286         testServiceCategoryExist();
287         testServiceBadCategoryCreate();
288     }
289
290     private void testServiceNameAlreadyExists() {
291         String serviceName = ALREADY_EXIST;
292         Service serviceExccedsNameLimit = createServiceObject(false);
293         // 51 chars, the limit is 50
294         serviceExccedsNameLimit.setName(serviceName);
295         List<String> tgs = new ArrayList<>();
296         tgs.add(serviceName);
297         serviceExccedsNameLimit.setTags(tgs);
298         try {
299             bl.createService(serviceExccedsNameLimit, user);
300         } catch (ComponentException exp) {
301             assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
302             return;
303         }
304         fail();
305     }
306
307     private void testServiceNameEmpty() {
308         Service serviceExccedsNameLimit = createServiceObject(false);
309         serviceExccedsNameLimit.setName(null);
310         try {
311             bl.createService(serviceExccedsNameLimit, user);
312         } catch (ComponentException e) {
313             assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
314             return;
315         }
316         fail();
317     }
318
319     private void testServiceNameWrongFormat() {
320         Service service = createServiceObject(false);
321         // contains :
322         String nameWrongFormat = "ljg\\fd";
323         service.setName(nameWrongFormat);
324         try {
325             bl.createService(service, user);
326         } catch (ComponentException e) {
327             assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
328             return;
329         }
330         fail();
331     }
332
333     // Service name - end
334     // Service description - start
335
336     private void testServiceDescriptionEmpty() {
337         Service serviceExist = createServiceObject(false);
338         serviceExist.setDescription("");
339         try {
340             bl.createService(serviceExist, user);
341         } catch (ComponentException e) {
342             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
343             return;
344         }
345         fail();
346     }
347
348     private void testServiceDescriptionMissing() {
349         Service serviceExist = createServiceObject(false);
350         serviceExist.setDescription(null);
351         try {
352             bl.createService(serviceExist, user);
353         } catch (ComponentException e) {
354             assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
355             return;
356         }
357         fail();
358     }
359
360     private void testServiceDescExceedsLimitCreate() {
361         Service serviceExccedsDescLimit = createServiceObject(false);
362         // 1025 chars, the limit is 1024
363         String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
364             + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
365             + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
366             + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
367             +
368             "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
369             +
370             "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
371             +
372             "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
373             + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
374
375         serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
376         try {
377             bl.createService(serviceExccedsDescLimit, user);
378         } catch (ComponentException e) {
379             assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(),
380                 "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
381             return;
382         }
383         fail();
384     }
385
386     private void testServiceDescNotEnglish() {
387         Service notEnglish = createServiceObject(false);
388         // Not english
389         String tooLongServiceDesc = "\uC2B5";
390         notEnglish.setDescription(tooLongServiceDesc);
391         try {
392             bl.createService(notEnglish, user);
393         } catch (ComponentException e) {
394             assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
395             return;
396         }
397         fail();
398     }
399
400     // Service description - stop
401     // Service icon - start
402
403     private void testServiceIconEmpty() {
404         Service serviceExist = createServiceObject(false);
405         serviceExist.setIcon("");
406         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
407         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
408
409     }
410
411     private void testServiceIconMissing() {
412         Service serviceExist = createServiceObject(false);
413         serviceExist.setIcon(null);
414         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
415         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
416     }
417
418     private void testResourceIconInvalid() {
419         Service resourceExist = createServiceObject(false);
420         resourceExist.setIcon("kjk3453^&");
421
422         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
423         assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
424
425     }
426
427     private void testTagsNoServiceName() {
428         Service serviceExccedsNameLimit = createServiceObject(false);
429         String tag1 = "afzs2qLBb";
430         List<String> tagsList = new ArrayList<>();
431         tagsList.add(tag1);
432         serviceExccedsNameLimit.setTags(tagsList);
433         try {
434             bl.createService(serviceExccedsNameLimit, user);
435         } catch (ComponentException e) {
436             assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
437             return;
438         }
439         fail();
440     }
441
442     private void testInvalidTag() {
443         Service serviceExccedsNameLimit = createServiceObject(false);
444         String tag1 = "afzs2qLBb%#%";
445         List<String> tagsList = new ArrayList<>();
446         tagsList.add(tag1);
447         serviceExccedsNameLimit.setTags(tagsList);
448         try {
449             bl.createService(serviceExccedsNameLimit, user);
450         } catch (ComponentException e) {
451             assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
452             return;
453         }
454         fail();
455     }
456
457     private void testServiceTagNotExist() {
458         Service serviceExist = createServiceObject(false);
459         serviceExist.setTags(null);
460
461         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
462         assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
463     }
464
465     private void testServiceTagEmpty() {
466         Service serviceExist = createServiceObject(false);
467         serviceExist.setTags(new ArrayList<>());
468
469         Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
470         assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
471     }
472
473     // Service tags - stop
474     // Service contactId - start
475
476     private void testContactIdTooLong() {
477         Service serviceContactId = createServiceObject(false);
478         // 59 chars instead of 50
479         String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
480         serviceContactId.setContactId(contactIdTooLong);
481         try {
482             bl.createService(serviceContactId, user);
483         } catch (ComponentException e) {
484             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
485             return;
486         }
487         fail();
488     }
489
490     private void testContactIdWrongFormatCreate() {
491         Service serviceContactId = createServiceObject(false);
492         // 3 letters and 3 digits and special characters
493         String contactIdTooLong = "yrt134!!!";
494         serviceContactId.setContactId(contactIdTooLong);
495         try {
496             bl.createService(serviceContactId, user);
497         } catch (ComponentException e) {
498             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
499             return;
500         }
501         fail();
502     }
503
504     private void testResourceContactIdMissing() {
505         Service resourceExist = createServiceObject(false);
506         resourceExist.setContactId(null);
507         try {
508             bl.createService(resourceExist, user);
509         } catch (ComponentException e) {
510             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
511             return;
512         }
513         fail();
514     }
515
516     // Service contactId - stop
517     // Service category - start
518
519     private void testServiceCategoryExist() {
520         Service serviceExist = createServiceObject(false);
521         serviceExist.setCategories(null);
522         try {
523             bl.createService(serviceExist, user);
524         } catch (ComponentException e) {
525             assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
526             return;
527         }
528         fail();
529     }
530
531     @Test
532     void markDistributionAsDeployedTestAlreadyDeployed() {
533         String notifyAction = "DNotify";
534         String requestAction = "DRequest";
535         String resultAction = "DResult";
536         String did = "123456";
537
538         setupBeforeDeploy(notifyAction, requestAction, did);
539         List<DistributionDeployEvent> resultList = new ArrayList<>();
540         Map<String, Object> params = new HashMap<>();
541         DistributionDeployEvent event = new DistributionDeployEvent();
542
543         event.setAction(resultAction);
544         event.setDid(did);
545         event.setStatus("200");
546         // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
547         // deployEvent.setFields(params);
548         resultList.add(event);
549         Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
550
551         Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString()))
552             .thenReturn(eventList);
553
554         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
555         assertTrue(markDeployed.isLeft());
556
557         Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
558
559     }
560
561     @Test
562     void markDistributionAsDeployedTestSuccess() {
563         String notifyAction = "DNotify";
564         String requestAction = "DRequest";
565         String did = "123456";
566
567         setupBeforeDeploy(notifyAction, requestAction, did);
568         List<Role> roles = new ArrayList<>();
569         roles.add(Role.ADMIN);
570         roles.add(Role.DESIGNER);
571         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
572         assertTrue(markDeployed.isLeft());
573     }
574
575     @Test
576     void markDistributionAsDeployedTestNotDistributed() {
577         String notifyAction = "DNotify";
578         String requestAction = "DRequest";
579         String did = "123456";
580
581         setupBeforeDeploy(notifyAction, requestAction, did);
582         List<ResourceAdminEvent> emptyList = new ArrayList<>();
583         Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
584         Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
585
586         Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
587         Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
588
589         Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
590         assertTrue(markDeployed.isRight());
591         assertEquals(404, markDeployed.right().value().getStatus().intValue());
592
593     }
594
595     private void testServiceBadCategoryCreate() {
596
597         Service serviceExist = createServiceObject(false);
598         CategoryDefinition category = new CategoryDefinition();
599         category.setName("koko");
600         category.setIcons(Arrays.asList(DEFAULT_ICON));
601         List<CategoryDefinition> categories = new ArrayList<>();
602         categories.add(category);
603         serviceExist.setCategories(categories);
604         try {
605             bl.createService(serviceExist, user);
606         } catch (ComponentException e) {
607             assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
608             return;
609         }
610         fail();
611     }
612
613     // Service category - stop
614     // Service projectCode - start
615
616     private void testInvalidProjectCode() {
617
618         Service serviceExist = createServiceObject(false);
619         serviceExist.setProjectCode("koko!!");
620
621         try {
622             bl.createService(serviceExist, user);
623         } catch (ComponentException exp) {
624             assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
625             return;
626         }
627         fail();
628     }
629
630     private void testProjectCodeTooLong() {
631
632         Service serviceExist = createServiceObject(false);
633         String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
634         serviceExist.setProjectCode(tooLongProjectCode);
635
636         try {
637             bl.createService(serviceExist, user);
638         } catch (ComponentException exp) {
639             assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
640             return;
641         }
642         fail();
643     }
644
645     private void testProjectCodeTooShort() {
646
647         Service serviceExist = createServiceObject(false);
648         serviceExist.setProjectCode("333");
649
650         try {
651             bl.createService(serviceExist, user);
652         } catch (ComponentException exp) {
653             assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
654             return;
655         }
656         fail();
657     }
658
659     @Test
660     void testDeleteMarkedServices() {
661         List<String> ids = new ArrayList<>();
662         List<String> responseIds = new ArrayList<>();
663         String resourceInUse = "123";
664         ids.add(resourceInUse);
665         String resourceFree = "456";
666         ids.add(resourceFree);
667         responseIds.add(resourceFree);
668         Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
669         when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
670
671         Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
672         Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
673
674         List<ArtifactDefinition> artifacts = new ArrayList<>();
675         Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
676
677         Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
678         when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
679         when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
680         Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
681         assertTrue(deleteMarkedResources.isLeft());
682         List<String> resourceIdList = deleteMarkedResources.left().value();
683         assertFalse(resourceIdList.isEmpty());
684         assertTrue(resourceIdList.contains(resourceFree));
685         assertFalse(resourceIdList.contains(resourceInUse));
686     }
687
688     @Test
689     void testDeleteArchivedService_NotFound() {
690         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
691         assertThrows(StorageException.class, () -> bl.deleteServiceAllVersions("1", user));
692     }
693
694     @Test
695     void testDeleteArchivedService_NotArchived() {
696         String serviceId = "12345";
697         Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
698         eitherService.left().value().setArchived(false);
699         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
700         final ComponentException actualException = assertThrows(ComponentException.class, () -> bl.deleteServiceAllVersions(serviceId, user));
701         assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualException.getActionStatus());
702         assertEquals(actualException.getParams()[0], serviceId);
703     }
704
705     @Test
706     void testDeleteArchivedService_DeleteServiceSpecificModel() throws ToscaOperationException {
707         String serviceId = "12345";
708         String model = "serviceSpecificModel";
709         List<String> deletedServcies = new ArrayList<>();
710         deletedServcies.add("54321");
711         Model normativeExtensionModel = new Model("normativeExtensionModel", ModelTypeEnum.NORMATIVE_EXTENSION);
712         Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
713         eitherService.left().value().setArchived(true);
714         eitherService.left().value().setModel(model);
715         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
716         Mockito.when(toscaOperationFacade.deleteService(Mockito.anyString(), Mockito.eq(true))).thenReturn(deletedServcies);
717         Mockito.when(modelOperation.findModelByName(model)).thenReturn(Optional.of(normativeExtensionModel));
718         bl.deleteServiceAllVersions(serviceId, user);
719         Mockito.verify(modelOperation, Mockito.times(1)).deleteModel(normativeExtensionModel, false);
720     }
721
722     @SuppressWarnings({"unchecked", "rawtypes"})
723     @Test
724     void testFindGroupInstanceOnRelatedComponentInstance() {
725
726         Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
727         String methodName = "findGroupInstanceOnRelatedComponentInstance";
728         Object invalidId = "invalidId";
729
730         Component service = createNewService();
731         List<ComponentInstance> componentInstances = service.getComponentInstances();
732
733         Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
734         Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
735         Class[] argClasses = {Component.class, String.class, String.class};
736         try {
737             Method method = targetClass.getDeclaredMethod(methodName, argClasses);
738             method.setAccessible(true);
739
740             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
741             assertNotNull(findGroupInstanceRes);
742             assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
743                 .getUniqueId());
744             assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
745                 .getGroupInstances()
746                 .get(1)
747                 .getUniqueId());
748
749             Object[] argObjectsInvalidCiId = {service, invalidId, componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
750
751             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
752             assertNotNull(findGroupInstanceRes);
753             assertTrue(findGroupInstanceRes.isRight());
754             assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
755
756             Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId(), invalidId};
757
758             findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
759             assertNotNull(findGroupInstanceRes);
760             assertTrue(findGroupInstanceRes.isRight());
761             assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
762         } catch (Exception e) {
763             e.printStackTrace();
764         }
765     }
766
767     private Component createNewComponent() {
768
769         Service service = new Service();
770         int listSize = 3;
771         service.setName("serviceName");
772         service.setUniqueId("serviceUniqueId");
773         List<ComponentInstance> componentInstances = new ArrayList<>();
774         ComponentInstance ci;
775         for (int i = 0; i < listSize; ++i) {
776             ci = new ComponentInstance();
777             ci.setName("ciName" + i);
778             ci.setUniqueId("ciId" + i);
779             List<GroupInstance> groupInstances = new ArrayList<>();
780             GroupInstance gi;
781             for (int j = 0; j < listSize; ++j) {
782                 gi = new GroupInstance();
783                 gi.setName(ci.getName() + "giName" + j);
784                 gi.setUniqueId(ci.getName() + "giId" + j);
785                 groupInstances.add(gi);
786             }
787             ci.setGroupInstances(groupInstances);
788             componentInstances.add(ci);
789         }
790         service.setComponentInstances(componentInstances);
791         return service;
792     }
793
794     protected Service createNewService() {
795         return (Service) createNewComponent();
796     }
797
798     @Test
799     void testDerivedFromGeneric() {
800         Service service = createServiceObject(true);
801         service.setDerivedFromGenericInfo(genericService);
802         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
803         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
804         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
805         assertTrue(createResponse.isLeft());
806         service = createResponse.left().value();
807         assertEquals(genericService.getToscaResourceName(), service.getDerivedFromGenericType());
808         assertEquals(genericService.getVersion(), service.getDerivedFromGenericVersion());
809     }
810
811     @Test
812     void testServiceWithoutDerivedFromGeneric() {
813         final Service service = createServiceObject(true);
814         when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
815         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
816         final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
817         assertTrue(createResponse.isLeft());
818         final Service actualService = createResponse.left().value();
819         assertNull(actualService.getDerivedFromGenericType());
820         assertNull(actualService.getDerivedFromGenericVersion());
821     }
822
823     @Test
824     void testUpdateMetadataNamingPolicy() {
825         Service currentService = createServiceObject(true);
826         Service newService = createServiceObject(false);
827         currentService.setEcompGeneratedNaming(false);
828         newService.setEcompGeneratedNaming(true);
829         newService.setNamingPolicy("policy");
830         Either<Service, ResponseFormat> resultOfUpdate =
831             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
832         assertThat(resultOfUpdate.isLeft()).isTrue();
833         Service updatedService = resultOfUpdate.left().value();
834         assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
835         assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
836     }
837
838     @Test
839     void testUpdateMetadataToEmptyProjectCode() {
840         Service currentService = createServiceObject(true);
841         Service newService = createServiceObject(false);
842         currentService.setProjectCode("12345");
843         newService.setProjectCode("");
844         Either<Service, ResponseFormat> resultOfUpdate =
845             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
846         assertThat(resultOfUpdate.isLeft()).isTrue();
847         Service updatedService = resultOfUpdate.left().value();
848         assertThat(updatedService.getProjectCode()).isEmpty();
849     }
850
851     @Test
852     void testUpdateMetadataFromEmptyProjectCode() {
853         Service currentService = createServiceObject(true);
854         Service newService = createServiceObject(false);
855         currentService.setProjectCode("");
856         newService.setProjectCode("12345");
857         Either<Service, ResponseFormat> resultOfUpdate =
858             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
859         assertThat(resultOfUpdate.isLeft()).isTrue();
860         Service updatedService = resultOfUpdate.left().value();
861         assertThat(updatedService.getProjectCode()).isEqualTo("12345");
862     }
863
864     @Test
865     void testUpdateMetadataProjectCode() {
866         Service currentService = createServiceObject(true);
867         Service newService = createServiceObject(false);
868         currentService.setProjectCode("33333");
869         newService.setProjectCode("12345");
870         Either<Service, ResponseFormat> resultOfUpdate =
871             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
872         assertThat(resultOfUpdate.isLeft()).isTrue();
873         Service updatedService = resultOfUpdate.left().value();
874         assertThat(updatedService.getProjectCode()).isEqualTo("12345");
875     }
876
877     @Test
878     void testUpdateMetadataServiceType() {
879         Service currentService = createServiceObject(true);
880         Service newService = createServiceObject(false);
881         currentService.setServiceType("alice");
882         //valid English word
883         newService.setServiceType("bob");
884         Either<Service, ResponseFormat> resultOfUpdate =
885             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
886         assertThat(resultOfUpdate.isLeft()).isTrue();
887         Service updatedService = resultOfUpdate.left().value();
888         assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
889         //empty string is invalid
890         newService.setServiceType("");
891         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
892         assertThat(resultOfUpdate.isLeft()).isTrue();
893         //null is valid
894         newService.setServiceType(null);
895         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
896         assertThat(resultOfUpdate.isLeft()).isTrue();
897     }
898
899     @Test
900     void testCreateDefaultMetadataServiceFunction() {
901         Service currentService = createServiceObject(true);
902         assertThat(currentService.getServiceFunction()).isEmpty();
903     }
904
905     @Test
906     void testCreateCustomMetadataServiceFunction() {
907         String customServiceFunctionName = "customName";
908         Service currentService = createServiceObject(true);
909         currentService.setServiceFunction(customServiceFunctionName);
910         assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
911     }
912
913     @Test
914     void testUpdateMetadataServiceFunction() {
915         Service currentService = createServiceObject(true);
916         Service newService = createServiceObject(false);
917         currentService.setServiceFunction("alice");
918         //valid English word
919         newService.setServiceFunction("bob");
920         Either<Service, ResponseFormat> resultOfUpdate =
921             bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
922         assertThat(resultOfUpdate.isLeft()).isTrue();
923         Service updatedService = resultOfUpdate.left().value();
924         assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
925         //empty string is valid
926         newService.setServiceFunction("");
927         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
928         assertThat(resultOfUpdate.isLeft()).isTrue();
929         //null is valid and assigner to ""
930         newService.setServiceFunction(null);
931         resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService, false, new ArrayList<>());
932         assertThat(resultOfUpdate.isLeft()).isTrue();
933         assertThat(updatedService.getServiceFunction()).isEmpty();
934     }
935
936     @Test
937     void testServiceFunctionExceedLength() {
938         String serviceName = "Service";
939         String serviceFunction =
940             "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
941         Service serviceFunctionExceedLength = createServiceObject(false);
942         serviceFunctionExceedLength.setName(serviceName);
943         serviceFunctionExceedLength.setServiceFunction(serviceFunction);
944         List<String> tgs = new ArrayList<>();
945         tgs.add(serviceName);
946         serviceFunctionExceedLength.setTags(tgs);
947         try {
948             serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
949         } catch (ComponentException exp) {
950             assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
951         }
952     }
953
954     @Test
955     void testServiceFunctionInvalidCharacter() {
956         String serviceName = "Service";
957         String serviceFunction = "a?";
958         Service serviceFunctionExceedLength = createServiceObject(false);
959         serviceFunctionExceedLength.setName(serviceName);
960         serviceFunctionExceedLength.setServiceFunction(serviceFunction);
961         List<String> tgs = new ArrayList<>();
962         tgs.add(serviceName);
963         serviceFunctionExceedLength.setTags(tgs);
964         try {
965             serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
966         } catch (ComponentException exp) {
967             assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
968         }
969     }
970
971     @Test
972     void testAddPropertyServiceConsumptionServiceNotFound() {
973         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
974
975         Either<Operation, ResponseFormat> operationEither =
976             bl.addPropertyServiceConsumption("1", "2", "3",
977                 user.getUserId(), new ServiceConsumptionData());
978         assertTrue(operationEither.isRight());
979         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
980     }
981
982     @Test
983     void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
984         Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
985         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
986
987         Either<Operation, ResponseFormat> operationEither =
988             bl.addPropertyServiceConsumption("1", "2", "3",
989                 user.getUserId(), new ServiceConsumptionData());
990         assertTrue(operationEither.isRight());
991         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
992     }
993
994     @Test
995     void testAddPropertyServiceConsumptionNoMatchingComponent() {
996         Service aService = createNewService();
997         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
998         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
999
1000         String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
1001
1002         Either<Operation, ResponseFormat> operationEither =
1003             bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
1004                 user.getUserId(), new ServiceConsumptionData());
1005         assertTrue(operationEither.isRight());
1006         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1007     }
1008
1009     @Test
1010     void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
1011         Service aService = createNewService();
1012         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1013         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1014         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1015
1016         Either<Operation, ResponseFormat> operationEither =
1017             bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
1018                 user.getUserId(), new ServiceConsumptionData());
1019         assertTrue(operationEither.isRight());
1020         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1021     }
1022
1023     @Test
1024     void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
1025         Service aService = createNewService();
1026         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1027         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1028         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1029
1030         Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
1031             Maps.newHashMap();
1032         componentInstancesInterfacesMap.put(aService.getUniqueId(),
1033             Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
1034
1035         aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1036
1037         Either<Operation, ResponseFormat> operationEither =
1038             bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
1039                 user.getUserId(), new ServiceConsumptionData());
1040         assertTrue(operationEither.isRight());
1041         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1042     }
1043
1044     @Test
1045     void testAddPropertyServiceConsumptionNoInputsCandidate() {
1046         Service aService = createNewService();
1047         aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1048         Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1049         Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1050
1051         String operationId = "operationId";
1052         ComponentInstanceInterface componentInstanceInterface =
1053             new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
1054         Map<String, Operation> operationsMap = Maps.newHashMap();
1055         operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
1056             new ListDataDefinition<>(), new ListDataDefinition<>(), new HashMap<>()));
1057         componentInstanceInterface.setOperationsMap(operationsMap);
1058
1059         Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
1060         componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
1061         aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1062
1063         Either<Operation, ResponseFormat> operationEither =
1064             bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
1065                 user.getUserId(), new ServiceConsumptionData());
1066         assertTrue(operationEither.isRight());
1067         assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1068     }
1069
1070     private Resource mockGenericTypeResource() {
1071         final Resource genericTypeResource = new Resource();
1072         genericTypeResource.setProperties(mockPropertyList());
1073         return genericTypeResource;
1074     }
1075
1076     private List<PropertyDefinition> mockPropertyList() {
1077         final List<PropertyDefinition> propertyList = new ArrayList<>();
1078         final PropertyDefinition propertyDefinition1 = new PropertyDefinition();
1079         propertyDefinition1.setName("property1");
1080         propertyDefinition1.setType("string");
1081         propertyList.add(propertyDefinition1);
1082
1083         final PropertyDefinition propertyDefinition2 = new PropertyDefinition();
1084         propertyDefinition2.setName("property2");
1085         propertyDefinition2.setType("boolean");
1086         propertyList.add(propertyDefinition2);
1087
1088         final PropertyDefinition propertyDefinition3 = new PropertyDefinition();
1089         propertyDefinition3.setName("property3");
1090         propertyDefinition3.setType("string");
1091         propertyList.add(propertyDefinition3);
1092         return propertyList;
1093     }
1094
1095     @Test
1096     void testCreateService_withMultitenancyValidTenant_Success() {
1097         Assert.assertTrue(MULTITENANCY_ENABLED);
1098         Service service = createServiceObject(false);
1099         service.setTenant(TEST_TENANT);
1100         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
1101         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
1102
1103         if (createResponse.isRight()) {
1104             assertEquals(new Integer(200), createResponse.right().value().getStatus());
1105         }
1106         MatcherAssert.assertThat("Unauthorized Tenant", getTestRoles().contains(service.getTenant()));
1107         assertEquals(TEST_TENANT, service.getTenant());
1108         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
1109     }
1110
1111     @Test
1112     void testCreateService_withMultitenancyInvalidTenant_Failure() {
1113         Service service = createServiceObject(false);
1114         service.setTenant("invalid_tenant");
1115         when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
1116         Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
1117         MatcherAssert.assertThat("Unauthorized Tenant", !getTestRoles().contains(service.getTenant()));
1118         assertNotEquals(TEST_TENANT, service.getTenant());
1119         assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
1120     }
1121
1122     @Test
1123     void testUpdateSubstitutionNodeTypeAndVersion() {
1124         Service currentService = createServiceObject(true);
1125         currentService.setDerivedFromGenericType("genericTypeOne");
1126         currentService.setDerivedFromGenericVersion("1.0");
1127         Service newService = createServiceObject(false);
1128         newService.setDerivedFromGenericType("genericTypeTwo");
1129         newService.setDerivedFromGenericVersion("2.0");
1130         List<String> subNodePropsToBeRemoved = new ArrayList<>();
1131         subNodePropsToBeRemoved.add("testProp");
1132         Either<Service, ResponseFormat> resultOfUpdate =
1133             bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
1134         assertThat(resultOfUpdate.isLeft()).isTrue();
1135         Service updatedService = resultOfUpdate.left().value();
1136         assertEquals("genericTypeTwo", updatedService.getDerivedFromGenericType());
1137         assertEquals("2.0", updatedService.getDerivedFromGenericVersion());
1138     }
1139
1140     @Test
1141     void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetProperty() {
1142         Service currentService = createServiceObject(true);
1143         setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_PROPERTY, "testProp");
1144         Service newService = createServiceObject(false);
1145         List<String> subNodePropsToBeRemoved = new ArrayList<>();
1146         subNodePropsToBeRemoved.add("testProp");
1147         Either<Service, ResponseFormat> resultOfUpdate =
1148             bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
1149         assertThat(resultOfUpdate.isRight()).isTrue();
1150         ResponseFormat response = resultOfUpdate.right().value();
1151         assertEquals(409, response.getStatus());
1152         assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
1153     }
1154
1155     @Test
1156     void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetAttribute() {
1157         Service currentService = createServiceObject(true);
1158         setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_ATTRIBUTE, "testProp");
1159         Service newService = createServiceObject(false);
1160         List<String> subNodePropsToBeRemoved = new ArrayList<>();
1161         subNodePropsToBeRemoved.add("testProp");
1162         Either<Service, ResponseFormat> resultOfUpdate =
1163             bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
1164         assertThat(resultOfUpdate.isRight()).isTrue();
1165         ResponseFormat response = resultOfUpdate.right().value();
1166         assertEquals(409, response.getStatus());
1167         assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
1168     }
1169
1170     @Test
1171     void testUpdateSubstitutionNodeTypePropsToRemoveThrowInUseGetInput() {
1172         Service currentService = createServiceObject(true);
1173         setComponentInstanceOnServiceWithPropWithToscaFunction(currentService, ToscaGetFunctionType.GET_INPUT, "testProp");
1174         Service newService = createServiceObject(false);
1175         List<String> subNodePropsToBeRemoved = new ArrayList<>();
1176         subNodePropsToBeRemoved.add("testProp");
1177         Either<Service, ResponseFormat> resultOfUpdate =
1178             bl.validateAndUpdateServiceMetadata(user, currentService, newService, true, subNodePropsToBeRemoved);
1179         assertThat(resultOfUpdate.isRight()).isTrue();
1180         ResponseFormat response = resultOfUpdate.right().value();
1181         assertEquals(409, response.getStatus());
1182         assertEquals("Cannot change substitution node type as properties of the existing type are referenced by properties %1.", response.getText());
1183     }
1184
1185     private void setComponentInstanceOnServiceWithPropWithToscaFunction(Service currentService, ToscaGetFunctionType toscaGetFunctionType,
1186                                                                         String testPropName) {
1187         ComponentInstance compInstance = new ComponentInstance();
1188         compInstance.setUniqueId("resourceUid");
1189
1190         List<ComponentInstance> compInstances = new ArrayList<>();
1191         compInstances.add(compInstance);
1192         currentService.setComponentInstances(compInstances);
1193
1194         ToscaGetFunctionDataDefinition toscaFunc = new ToscaGetFunctionDataDefinition();
1195         toscaFunc.setPropertyName(testPropName);
1196         toscaFunc.setPropertyUniqueId(testPropName + "Uid");
1197         toscaFunc.setFunctionType(toscaGetFunctionType);
1198
1199         if (ToscaGetFunctionType.GET_INPUT.equals(toscaGetFunctionType)) {
1200             toscaFunc.setPropertyName(testPropName + "Input");
1201             toscaFunc.setPropertyUniqueId(testPropName + "InputUid");
1202             InputDefinition compInput = new InputDefinition();
1203             compInput.setName(testPropName + "Input");
1204             compInput.setUniqueId(testPropName + "InputUid");
1205             compInput.setPropertyId(testPropName + "Uid");
1206             List<InputDefinition> compInputs = new ArrayList<>();
1207             compInputs.add(compInput);
1208             currentService.setInputs(compInputs);
1209         }
1210
1211         ComponentInstanceProperty compInstProp = new ComponentInstanceProperty();
1212         compInstProp.setName("compInstProp");
1213         compInstProp.setToscaFunction(toscaFunc);
1214
1215         List<ComponentInstanceProperty> compInstProps = new ArrayList<>();
1216         compInstProps.add(compInstProp);
1217
1218         Map<String, List<ComponentInstanceProperty>> mapCompInstProps = new HashMap<>();
1219         mapCompInstProps.put("resourceUid", compInstProps);
1220
1221         PropertyDefinition compProp = new PropertyDefinition();
1222         compProp.setName(testPropName);
1223         compProp.setUniqueId(testPropName + "Uid");
1224         List<PropertyDefinition> compProps = new ArrayList<>();
1225         compProps.add(compProp);
1226         currentService.setProperties(compProps);
1227
1228         currentService.setComponentInstancesProperties(mapCompInstProps);
1229     }
1230
1231     private Set<String> getTestRoles() {
1232         Set<String> roles = new HashSet<>();
1233         roles.add("test_admin");
1234         roles.add("test_tenant");
1235         return roles;
1236     }
1237 }