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