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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import fj.data.Either;
26 import org.apache.commons.lang3.tuple.ImmutablePair;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.mockito.Mockito;
30 import org.openecomp.sdc.ElementOperationMock;
31 import org.openecomp.sdc.be.auditing.impl.AuditingManager;
32 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
33 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
34 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
35 import org.openecomp.sdc.be.components.impl.generic.GenericTypeBusinessLogic;
36 import org.openecomp.sdc.be.components.validation.UserValidations;
37 import org.openecomp.sdc.be.config.ConfigurationManager;
38 import org.openecomp.sdc.be.dao.api.ActionStatus;
39 import org.openecomp.sdc.be.dao.cassandra.AuditCassandraDao;
40 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
41 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
43 import org.openecomp.sdc.be.impl.ComponentsUtils;
44 import org.openecomp.sdc.be.impl.WebAppContextWrapper;
45 import org.openecomp.sdc.be.model.*;
46 import org.openecomp.sdc.be.model.category.CategoryDefinition;
47 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
48 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
49 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
50 import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation;
51 import org.openecomp.sdc.be.resources.data.auditing.DistributionDeployEvent;
52 import org.openecomp.sdc.be.resources.data.auditing.DistributionNotificationEvent;
53 import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent;
54 import org.openecomp.sdc.be.user.Role;
55 import org.openecomp.sdc.be.user.UserBusinessLogic;
56 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
57 import org.openecomp.sdc.common.api.ConfigurationSource;
58 import org.openecomp.sdc.common.api.Constants;
59 import org.openecomp.sdc.common.impl.ExternalConfiguration;
60 import org.openecomp.sdc.common.impl.FSConfigurationSource;
61 import org.openecomp.sdc.common.util.ValidationUtils;
62 import org.openecomp.sdc.exception.ResponseFormat;
63 import org.springframework.web.context.WebApplicationContext;
65 import javax.servlet.ServletContext;
66 import java.lang.reflect.Method;
68 import java.util.stream.Collectors;
69 import java.util.stream.Stream;
71 import static org.assertj.core.api.Assertions.assertThat;
72 import static org.junit.Assert.*;
73 import static org.junit.Assert.assertNotNull;
74 import static org.mockito.ArgumentMatchers.anyString;
75 import static org.mockito.ArgumentMatchers.eq;
76 import static org.mockito.Mockito.when;
77 import static org.mockito.ArgumentMatchers.eq;
79 public class ServiceBusinessLogicTest {
81 private static final String SERVICE_CATEGORY = "Mobility";
82 private static final String INSTANTIATION_TYPE = "A-la-carte";
83 private final ServletContext servletContext = Mockito.mock(ServletContext.class);
84 private UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class);
85 private WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class);
86 private WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class);
87 private ServiceBusinessLogic bl = new ServiceBusinessLogic();
88 private ResponseFormatManager responseManager = null;
89 private ComponentsUtils componentsUtils;
90 private AuditCassandraDao auditingDao = Mockito.mock(AuditCassandraDao.class);
91 private ArtifactsBusinessLogic artifactBl = Mockito.mock(ArtifactsBusinessLogic.class);
92 private GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class);
93 private JanusGraphDao mockJanusGraphDao = Mockito.mock(JanusGraphDao.class);
94 private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class);
95 private GenericTypeBusinessLogic genericTypeBusinessLogic = Mockito.mock(GenericTypeBusinessLogic.class);
96 private UserValidations userValidations = Mockito.mock(UserValidations.class);
97 private ResourceAdminEvent auditArchive1 = Mockito.mock(ResourceAdminEvent.class);
98 private ResourceAdminEvent auditArchive2 = Mockito.mock(ResourceAdminEvent.class);
99 private ResourceAdminEvent auditRestore = Mockito.mock(ResourceAdminEvent.class);
101 private User user = null;
102 private Resource genericService = null;
104 private static final String CERTIFIED_VERSION = "1.0";
105 private static final String UNCERTIFIED_VERSION = "0.2";
106 private static final String COMPONNET_ID = "myUniqueId";
107 private static final String GENERIC_SERVICE_NAME = "org.openecomp.resource.abstract.nodes.service";
109 public ServiceBusinessLogicTest() {
114 public void setup() {
116 ExternalConfiguration.setAppName("catalog-be");
117 // init Configuration
118 String appConfigDir = "src/test/resources/config/catalog-be";
119 ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir);
120 ConfigurationManager configurationManager = new ConfigurationManager(configurationSource);
121 componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class));
124 IElementOperation mockElementDao = new ElementOperationMock();
126 // User data and management
128 user.setUserId("jh0003");
129 user.setFirstName("Jimmi");
130 user.setLastName("Hendrix");
131 user.setRole(Role.ADMIN.name());
133 Either<User, ActionStatus> eitherGetUser = Either.left(user);
134 when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser);
135 when(userValidations.validateUserExists(eq("jh0003"), anyString(), eq(false))).thenReturn(user);
136 when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user);
137 when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager);
138 when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper);
139 when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext);
140 when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao);
141 when(graphLockOperation.lockComponent(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
142 when(graphLockOperation.lockComponentByName(Mockito.anyString(), Mockito.eq(NodeTypeEnum.Service))).thenReturn(StorageOperationStatus.OK);
144 // artifact bussinesslogic
145 ArtifactDefinition artifactDef = new ArtifactDefinition();
146 when(artifactBl.createArtifactPlaceHolderInfo(Mockito.any(), Mockito.anyString(), Mockito.anyMap(), Mockito.any(User.class), Mockito.any(ArtifactGroupTypeEnum.class))).thenReturn(artifactDef);
149 Service serviceResponse = createServiceObject(true);
150 Either<Component, StorageOperationStatus> eitherCreate = Either.left(serviceResponse);
151 when(toscaOperationFacade.createToscaComponent(Mockito.any(Component.class))).thenReturn(eitherCreate);
152 Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false);
153 when(toscaOperationFacade.validateComponentNameExists("Service", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCount);
154 Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true);
155 when(toscaOperationFacade.validateComponentNameExists("alreadyExist", null, ComponentTypeEnum.SERVICE)).thenReturn(eitherCountExist);
157 genericService = setupGenericServiceMock();
158 Either<Resource, StorageOperationStatus> findLatestGeneric = Either.left(genericService);
159 when(toscaOperationFacade.getLatestCertifiedNodeTypeByToscaResourceName(GENERIC_SERVICE_NAME)).thenReturn(findLatestGeneric);
162 bl = new ServiceBusinessLogic();
163 bl.setElementDao(mockElementDao);
164 bl.setUserAdmin(mockUserAdmin);
165 bl.setArtifactBl(artifactBl);
166 bl.setGraphLockOperation(graphLockOperation);
167 bl.setJanusGraphGenericDao(mockJanusGraphDao);
168 bl.setToscaOperationFacade(toscaOperationFacade);
169 bl.setGenericTypeBusinessLogic(genericTypeBusinessLogic);
170 bl.setComponentsUtils(componentsUtils);
171 bl.setCassandraAuditingDao(auditingDao);
172 bl.setUserValidations(userValidations);
174 mockAuditingDaoLogic();
176 responseManager = ResponseFormatManager.getInstance();
181 public void testGetComponentAuditRecordsCertifiedVersion() {
182 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(CERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
183 assertTrue(componentAuditRecords.isLeft());
184 assertEquals(3, componentAuditRecords.left().value().size());
188 public void testGetComponentAuditRecordsUnCertifiedVersion() {
189 Either<List<Map<String, Object>>, ResponseFormat> componentAuditRecords = bl.getComponentAuditRecords(UNCERTIFIED_VERSION, COMPONNET_ID, user.getUserId());
190 assertTrue(componentAuditRecords.isLeft());
191 assertEquals(4, componentAuditRecords.left().value().size());
195 public void testHappyScenario() {
196 Service service = createServiceObject(false);
197 validateUserRoles(Role.ADMIN, Role.DESIGNER);
198 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
199 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
201 if (createResponse.isRight()) {
202 assertEquals(new Integer(200), createResponse.right().value().getStatus());
204 assertEqualsServiceObject(createServiceObject(true), createResponse.left().value());
207 private void validateUserRoles(Role ... roles) {
208 List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList());
211 private void assertEqualsServiceObject(Service origService, Service newService) {
212 assertEquals(origService.getContactId(), newService.getContactId());
213 assertEquals(origService.getCategories(), newService.getCategories());
214 assertEquals(origService.getCreatorUserId(), newService.getCreatorUserId());
215 assertEquals(origService.getCreatorFullName(), newService.getCreatorFullName());
216 assertEquals(origService.getDescription(), newService.getDescription());
217 assertEquals(origService.getIcon(), newService.getIcon());
218 assertEquals(origService.getLastUpdaterUserId(), newService.getLastUpdaterUserId());
219 assertEquals(origService.getLastUpdaterFullName(), newService.getLastUpdaterFullName());
220 assertEquals(origService.getName(), newService.getName());
221 assertEquals(origService.getName(), newService.getName());
222 assertEquals(origService.getUniqueId(), newService.getUniqueId());
223 assertEquals(origService.getVersion(), newService.getVersion());
224 assertEquals(origService.getArtifacts(), newService.getArtifacts());
225 assertEquals(origService.getCreationDate(), newService.getCreationDate());
226 assertEquals(origService.getLastUpdateDate(), newService.getLastUpdateDate());
227 assertEquals(origService.getLifecycleState(), newService.getLifecycleState());
228 assertEquals(origService.getTags(), newService.getTags());
231 private void assertResponse(Either<Service, ResponseFormat> createResponse, ActionStatus expectedStatus, String... variables) {
232 assertResponse(createResponse.right().value(), expectedStatus, variables);
235 private void assertComponentException(ByActionStatusComponentException e, ActionStatus expectedStatus, String... variables) {
236 ResponseFormat actualResponse = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
237 assertResponse(actualResponse, expectedStatus, variables);
240 private void assertComponentException(ByResponseFormatComponentException e, ActionStatus expectedStatus, String... variables) {
241 ResponseFormat actualResponse = e.getResponseFormat();
242 assertResponse(actualResponse, expectedStatus, variables);
245 private void assertResponse(ResponseFormat actualResponse, ActionStatus expectedStatus, String... variables) {
246 ResponseFormat expectedResponse = responseManager.getResponseFormat(expectedStatus, variables);
247 assertEquals(expectedResponse.getStatus(), actualResponse.getStatus());
248 assertEquals("assert error description", expectedResponse.getFormattedMessage(), actualResponse.getFormattedMessage());
253 public void testFailedServiceValidations() {
254 testServiceNameAlreadyExists();
255 testServiceNameEmpty();
256 testServiceNameWrongFormat();
257 testServiceDescriptionEmpty();
258 testServiceDescriptionMissing();
259 testServiceDescExceedsLimitCreate();
260 testServiceDescNotEnglish();
261 testServiceIconEmpty();
262 testServiceIconMissing();
263 testResourceIconInvalid();
264 testResourceIconExceedsLimit();
265 testTagsNoServiceName();
267 testServiceTagNotExist();
268 testServiceTagEmpty();
270 testContactIdTooLong();
271 testContactIdWrongFormatCreate();
272 testInvalidProjectCode();
273 testProjectCodeTooLong();
274 testProjectCodeTooShort();
276 testResourceContactIdMissing();
277 testServiceCategoryExist();
278 testServiceBadCategoryCreate();
279 testMissingProjectCode();
282 private void testServiceNameAlreadyExists() {
283 String serviceName = "alreadyExist";
284 Service serviceExccedsNameLimit = createServiceObject(false);
285 // 51 chars, the limit is 50
286 serviceExccedsNameLimit.setName(serviceName);
287 List<String> tgs = new ArrayList<>();
288 tgs.add(serviceName);
289 serviceExccedsNameLimit.setTags(tgs);
290 validateUserRoles(Role.ADMIN, Role.DESIGNER);
291 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExccedsNameLimit, user);
292 assertTrue(createResponse.isRight());
293 assertResponse(createResponse, 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(ByActionStatusComponentException e){
302 assertComponentException(e, ActionStatus.MISSING_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
306 private void testServiceNameWrongFormat() {
307 Service service = createServiceObject(false);
309 String nameWrongFormat = "ljg\fd";
310 service.setName(nameWrongFormat);
312 bl.createService(service, user);
313 } catch(ByActionStatusComponentException e){
314 assertComponentException(e, ActionStatus.INVALID_COMPONENT_NAME, ComponentTypeEnum.SERVICE.getValue());
318 private void testServiceDescriptionEmpty() {
319 Service serviceExist = createServiceObject(false);
320 serviceExist.setDescription("");
322 bl.createService(serviceExist, user);
323 } catch(ByActionStatusComponentException e){
324 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
328 private void testServiceDescriptionMissing() {
329 Service serviceExist = createServiceObject(false);
330 serviceExist.setDescription(null);
332 bl.createService(serviceExist, user);
333 } catch(ByActionStatusComponentException e){
334 assertComponentException(e, ActionStatus.COMPONENT_MISSING_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
338 private void testServiceDescExceedsLimitCreate() {
339 Service serviceExccedsDescLimit = createServiceObject(false);
340 // 1025 chars, the limit is 1024
341 String tooLongServiceDesc = "1GUODojQ0sGzKR4NP7e5j82ADQ3KHTVOaezL95qcbuaqDtjZhAQGQ3iFwKAy580K4WiiXs3u3zq7RzXcSASl5fm0RsWtCMOIDP"
342 + "AOf9Tf2xtXxPCuCIMCR5wOGnNTaFxgnJEHAGxilBhZDgeMNHmCN1rMK5B5IRJOnZxcpcL1NeG3APTCIMP1lNAxngYulDm9heFSBc8TfXAADq7703AvkJT0QPpGq2z2P"
343 + "tlikcAnIjmWgfC5Tm7UH462BAlTyHg4ExnPPL4AO8c92VrD7kZSgSqiy73cN3gLT8uigkKrUgXQFGVUFrXVyyQXYtVM6bLBeuCGQf4C2j8lkNg6M0J3PC0PzMRoinOxk"
344 + "Ae2teeCtVcIj4A1KQo3210j8q2v7qQU69Mabsa6DT9FgE4rcrbiFWrg0Zto4SXWD3o1eJA9o29lTg6kxtklH3TuZTmpi5KVp1NFhS1RpnqF83tzv4mZLKsx7Zh1fEgYvRFwx1"
345 + "ar3RolyDfNoZiGBGTMsZzz7RPFBf2hTnLmNqVGQnHKhhGj0Y5s8t2cbqbO2nmHiJb9uaUVrCGypgbAcJL3KPOBfAVW8PcpmNj4yVjI3L4x5zHjmGZbp9vKshEQODcrmcgsYAoKqe"
346 + "uu5u7jk8XVxEfQ0m5qL8UOErXPlJovSmKUmP5B5T0w299zIWDYCzSoNasHpHjOMDLAiDDeHbozUOn9t3Qou00e9POq4RMM0VnIx1H38nJoJZz2XH8CI5YMQe7oTagaxgQTF2aa0qaq2"
347 + "V6nJsfRGRklGjNhFFYP2cS4Xv2IJO9DSX6LTXOmENrGVJJvMOZcvnBaZPfoAHN0LU4i1SoepLzulIxnZBfkUWFJgZ5wQ0Bco2GC1HMqzW21rwy4XHRxXpXbmW8LVyoA1KbnmVmROycU4"
348 + "scTZ62IxIcIWCVeMjBIcTviXULbPUyqlfEPXWr8IMJtpAaELWgyquPClAREMDs2b9ztKmUeXlMccFES1XWbFTrhBHhmmDyVReEgCwfokrUFR13LTUK1k8I6OEHOs";
350 serviceExccedsDescLimit.setDescription(tooLongServiceDesc);
352 bl.createService(serviceExccedsDescLimit, user);
353 } catch(ByActionStatusComponentException e){
354 assertComponentException(e, ActionStatus.COMPONENT_DESCRIPTION_EXCEEDS_LIMIT, ComponentTypeEnum.SERVICE.getValue(), "" + ValidationUtils.COMPONENT_DESCRIPTION_MAX_LENGTH);
358 private void testServiceDescNotEnglish() {
359 Service notEnglish = createServiceObject(false);
361 String tooLongServiceDesc = "\uC2B5";
362 notEnglish.setDescription(tooLongServiceDesc);
364 bl.createService(notEnglish, user);
365 } catch(ByActionStatusComponentException e){
366 assertComponentException(e, ActionStatus.COMPONENT_INVALID_DESCRIPTION, ComponentTypeEnum.SERVICE.getValue());
370 // Service description - stop
371 // Service icon - start
372 private void testServiceIconEmpty() {
373 Service serviceExist = createServiceObject(false);
374 serviceExist.setIcon("");
376 bl.createService(serviceExist, user);
377 } catch(ByActionStatusComponentException e) {
378 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
382 private void testServiceIconMissing() {
383 Service serviceExist = createServiceObject(false);
384 serviceExist.setIcon(null);
386 bl.createService(serviceExist, user);
387 } catch(ByActionStatusComponentException e) {
388 assertComponentException(e, ActionStatus.COMPONENT_MISSING_ICON, ComponentTypeEnum.SERVICE.getValue());
392 private void testResourceIconInvalid() {
393 Service resourceExist = createServiceObject(false);
394 resourceExist.setIcon("kjk3453^&");
396 bl.createService(resourceExist, user);
397 } catch(ByActionStatusComponentException e) {
398 assertComponentException(e, ActionStatus.COMPONENT_INVALID_ICON, ComponentTypeEnum.SERVICE.getValue());
402 private void testResourceIconExceedsLimit() {
403 Service resourceExist = createServiceObject(false);
404 resourceExist.setIcon("dsjfhskdfhskjdhfskjdhkjdhfkshdfksjsdkfhsdfsdfsdfsfsdfsf");
406 bl.createService(resourceExist, user);
407 } catch(ByActionStatusComponentException e) {
408 assertComponentException(e, ActionStatus.COMPONENT_ICON_EXCEEDS_LIMIT, "Service", "25");
412 private void testTagsNoServiceName() {
413 Service serviceExccedsNameLimit = createServiceObject(false);
414 String tag1 = "afzs2qLBb";
415 List<String> tagsList = new ArrayList<>();
417 serviceExccedsNameLimit.setTags(tagsList);
419 bl.createService(serviceExccedsNameLimit, user);
420 } catch(ByActionStatusComponentException e) {
421 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(ByActionStatusComponentException e) {
434 assertComponentException(e, ActionStatus.INVALID_FIELD_FORMAT, "Service", "tag");
438 private void testServiceTagNotExist() {
439 Service serviceExist = createServiceObject(false);
440 serviceExist.setTags(null);
442 bl.createService(serviceExist, user);
443 } catch(ByActionStatusComponentException e) {
444 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
448 private void testServiceTagEmpty() {
449 Service serviceExist = createServiceObject(false);
450 serviceExist.setTags(new ArrayList<>());
452 bl.createService(serviceExist, user);
453 } catch(ByActionStatusComponentException e) {
454 assertComponentException(e, ActionStatus.COMPONENT_MISSING_TAGS);
458 // Service tags - stop
459 // Service contactId - start
460 private void testContactIdTooLong() {
461 Service serviceContactId = createServiceObject(false);
462 // 59 chars instead of 50
463 String contactIdTooLong = "thisNameIsVeryLongAndExeccedsTheNormalLengthForContactId";
464 serviceContactId.setContactId(contactIdTooLong);
466 bl.createService(serviceContactId, user);
467 } catch(ByActionStatusComponentException e) {
468 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(ByActionStatusComponentException e) {
480 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, ComponentTypeEnum.SERVICE.getValue());
484 private void testResourceContactIdMissing() {
485 Service resourceExist = createServiceObject(false);
486 resourceExist.setContactId(null);
488 bl.createService(resourceExist, user);
489 } catch(ByActionStatusComponentException e) {
490 assertComponentException(e, ActionStatus.COMPONENT_MISSING_CONTACT, ComponentTypeEnum.SERVICE.getValue());
494 // Service contactId - stop
495 // Service category - start
496 private void testServiceCategoryExist() {
497 Service serviceExist = createServiceObject(false);
498 serviceExist.setCategories(null);
500 bl.createService(serviceExist, user);
501 } catch(ByActionStatusComponentException e) {
502 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CONTACT, 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);
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 List<CategoryDefinition> categories = new ArrayList<>();
575 categories.add(category);
576 serviceExist.setCategories(categories);
578 bl.createService(serviceExist, user);
579 } catch(ByActionStatusComponentException e) {
580 assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.SERVICE.getValue());
584 // Service category - stop
585 // Service projectCode - start
586 private void testInvalidProjectCode() {
588 Service serviceExist = createServiceObject(false);
589 serviceExist.setProjectCode("koko!!");
591 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
592 assertTrue(createResponse.isRight());
594 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
597 private void testProjectCodeTooLong() {
599 Service serviceExist = createServiceObject(false);
600 String tooLongProjectCode = "thisNameIsVeryLongAndExeccedsTheNormalLengthForProjectCode";
601 serviceExist.setProjectCode(tooLongProjectCode);
603 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
604 assertTrue(createResponse.isRight());
606 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
609 private void testProjectCodeTooShort() {
611 Service serviceExist = createServiceObject(false);
612 serviceExist.setProjectCode("333");
614 Either<Service, ResponseFormat> createResponse = bl.createService(serviceExist, user);
615 assertTrue(createResponse.isRight());
617 assertResponse(createResponse, ActionStatus.INVALID_PROJECT_CODE);
620 private void testMissingProjectCode() {
622 Service serviceExist = createServiceObject(false);
623 serviceExist.setProjectCode(null);
625 bl.createService(serviceExist, user);
626 } catch(ByActionStatusComponentException e) {
627 assertComponentException(e, ActionStatus.MISSING_PROJECT_CODE);
632 public void testDeleteMarkedServices() {
633 List<String> ids = new ArrayList<>();
634 List<String> responseIds = new ArrayList<>();
635 String resourceInUse = "123";
636 ids.add(resourceInUse);
637 String resourceFree = "456";
638 ids.add(resourceFree);
639 responseIds.add(resourceFree);
640 Either<List<String>, StorageOperationStatus> eitherNoResources = Either.left(ids);
641 when(toscaOperationFacade.getAllComponentsMarkedForDeletion(ComponentTypeEnum.RESOURCE)).thenReturn(eitherNoResources);
643 Either<Boolean, StorageOperationStatus> resourceInUseResponse = Either.left(true);
644 Either<Boolean, StorageOperationStatus> resourceFreeResponse = Either.left(false);
646 List<ArtifactDefinition> artifacts = new ArrayList<>();
647 Either<List<ArtifactDefinition>, StorageOperationStatus> getArtifactsResponse = Either.left(artifacts);
649 Either<Component, StorageOperationStatus> eitherDelete = Either.left(new Resource());
650 when(toscaOperationFacade.deleteToscaComponent(resourceFree)).thenReturn(eitherDelete);
651 when(toscaOperationFacade.deleteMarkedElements(ComponentTypeEnum.SERVICE)).thenReturn(Either.left(responseIds));
652 Either<List<String>, ResponseFormat> deleteMarkedResources = bl.deleteMarkedComponents();
653 assertTrue(deleteMarkedResources.isLeft());
654 List<String> resourceIdList = deleteMarkedResources.left().value();
655 assertFalse(resourceIdList.isEmpty());
656 assertTrue(resourceIdList.contains(resourceFree));
657 assertFalse(resourceIdList.contains(resourceInUse));
661 private Service createServiceObject(boolean afterCreate) {
662 Service service = new Service();
663 service.setUniqueId("sid");
664 service.setName("Service");
665 CategoryDefinition category = new CategoryDefinition();
666 category.setName(SERVICE_CATEGORY);
667 List<CategoryDefinition> categories = new ArrayList<>();
668 categories.add(category);
669 service.setCategories(categories);
670 service.setInstantiationType(INSTANTIATION_TYPE);
672 service.setDescription("description");
673 List<String> tgs = new ArrayList<>();
674 tgs.add(service.getName());
675 service.setTags(tgs);
676 service.setIcon("MyIcon");
677 service.setContactId("aa1234");
678 service.setProjectCode("12345");
681 service.setVersion("0.1");
682 service.setUniqueId(service.getName() + ":" + service.getVersion());
683 service.setCreatorUserId(user.getUserId());
684 service.setCreatorFullName(user.getFirstName() + " " + user.getLastName());
689 private void mockAuditingDaoLogic() {
690 final ResourceAdminEvent createResourceAudit = new ResourceAdminEvent();
691 createResourceAudit.setModifier("Carlos Santana(cs0008)");
692 createResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
693 createResourceAudit.setCurrVersion("0.1");
694 createResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
695 createResourceAudit.setRequestId("3e65cea1-7403-4bc7-b461-e2544d83799f");
696 createResourceAudit.setDesc("OK");
697 createResourceAudit.setResourceType("Resource");
698 createResourceAudit.setStatus("201");
699 createResourceAudit.setPrevVersion("");
700 createResourceAudit.setAction("Create");
701 // fields.put("TIMESTAMP", "2015-11-22 09:19:12.977");
702 createResourceAudit.setPrevState("");
703 createResourceAudit.setResourceName("MyTestResource");
704 // createResourceAudit.setFields(fields);
706 final ResourceAdminEvent checkInResourceAudit = new ResourceAdminEvent();
707 checkInResourceAudit.setModifier("Carlos Santana(cs0008)");
708 checkInResourceAudit.setCurrState("NOT_CERTIFIED_CHECKIN");
709 checkInResourceAudit.setCurrVersion("0.1");
710 checkInResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
711 checkInResourceAudit.setRequestId("ffacbf5d-eeb1-43c6-a310-37fe7e1cc091");
712 checkInResourceAudit.setDesc("OK");
713 checkInResourceAudit.setComment("Stam");
714 checkInResourceAudit.setResourceType("Resource");
715 checkInResourceAudit.setStatus("200");
716 checkInResourceAudit.setPrevVersion("0.1");
717 checkInResourceAudit.setAction("Checkin");
718 // fields.put("TIMESTAMP", "2015-11-22 09:25:03.797");
719 checkInResourceAudit.setPrevState("NOT_CERTIFIED_CHECKOUT");
720 checkInResourceAudit.setResourceName("MyTestResource");
722 final ResourceAdminEvent checkOutResourceAudit = new ResourceAdminEvent();
723 checkOutResourceAudit.setModifier("Carlos Santana(cs0008)");
724 checkOutResourceAudit.setCurrState("NOT_CERTIFIED_CHECKOUT");
725 checkOutResourceAudit.setCurrVersion("0.2");
726 checkOutResourceAudit.setServiceInstanceId("82eddd99-0bd9-4742-ab0a-1bdb5e262a05");
727 checkOutResourceAudit.setRequestId("7add5078-4c16-4d74-9691-cc150e3c96b8");
728 checkOutResourceAudit.setDesc("OK");
729 checkOutResourceAudit.setComment("");
730 checkOutResourceAudit.setResourceType("Resource");
731 checkOutResourceAudit.setStatus("200");
732 checkOutResourceAudit.setPrevVersion("0.1");
733 checkOutResourceAudit.setAction("Checkout");
734 // fields.put("TIMESTAMP", "2015-11-22 09:39:41.024");
735 checkOutResourceAudit.setPrevState("NOT_CERTIFIED_CHECKIN");
736 checkOutResourceAudit.setResourceName("MyTestResource");
737 List<ResourceAdminEvent> list = new ArrayList<ResourceAdminEvent>() {
739 add(createResourceAudit);
740 add(checkInResourceAudit);
741 add(checkOutResourceAudit);
744 Either<List<ResourceAdminEvent>, ActionStatus> result = Either.left(list);
745 Mockito.when(auditingDao.getByServiceInstanceId(Mockito.anyString())).thenReturn(result);
747 List<ResourceAdminEvent> listPrev = new ArrayList<>();
748 Either<List<ResourceAdminEvent>, ActionStatus> resultPrev = Either.left(listPrev);
749 Mockito.when(auditingDao.getAuditByServiceIdAndPrevVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultPrev);
751 List<ResourceAdminEvent> listCurr = new ArrayList<ResourceAdminEvent>() {
753 add(checkOutResourceAudit);
756 Either<List<ResourceAdminEvent>, ActionStatus> resultCurr = Either.left(listCurr);
757 Mockito.when(auditingDao.getAuditByServiceIdAndCurrVersion(Mockito.anyString(), Mockito.anyString())).thenReturn(resultCurr);
759 Either<List<ResourceAdminEvent>, ActionStatus> archiveAuditList = Either.left(Arrays.asList(auditArchive1, auditArchive2));
760 when(auditingDao.getArchiveAuditByServiceInstanceId(anyString())).thenReturn(archiveAuditList);
762 Either<List<ResourceAdminEvent>, ActionStatus> restoreAuditList = Either.left(Arrays.asList(auditRestore));
763 when(auditingDao.getRestoreAuditByServiceInstanceId(anyString())).thenReturn(restoreAuditList);
767 private void setupBeforeDeploy(String notifyAction, String requestAction, String did) {
769 DistributionNotificationEvent notifyEvent = new DistributionNotificationEvent();
770 notifyEvent.setAction(notifyAction);
771 notifyEvent.setDid(did);
772 notifyEvent.setStatus("200");
774 ResourceAdminEvent requestEvent = new ResourceAdminEvent();
775 requestEvent.setAction(requestAction);
776 requestEvent.setDid(did);
777 requestEvent.setStatus("200");
779 List<DistributionNotificationEvent> notifyResults = Collections.singletonList(notifyEvent);
780 Either<List<DistributionNotificationEvent>, ActionStatus> eitherNotify = Either.left(notifyResults);
782 Mockito.when(auditingDao.getDistributionNotify(Mockito.anyString(), Mockito.eq(notifyAction))).thenReturn(eitherNotify);
784 List<ResourceAdminEvent> requestResults = Collections.singletonList(requestEvent);
785 Either<List<ResourceAdminEvent>, ActionStatus> eitherRequest = Either.left(requestResults);
786 Mockito.when(auditingDao.getDistributionRequest(Mockito.anyString(), Mockito.eq(requestAction))).thenReturn(eitherRequest);
788 Either<Component, StorageOperationStatus> eitherService = Either.left(createServiceObject(true));
789 Mockito.when(toscaOperationFacade.getToscaElement(Mockito.anyString())).thenReturn(eitherService);
791 Either<List<DistributionDeployEvent>, ActionStatus> emptyEventList = Either.left(Collections.emptyList());
792 Mockito.when(auditingDao.getDistributionDeployByStatus(Mockito.anyString(), Mockito.eq("DResult"), Mockito.anyString())).thenReturn(emptyEventList);
795 @SuppressWarnings({ "unchecked", "rawtypes" })
797 public void testFindGroupInstanceOnRelatedComponentInstance() {
799 Class<ServiceBusinessLogic> targetClass = ServiceBusinessLogic.class;
800 String methodName = "findGroupInstanceOnRelatedComponentInstance";
801 Object invalidId = "invalidId";
803 Component service = createNewService();
804 List<ComponentInstance> componentInstances = service.getComponentInstances();
806 Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat> findGroupInstanceRes;
807 Object[] argObjects = {service, componentInstances.get(1).getUniqueId(), componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
808 Class[] argClasses = {Component.class, String.class,String.class};
810 Method method = targetClass.getDeclaredMethod(methodName, argClasses);
811 method.setAccessible(true);
813 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjects);
814 assertNotNull(findGroupInstanceRes);
815 assertEquals(findGroupInstanceRes.left().value().getKey().getUniqueId(), componentInstances.get(1)
817 assertEquals(findGroupInstanceRes.left().value().getValue().getUniqueId(), componentInstances.get(1)
822 Object[] argObjectsInvalidCiId = {service, invalidId , componentInstances.get(1).getGroupInstances().get(1).getUniqueId()};
824 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidCiId);
825 assertNotNull(findGroupInstanceRes);
826 assertTrue(findGroupInstanceRes.isRight());
827 assertEquals("SVC4593", findGroupInstanceRes.right().value().getMessageId());
829 Object[] argObjectsInvalidGiId = {service, componentInstances.get(1).getUniqueId() , invalidId};
831 findGroupInstanceRes = (Either<ImmutablePair<ComponentInstance, GroupInstance>, ResponseFormat>) method.invoke(bl, argObjectsInvalidGiId);
832 assertNotNull(findGroupInstanceRes);
833 assertTrue(findGroupInstanceRes.isRight());
834 assertEquals("SVC4653", findGroupInstanceRes.right().value().getMessageId());
836 catch (Exception e) {
841 private Component createNewService() {
843 Service service = new Service();
845 service.setName("serviceName");
846 service.setUniqueId("serviceUniqueId");
847 List<ComponentInstance> componentInstances = new ArrayList<>();
848 ComponentInstance ci;
849 for(int i= 0; i<listSize; ++i){
850 ci = new ComponentInstance();
851 ci.setName("ciName" + i);
852 ci.setUniqueId("ciId" + i);
853 List<GroupInstance> groupInstances= new ArrayList<>();
855 for(int j = 0; j<listSize; ++j){
856 gi = new GroupInstance();
857 gi.setName(ci.getName( )+ "giName" + j);
858 gi.setUniqueId(ci.getName() + "giId" + j);
859 groupInstances.add(gi);
861 ci.setGroupInstances(groupInstances);
862 componentInstances.add(ci);
864 service.setComponentInstances(componentInstances);
870 public void testDerivedFromGeneric() {
871 Service service = createServiceObject(true);
872 validateUserRoles(Role.ADMIN, Role.DESIGNER);
873 when(toscaOperationFacade.createToscaComponent(service)).thenReturn(Either.left(service));
874 when(genericTypeBusinessLogic.fetchDerivedFromGenericType(service)).thenReturn(Either.left(genericService));
875 Either<Service, ResponseFormat> createResponse = bl.createService(service, user);
876 assertTrue(createResponse.isLeft());
877 service = createResponse.left().value();
878 assertEquals(service.getDerivedFromGenericType(), genericService.getToscaResourceName());
879 assertEquals(service.getDerivedFromGenericVersion(), genericService.getVersion());
883 public void testUpdateMetadataNamingPolicy() {
884 Service currentService = createServiceObject(true);
885 Service newService = createServiceObject(false);
886 currentService.setEcompGeneratedNaming(false);
887 newService.setEcompGeneratedNaming(true);
888 newService.setNamingPolicy("policy");
889 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
890 assertThat(resultOfUpdate.isLeft()).isTrue();
891 Service updatedService = resultOfUpdate.left().value();
892 assertThat(updatedService.isEcompGeneratedNaming()).isTrue();
893 assertThat(updatedService.getNamingPolicy()).isEqualToIgnoringCase("policy");
897 public void testUpdateMetadataServiceType() {
898 Service currentService = createServiceObject(true);
899 Service newService = createServiceObject(false);
900 currentService.setServiceType("alice");
902 newService.setServiceType("bob");
903 Either<Service, ResponseFormat> resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
904 assertThat(resultOfUpdate.isLeft()).isTrue();
905 Service updatedService = resultOfUpdate.left().value();
906 assertThat(updatedService.getServiceType()).isEqualToIgnoringCase("bob");
907 //empty string is invalid
908 newService.setServiceType("");
909 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
910 assertThat(resultOfUpdate.isLeft()).isTrue();
912 newService.setServiceType(null);
913 resultOfUpdate = bl.validateAndUpdateServiceMetadata(user, currentService, newService);
914 assertThat(resultOfUpdate.isRight()).isTrue();
917 private Resource setupGenericServiceMock(){
918 Resource genericService = new Resource();
919 genericService.setVersion("1.0");
920 genericService.setToscaResourceName(GENERIC_SERVICE_NAME);
921 return genericService;