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.Assert.assertEquals;
28 import static org.junit.Assert.assertFalse;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertTrue;
31 import static org.junit.Assert.fail;
32 import static org.mockito.Mockito.when;
34 import com.google.common.collect.Lists;
35 import com.google.common.collect.Maps;
36 import fj.data.Either;
37 import java.lang.reflect.Method;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.HashMap;
41 import java.util.List;
43 import java.util.UUID;
44 import org.apache.commons.lang3.tuple.ImmutablePair;
45 import org.junit.Assert;
46 import org.junit.Test;
47 import org.mockito.Mockito;
48 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.InterfaceInstanceDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.model.ArtifactDefinition;
55 import org.openecomp.sdc.be.model.Component;
56 import org.openecomp.sdc.be.model.ComponentInstance;
57 import org.openecomp.sdc.be.model.ComponentInstanceInterface;
58 import org.openecomp.sdc.be.model.GroupInstance;
59 import org.openecomp.sdc.be.model.Operation;
60 import org.openecomp.sdc.be.model.PropertyDefinition;
61 import org.openecomp.sdc.be.model.Resource;
62 import org.openecomp.sdc.be.model.Service;
63 import org.openecomp.sdc.be.model.category.CategoryDefinition;
64 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
65 import org.openecomp.sdc.be.plugins.ServiceCreationPlugin;
66 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
67 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
68 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
69 import org.openecomp.sdc.be.types.ServiceConsumptionData;
70 import org.openecomp.sdc.be.user.Role;
71 import org.openecomp.sdc.common.util.ValidationUtils;
72 import org.openecomp.sdc.exception.ResponseFormat;
73 import org.springframework.http.HttpStatus;
75 public class ServiceBusinessLogicTest extends ServiceBussinessLogicBaseTestSetup {
77 private final static String DEFAULT_ICON = "defaulticon";
78 private static final String ALREADY_EXIST = "alreadyExist";
79 private static final String DOES_NOT_EXIST = "doesNotExist";
82 public void testGetComponentAuditRecordsCertifiedVersion() {
83 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
84 assertTrue(componentAuditRecords.isLeft());
85 assertEquals(3, componentAuditRecords.left().value().size());
89 public void testGetComponentAuditRecordsUnCertifiedVersion() {
90 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
91 assertTrue(componentAuditRecords.isLeft());
92 assertEquals(4, componentAuditRecords.left().value().size());
96 public void testHappyScenario() {
97 Service service = createServiceObject(false);
98 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
99 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
101 if (createResponse.isRight()) {
102 assertEquals(new Integer(200), createResponse.right().value().getStatus());
104 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
108 public void testServiceCreationPluginCall() {
109 final Service service = createServiceObject(false);
110 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
111 final List<ServiceCreationPlugin> serviceCreationPlugins = new ArrayList<>();
112 serviceCreationPlugins.add(new ServiceCreationPlugin() {
114 public void beforeCreate(Service service) {
119 public int getOrder() {
123 serviceCreationPlugins.add(new ServiceCreationPlugin() {
125 public void beforeCreate(Service service) {
126 throw new RuntimeException();
130 public int getOrder() {
134 bl.setServiceCreationPluginList(serviceCreationPlugins);
135 final Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
136 assertTrue(createResponse.isLeft());
141 public void testCreateServiceWhenGenericTypeHasProperties() {
142 final Service service = createServiceObject(false);
144 final Resource genericTypeResource = mockGenericTypeResource();
146 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericTypeResource));
147 final Service expectedService = createServiceObject(true);
148 expectedService.setProperties(mockPropertyList());
149 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
150 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
152 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
153 createResponse.isLeft(), is(true));
154 final Service actualService = createResponse.left().value();
155 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
157 assertEqualsServiceObject(expectedService, actualService);
161 public void testCreateServiceWhenGenericTypeAndServiceHasProperties() {
162 final Service service = createServiceObject(false);
163 service.setProperties(mockPropertyList());
164 service.getProperties().remove(0);
165 final PropertyDefinition serviceProperty = new PropertyDefinition();
166 serviceProperty.setName("aServiceProperty");
167 service.getProperties().add(serviceProperty);
169 final Resource genericTypeResource = mockGenericTypeResource();
171 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericTypeResource));
172 final Service expectedService = createServiceObject(true);
173 expectedService.setProperties(mockPropertyList());
174 expectedService.getProperties().add(serviceProperty);
175 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(expectedService));
176 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
178 org.hamcrest.MatcherAssert.assertThat("Service creation should be successful",
179 createResponse.isLeft(), is(true));
180 final Service actualService = createResponse.left().value();
181 org.hamcrest.MatcherAssert.assertThat("Service should not be null", service, is(notNullValue()));
184 assertEqualsServiceObject(expectedService, actualService);
188 public void testHappyScenarioCRNullProjectCode() {
189 Service service = createServiceObject(false);
190 service.setProjectCode(null);
191 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
192 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
194 if (createResponse.isRight()) {
195 assertEquals(new Integer(200), createResponse.right().value().getStatus());
197 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
201 public void testHappyScenarioCREmptyStringProjectCode() {
202 createServiceValidator();
203 Service service = createServiceObject(false);
204 service.setProjectCode("");
205 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
206 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
208 if (createResponse.isRight()) {
209 assertEquals(new Integer(200), createResponse.right().value().getStatus());
211 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
213 private void assertEqualsServiceObject(final Service expectedService, final Service actualService) {
214 assertEquals(expectedService.getContactId(), actualService.getContactId());
215 assertEquals(expectedService.getCategories(), actualService.getCategories());
216 assertEquals(expectedService.getCreatorUserId(), actualService.getCreatorUserId());
217 assertEquals(expectedService.getCreatorFullName(), actualService.getCreatorFullName());
218 assertEquals(expectedService.getDescription(), actualService.getDescription());
219 assertEquals(expectedService.getIcon(), actualService.getIcon());
220 assertEquals(expectedService.getLastUpdaterUserId(), actualService.getLastUpdaterUserId());
221 assertEquals(expectedService.getLastUpdaterFullName(), actualService.getLastUpdaterFullName());
222 assertEquals(expectedService.getName(), actualService.getName());
223 assertEquals(expectedService.getUniqueId(), actualService.getUniqueId());
224 assertEquals(expectedService.getVersion(), actualService.getVersion());
225 assertEquals(expectedService.getArtifacts(), actualService.getArtifacts());
226 assertEquals(expectedService.getCreationDate(), actualService.getCreationDate());
227 assertEquals(expectedService.getLastUpdateDate(), actualService.getLastUpdateDate());
228 assertEquals(expectedService.getLifecycleState(), actualService.getLifecycleState());
229 assertEquals(expectedService.getTags(), actualService.getTags());
230 if (expectedService.getProperties() == null) {
231 org.hamcrest.MatcherAssert.assertThat("Service properties should be null",
232 actualService.getProperties(), is(nullValue()));
235 org.hamcrest.MatcherAssert.assertThat("Service properties should be as expected",
236 actualService.getProperties(), is(expectedService.getProperties()));
241 /* CREATE validations - start ***********************/
242 // Service name - start
245 public void testFailedServiceValidations() {
247 testServiceNameAlreadyExists();
248 testServiceNameEmpty();
249 testServiceNameWrongFormat();
250 testServiceDescriptionEmpty();
251 testServiceDescriptionMissing();
252 testServiceDescExceedsLimitCreate();
253 testServiceDescNotEnglish();
254 testServiceIconEmpty();
255 testServiceIconMissing();
256 testResourceIconInvalid();
257 testTagsNoServiceName();
259 testServiceTagNotExist();
260 testServiceTagEmpty();
262 testContactIdTooLong();
263 testContactIdWrongFormatCreate();
264 testInvalidProjectCode();
265 testProjectCodeTooLong();
266 testProjectCodeTooShort();
268 testResourceContactIdMissing();
269 testServiceCategoryExist();
270 testServiceBadCategoryCreate();
273 private void testServiceNameAlreadyExists() {
274 String serviceName = ALREADY_EXIST;
275 Service serviceExccedsNameLimit = createServiceObject(false);
276 // 51 chars, the limit is 50
277 serviceExccedsNameLimit.setName(serviceName);
278 List<String> tgs = new ArrayList<>();
279 tgs.add(serviceName);
280 serviceExccedsNameLimit.setTags(tgs);
282 bl.createService(serviceExccedsNameLimit, user);
283 } catch (ComponentException exp) {
284 assertResponse(exp.getResponseFormat(), ActionStatus.COMPONENT_NAME_ALREADY_EXIST, ComponentTypeEnum.SERVICE.getValue(), serviceName);
290 private void testServiceNameEmpty() {
291 Service serviceExccedsNameLimit = createServiceObject(false);
292 serviceExccedsNameLimit.setName(null);
294 bl.createService(serviceExccedsNameLimit, user);
295 } catch(ComponentException e){
296 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
302 private void testServiceNameWrongFormat() {
303 Service service = createServiceObject(false);
305 String nameWrongFormat = "ljg\\fd";
306 service.setName(nameWrongFormat);
308 bl.createService(service, user);
309 } catch(ComponentException e){
310 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
316 // Service name - end
317 // Service description - start
319 private void testServiceDescriptionEmpty() {
320 Service serviceExist = createServiceObject(false);
321 serviceExist.setDescription("");
323 bl.createService(serviceExist, user);
324 } catch(ComponentException e){
325 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
330 private void testServiceDescriptionMissing() {
331 Service serviceExist = createServiceObject(false);
332 serviceExist.setDescription(null);
334 bl.createService(serviceExist, user);
335 } catch(ComponentException e){
336 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
342 private void testServiceDescExceedsLimitCreate() {
343 Service serviceExccedsDescLimit = createServiceObject(false);
344 // 1025 chars, the limit is 1024
345 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
346 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
347 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
348 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
349 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
350 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
351 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
352 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
354 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
356 bl.createService(serviceExccedsDescLimit, user);
357 } catch(ComponentException e){
358 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
364 private void testServiceDescNotEnglish() {
365 Service notEnglish = createServiceObject(false);
367 String tooLongServiceDesc = "\uC2B5";
368 notEnglish.setDescription(tooLongServiceDesc);
370 bl.createService(notEnglish, user);
371 } catch(ComponentException e){
372 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
378 // Service description - stop
379 // Service icon - start
381 private void testServiceIconEmpty() {
382 Service serviceExist = createServiceObject(false);
383 serviceExist.setIcon("");
384 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
385 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
388 private void testServiceIconMissing() {
389 Service serviceExist = createServiceObject(false);
390 serviceExist.setIcon(null);
391 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist,user,AuditingActionEnum.CREATE_SERVICE);
392 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
395 private void testResourceIconInvalid() {
396 Service resourceExist = createServiceObject(false);
397 resourceExist.setIcon("kjk3453^&");
399 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(resourceExist, user, AuditingActionEnum.CREATE_RESOURCE);
400 assertThat(service.left().value().getIcon()).isEqualTo(DEFAULT_ICON);
404 private void testTagsNoServiceName() {
405 Service serviceExccedsNameLimit = createServiceObject(false);
406 String tag1 = "afzs2qLBb";
407 List<String> tagsList = new ArrayList<>();
409 serviceExccedsNameLimit.setTags(tagsList);
411 bl.createService(serviceExccedsNameLimit, user);
412 } catch(ComponentException e) {
413 assertComponentException(e, ActionStatus.COMPONENT_INVALID_TAGS_NO_COMP_NAME);
419 private void testInvalidTag() {
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.INVALID_FIELD_FORMAT, "Service", "tag");
434 private void testServiceTagNotExist() {
435 Service serviceExist = createServiceObject(false);
436 serviceExist.setTags(null);
438 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
439 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
442 private void testServiceTagEmpty() {
443 Service serviceExist = createServiceObject(false);
444 serviceExist.setTags(new ArrayList<>());
446 Either<Service, ResponseFormat> service = bl.validateServiceBeforeCreate(serviceExist, user, AuditingActionEnum.CREATE_RESOURCE);
447 assertThat(service.left().value().getTags().get(0)).isEqualTo(serviceExist.getName());
450 // Service tags - stop
451 // Service contactId - start
453 private void testContactIdTooLong() {
454 Service serviceContactId = createServiceObject(false);
455 // 59 chars instead of 50
456 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
457 serviceContactId.setContactId(contactIdTooLong);
459 bl.createService(serviceContactId, user);
460 } catch(ComponentException e) {
461 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
466 private void testContactIdWrongFormatCreate() {
467 Service serviceContactId = createServiceObject(false);
468 // 3 letters and 3 digits and special characters
469 String contactIdTooLong = "yrt134!!!";
470 serviceContactId.setContactId(contactIdTooLong);
472 bl.createService(serviceContactId, user);
473 } catch(ComponentException e) {
474 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
480 private void testResourceContactIdMissing() {
481 Service resourceExist = createServiceObject(false);
482 resourceExist.setContactId(null);
484 bl.createService(resourceExist, user);
485 } catch(ComponentException e) {
486 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
492 // Service contactId - stop
493 // Service category - start
495 private void testServiceCategoryExist() {
496 Service serviceExist = createServiceObject(false);
497 serviceExist.setCategories(null);
499 bl.createService(serviceExist, user);
500 } catch(ComponentException e) {
501 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
507 public void markDistributionAsDeployedTestAlreadyDeployed() {
508 String notifyAction = "DNotify";
509 String requestAction = "DRequest";
510 String resultAction = "DResult";
511 String did = "123456";
513 setupBeforeDeploy(notifyAction, requestAction, did);
514 List<DistributionDeployEvent> resultList = new ArrayList<>();
515 Map<String, Object> params = new HashMap<>();
516 DistributionDeployEvent event = new DistributionDeployEvent();
518 event.setAction(resultAction);
520 event.setStatus("200");
521 // ESTimeBasedEvent deployEvent = new ESTimeBasedEvent();
522 // deployEvent.setFields(params);
523 resultList.add(event);
524 Either<List<DistributionDeployEvent>, ActionStatus> eventList = Either.left(resultList);
526 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq(resultAction), Mockito.anyString())).thenReturn(eventList);
528 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
529 assertTrue(markDeployed.isLeft());
531 Mockito.verify(auditingDao, Mockito.times(0)).getDistributionRequest(did, requestAction);
536 public void markDistributionAsDeployedTestSuccess() {
537 String notifyAction = "DNotify";
538 String requestAction = "DRequest";
539 String did = "123456";
541 setupBeforeDeploy(notifyAction, requestAction, did);
542 List<Role> roles = new ArrayList<>();
543 roles.add(Role.ADMIN);
544 roles.add(Role.DESIGNER);
545 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
546 assertTrue(markDeployed.isLeft());
550 public void markDistributionAsDeployedTestNotDistributed() {
551 String notifyAction = "DNotify";
552 String requestAction = "DRequest";
553 String did = "123456";
555 setupBeforeDeploy(notifyAction, requestAction, did);
556 List<ResourceAdminEvent> emptyList = new ArrayList<>();
557 Either<List<ResourceAdminEvent>, ActionStatus> emptyEventList = Either.left(emptyList);
558 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(emptyEventList);
560 Either<Component, StorageOperationStatus> notFound = Either.right(StorageOperationStatus.NOT_FOUND);
561 Mockito.when(toscaOperationFacade.getToscaElement(did)).thenReturn(notFound);
563 Either<Service, ResponseFormat> markDeployed = bl.markDistributionAsDeployed(did, did, user);
564 assertTrue(markDeployed.isRight());
565 assertEquals(404, markDeployed.right().value().getStatus().intValue());
569 private void testServiceBadCategoryCreate() {
571 Service serviceExist = createServiceObject(false);
572 CategoryDefinition category = new CategoryDefinition();
573 category.setName("koko");
574 category.setIcons(Arrays.asList(DEFAULT_ICON));
575 List<CategoryDefinition> categories = new ArrayList<>();
576 categories.add(category);
577 serviceExist.setCategories(categories);
579 bl.createService(serviceExist, user);
580 } catch(ComponentException e) {
581 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
587 // Service category - stop
588 // Service projectCode - start
590 private void testInvalidProjectCode() {
592 Service serviceExist = createServiceObject(false);
593 serviceExist.setProjectCode("koko!!");
596 bl.createService(serviceExist, user);
597 } catch(ComponentException exp) {
598 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
604 private void testProjectCodeTooLong() {
606 Service serviceExist = createServiceObject(false);
607 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
608 serviceExist.setProjectCode(tooLongProjectCode);
611 bl.createService(serviceExist, user);
612 } catch(ComponentException exp) {
613 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
620 private void testProjectCodeTooShort() {
622 Service serviceExist = createServiceObject(false);
623 serviceExist.setProjectCode("333");
626 bl.createService(serviceExist, user);
627 } catch(ComponentException exp) {
628 assertComponentException(exp, ActionStatus.INVALID_PROJECT_CODE);
635 public void testDeleteMarkedServices() {
636 List<String> ids = new ArrayList<>();
637 List<String> responseIds = new ArrayList<>();
638 String resourceInUse = "123";
639 ids.add(resourceInUse);
640 String resourceFree = "456";
641 ids.add(resourceFree);
642 responseIds.add(resourceFree);
643 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
644 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
646 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
647 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
649 List<ArtifactDefinition> artifacts = new ArrayList<>();
650 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
652 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
653 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
654 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
655 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
656 assertTrue(deleteMarkedResources.isLeft());
657 List<String> resourceIdList = deleteMarkedResources.left().value();
658 assertFalse(resourceIdList.isEmpty());
659 assertTrue(resourceIdList.contains(resourceFree));
660 assertFalse(resourceIdList.contains(resourceInUse));
665 @SuppressWarnings({ "unchecked", "rawtypes" })
667 public void testFindGroupInstanceOnRelatedComponentInstance() {
669 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
670 String methodName = "findGroupInstanceOnRelatedComponentInstance";
671 Object invalidId = "invalidId";
673 Component service = createNewService();
674 List<ComponentInstance> componentInstances = service.getComponentInstances();
676 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
677 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
678 Class[] argClasses = {Component.class, String.class,String.class};
680 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
681 method.setAccessible(true);
683 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
684 assertNotNull(findGroupInstanceRes);
685 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
687 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
692 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
694 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
695 assertNotNull(findGroupInstanceRes);
696 assertTrue(findGroupInstanceRes.isRight());
697 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
699 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
701 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
702 assertNotNull(findGroupInstanceRes);
703 assertTrue(findGroupInstanceRes.isRight());
704 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
706 catch (Exception e) {
711 private Component createNewComponent() {
713 Service service = new Service();
715 service.setName("serviceName");
716 service.setUniqueId("serviceUniqueId");
717 List<ComponentInstance> componentInstances = new ArrayList<>();
718 ComponentInstance ci;
719 for(int i= 0; i<listSize; ++i){
720 ci = new ComponentInstance();
721 ci.setName("ciName" + i);
722 ci.setUniqueId("ciId" + i);
723 List<GroupInstance> groupInstances= new ArrayList<>();
725 for(int j = 0; j<listSize; ++j){
726 gi = new GroupInstance();
727 gi.setName(ci.getName( )+ "giName" + j);
728 gi.setUniqueId(ci.getName() + "giId" + j);
729 groupInstances.add(gi);
731 ci.setGroupInstances(groupInstances);
732 componentInstances.add(ci);
734 service.setComponentInstances(componentInstances);
738 protected Service createNewService() {
739 return (Service)createNewComponent();
744 public void testDerivedFromGeneric() {
745 Service service = createServiceObject(true);
746 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
747 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
748 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
749 assertTrue(createResponse.isLeft());
750 service = createResponse.left().value();
751 assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
752 assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
756 public void testUpdateMetadataNamingPolicy() {
757 Service currentService = createServiceObject(true);
758 Service newService = createServiceObject(false);
759 currentService.setEcompGeneratedNaming(false);
760 newService.setEcompGeneratedNaming(true);
761 newService.setNamingPolicy("policy");
762 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
763 assertThat(resultOfUpdate.isLeft()).isTrue();
764 Service updatedService = resultOfUpdate.left().value();
765 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
766 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
770 public void testUpdateMetadataToEmptyProjectCode() {
771 Service currentService = createServiceObject(true);
772 Service newService = createServiceObject(false);
773 currentService.setProjectCode("12345");
774 newService.setProjectCode("");
775 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
776 assertThat(resultOfUpdate.isLeft()).isTrue();
777 Service updatedService = resultOfUpdate.left().value();
778 assertThat(updatedService.getProjectCode()).isEmpty();
782 public void testUpdateMetadataFromEmptyProjectCode() {
783 Service currentService = createServiceObject(true);
784 Service newService = createServiceObject(false);
785 currentService.setProjectCode("");
786 newService.setProjectCode("12345");
787 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
788 assertThat(resultOfUpdate.isLeft()).isTrue();
789 Service updatedService = resultOfUpdate.left().value();
790 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
794 public void testUpdateMetadataProjectCode() {
795 Service currentService = createServiceObject(true);
796 Service newService = createServiceObject(false);
797 currentService.setProjectCode("33333");
798 newService.setProjectCode("12345");
799 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
800 assertThat(resultOfUpdate.isLeft()).isTrue();
801 Service updatedService = resultOfUpdate.left().value();
802 assertThat(updatedService.getProjectCode()).isEqualTo("12345");
806 public void testUpdateMetadataServiceType() {
807 Service currentService = createServiceObject(true);
808 Service newService = createServiceObject(false);
809 currentService.setServiceType("alice");
811 newService.setServiceType("bob");
812 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
813 assertThat(resultOfUpdate.isLeft()).isTrue();
814 Service updatedService = resultOfUpdate.left().value();
815 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
816 //empty string is invalid
817 newService.setServiceType("");
818 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
819 assertThat(resultOfUpdate.isLeft()).isTrue();
821 newService.setServiceType(null);
822 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
823 assertThat(resultOfUpdate.isRight()).isTrue();
827 public void testCreateDefaultMetadataServiceFunction() {
828 Service currentService = createServiceObject(true);
829 assertThat(currentService.getServiceFunction()).isEqualTo("");
833 public void testCreateCustomMetadataServiceFunction() {
834 String customServiceFunctionName = "customName";
835 Service currentService = createServiceObject(true);
836 currentService.setServiceFunction(customServiceFunctionName);
837 assertThat(currentService.getServiceFunction()).isEqualTo(customServiceFunctionName);
841 public void testUpdateMetadataServiceFunction() {
842 Service currentService = createServiceObject(true);
843 Service newService = createServiceObject(false);
844 currentService.setServiceFunction("alice");
846 newService.setServiceFunction("bob");
847 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
848 assertThat(resultOfUpdate.isLeft()).isTrue();
849 Service updatedService = resultOfUpdate.left().value();
850 assertThat(updatedService.getServiceFunction()).isEqualToIgnoringCase("bob");
851 //empty string is valid
852 newService.setServiceFunction("");
853 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
854 assertThat(resultOfUpdate.isLeft()).isTrue();
855 //null is valid and assigner to ""
856 newService.setServiceFunction(null);
857 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
858 assertThat(resultOfUpdate.isLeft()).isTrue();
859 assertThat(updatedService.getServiceFunction()).isEqualTo("");
865 public void testServiceFunctionExceedLength() {
866 String serviceName = "Service";
867 String serviceFunction = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
868 Service serviceFunctionExceedLength = createServiceObject(false);
869 serviceFunctionExceedLength.setName(serviceName);
870 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
871 List<String> tgs = new ArrayList<>();
872 tgs.add(serviceName);
873 serviceFunctionExceedLength.setTags(tgs);
875 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
876 } catch (ComponentException exp) {
877 assertResponse(exp.getResponseFormat(), ActionStatus.PROPERTY_EXCEEDS_LIMIT, SERVICE_FUNCTION);
882 public void testServiceFunctionInvalidCharacter(){
883 String serviceName = "Service";
884 String serviceFunction = "a?";
885 Service serviceFunctionExceedLength = createServiceObject(false);
886 serviceFunctionExceedLength.setName(serviceName);
887 serviceFunctionExceedLength.setServiceFunction(serviceFunction);
888 List<String> tgs = new ArrayList<>();
889 tgs.add(serviceName);
890 serviceFunctionExceedLength.setTags(tgs);
892 serviceFunctionValidator.validateAndCorrectField(user, serviceFunctionExceedLength, AuditingActionEnum.CREATE_SERVICE);
893 } catch (ComponentException exp) {
894 assertResponse(exp.getResponseFormat(), ActionStatus.INVALID_PROPERY, SERVICE_FUNCTION);
899 public void testAddPropertyServiceConsumptionServiceNotFound() {
900 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND));
902 Either<Operation, ResponseFormat> operationEither =
903 bl.addPropertyServiceConsumption("1", "2", "3",
904 user.getUserId(), new ServiceConsumptionData());
905 Assert.assertTrue(operationEither.isRight());
906 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
910 public void testAddPropertyServiceConsumptionParentServiceIsEmpty() {
911 Either<Component, StorageOperationStatus> eitherService = Either.left(createNewComponent());
912 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
914 Either<Operation, ResponseFormat> operationEither =
915 bl.addPropertyServiceConsumption("1", "2", "3",
916 user.getUserId(), new ServiceConsumptionData());
917 Assert.assertTrue(operationEither.isRight());
918 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
922 public void testAddPropertyServiceConsumptionNoMatchingComponent() {
923 Service aService = createNewService();
924 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
925 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
927 String weirdUniqueServiceInstanceId = UUID.randomUUID().toString();
929 Either<Operation, ResponseFormat> operationEither =
930 bl.addPropertyServiceConsumption("1", weirdUniqueServiceInstanceId, "3",
931 user.getUserId(), new ServiceConsumptionData());
932 Assert.assertTrue(operationEither.isRight());
933 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
937 public void testAddPropertyServiceConsumptionNotComponentInstancesInterfacesOnParentService() {
938 Service aService = createNewService();
939 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
940 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
941 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
943 Either<Operation, ResponseFormat> operationEither =
944 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
945 user.getUserId(), new ServiceConsumptionData());
946 Assert.assertTrue(operationEither.isRight());
947 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
951 public void testAddPropertyServiceConsumptionInterfaceCandidateNotPresent() {
952 Service aService = createNewService();
953 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
954 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
955 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
957 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap =
959 componentInstancesInterfacesMap.put(aService.getUniqueId(),
960 Lists.newArrayList(new ComponentInstanceInterface("1", new InterfaceInstanceDataDefinition())));
962 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
964 Either<Operation, ResponseFormat> operationEither =
965 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), "3",
966 user.getUserId(), new ServiceConsumptionData());
967 Assert.assertTrue(operationEither.isRight());
968 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
972 public void testAddPropertyServiceConsumptionNoInputsCandidate() {
973 Service aService = createNewService();
974 aService.getComponentInstances().get(0).setUniqueId(aService.getUniqueId());
975 Either<Component, StorageOperationStatus> eitherService = Either.left(aService);
976 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
978 String operationId = "operationId";
979 ComponentInstanceInterface componentInstanceInterface =
980 new ComponentInstanceInterface("interfaceId", new InterfaceInstanceDataDefinition());
981 Map<String, Operation> operationsMap = Maps.newHashMap();
982 operationsMap.put(operationId, new Operation(new ArtifactDataDefinition(), "1",
983 new ListDataDefinition<>(), new ListDataDefinition<>()));
984 componentInstanceInterface.setOperationsMap(operationsMap);
986 Map<String, List<ComponentInstanceInterface>> componentInstancesInterfacesMap = Maps.newHashMap();
987 componentInstancesInterfacesMap.put(aService.getUniqueId(), Lists.newArrayList(componentInstanceInterface));
988 aService.setComponentInstancesInterfaces(componentInstancesInterfacesMap);
990 Either<Operation, ResponseFormat> operationEither =
991 bl.addPropertyServiceConsumption("1", aService.getUniqueId(), operationId,
992 user.getUserId(), new ServiceConsumptionData());
993 Assert.assertTrue(operationEither.isRight());
994 Assert.assertEquals(HttpStatus.NOT_FOUND.value(), operationEither.right().value().getStatus().intValue());
997 private Resource mockGenericTypeResource() {
998 final Resource genericTypeResource = new Resource();
999 genericTypeResource.setProperties(mockPropertyList());
1000 return genericTypeResource;
1003 private List<PropertyDefinition> mockPropertyList() {
1004 final List<PropertyDefinition> propertyList = new ArrayList<>();
1005 final PropertyDefinition propertyDefinition1 = new PropertyDefinition();
1006 propertyDefinition1.setName("property1");
1007 propertyDefinition1.setType("string");
1008 propertyList.add(propertyDefinition1);
1010 final PropertyDefinition propertyDefinition2 = new PropertyDefinition();
1011 propertyDefinition2.setName("property2");
1012 propertyDefinition2.setType("boolean");
1013 propertyList.add(propertyDefinition2);
1015 final PropertyDefinition propertyDefinition3 = new PropertyDefinition();
1016 propertyDefinition3.setName("property3");
1017 propertyDefinition3.setType("string");
1018 propertyList.add(propertyDefinition3);
1019 return propertyList;