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