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.ArgumentMatchers.any;
35 import static org.mockito.ArgumentMatchers.eq;
36 import static org.mockito.Mockito.when;
38 import com.google.common.collect.Lists;
39 import com.google.common.collect.Maps;
40 import fj.data.Either;
41 import java.lang.reflect.Method;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.List;
48 import java.util.Optional;
49 import java.util.UUID;
50 import org.apache.commons.lang3.tuple.ImmutablePair;
51 import org.junit.jupiter.api.Test;
52 import org.mockito.Mockito;
53 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
54 import org.openecomp.sdc.be.dao.api.ActionStatus;
55 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
58 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.ModelTypeEnum;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.Component;
62 import org.openecomp.sdc.be.model.ComponentInstInputsMap;
63 import org.openecomp.sdc.be.model.ComponentInstance;
64 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
65 import org.openecomp.sdc.be.model.GroupInstance;
66 import org.openecomp.sdc.be.model.InputDefinition;
67 import org.openecomp.sdc.be.model.Model;
68 import org.openecomp.sdc.be.model.Operation;
69 import org.openecomp.sdc.be.model.PropertyDefinition;
70 import org.openecomp.sdc.be.model.Resource;
71 import org.openecomp.sdc.be.model.Service;
72 import org.openecomp.sdc.be.model.category.CategoryDefinition;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ToscaOperationException;
74 import org.openecomp.sdc.be.model.operations.StorageException;
75 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
76 import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
77 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
78 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
79 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
80 import org.openecomp.sdc.be.types.ServiceConsumptionData;
81 import org.openecomp.sdc.be.user.Role;
82 import org.openecomp.sdc.common.util.ValidationUtils;
83 import org.openecomp.sdc.exception.ResponseFormat;
84 import org.springframework.http.HttpStatus;
86 class ServiceBusinessLogicTest extends ServiceBusinessLogicBaseTestSetup {
88 private final static String DEFAULT_ICON = "defaulticon";
89 private static final String ALREADY_EXIST = "alreadyExist";
92 void testGetComponentAuditRecordsCertifiedVersion() {
93 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID,
95 assertTrue(componentAuditRecords.isLeft());
96 assertEquals(3, componentAuditRecords.left().value().size());
100 void testGetComponentAuditRecordsUnCertifiedVersion() {
101 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID,
103 assertTrue(componentAuditRecords.isLeft());
104 assertEquals(4, componentAuditRecords.left().value().size());
108 void testHappyScenario() {
109 Service service = createServiceObject(false);
110 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
111 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
113 if (createResponse.isRight()) {
114 assertEquals(new Integer(200), createResponse.right().value().getStatus());
116 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
120 void testServiceCreationPluginCall() {
121 final Service service = createServiceObject(false);
122 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
123 final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
124 serviceCreationPlugins.add(new ServiceCreationPlugin() {
126 public void beforeCreate(Service service) {
131 public int getOrder() {
135 serviceCreationPlugins.add(new ServiceCreationPlugin() {
137 public void beforeCreate(Service service) {
138 throw new RuntimeException();
142 public int getOrder() {
146 bl.setServiceCreationPluginList(serviceCreationPlugins);
147 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
148 assertTrue(createResponse.isLeft());
153 void testCreateServiceWhenGenericTypeHasProperties() {
154 final Service service = createServiceObject(false);
156 final Resource genericTypeResource = mockGenericTypeResource();
158 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
159 final Service expectedService = createServiceObject(true);
160 expectedService.setProperties(mockPropertyList());
161 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
162 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
164 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
165 createResponse.isLeft(), is(true));
166 final Service actualService = createResponse.left().value();
167 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
169 assertEqualsServiceObject(expectedService, actualService);
173 void testCreateServiceWhenGenericTypeAndServiceHasProperties() {
174 final Service service = createServiceObject(false);
175 service.setProperties(mockPropertyList());
176 service.getProperties().remove(0);
177 final PropertyDefinition serviceProperty = new PropertyDefinition();
178 serviceProperty.setName("aServiceProperty");
179 service.getProperties().add(serviceProperty);
181 final Resource genericTypeResource = mockGenericTypeResource();
183 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericTypeResource));
184 final Service expectedService = createServiceObject(true);
185 expectedService.setProperties(mockPropertyList());
186 expectedService.getProperties().add(serviceProperty);
187 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
188 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
190 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
191 createResponse.isLeft(), is(true));
192 final Service actualService = createResponse.left().value();
193 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
195 assertEqualsServiceObject(expectedService, actualService);
199 void testHappyScenarioCRNullProjectCode() {
200 Service service = createServiceObject(false);
201 service.setProjectCode(null);
202 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
203 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
205 if (createResponse.isRight()) {
206 assertEquals(new Integer(200), createResponse.right().value().getStatus());
208 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
212 void testHappyScenarioCREmptyStringProjectCode() {
213 createServiceValidator();
214 Service service = createServiceObject(false);
215 service.setProjectCode("");
216 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
217 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
219 if (createResponse.isRight()) {
220 assertEquals(new Integer(200), createResponse.right().value().getStatus());
222 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
225 private void assertEqualsServiceObject(final Service expectedService, final Service actualService) {
226 assertEquals(expectedService.getContactId(), actualService.getContactId());
227 assertEquals(expectedService.getCategories(), actualService.getCategories());
228 assertEquals(expectedService.getCreatorUserId(), actualService.getCreatorUserId());
229 assertEquals(expectedService.getCreatorFullName(), actualService.getCreatorFullName());
230 assertEquals(expectedService.getDescription(), actualService.getDescription());
231 assertEquals(expectedService.getIcon(), actualService.getIcon());
232 assertEquals(expectedService.getLastUpdaterUserId(), actualService.getLastUpdaterUserId());
233 assertEquals(expectedService.getLastUpdaterFullName(), actualService.getLastUpdaterFullName());
234 assertEquals(expectedService.getName(), actualService.getName());
235 assertEquals(expectedService.getUniqueId(), actualService.getUniqueId());
236 assertEquals(expectedService.getVersion(), actualService.getVersion());
237 assertEquals(expectedService.getArtifacts(), actualService.getArtifacts());
238 assertEquals(expectedService.getCreationDate(), actualService.getCreationDate());
239 assertEquals(expectedService.getLastUpdateDate(), actualService.getLastUpdateDate());
240 assertEquals(expectedService.getLifecycleState(), actualService.getLifecycleState());
241 assertEquals(expectedService.getTags(), actualService.getTags());
242 if (expectedService.getProperties() == null) {
243 org.hamcrest.MatcherAssert.assertThat("Service properties should be null",
244 actualService.getProperties(), is(nullValue()));
247 org.hamcrest.MatcherAssert.assertThat("Service properties should be as expected",
248 actualService.getProperties(), is(expectedService.getProperties()));
253 /* CREATE validations - start ***********************/
254 // Service name - start
257 void testFailedServiceValidations() {
259 testServiceNameAlreadyExists();
260 testServiceNameEmpty();
261 testServiceNameWrongFormat();
262 testServiceDescriptionEmpty();
263 testServiceDescriptionMissing();
264 testServiceDescExceedsLimitCreate();
265 testServiceDescNotEnglish();
266 testServiceIconEmpty();
267 testServiceIconMissing();
268 testResourceIconInvalid();
269 testTagsNoServiceName();
271 testServiceTagNotExist();
272 testServiceTagEmpty();
274 testContactIdTooLong();
275 testContactIdWrongFormatCreate();
276 testInvalidProjectCode();
277 testProjectCodeTooLong();
278 testProjectCodeTooShort();
280 testResourceContactIdMissing();
281 testServiceCategoryExist();
282 testServiceBadCategoryCreate();
285 private void testServiceNameAlreadyExists() {
286 String serviceName = ALREADY_EXIST;
287 Service serviceExccedsNameLimit = createServiceObject(false);
288 // 51 chars, the limit is 50
289 serviceExccedsNameLimit.setName(serviceName);
290 List<String> tgs = new ArrayList<>();
291 tgs.add(serviceName);
292 serviceExccedsNameLimit.setTags(tgs);
294 bl.createService(serviceExccedsNameLimit, user);
295 } catch (ComponentException exp) {
296 assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
302 private void testServiceNameEmpty() {
303 Service serviceExccedsNameLimit = createServiceObject(false);
304 serviceExccedsNameLimit.setName(null);
306 bl.createService(serviceExccedsNameLimit, user);
307 } catch (ComponentException e) {
308 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
314 private void testServiceNameWrongFormat() {
315 Service service = createServiceObject(false);
317 String nameWrongFormat = "ljg\\fd";
318 service.setName(nameWrongFormat);
320 bl.createService(service, user);
321 } catch (ComponentException e) {
322 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
328 // Service name - end
329 // Service description - start
331 private void testServiceDescriptionEmpty() {
332 Service serviceExist = createServiceObject(false);
333 serviceExist.setDescription("");
335 bl.createService(serviceExist, user);
336 } catch (ComponentException e) {
337 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
343 private void testServiceDescriptionMissing() {
344 Service serviceExist = createServiceObject(false);
345 serviceExist.setDescription(null);
347 bl.createService(serviceExist, user);
348 } catch (ComponentException e) {
349 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
355 private void testServiceDescExceedsLimitCreate() {
356 Service serviceExccedsDescLimit = createServiceObject(false);
357 // 1025 chars, the limit is 1024
358 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
359 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
360 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
361 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
362 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
363 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
364 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
365 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
367 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
369 bl.createService(serviceExccedsDescLimit, user);
370 } catch (ComponentException e) {
371 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(),
372 "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
378 private void testServiceDescNotEnglish() {
379 Service notEnglish = createServiceObject(false);
381 String tooLongServiceDesc = "\uC2B5";
382 notEnglish.setDescription(tooLongServiceDesc);
384 bl.createService(notEnglish, user);
385 } catch (ComponentException e) {
386 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
392 // Service description - stop
393 // Service icon - start
395 private void testServiceIconEmpty() {
396 Service serviceExist = createServiceObject(false);
397 serviceExist.setIcon("");
398 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
399 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
403 private void testServiceIconMissing() {
404 Service serviceExist = createServiceObject(false);
405 serviceExist.setIcon(null);
406 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_SERVICE);
407 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
410 private void testResourceIconInvalid() {
411 Service resourceExist = createServiceObject(false);
412 resourceExist.setIcon("kjk3453^&");
414 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
415 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
419 private void testTagsNoServiceName() {
420 Service serviceExccedsNameLimit = createServiceObject(false);
421 String tag1 = "afzs2qLBb";
422 List<String> tagsList = new ArrayList<>();
424 serviceExccedsNameLimit.setTags(tagsList);
426 bl.createService(serviceExccedsNameLimit, user);
427 } catch (ComponentException e) {
428 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
434 private void testInvalidTag() {
435 Service serviceExccedsNameLimit = createServiceObject(false);
436 String tag1 = "afzs2qLBb%#%";
437 List<String> tagsList = new ArrayList<>();
439 serviceExccedsNameLimit.setTags(tagsList);
441 bl.createService(serviceExccedsNameLimit, user);
442 } catch (ComponentException e) {
443 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
449 private void testServiceTagNotExist() {
450 Service serviceExist = createServiceObject(false);
451 serviceExist.setTags(null);
453 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
454 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
457 private void testServiceTagEmpty() {
458 Service serviceExist = createServiceObject(false);
459 serviceExist.setTags(new ArrayList<>());
461 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
462 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
465 // Service tags - stop
466 // Service contactId - start
468 private void testContactIdTooLong() {
469 Service serviceContactId = createServiceObject(false);
470 // 59 chars instead of 50
471 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
472 serviceContactId.setContactId(contactIdTooLong);
474 bl.createService(serviceContactId, user);
475 } catch (ComponentException e) {
476 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
482 private void testContactIdWrongFormatCreate() {
483 Service serviceContactId = createServiceObject(false);
484 // 3 letters and 3 digits and special characters
485 String contactIdTooLong = "yrt134!!!";
486 serviceContactId.setContactId(contactIdTooLong);
488 bl.createService(serviceContactId, user);
489 } catch (ComponentException e) {
490 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
496 private void testResourceContactIdMissing() {
497 Service resourceExist = createServiceObject(false);
498 resourceExist.setContactId(null);
500 bl.createService(resourceExist, user);
501 } catch (ComponentException e) {
502 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
508 // Service contactId - stop
509 // Service category - start
511 private void testServiceCategoryExist() {
512 Service serviceExist = createServiceObject(false);
513 serviceExist.setCategories(null);
515 bl.createService(serviceExist, user);
516 } catch (ComponentException e) {
517 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
524 void markDistributionAsDeployedTestAlreadyDeployed() {
525 String notifyAction = "DNotify";
526 String requestAction = "DRequest";
527 String resultAction = "DResult";
528 String did = "123456";
530 setupBeforeDeploy(notifyAction, requestAction, did);
531 List<DistributionDeployEvent> resultList = new ArrayList<>();
532 Map<String, Object> params = new HashMap<>();
533 DistributionDeployEvent event = new DistributionDeployEvent();
535 event.setAction(resultAction);
537 event.setStatus("200");
538 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
539 // deployEvent.setFields(params);
540 resultList.add(event);
541 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
543 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), eq(resultAction), Mockito.anyString())).thenReturn(eventList);
545 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
546 assertTrue(markDeployed.isLeft());
548 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
553 void markDistributionAsDeployedTestSuccess() {
554 String notifyAction = "DNotify";
555 String requestAction = "DRequest";
556 String did = "123456";
558 setupBeforeDeploy(notifyAction, requestAction, did);
559 List<Role> roles = new ArrayList<>();
560 roles.add(Role.ADMIN);
561 roles.add(Role.DESIGNER);
562 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
563 assertTrue(markDeployed.isLeft());
567 void markDistributionAsDeployedTestNotDistributed() {
568 String notifyAction = "DNotify";
569 String requestAction = "DRequest";
570 String did = "123456";
572 setupBeforeDeploy(notifyAction, requestAction, did);
573 List<ResourceAdminEvent> emptyList = new ArrayList<>();
574 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
575 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), eq(requestAction))).thenReturn(emptyEventList);
577 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
578 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
580 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
581 assertTrue(markDeployed.isRight());
582 assertEquals(404, markDeployed.right().value().getStatus().intValue());
586 private void testServiceBadCategoryCreate() {
588 Service serviceExist = createServiceObject(false);
589 CategoryDefinition category = new CategoryDefinition();
590 category.setName("koko");
591 category.setIcons(Arrays.asList(DEFAULT_ICON));
592 List<CategoryDefinition> categories = new ArrayList<>();
593 categories.add(category);
594 serviceExist.setCategories(categories);
596 bl.createService(serviceExist, user);
597 } catch (ComponentException e) {
598 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
604 // Service category - stop
605 // Service projectCode - start
607 private void testInvalidProjectCode() {
609 Service serviceExist = createServiceObject(false);
610 serviceExist.setProjectCode("koko!!");
613 bl.createService(serviceExist, user);
614 } catch (ComponentException exp) {
615 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
621 private void testProjectCodeTooLong() {
623 Service serviceExist = createServiceObject(false);
624 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
625 serviceExist.setProjectCode(tooLongProjectCode);
628 bl.createService(serviceExist, user);
629 } catch (ComponentException exp) {
630 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
637 private void testProjectCodeTooShort() {
639 Service serviceExist = createServiceObject(false);
640 serviceExist.setProjectCode("333");
643 bl.createService(serviceExist, user);
644 } catch (ComponentException exp) {
645 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
652 void testDeleteMarkedServices() {
653 List<String> ids = new ArrayList<>();
654 List<String> responseIds = new ArrayList<>();
655 String resourceInUse = "123";
656 ids.add(resourceInUse);
657 String resourceFree = "456";
658 ids.add(resourceFree);
659 responseIds.add(resourceFree);
660 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
661 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
663 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
664 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
666 List<ArtifactDefinition> artifacts = new ArrayList<>();
667 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
669 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
670 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
671 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
672 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
673 assertTrue(deleteMarkedResources.isLeft());
674 List<String> resourceIdList = deleteMarkedResources.left().value();
675 assertFalse(resourceIdList.isEmpty());
676 assertTrue(resourceIdList.contains(resourceFree));
677 assertFalse(resourceIdList.contains(resourceInUse));
681 void testDeleteArchivedService_NotFound() {
682 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
683 assertThrows(StorageException.class, () -> bl.deleteServiceAllVersions("1", user));
687 void testDeleteArchivedService_NotArchived() {
688 String serviceId = "12345";
689 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
690 eitherService.left().value().setArchived(false);
691 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
692 final ComponentException actualException = assertThrows(ComponentException.class, () -> bl.deleteServiceAllVersions(serviceId, user));
693 assertEquals(ActionStatus.COMPONENT_NOT_ARCHIVED, actualException.getActionStatus());
694 assertEquals(actualException.getParams()[0], serviceId);
698 void testDeleteArchivedService_DeleteServiceSpecificModel() throws ToscaOperationException {
699 String serviceId = "12345";
700 String model = "serviceSpecificModel";
701 List<String> deletedServcies = new ArrayList<>();
702 deletedServcies.add("54321");
703 Model normativeExtensionModel = new Model("normativeExtensionModel", ModelTypeEnum.NORMATIVE_EXTENSION);
704 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewService());
705 eitherService.left().value().setArchived(true);
706 eitherService.left().value().setModel(model);
707 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
708 Mockito.when(toscaOperationFacade.deleteService(Mockito.anyString(), eq(true))).thenReturn(deletedServcies);
709 Mockito.when(modelOperation.findModelByName(model)).thenReturn(Optional.of(normativeExtensionModel));
710 bl.deleteServiceAllVersions(serviceId, user);
711 Mockito.verify(modelOperation, Mockito.times(1)).deleteModel(normativeExtensionModel, false);
714 @SuppressWarnings({"unchecked", "rawtypes"})
716 void testFindGroupInstanceOnRelatedComponentInstance() {
718 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
719 String methodName = "findGroupInstanceOnRelatedComponentInstance";
720 Object invalidId = "invalidId";
722 Component service = createNewService();
723 List<ComponentInstance> componentInstances = service.getComponentInstances();
725 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
726 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
727 Class[] argClasses = {Component.class, String.class, String.class};
729 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
730 method.setAccessible(true);
732 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
733 assertNotNull(findGroupInstanceRes);
734 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
736 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
741 Object[] argObjectsInvalidCiId = {service, invalidId, componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
743 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
744 assertNotNull(findGroupInstanceRes);
745 assertTrue(findGroupInstanceRes.isRight());
746 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
748 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId(), invalidId};
750 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
751 assertNotNull(findGroupInstanceRes);
752 assertTrue(findGroupInstanceRes.isRight());
753 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
754 } catch (Exception e) {
759 private Component createNewComponent() {
761 Service service = new Service();
763 service.setName("serviceName");
764 service.setUniqueId("serviceUniqueId");
765 List<ComponentInstance> componentInstances = new ArrayList<>();
766 ComponentInstance ci;
767 for (int i = 0; i < listSize; ++i) {
768 ci = new ComponentInstance();
769 ci.setName("ciName" + i);
770 ci.setUniqueId("ciId" + i);
771 List<GroupInstance> groupInstances = new ArrayList<>();
773 for (int j = 0; j < listSize; ++j) {
774 gi = new GroupInstance();
775 gi.setName(ci.getName() + "giName" + j);
776 gi.setUniqueId(ci.getName() + "giId" + j);
777 groupInstances.add(gi);
779 ci.setGroupInstances(groupInstances);
780 componentInstances.add(ci);
782 service.setComponentInstances(componentInstances);
786 protected Service createNewService() {
787 return (Service) createNewComponent();
791 void testDerivedFromGeneric() {
792 Service service = createServiceObject(true);
793 Service newService = createServiceObject(false);
794 newService.setInputs(Collections.singletonList(new InputDefinition()));
795 service.setDerivedFromGenericInfo(genericService);
796 newService.setDerivedFromGenericInfo(genericService);
797 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(newService));
798 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
799 when(inputsBusinessLogic.getInputs(any(), any())).thenReturn(Either.left(Collections.singletonList(new InputDefinition())));
800 when(inputsBusinessLogic.declareProperties(any(), any(), eq(ComponentTypeEnum.SERVICE), any(ComponentInstInputsMap.class)))
801 .thenReturn(Either.left(Collections.singletonList(new InputDefinition())));
803 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
804 assertTrue(createResponse.isLeft());
805 service = createResponse.left().value();
806 assertEquals(genericService.getToscaResourceName(), service.getDerivedFromGenericType());
807 assertEquals(genericService.getVersion(), service.getDerivedFromGenericVersion());
811 void testServiceWithoutDerivedFromGeneric() {
812 final Service service = createServiceObject(true);
813 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
814 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service, null)).thenReturn(Either.left(genericService));
815 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
816 assertTrue(createResponse.isLeft());
817 final Service actualService = createResponse.left().value();
818 assertNull(actualService.getDerivedFromGenericType());
819 assertNull(actualService.getDerivedFromGenericVersion());
823 void testUpdateMetadataNamingPolicy() {
824 Service currentService = createServiceObject(true);
825 Service newService = createServiceObject(false);
826 currentService.setEcompGeneratedNaming(false);
827 newService.setEcompGeneratedNaming(true);
828 newService.setNamingPolicy("policy");
829 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
830 assertThat(resultOfUpdate.isLeft()).isTrue();
831 Service updatedService = resultOfUpdate.left().value();
832 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
833 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
837 void testUpdateMetadataToEmptyProjectCode() {
838 Service currentService = createServiceObject(true);
839 Service newService = createServiceObject(false);
840 currentService.setProjectCode("12345");
841 newService.setProjectCode("");
842 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
843 assertThat(resultOfUpdate.isLeft()).isTrue();
844 Service updatedService = resultOfUpdate.left().value();
845 assertThat(updatedService.getProjectCode()).isEmpty();
849 void testUpdateMetadataFromEmptyProjectCode() {
850 Service currentService = createServiceObject(true);
851 Service newService = createServiceObject(false);
852 currentService.setProjectCode("");
853 newService.setProjectCode("12345");
854 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
855 assertThat(resultOfUpdate.isLeft()).isTrue();
856 Service updatedService = resultOfUpdate.left().value();
857 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
861 void testUpdateMetadataProjectCode() {
862 Service currentService = createServiceObject(true);
863 Service newService = createServiceObject(false);
864 currentService.setProjectCode("33333");
865 newService.setProjectCode("12345");
866 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
867 assertThat(resultOfUpdate.isLeft()).isTrue();
868 Service updatedService = resultOfUpdate.left().value();
869 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
873 void testUpdateMetadataServiceType() {
874 Service currentService = createServiceObject(true);
875 Service newService = createServiceObject(false);
876 currentService.setServiceType("alice");
878 newService.setServiceType("bob");
879 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
880 assertThat(resultOfUpdate.isLeft()).isTrue();
881 Service updatedService = resultOfUpdate.left().value();
882 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
883 //empty string is invalid
884 newService.setServiceType("");
885 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
886 assertThat(resultOfUpdate.isLeft()).isTrue();
888 newService.setServiceType(null);
889 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
890 assertThat(resultOfUpdate.isRight()).isTrue();
894 void testCreateDefaultMetadataServiceFunction() {
895 Service currentService = createServiceObject(true);
896 assertThat(currentService.getServiceFunction()).isEmpty();
900 void testCreateCustomMetadataServiceFunction() {
901 String customServiceFunctionName = "customName";
902 Service currentService = createServiceObject(true);
903 currentService.setServiceFunction(customServiceFunctionName);
904 assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
908 void testUpdateMetadataServiceFunction() {
909 Service currentService = createServiceObject(true);
910 Service newService = createServiceObject(false);
911 currentService.setServiceFunction("alice");
913 newService.setServiceFunction("bob");
914 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
915 assertThat(resultOfUpdate.isLeft()).isTrue();
916 Service updatedService = resultOfUpdate.left().value();
917 assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
918 //empty string is valid
919 newService.setServiceFunction("");
920 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
921 assertThat(resultOfUpdate.isLeft()).isTrue();
922 //null is valid and assigner to ""
923 newService.setServiceFunction(null);
924 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
925 assertThat(resultOfUpdate.isLeft()).isTrue();
926 assertThat(updatedService.getServiceFunction()).isEmpty();
931 void testServiceFunctionExceedLength() {
932 String serviceName = "Service";
933 String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
934 Service serviceFunctionExceedLength = createServiceObject(false);
935 serviceFunctionExceedLength.setName(serviceName);
936 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
937 List<String> tgs = new ArrayList<>();
938 tgs.add(serviceName);
939 serviceFunctionExceedLength.setTags(tgs);
941 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
942 } catch (ComponentException exp) {
943 assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
948 void testServiceFunctionInvalidCharacter() {
949 String serviceName = "Service";
950 String serviceFunction = "a?";
951 Service serviceFunctionExceedLength = createServiceObject(false);
952 serviceFunctionExceedLength.setName(serviceName);
953 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
954 List<String> tgs = new ArrayList<>();
955 tgs.add(serviceName);
956 serviceFunctionExceedLength.setTags(tgs);
958 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
959 } catch (ComponentException exp) {
960 assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
965 void testAddPropertyServiceConsumptionServiceNotFound() {
966 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
968 Either<Operation, ResponseFormat> operationEither =
969 bl.addPropertyServiceConsumption("1", "2", "3",
970 user.getUserId(), new ServiceConsumptionData());
971 assertTrue(operationEither.isRight());
972 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
976 void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
977 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
978 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
980 Either<Operation, ResponseFormat> operationEither =
981 bl.addPropertyServiceConsumption("1", "2", "3",
982 user.getUserId(), new ServiceConsumptionData());
983 assertTrue(operationEither.isRight());
984 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
988 void testAddPropertyServiceConsumptionNoMatchingComponent() {
989 Service aService = createNewService();
990 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
991 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
993 String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
995 Either<Operation, ResponseFormat> operationEither =
996 bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
997 user.getUserId(), new ServiceConsumptionData());
998 assertTrue(operationEither.isRight());
999 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1003 void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
1004 Service aService = createNewService();
1005 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1006 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1007 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1009 Either<Operation, ResponseFormat> operationEither =
1010 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
1011 user.getUserId(), new ServiceConsumptionData());
1012 assertTrue(operationEither.isRight());
1013 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1017 void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
1018 Service aService = createNewService();
1019 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1020 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1021 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1023 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
1025 componentInstancesInterfacesMap.put(aService.getUniqueId(),
1026 Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
1028 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1030 Either<Operation, ResponseFormat> operationEither =
1031 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
1032 user.getUserId(), new ServiceConsumptionData());
1033 assertTrue(operationEither.isRight());
1034 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1038 void testAddPropertyServiceConsumptionNoInputsCandidate() {
1039 Service aService = createNewService();
1040 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
1041 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
1042 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
1044 String operationId = "operationId";
1045 ComponentInstanceInterface componentInstanceInterface =
1046 new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
1047 Map<String, Operation> operationsMap = Maps.newHashMap();
1048 operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
1049 new ListDataDefinition<>(), new ListDataDefinition<>()));
1050 componentInstanceInterface.setOperationsMap(operationsMap);
1052 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
1053 componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
1054 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
1056 Either<Operation, ResponseFormat> operationEither =
1057 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
1058 user.getUserId(), new ServiceConsumptionData());
1059 assertTrue(operationEither.isRight());
1060 assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
1063 private Resource mockGenericTypeResource() {
1064 final Resource genericTypeResource = new Resource();
1065 genericTypeResource.setProperties(mockPropertyList());
1066 return genericTypeResource;
1069 private List<PropertyDefinition> mockPropertyList() {
1070 final List<PropertyDefinition> propertyList = new ArrayList<>();
1071 final PropertyDefinition propertyDefinition1 = new PropertyDefinition();
1072 propertyDefinition1.setName("property1");
1073 propertyDefinition1.setType("string");
1074 propertyList.add(propertyDefinition1);
1076 final PropertyDefinition propertyDefinition2 = new PropertyDefinition();
1077 propertyDefinition2.setName("property2");
1078 propertyDefinition2.setType("boolean");
1079 propertyList.add(propertyDefinition2);
1081 final PropertyDefinition propertyDefinition3 = new PropertyDefinition();
1082 propertyDefinition3.setName("property3");
1083 propertyDefinition3.setType("string");
1084 propertyList.add(propertyDefinition3);
1085 return propertyList;