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.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.assertNotNull;
30 import static org.junit.jupiter.api.Assertions.assertNull;
31 import static org.junit.jupiter.api.Assertions.assertThrows;
32 import static org.junit.jupiter.api.Assertions.assertTrue;
33 import static org.junit.jupiter.api.Assertions.fail;
34 import static org.mockito.Mockito.when;
36 import com.google.common.collect.Lists;
37 import com.google.common.collect.Maps;
38 import fj.data.Either;
39 import java.lang.reflect.Method;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.HashMap;
43 import java.util.List;
45 import java.util.Optional;
46 import java.util.UUID;
48 import org.apache.commons.lang3.tuple.ImmutablePair;
49 import org.junit.jupiter.api.Test;
50 import org.mockito.Mockito;
51 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.ModelTypeEnum;
58 import org.openecomp.sdc.be.model.ArtifactDefinition;
59 import org.openecomp.sdc.be.model.Component;
60 import org.openecomp.sdc.be.model.ComponentInstance;
61 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
62 import org.openecomp.sdc.be.model.GroupInstance;
63 import org.openecomp.sdc.be.model.Model;
64 import org.openecomp.sdc.be.model.Operation;
65 import org.openecomp.sdc.be.model.PropertyDefinition;
66 import org.openecomp.sdc.be.model.Resource;
67 import org.openecomp.sdc.be.model.Service;
68 import org.openecomp.sdc.be.model.category.CategoryDefinition;
69 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
70 import org.openecomp.sdc.be.model.operations.StorageException;
71 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
72 import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
73 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
74 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
75 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
76 import org.openecomp.sdc.be.types.ServiceConsumptionData;
77 import org.openecomp.sdc.be.user.Role;
78 import org.openecomp.sdc.common.util.ValidationUtils;
79 import org.openecomp.sdc.exception.ResponseFormat;
80 import org.springframework.http.HttpStatus;
82 class ServiceBusinessLogicTest extends ServiceBusinessLogicBaseTestSetup {
84 private final static String DEFAULT_ICON = "defaulticon";
85 private static final String ALREADY_EXIST = "alreadyExist";
88 void testGetComponentAuditRecordsCertifiedVersion() {
89 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
90 assertTrue(componentAuditRecords.isLeft());
91 assertEquals(3, componentAuditRecords.left().value().size());
95 void testGetComponentAuditRecordsUnCertifiedVersion() {
96 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
97 assertTrue(componentAuditRecords.isLeft());
98 assertEquals(4, componentAuditRecords.left().value().size());
102 void testHappyScenario() {
103 Service service = createServiceObject(false);
104 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
105 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
107 if (createResponse.isRight()) {
108 assertEquals(new Integer(200), createResponse.right().value().getStatus());
110 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
114 void testServiceCreationPluginCall() {
115 final Service service = createServiceObject(false);
116 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
117 final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
118 serviceCreationPlugins.add(new ServiceCreationPlugin() {
120 public void beforeCreate(Service service) {
125 public int getOrder() {
129 serviceCreationPlugins.add(new ServiceCreationPlugin() {
131 public void beforeCreate(Service service) {
132 throw new RuntimeException();
136 public int getOrder() {
140 bl.setServiceCreationPluginList(serviceCreationPlugins);
141 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
142 assertTrue(createResponse.isLeft());
147 void testCreateServiceWhenGenericTypeHasProperties() {
148 final Service service = createServiceObject(false);
150 final Resource genericTypeResource = mockGenericTypeResource();
152 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
153 final Service expectedService = createServiceObject(true);
154 expectedService.setProperties(mockPropertyList());
155 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
156 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
158 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
159 createResponse.isLeft(), is(true));
160 final Service actualService = createResponse.left().value();
161 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
163 assertEqualsServiceObject(expectedService, actualService);
167 void testCreateServiceWhenGenericTypeAndServiceHasProperties() {
168 final Service service = createServiceObject(false);
169 service.setProperties(mockPropertyList());
170 service.getProperties().remove(0);
171 final PropertyDefinition serviceProperty = new PropertyDefinition();
172 serviceProperty.setName("aServiceProperty");
173 service.getProperties().add(serviceProperty);
175 final Resource genericTypeResource = mockGenericTypeResource();
177 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
178 final Service expectedService = createServiceObject(true);
179 expectedService.setProperties(mockPropertyList());
180 expectedService.getProperties().add(serviceProperty);
181 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
182 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
184 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
185 createResponse.isLeft(), is(true));
186 final Service actualService = createResponse.left().value();
187 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
190 assertEqualsServiceObject(expectedService, actualService);
194 void testHappyScenarioCRNullProjectCode() {
195 Service service = createServiceObject(false);
196 service.setProjectCode(null);
197 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
198 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
200 if (createResponse.isRight()) {
201 assertEquals(new Integer(200), createResponse.right().value().getStatus());
203 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
207 void testHappyScenarioCREmptyStringProjectCode() {
208 createServiceValidator();
209 Service service = createServiceObject(false);
210 service.setProjectCode("");
211 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
212 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
214 if (createResponse.isRight()) {
215 assertEquals(new Integer(200), createResponse.right().value().getStatus());
217 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
219 private void assertEqualsServiceObject(final Service expectedService, final Service actualService) {
220 assertEquals(expectedService.getContactId(), actualService.getContactId());
221 assertEquals(expectedService.getCategories(), actualService.getCategories());
222 assertEquals(expectedService.getCreatorUserId(), actualService.getCreatorUserId());
223 assertEquals(expectedService.getCreatorFullName(), actualService.getCreatorFullName());
224 assertEquals(expectedService.getDescription(), actualService.getDescription());
225 assertEquals(expectedService.getIcon(), actualService.getIcon());
226 assertEquals(expectedService.getLastUpdaterUserId(), actualService.getLastUpdaterUserId());
227 assertEquals(expectedService.getLastUpdaterFullName(), actualService.getLastUpdaterFullName());
228 assertEquals(expectedService.getName(), actualService.getName());
229 assertEquals(expectedService.getUniqueId(), actualService.getUniqueId());
230 assertEquals(expectedService.getVersion(), actualService.getVersion());
231 assertEquals(expectedService.getArtifacts(), actualService.getArtifacts());
232 assertEquals(expectedService.getCreationDate(), actualService.getCreationDate());
233 assertEquals(expectedService.getLastUpdateDate(), actualService.getLastUpdateDate());
234 assertEquals(expectedService.getLifecycleState(), actualService.getLifecycleState());
235 assertEquals(expectedService.getTags(), actualService.getTags());
236 if (expectedService.getProperties() == null) {
237 org.hamcrest.MatcherAssert.assertThat("Service properties should be null",
238 actualService.getProperties(), is(nullValue()));
241 org.hamcrest.MatcherAssert.assertThat("Service properties should be as expected",
242 actualService.getProperties(), is(expectedService.getProperties()));
247 /* CREATE validations - start ***********************/
248 // Service name - start
251 void testFailedServiceValidations() {
253 testServiceNameAlreadyExists();
254 testServiceNameEmpty();
255 testServiceNameWrongFormat();
256 testServiceDescriptionEmpty();
257 testServiceDescriptionMissing();
258 testServiceDescExceedsLimitCreate();
259 testServiceDescNotEnglish();
260 testServiceIconEmpty();
261 testServiceIconMissing();
262 testResourceIconInvalid();
263 testTagsNoServiceName();
265 testServiceTagNotExist();
266 testServiceTagEmpty();
268 testContactIdTooLong();
269 testContactIdWrongFormatCreate();
270 testInvalidProjectCode();
271 testProjectCodeTooLong();
272 testProjectCodeTooShort();
274 testResourceContactIdMissing();
275 testServiceCategoryExist();
276 testServiceBadCategoryCreate();
279 private void testServiceNameAlreadyExists() {
280 String serviceName = ALREADY_EXIST;
281 Service serviceExccedsNameLimit = createServiceObject(false);
282 // 51 chars, the limit is 50
283 serviceExccedsNameLimit.setName(serviceName);
284 List<String> tgs = new ArrayList<>();
285 tgs.add(serviceName);
286 serviceExccedsNameLimit.setTags(tgs);
288 bl.createService(serviceExccedsNameLimit, user);
289 } catch (ComponentException exp) {
290 assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
296 private void testServiceNameEmpty() {
297 Service serviceExccedsNameLimit = createServiceObject(false);
298 serviceExccedsNameLimit.setName(null);
300 bl.createService(serviceExccedsNameLimit, user);
301 } catch(ComponentException e){
302 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
308 private void testServiceNameWrongFormat() {
309 Service service = createServiceObject(false);
311 String nameWrongFormat = "ljg\\fd";
312 service.setName(nameWrongFormat);
314 bl.createService(service, user);
315 } catch(ComponentException e){
316 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
322 // Service name - end
323 // Service description - start
325 private void testServiceDescriptionEmpty() {
326 Service serviceExist = createServiceObject(false);
327 serviceExist.setDescription("");
329 bl.createService(serviceExist, user);
330 } catch(ComponentException e){
331 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
336 private void testServiceDescriptionMissing() {
337 Service serviceExist = createServiceObject(false);
338 serviceExist.setDescription(null);
340 bl.createService(serviceExist, user);
341 } catch(ComponentException e){
342 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
348 private void testServiceDescExceedsLimitCreate() {
349 Service serviceExccedsDescLimit = createServiceObject(false);
350 // 1025 chars, the limit is 1024
351 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
352 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
353 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
354 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
355 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
356 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
357 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
358 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
360 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
362 bl.createService(serviceExccedsDescLimit, user);
363 } catch(ComponentException e){
364 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
370 private void testServiceDescNotEnglish() {
371 Service notEnglish = createServiceObject(false);
373 String tooLongServiceDesc = "\uC2B5";
374 notEnglish.setDescription(tooLongServiceDesc);
376 bl.createService(notEnglish, user);
377 } catch(ComponentException e){
378 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
384 // Service description - stop
385 // Service icon - start
387 private void testServiceIconEmpty() {
388 Service serviceExist = createServiceObject(false);
389 serviceExist.setIcon("");
390 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
391 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
394 private void testServiceIconMissing() {
395 Service serviceExist = createServiceObject(false);
396 serviceExist.setIcon(null);
397 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
398 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
401 private void testResourceIconInvalid() {
402 Service resourceExist = createServiceObject(false);
403 resourceExist.setIcon("kjk3453^&");
405 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
406 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
410 private void testTagsNoServiceName() {
411 Service serviceExccedsNameLimit = createServiceObject(false);
412 String tag1 = "afzs2qLBb";
413 List<String> tagsList = new ArrayList<>();
415 serviceExccedsNameLimit.setTags(tagsList);
417 bl.createService(serviceExccedsNameLimit, user);
418 } catch(ComponentException e) {
419 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
425 private void testInvalidTag() {
426 Service serviceExccedsNameLimit = createServiceObject(false);
427 String tag1 = "afzs2qLBb%#%";
428 List<String> tagsList = new ArrayList<>();
430 serviceExccedsNameLimit.setTags(tagsList);
432 bl.createService(serviceExccedsNameLimit, user);
433 } catch(ComponentException e) {
434 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
440 private void testServiceTagNotExist() {
441 Service serviceExist = createServiceObject(false);
442 serviceExist.setTags(null);
444 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
445 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
448 private void testServiceTagEmpty() {
449 Service serviceExist = createServiceObject(false);
450 serviceExist.setTags(new ArrayList<>());
452 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
453 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
456 // Service tags - stop
457 // Service contactId - start
459 private void testContactIdTooLong() {
460 Service serviceContactId = createServiceObject(false);
461 // 59 chars instead of 50
462 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
463 serviceContactId.setContactId(contactIdTooLong);
465 bl.createService(serviceContactId, user);
466 } catch(ComponentException e) {
467 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
472 private void testContactIdWrongFormatCreate() {
473 Service serviceContactId = createServiceObject(false);
474 // 3 letters and 3 digits and special characters
475 String contactIdTooLong = "yrt134!!!";
476 serviceContactId.setContactId(contactIdTooLong);
478 bl.createService(serviceContactId, user);
479 } catch(ComponentException e) {
480 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
486 private void testResourceContactIdMissing() {
487 Service resourceExist = createServiceObject(false);
488 resourceExist.setContactId(null);
490 bl.createService(resourceExist, user);
491 } catch(ComponentException e) {
492 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
498 // Service contactId - stop
499 // Service category - start
501 private void testServiceCategoryExist() {
502 Service serviceExist = createServiceObject(false);
503 serviceExist.setCategories(null);
505 bl.createService(serviceExist, user);
506 } catch(ComponentException e) {
507 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
513 void markDistributionAsDeployedTestAlreadyDeployed() {
514 String notifyAction = "DNotify";
515 String requestAction = "DRequest";
516 String resultAction = "DResult";
517 String did = "123456";
519 setupBeforeDeploy(notifyAction, requestAction, did);
520 List<DistributionDeployEvent> resultList = new ArrayList<>();
521 Map<String, Object> params = new HashMap<>();
522 DistributionDeployEvent event = new DistributionDeployEvent();
524 event.setAction(resultAction);
526 event.setStatus("200");
527 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
528 // deployEvent.setFields(params);
529 resultList.add(event);
530 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
532 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
534 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
535 assertTrue(markDeployed.isLeft());
537 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
542 void markDistributionAsDeployedTestSuccess() {
543 String notifyAction = "DNotify";
544 String requestAction = "DRequest";
545 String did = "123456";
547 setupBeforeDeploy(notifyAction, requestAction, did);
548 List<Role> roles = new ArrayList<>();
549 roles.add(Role.ADMIN);
550 roles.add(Role.DESIGNER);
551 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
552 assertTrue(markDeployed.isLeft());
556 void markDistributionAsDeployedTestNotDistributed() {
557 String notifyAction = "DNotify";
558 String requestAction = "DRequest";
559 String did = "123456";
561 setupBeforeDeploy(notifyAction, requestAction, did);
562 List<ResourceAdminEvent> emptyList = new ArrayList<>();
563 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
564 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
566 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
567 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
569 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
570 assertTrue(markDeployed.isRight());
571 assertEquals(404, markDeployed.right().value().getStatus().intValue());
575 private void testServiceBadCategoryCreate() {
577 Service serviceExist = createServiceObject(false);
578 CategoryDefinition category = new CategoryDefinition();
579 category.setName("koko");
580 category.setIcons(Arrays.asList(DEFAULT_ICON));
581 List<CategoryDefinition> categories = new ArrayList<>();
582 categories.add(category);
583 serviceExist.setCategories(categories);
585 bl.createService(serviceExist, user);
586 } catch(ComponentException e) {
587 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
593 // Service category - stop
594 // Service projectCode - start
596 private void testInvalidProjectCode() {
598 Service serviceExist = createServiceObject(false);
599 serviceExist.setProjectCode("koko!!");
602 bl.createService(serviceExist, user);
603 } catch(ComponentException exp) {
604 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
610 private void testProjectCodeTooLong() {
612 Service serviceExist = createServiceObject(false);
613 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
614 serviceExist.setProjectCode(tooLongProjectCode);
617 bl.createService(serviceExist, user);
618 } catch(ComponentException exp) {
619 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
626 private void testProjectCodeTooShort() {
628 Service serviceExist = createServiceObject(false);
629 serviceExist.setProjectCode("333");
632 bl.createService(serviceExist, user);
633 } catch(ComponentException exp) {
634 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
641 void testDeleteMarkedServices() {
642 List<String> ids = new ArrayList<>();
643 List<String> responseIds = new ArrayList<>();
644 String resourceInUse = "123";
645 ids.add(resourceInUse);
646 String resourceFree = "456";
647 ids.add(resourceFree);
648 responseIds.add(resourceFree);
649 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
650 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
652 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
653 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
655 List<ArtifactDefinition> artifacts = new ArrayList<>();
656 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
658 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
659 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
660 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
661 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
662 assertTrue(deleteMarkedResources.isLeft());
663 List<String> resourceIdList = deleteMarkedResources.left().value();
664 assertFalse(resourceIdList.isEmpty());
665 assertTrue(resourceIdList.contains(resourceFree));
666 assertFalse(resourceIdList.contains(resourceInUse));
670 void testDeleteArchivedService_NotFound() {
671 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
672 assertThrows(StorageException.class, () -> bl.deleteServiceAllVersions("1", user));
676 void testDeleteArchivedService_NotArchived() {
677 String serviceId = "12345";
678 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
679 eitherService.left().value().setArchived(false);
680 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
681 final ComponentException actualException = assertThrows(ComponentException.class, () -> bl.deleteServiceAllVersions(serviceId, user));
682 assertEquals(actualException.getActionStatus(), ActionStatus.COMPONENT_NOT_ARCHIVED);
683 assertEquals(actualException.getParams()[0], serviceId);
687 void testDeleteArchivedService_DeleteServiceSpecificModel() throws ToscaOperationException {
688 String serviceId = "12345";
689 String model = "serviceSpecificModel";
690 List<String> deletedServcies= new ArrayList<>();
691 deletedServcies.add("54321");
692 Model normativeExtensionModel = new Model("normativeExtensionModel", ModelTypeEnum.NORMATIVE_EXTENSION);
693 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
694 eitherService.left().value().setArchived(true);
695 eitherService.left().value().setModel(model);
696 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
697 Mockito.when(toscaOperationFacade.deleteService(Mockito.anyString(), Mockito.eq(true))).thenReturn(deletedServcies);
698 Mockito.when(modelOperation.findModelByName(model)).thenReturn(Optional.of(normativeExtensionModel));
699 bl.deleteServiceAllVersions(serviceId, user);
700 Mockito.verify(modelOperation, Mockito.times(1)).deleteModel(normativeExtensionModel, false);
703 @SuppressWarnings({ "unchecked", "rawtypes" })
705 void testFindGroupInstanceOnRelatedComponentInstance() {
707 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
708 String methodName = "findGroupInstanceOnRelatedComponentInstance";
709 Object invalidId = "invalidId";
711 Component service = createNewService();
712 List<ComponentInstance> componentInstances = service.getComponentInstances();
714 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
715 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
716 Class[] argClasses = {Component.class, String.class,String.class};
718 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
719 method.setAccessible(true);
721 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
722 assertNotNull(findGroupInstanceRes);
723 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
725 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
730 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
732 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
733 assertNotNull(findGroupInstanceRes);
734 assertTrue(findGroupInstanceRes.isRight());
735 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
737 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
739 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
740 assertNotNull(findGroupInstanceRes);
741 assertTrue(findGroupInstanceRes.isRight());
742 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
744 catch (Exception e) {
749 private Component createNewComponent() {
751 Service service = new Service();
753 service.setName("serviceName");
754 service.setUniqueId("serviceUniqueId");
755 List<ComponentInstance> componentInstances = new ArrayList<>();
756 ComponentInstance ci;
757 for(int i= 0; i<listSize; ++i){
758 ci = new ComponentInstance();
759 ci.setName("ciName" + i);
760 ci.setUniqueId("ciId" + i);
761 List<GroupInstance> groupInstances= new ArrayList<>();
763 for(int j = 0; j<listSize; ++j){
764 gi = new GroupInstance();
765 gi.setName(ci.getName( )+ "giName" + j);
766 gi.setUniqueId(ci.getName() + "giId" + j);
767 groupInstances.add(gi);
769 ci.setGroupInstances(groupInstances);
770 componentInstances.add(ci);
772 service.setComponentInstances(componentInstances);
776 protected Service createNewService() {
777 return (Service)createNewComponent();
781 void testDerivedFromGeneric() {
782 Service service = createServiceObject(true);
783 service.setDerivedFromGenericInfo(genericService);
784 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
785 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
786 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
787 assertTrue(createResponse.isLeft());
788 service = createResponse.left().value();
789 assertEquals(genericService.getToscaResourceName(), service.getDerivedFromGenericType());
790 assertEquals(genericService.getVersion(), service.getDerivedFromGenericVersion());
794 void testServiceWithoutDerivedFromGeneric() {
795 final Service service = createServiceObject(true);
796 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
797 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
798 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
799 assertTrue(createResponse.isLeft());
800 final Service actualService = createResponse.left().value();
801 assertNull(actualService.getDerivedFromGenericType());
802 assertNull(actualService.getDerivedFromGenericVersion());
806 void testUpdateMetadataNamingPolicy() {
807 Service currentService = createServiceObject(true);
808 Service newService = createServiceObject(false);
809 currentService.setEcompGeneratedNaming(false);
810 newService.setEcompGeneratedNaming(true);
811 newService.setNamingPolicy("policy");
812 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
813 assertThat(resultOfUpdate.isLeft()).isTrue();
814 Service updatedService = resultOfUpdate.left().value();
815 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
816 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
820 void testUpdateMetadataToEmptyProjectCode() {
821 Service currentService = createServiceObject(true);
822 Service newService = createServiceObject(false);
823 currentService.setProjectCode("12345");
824 newService.setProjectCode("");
825 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
826 assertThat(resultOfUpdate.isLeft()).isTrue();
827 Service updatedService = resultOfUpdate.left().value();
828 assertThat(updatedService.getProjectCode()).isEmpty();
832 void testUpdateMetadataFromEmptyProjectCode() {
833 Service currentService = createServiceObject(true);
834 Service newService = createServiceObject(false);
835 currentService.setProjectCode("");
836 newService.setProjectCode("12345");
837 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
838 assertThat(resultOfUpdate.isLeft()).isTrue();
839 Service updatedService = resultOfUpdate.left().value();
840 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
844 void testUpdateMetadataProjectCode() {
845 Service currentService = createServiceObject(true);
846 Service newService = createServiceObject(false);
847 currentService.setProjectCode("33333");
848 newService.setProjectCode("12345");
849 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
850 assertThat(resultOfUpdate.isLeft()).isTrue();
851 Service updatedService = resultOfUpdate.left().value();
852 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
856 void testUpdateMetadataServiceType() {
857 Service currentService = createServiceObject(true);
858 Service newService = createServiceObject(false);
859 currentService.setServiceType("alice");
861 newService.setServiceType("bob");
862 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
863 assertThat(resultOfUpdate.isLeft()).isTrue();
864 Service updatedService = resultOfUpdate.left().value();
865 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
866 //empty string is invalid
867 newService.setServiceType("");
868 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
869 assertThat(resultOfUpdate.isLeft()).isTrue();
871 newService.setServiceType(null);
872 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
873 assertThat(resultOfUpdate.isRight()).isTrue();
877 void testCreateDefaultMetadataServiceFunction() {
878 Service currentService = createServiceObject(true);
879 assertThat(currentService.getServiceFunction()).isEqualTo("");
883 void testCreateCustomMetadataServiceFunction() {
884 String customServiceFunctionName = "customName";
885 Service currentService = createServiceObject(true);
886 currentService.setServiceFunction(customServiceFunctionName);
887 assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
891 void testUpdateMetadataServiceFunction() {
892 Service currentService = createServiceObject(true);
893 Service newService = createServiceObject(false);
894 currentService.setServiceFunction("alice");
896 newService.setServiceFunction("bob");
897 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
898 assertThat(resultOfUpdate.isLeft()).isTrue();
899 Service updatedService = resultOfUpdate.left().value();
900 assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
901 //empty string is valid
902 newService.setServiceFunction("");
903 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
904 assertThat(resultOfUpdate.isLeft()).isTrue();
905 //null is valid and assigner to ""
906 newService.setServiceFunction(null);
907 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
908 assertThat(resultOfUpdate.isLeft()).isTrue();
909 assertThat(updatedService.getServiceFunction()).isEqualTo("");
915 void testServiceFunctionExceedLength() {
916 String serviceName = "Service";
917 String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
918 Service serviceFunctionExceedLength = createServiceObject(false);
919 serviceFunctionExceedLength.setName(serviceName);
920 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
921 List<String> tgs = new ArrayList<>();
922 tgs.add(serviceName);
923 serviceFunctionExceedLength.setTags(tgs);
925 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
926 } catch (ComponentException exp) {
927 assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
932 void testServiceFunctionInvalidCharacter(){
933 String serviceName = "Service";
934 String serviceFunction = "a?";
935 Service serviceFunctionExceedLength = createServiceObject(false);
936 serviceFunctionExceedLength.setName(serviceName);
937 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
938 List<String> tgs = new ArrayList<>();
939 tgs.add(serviceName);
940 serviceFunctionExceedLength.setTags(tgs);
942 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
943 } catch (ComponentException exp) {
944 assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
949 void testAddPropertyServiceConsumptionServiceNotFound() {
950 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
952 Either<Operation, ResponseFormat> operationEither =
953 bl.addPropertyServiceConsumption("1", "2", "3",
954 user.getUserId(), new ServiceConsumptionData());
955 assertTrue(operationEither.isRight());
956 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
960 void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
961 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
962 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
964 Either<Operation, ResponseFormat> operationEither =
965 bl.addPropertyServiceConsumption("1", "2", "3",
966 user.getUserId(), new ServiceConsumptionData());
967 assertTrue(operationEither.isRight());
968 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
972 void testAddPropertyServiceConsumptionNoMatchingComponent() {
973 Service aService = createNewService();
974 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
975 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
977 String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
979 Either<Operation, ResponseFormat> operationEither =
980 bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
981 user.getUserId(), new ServiceConsumptionData());
982 assertTrue(operationEither.isRight());
983 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
987 void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
988 Service aService = createNewService();
989 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
990 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
991 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
993 Either<Operation, ResponseFormat> operationEither =
994 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
995 user.getUserId(), new ServiceConsumptionData());
996 assertTrue(operationEither.isRight());
997 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1001 void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
1002 Service aService = createNewService();
1003 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1004 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1005 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1007 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
1009 componentInstancesInterfacesMap.put(aService.getUniqueId(),
1010 Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
1012 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1014 Either<Operation, ResponseFormat> operationEither =
1015 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
1016 user.getUserId(), new ServiceConsumptionData());
1017 assertTrue(operationEither.isRight());
1018 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1022 void testAddPropertyServiceConsumptionNoInputsCandidate() {
1023 Service aService = createNewService();
1024 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1025 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1026 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1028 String operationId = "operationId";
1029 ComponentInstanceInterface componentInstanceInterface =
1030 new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
1031 Map<String, Operation> operationsMap = Maps.newHashMap();
1032 operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
1033 new ListDataDefinition<>(), new ListDataDefinition<>()));
1034 componentInstanceInterface.setOperationsMap(operationsMap);
1036 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
1037 componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
1038 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1040 Either<Operation, ResponseFormat> operationEither =
1041 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
1042 user.getUserId(), new ServiceConsumptionData());
1043 assertTrue(operationEither.isRight());
1044 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1047 private Resource mockGenericTypeResource() {
1048 final Resource genericTypeResource = new Resource();
1049 genericTypeResource.setProperties(mockPropertyList());
1050 return genericTypeResource;
1053 private List<PropertyDefinition> mockPropertyList() {
1054 final List<PropertyDefinition> propertyList = new ArrayList<>();
1055 final PropertyDefinition propertyDefinition1 = new PropertyDefinition();
1056 propertyDefinition1.setName("property1");
1057 propertyDefinition1.setType("string");
1058 propertyList.add(propertyDefinition1);
1060 final PropertyDefinition propertyDefinition2 = new PropertyDefinition();
1061 propertyDefinition2.setName("property2");
1062 propertyDefinition2.setType("boolean");
1063 propertyList.add(propertyDefinition2);
1065 final PropertyDefinition propertyDefinition3 = new PropertyDefinition();
1066 propertyDefinition3.setName("property3");
1067 propertyDefinition3.setType("string");
1068 propertyList.add(propertyDefinition3);
1069 return propertyList;