2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.junit.Assert.fail;
29 import static org.mockito.Mockito.when;
31 import com.google.common.collect.Lists;
32 import com.google.common.collect.Maps;
33 import fj.data.Either;
34 import java.lang.reflect.Method;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.List;
40 import java.util.UUID;
41 import java.util.stream.Collectors;
42 import java.util.stream.Stream;
43 import org.apache.commons.lang3.tuple.ImmutablePair;
44 import org.junit.Assert;
45 import org.junit.Test;
46 import org.mockito.Mockito;
47 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
48 import org.openecomp.sdc.be.dao.api.ActionStatus;
49 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
52 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
53 import org.openecomp.sdc.be.model.ArtifactDefinition;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.ComponentInstance;
56 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
57 import org.openecomp.sdc.be.model.GroupInstance;
58 import org.openecomp.sdc.be.model.Operation;
59 import org.openecomp.sdc.be.model.Resource;
60 import org.openecomp.sdc.be.model.Service;
61 import org.openecomp.sdc.be.model.category.CategoryDefinition;
62 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
63 import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
64 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
65 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
66 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
67 import org.openecomp.sdc.be.types.ServiceConsumptionData;
68 import org.openecomp.sdc.be.user.Role;
69 import org.openecomp.sdc.common.util.ValidationUtils;
70 import org.openecomp.sdc.exception.ResponseFormat;
71 import org.springframework.http.HttpStatus;
73 public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup {
75 private final static String DEFAULT_ICON = "defaulticon";
76 private static final String ALREADY_EXIST = "alreadyExist";
77 private static final String DOES_NOT_EXIST = "doesNotExist";
80 public void testGetComponentAuditRecordsCertifiedVersion() {
81 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
82 assertTrue(componentAuditRecords.isLeft());
83 assertEquals(3, componentAuditRecords.left().value().size());
87 public void testGetComponentAuditRecordsUnCertifiedVersion() {
88 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
89 assertTrue(componentAuditRecords.isLeft());
90 assertEquals(4, componentAuditRecords.left().value().size());
94 public void testHappyScenario() {
95 Service service = createServiceObject(false);
96 validateUserRoles(Role.ADMIN, Role.DESIGNER);
97 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
98 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
100 if (createResponse.isRight()) {
101 assertEquals(new Integer(200), createResponse.right().value().getStatus());
103 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
107 public void testServiceCreationPluginCall() {
108 final Service service = createServiceObject(false);
109 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
110 final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
111 serviceCreationPlugins.add(new ServiceCreationPlugin() {
113 public void beforeCreate(Service service) {
118 public int getOrder() {
122 serviceCreationPlugins.add(new ServiceCreationPlugin() {
124 public void beforeCreate(Service service) {
125 throw new RuntimeException();
129 public int getOrder() {
133 bl.setServiceCreationPluginList(serviceCreationPlugins);
134 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
135 assertTrue(createResponse.isLeft());
139 public void testHappyScenarioCRNullProjectCode() {
140 Service service = createServiceObject(false);
141 service.setProjectCode(null);
142 validateUserRoles(Role.ADMIN, Role.DESIGNER);
143 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
144 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
146 if (createResponse.isRight()) {
147 assertEquals(new Integer(200), createResponse.right().value().getStatus());
149 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
152 public void testHappyScenarioCREmptyStringProjectCode() {
153 createServiceValidator();
154 Service service = createServiceObject(false);
155 service.setProjectCode("");
156 validateUserRoles(Role.ADMIN, Role.DESIGNER);
157 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
158 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
160 if (createResponse.isRight()) {
161 assertEquals(new Integer(200), createResponse.right().value().getStatus());
163 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
166 private void validateUserRoles(Role ... roles) {
167 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
170 private void assertEqualsServiceObject(Service origService, Service newService) {
171 assertEquals(origService.getContactId(), newService.getContactId());
172 assertEquals(origService.getCategories(), newService.getCategories());
173 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
174 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
175 assertEquals(origService.getDescription(), newService.getDescription());
176 assertEquals(origService.getIcon(), newService.getIcon());
177 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
178 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
179 assertEquals(origService.getName(), newService.getName());
180 assertEquals(origService.getName(), newService.getName());
181 assertEquals(origService.getUniqueId(), newService.getUniqueId());
182 assertEquals(origService.getVersion(), newService.getVersion());
183 assertEquals(origService.getArtifacts(), newService.getArtifacts());
184 assertEquals(origService.getCreationDate(), newService.getCreationDate());
185 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
186 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
187 assertEquals(origService.getTags(), newService.getTags());
191 /* CREATE validations - start ***********************/
192 // Service name - start
196 public void testFailedServiceValidations() {
198 testServiceNameAlreadyExists();
199 testServiceNameEmpty();
200 testServiceNameWrongFormat();
201 testServiceDescriptionEmpty();
202 testServiceDescriptionMissing();
203 testServiceDescExceedsLimitCreate();
204 testServiceDescNotEnglish();
205 testServiceIconEmpty();
206 testServiceIconMissing();
207 testResourceIconInvalid();
208 testTagsNoServiceName();
210 testServiceTagNotExist();
211 testServiceTagEmpty();
213 testContactIdTooLong();
214 testContactIdWrongFormatCreate();
215 testInvalidProjectCode();
216 testProjectCodeTooLong();
217 testProjectCodeTooShort();
219 testResourceContactIdMissing();
220 testServiceCategoryExist();
221 testServiceBadCategoryCreate();
224 private void testServiceNameAlreadyExists() {
225 String serviceName = ALREADY_EXIST;
226 Service serviceExccedsNameLimit = createServiceObject(false);
227 // 51 chars, the limit is 50
228 serviceExccedsNameLimit.setName(serviceName);
229 List<String> tgs = new ArrayList<>();
230 tgs.add(serviceName);
231 serviceExccedsNameLimit.setTags(tgs);
232 validateUserRoles(Role.ADMIN, Role.DESIGNER);
234 bl.createService(serviceExccedsNameLimit, user);
235 } catch (ComponentException exp) {
236 assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
242 private void testServiceNameEmpty() {
243 Service serviceExccedsNameLimit = createServiceObject(false);
244 serviceExccedsNameLimit.setName(null);
246 bl.createService(serviceExccedsNameLimit, user);
247 } catch(ComponentException e){
248 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
254 private void testServiceNameWrongFormat() {
255 Service service = createServiceObject(false);
257 String nameWrongFormat = "ljg\\fd";
258 service.setName(nameWrongFormat);
260 bl.createService(service, user);
261 } catch(ComponentException e){
262 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
268 // Service name - end
269 // Service description - start
270 private void testServiceDescriptionEmpty() {
271 Service serviceExist = createServiceObject(false);
272 serviceExist.setDescription("");
274 bl.createService(serviceExist, user);
275 } catch(ComponentException e){
276 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
282 private void testServiceDescriptionMissing() {
283 Service serviceExist = createServiceObject(false);
284 serviceExist.setDescription(null);
286 bl.createService(serviceExist, user);
287 } catch(ComponentException e){
288 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
294 private void testServiceDescExceedsLimitCreate() {
295 Service serviceExccedsDescLimit = createServiceObject(false);
296 // 1025 chars, the limit is 1024
297 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
298 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
299 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
300 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
301 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
302 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
303 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
304 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
306 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
308 bl.createService(serviceExccedsDescLimit, user);
309 } catch(ComponentException e){
310 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
316 private void testServiceDescNotEnglish() {
317 Service notEnglish = createServiceObject(false);
319 String tooLongServiceDesc = "\uC2B5";
320 notEnglish.setDescription(tooLongServiceDesc);
322 bl.createService(notEnglish, user);
323 } catch(ComponentException e){
324 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
330 // Service description - stop
331 // Service icon - start
332 private void testServiceIconEmpty() {
333 Service serviceExist = createServiceObject(false);
334 serviceExist.setIcon("");
335 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
336 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
340 private void testServiceIconMissing() {
341 Service serviceExist = createServiceObject(false);
342 serviceExist.setIcon(null);
343 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
344 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
347 private void testResourceIconInvalid() {
348 Service resourceExist = createServiceObject(false);
349 resourceExist.setIcon("kjk3453^&");
351 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
352 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
356 private void testTagsNoServiceName() {
357 Service serviceExccedsNameLimit = createServiceObject(false);
358 String tag1 = "afzs2qLBb";
359 List<String> tagsList = new ArrayList<>();
361 serviceExccedsNameLimit.setTags(tagsList);
363 bl.createService(serviceExccedsNameLimit, user);
364 } catch(ComponentException e) {
365 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
371 private void testInvalidTag() {
372 Service serviceExccedsNameLimit = createServiceObject(false);
373 String tag1 = "afzs2qLBb%#%";
374 List<String> tagsList = new ArrayList<>();
376 serviceExccedsNameLimit.setTags(tagsList);
378 bl.createService(serviceExccedsNameLimit, user);
379 } catch(ComponentException e) {
380 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
386 private void testServiceTagNotExist() {
387 Service serviceExist = createServiceObject(false);
388 serviceExist.setTags(null);
390 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
391 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
394 private void testServiceTagEmpty() {
395 Service serviceExist = createServiceObject(false);
396 serviceExist.setTags(new ArrayList<>());
398 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
399 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
402 // Service tags - stop
403 // Service contactId - start
404 private void testContactIdTooLong() {
405 Service serviceContactId = createServiceObject(false);
406 // 59 chars instead of 50
407 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
408 serviceContactId.setContactId(contactIdTooLong);
410 bl.createService(serviceContactId, user);
411 } catch(ComponentException e) {
412 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
418 private void testContactIdWrongFormatCreate() {
419 Service serviceContactId = createServiceObject(false);
420 // 3 letters and 3 digits and special characters
421 String contactIdTooLong = "yrt134!!!";
422 serviceContactId.setContactId(contactIdTooLong);
424 bl.createService(serviceContactId, user);
425 } catch(ComponentException e) {
426 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
432 private void testResourceContactIdMissing() {
433 Service resourceExist = createServiceObject(false);
434 resourceExist.setContactId(null);
436 bl.createService(resourceExist, user);
437 } catch(ComponentException e) {
438 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
444 // Service contactId - stop
445 // Service category - start
446 private void testServiceCategoryExist() {
447 Service serviceExist = createServiceObject(false);
448 serviceExist.setCategories(null);
450 bl.createService(serviceExist, user);
451 } catch(ComponentException e) {
452 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
459 public void markDistributionAsDeployedTestAlreadyDeployed() {
460 String notifyAction = "DNotify";
461 String requestAction = "DRequest";
462 String resultAction = "DResult";
463 String did = "123456";
465 setupBeforeDeploy(notifyAction, requestAction, did);
466 List<DistributionDeployEvent> resultList = new ArrayList<>();
467 Map<String, Object> params = new HashMap<>();
468 DistributionDeployEvent event = new DistributionDeployEvent();
470 event.setAction(resultAction);
472 event.setStatus("200");
473 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
474 // deployEvent.setFields(params);
475 resultList.add(event);
476 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
478 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
480 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
481 assertTrue(markDeployed.isLeft());
483 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
488 public void markDistributionAsDeployedTestSuccess() {
489 String notifyAction = "DNotify";
490 String requestAction = "DRequest";
491 String did = "123456";
493 setupBeforeDeploy(notifyAction, requestAction, did);
494 List<Role> roles = new ArrayList<>();
495 roles.add(Role.ADMIN);
496 roles.add(Role.DESIGNER);
497 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
498 assertTrue(markDeployed.isLeft());
502 public void markDistributionAsDeployedTestNotDistributed() {
503 String notifyAction = "DNotify";
504 String requestAction = "DRequest";
505 String did = "123456";
507 setupBeforeDeploy(notifyAction, requestAction, did);
508 List<ResourceAdminEvent> emptyList = new ArrayList<>();
509 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
510 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
512 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
513 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
515 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
516 assertTrue(markDeployed.isRight());
517 assertEquals(404, markDeployed.right().value().getStatus().intValue());
521 private void testServiceBadCategoryCreate() {
523 Service serviceExist = createServiceObject(false);
524 CategoryDefinition category = new CategoryDefinition();
525 category.setName("koko");
526 category.setIcons(Arrays.asList(DEFAULT_ICON));
527 List<CategoryDefinition> categories = new ArrayList<>();
528 categories.add(category);
529 serviceExist.setCategories(categories);
531 bl.createService(serviceExist, user);
532 } catch(ComponentException e) {
533 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
539 // Service category - stop
540 // Service projectCode - start
541 private void testInvalidProjectCode() {
543 Service serviceExist = createServiceObject(false);
544 serviceExist.setProjectCode("koko!!");
547 bl.createService(serviceExist, user);
548 } catch(ComponentException exp) {
549 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
556 private void testProjectCodeTooLong() {
558 Service serviceExist = createServiceObject(false);
559 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
560 serviceExist.setProjectCode(tooLongProjectCode);
563 bl.createService(serviceExist, user);
564 } catch(ComponentException exp) {
565 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
572 private void testProjectCodeTooShort() {
574 Service serviceExist = createServiceObject(false);
575 serviceExist.setProjectCode("333");
578 bl.createService(serviceExist, user);
579 } catch(ComponentException exp) {
580 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
587 public void testDeleteMarkedServices() {
588 List<String> ids = new ArrayList<>();
589 List<String> responseIds = new ArrayList<>();
590 String resourceInUse = "123";
591 ids.add(resourceInUse);
592 String resourceFree = "456";
593 ids.add(resourceFree);
594 responseIds.add(resourceFree);
595 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
596 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
598 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
599 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
601 List<ArtifactDefinition> artifacts = new ArrayList<>();
602 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
604 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
605 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
606 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
607 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
608 assertTrue(deleteMarkedResources.isLeft());
609 List<String> resourceIdList = deleteMarkedResources.left().value();
610 assertFalse(resourceIdList.isEmpty());
611 assertTrue(resourceIdList.contains(resourceFree));
612 assertFalse(resourceIdList.contains(resourceInUse));
617 @SuppressWarnings({ "unchecked", "rawtypes" })
619 public void testFindGroupInstanceOnRelatedComponentInstance() {
621 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
622 String methodName = "findGroupInstanceOnRelatedComponentInstance";
623 Object invalidId = "invalidId";
625 Component service = createNewService();
626 List<ComponentInstance> componentInstances = service.getComponentInstances();
628 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
629 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
630 Class[] argClasses = {Component.class, String.class,String.class};
632 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
633 method.setAccessible(true);
635 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
636 assertNotNull(findGroupInstanceRes);
637 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
639 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
644 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
646 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
647 assertNotNull(findGroupInstanceRes);
648 assertTrue(findGroupInstanceRes.isRight());
649 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
651 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
653 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
654 assertNotNull(findGroupInstanceRes);
655 assertTrue(findGroupInstanceRes.isRight());
656 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
658 catch (Exception e) {
663 private Component createNewComponent() {
665 Service service = new Service();
667 service.setName("serviceName");
668 service.setUniqueId("serviceUniqueId");
669 List<ComponentInstance> componentInstances = new ArrayList<>();
670 ComponentInstance ci;
671 for(int i= 0; i<listSize; ++i){
672 ci = new ComponentInstance();
673 ci.setName("ciName" + i);
674 ci.setUniqueId("ciId" + i);
675 List<GroupInstance> groupInstances= new ArrayList<>();
677 for(int j = 0; j<listSize; ++j){
678 gi = new GroupInstance();
679 gi.setName(ci.getName( )+ "giName" + j);
680 gi.setUniqueId(ci.getName() + "giId" + j);
681 groupInstances.add(gi);
683 ci.setGroupInstances(groupInstances);
684 componentInstances.add(ci);
686 service.setComponentInstances(componentInstances);
690 protected Service createNewService() {
691 return (Service)createNewComponent();
696 public void testDerivedFromGeneric() {
697 Service service = createServiceObject(true);
698 validateUserRoles(Role.ADMIN, Role.DESIGNER);
699 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
700 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
701 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
702 assertTrue(createResponse.isLeft());
703 service = createResponse.left().value();
704 assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
705 assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
709 public void testUpdateMetadataNamingPolicy() {
710 Service currentService = createServiceObject(true);
711 Service newService = createServiceObject(false);
712 currentService.setEcompGeneratedNaming(false);
713 newService.setEcompGeneratedNaming(true);
714 newService.setNamingPolicy("policy");
715 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
716 assertThat(resultOfUpdate.isLeft()).isTrue();
717 Service updatedService = resultOfUpdate.left().value();
718 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
719 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
723 public void testUpdateMetadataToEmptyProjectCode() {
724 Service currentService = createServiceObject(true);
725 Service newService = createServiceObject(false);
726 currentService.setProjectCode("12345");
727 newService.setProjectCode("");
728 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
729 assertThat(resultOfUpdate.isLeft()).isTrue();
730 Service updatedService = resultOfUpdate.left().value();
731 assertThat(updatedService.getProjectCode()).isEmpty();
735 public void testUpdateMetadataFromEmptyProjectCode() {
736 Service currentService = createServiceObject(true);
737 Service newService = createServiceObject(false);
738 currentService.setProjectCode("");
739 newService.setProjectCode("12345");
740 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
741 assertThat(resultOfUpdate.isLeft()).isTrue();
742 Service updatedService = resultOfUpdate.left().value();
743 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
747 public void testUpdateMetadataProjectCode() {
748 Service currentService = createServiceObject(true);
749 Service newService = createServiceObject(false);
750 currentService.setProjectCode("33333");
751 newService.setProjectCode("12345");
752 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
753 assertThat(resultOfUpdate.isLeft()).isTrue();
754 Service updatedService = resultOfUpdate.left().value();
755 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
759 public void testUpdateMetadataServiceType() {
760 Service currentService = createServiceObject(true);
761 Service newService = createServiceObject(false);
762 currentService.setServiceType("alice");
764 newService.setServiceType("bob");
765 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
766 assertThat(resultOfUpdate.isLeft()).isTrue();
767 Service updatedService = resultOfUpdate.left().value();
768 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
769 //empty string is invalid
770 newService.setServiceType("");
771 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
772 assertThat(resultOfUpdate.isLeft()).isTrue();
774 newService.setServiceType(null);
775 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
776 assertThat(resultOfUpdate.isRight()).isTrue();
780 public void testCreateDefaultMetadataServiceFunction() {
781 Service currentService = createServiceObject(true);
782 assertThat(currentService.getServiceFunction()).isEqualTo("");
786 public void testCreateCustomMetadataServiceFunction() {
787 String customServiceFunctionName = "customName";
788 Service currentService = createServiceObject(true);
789 currentService.setServiceFunction(customServiceFunctionName);
790 assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
794 public void testUpdateMetadataServiceFunction() {
795 Service currentService = createServiceObject(true);
796 Service newService = createServiceObject(false);
797 currentService.setServiceFunction("alice");
799 newService.setServiceFunction("bob");
800 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
801 assertThat(resultOfUpdate.isLeft()).isTrue();
802 Service updatedService = resultOfUpdate.left().value();
803 assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
804 //empty string is valid
805 newService.setServiceFunction("");
806 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
807 assertThat(resultOfUpdate.isLeft()).isTrue();
808 //null is valid and assigner to ""
809 newService.setServiceFunction(null);
810 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
811 assertThat(resultOfUpdate.isLeft()).isTrue();
812 assertThat(updatedService.getServiceFunction()).isEqualTo("");
818 public void testServiceFunctionExceedLength() {
819 String serviceName = "Service";
820 String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
821 Service serviceFunctionExceedLength = createServiceObject(false);
822 serviceFunctionExceedLength.setName(serviceName);
823 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
824 List<String> tgs = new ArrayList<>();
825 tgs.add(serviceName);
826 serviceFunctionExceedLength.setTags(tgs);
828 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
829 } catch (ComponentException exp) {
830 assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
835 public void testServiceFunctionInvalidCharacter(){
836 String serviceName = "Service";
837 String serviceFunction = "a?";
838 Service serviceFunctionExceedLength = createServiceObject(false);
839 serviceFunctionExceedLength.setName(serviceName);
840 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
841 List<String> tgs = new ArrayList<>();
842 tgs.add(serviceName);
843 serviceFunctionExceedLength.setTags(tgs);
845 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
846 } catch (ComponentException exp) {
847 assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
852 public void testAddPropertyServiceConsumptionServiceNotFound() {
853 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
855 Either<Operation, ResponseFormat> operationEither =
856 bl.addPropertyServiceConsumption("1", "2", "3",
857 user.getUserId(), new ServiceConsumptionData());
858 Assert.assertTrue(operationEither.isRight());
859 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
863 public void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
864 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
865 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
867 Either<Operation, ResponseFormat> operationEither =
868 bl.addPropertyServiceConsumption("1", "2", "3",
869 user.getUserId(), new ServiceConsumptionData());
870 Assert.assertTrue(operationEither.isRight());
871 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
875 public void testAddPropertyServiceConsumptionNoMatchingComponent() {
876 Service aService = createNewService();
877 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
878 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
880 String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
882 Either<Operation, ResponseFormat> operationEither =
883 bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
884 user.getUserId(), new ServiceConsumptionData());
885 Assert.assertTrue(operationEither.isRight());
886 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
890 public void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
891 Service aService = createNewService();
892 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
893 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
894 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
896 Either<Operation, ResponseFormat> operationEither =
897 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
898 user.getUserId(), new ServiceConsumptionData());
899 Assert.assertTrue(operationEither.isRight());
900 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
904 public void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
905 Service aService = createNewService();
906 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
907 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
908 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
910 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
912 componentInstancesInterfacesMap.put(aService.getUniqueId(),
913 Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
915 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
917 Either<Operation, ResponseFormat> operationEither =
918 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
919 user.getUserId(), new ServiceConsumptionData());
920 Assert.assertTrue(operationEither.isRight());
921 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
925 public void testAddPropertyServiceConsumptionNoInputsCandidate() {
926 Service aService = createNewService();
927 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
928 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
929 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
931 String operationId = "operationId";
932 ComponentInstanceInterface componentInstanceInterface =
933 new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
934 Map<String, Operation> operationsMap = Maps.newHashMap();
935 operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
936 new ListDataDefinition<>(), new ListDataDefinition<>()));
937 componentInstanceInterface.setOperationsMap(operationsMap);
939 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
940 componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
941 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
943 Either<Operation, ResponseFormat> operationEither =
944 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
945 user.getUserId(), new ServiceConsumptionData());
946 Assert.assertTrue(operationEither.isRight());
947 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());