diff options
Diffstat (limited to 'sdc-workflow-designer-be/src/test/java/org')
24 files changed, 3531 insertions, 0 deletions
diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/RestPath.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/RestPath.java new file mode 100644 index 00000000..d73d5d6f --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/RestPath.java @@ -0,0 +1,76 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow; + +import static org.onap.sdc.workflow.api.RestParams.LIMIT; +import static org.onap.sdc.workflow.api.RestParams.OFFSET; +import static org.onap.sdc.workflow.api.RestParams.SORT; + +public class RestPath { + + private RestPath() { + //Hiding implicit constructor + } + + private static final String WORKFLOWS_URL = "/wf/workflows"; + private static final String WORKFLOW_URL_FORMATTER = WORKFLOWS_URL + "/%s"; + private static final String ARCHIVE_URL_FORMATTER = WORKFLOWS_URL + "/%s/archiving"; + private static final String VERSIONS_URL_FORMATTER = WORKFLOWS_URL + "/%s/versions"; + private static final String VERSION_URL_FORMATTER = WORKFLOWS_URL + "/%s/versions/%s"; + private static final String SORT_QUERY_STRING_FORMATTER = SORT + "=%s"; + private static final String LIMIT_QUERY_STRING_FORMATTER = LIMIT + "=%s"; + private static final String OFFSET_QUERY_STRING_FORMATTER = OFFSET + "=%s"; + private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_ALL = + WORKFLOWS_URL + "?" + SORT_QUERY_STRING_FORMATTER+ "&" + LIMIT_QUERY_STRING_FORMATTER + "&" + + OFFSET_QUERY_STRING_FORMATTER; + private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_LIMIT = + WORKFLOWS_URL + "?" + OFFSET_QUERY_STRING_FORMATTER; + private static final String WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_OFFSET = + WORKFLOWS_URL + "?" + LIMIT_QUERY_STRING_FORMATTER; + + public static String getWorkflowsPathAllQueryParams(String sort, String limit, String offset) { + return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_ALL, sort, limit, offset); + } + + public static String getWorkflowsPathNoSortAndLimit(String offset) { + return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_LIMIT, offset); + } + + public static String getWorkflowsPathNoSortAndOffset(String limit) { + return String.format(WORKFLOW_URL_FORMATTER_QUERY_PARAMS_NO_SORT_AND_OFFSET, limit); + } + + public static String getWorkflowsPath() { + return WORKFLOWS_URL; + } + + public static String getWorkflowPath(String workflowId) { + return String.format(WORKFLOW_URL_FORMATTER, workflowId); + } + + public static String getArchiveWorkflowPath(String workflowId) { + return String.format(ARCHIVE_URL_FORMATTER, workflowId); + } + + public static String getWorkflowVersions(String workflowId) { + return String.format(VERSIONS_URL_FORMATTER, workflowId); + } + + public static String getWorkflowVersion(String workflowId, String versionId) { + return String.format(VERSION_URL_FORMATTER, workflowId, versionId); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/TestUtil.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/TestUtil.java new file mode 100644 index 00000000..33cc0700 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/TestUtil.java @@ -0,0 +1,65 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow; + +import static org.onap.sdc.workflow.services.impl.ItemType.WORKFLOW; + +import org.onap.sdc.common.versioning.persistence.types.InternalItem; +import org.onap.sdc.common.versioning.persistence.types.InternalVersion; +import org.onap.sdc.common.versioning.services.types.VersionStatus; +import org.onap.sdc.workflow.services.types.Workflow; +import org.onap.sdc.workflow.services.types.ArchivingStatus; +import org.onap.sdc.common.versioning.services.types.Item; +import org.onap.sdc.common.versioning.services.types.ItemStatus; + +public class TestUtil { + + public static Workflow createWorkflow(int workflowNum, boolean createId, ArchivingStatus archivingStatus) { + Workflow workflow = new Workflow(); + if (createId) { + workflow.setId(String.valueOf(workflowNum)); + } + workflow.setName("Workflow_" + workflowNum); + workflow.setDescription("Description_" + workflowNum); + workflow.setArchiving(archivingStatus); + + return workflow; + } + + public static Item createItem(int itemNum, boolean setType, boolean setId, ItemStatus archivingStatus) { + InternalItem item = new InternalItem(); + if (setId) { + item.setId(String.valueOf(itemNum)); + } + item.setName("Workflow_" + itemNum); + item.setDescription("Description_" + itemNum); + if (setType) { + item.setType(WORKFLOW.name()); + } + item.setStatus(archivingStatus); + return item; + } + + public static InternalVersion createRetrievedVersion(String id, VersionStatus status) { + InternalVersion version = new InternalVersion(); + version.setId(id); + version.setStatus(status); + return version; + } + + +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ArtifactAssociationHandlerTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ArtifactAssociationHandlerTest.java new file mode 100644 index 00000000..b4d1180b --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ArtifactAssociationHandlerTest.java @@ -0,0 +1,124 @@ +/* + * Copyright © 2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api; + +import static junit.framework.TestCase.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.io.InputStream; +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.sdc.workflow.api.types.dto.ArtifactDeliveriesRequestDto; +import org.onap.sdc.workflow.persistence.types.ArtifactEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.client.RestTemplate; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration( + classes = {ArtifactAssociationHandlerTest.RestBuilderMockProvider.class, ArtifactAssociationService.class}) +@TestPropertySource(locations = "classpath:application-test.properties") +@Component("ArtifactAssociationHandlerTest") +public class ArtifactAssociationHandlerTest { + + @Configuration + static class RestBuilderMockProvider { + + @Bean + public RestTemplateBuilder templateBuilder() { + return Mockito.mock(RestTemplateBuilder.class); + } + + @Bean + public RestTemplate restTemplate() { + return Mockito.mock(RestTemplate.class); + } + } + + private static final String FILE_NAME = "fileName.txt"; + private static final String USER_ID = "cs0008"; + private static final String END_POINT = + "sdc/v1/catalog/resources/46434d20-40f6-4a5f-a0c4-8c1da6791bdb/interfaces/137a0264-47a5-4dab-b79d-cfdd8cd9a9a1/artifacts/ef82dec9-cb99-48a3-aaba-5ae832417dc5"; + private final String EROR_MSG = + "Failed while attaching workflow artifact to Operation in SDC. Parameters were not initialized: [SDC_ENDPOINT]"; + private InputStream inputStreamMock; + private ArtifactEntity artifactMock; + private ArtifactDeliveriesRequestDto requestDto; + @Value("${sdc.be.endpoint}") + private String sdcBeEndpoint; + @Value("${sdc.be.protocol}") + private String sdcBeProtocol; + @Value("${sdc.be.external.user}") + private String sdcUser; + @Value("${sdc.be.external.password}") + private String sdcPassword; + + @Autowired + private RestTemplate restClientMock; + + + @Autowired + private ArtifactAssociationService associationService; + + @Before + public void setUp() throws IOException { + inputStreamMock = IOUtils.toInputStream("some test data for my input stream", "UTF-8"); + artifactMock = new ArtifactEntity(FILE_NAME, inputStreamMock); + requestDto = new ArtifactDeliveriesRequestDto("POST", END_POINT); + associationService.setRestClient(restClientMock); + } + + + @Test + public void shouldGetResponseStatusOk() { + ResponseEntity<String> responseEntity = new ResponseEntity(HttpStatus.OK); + when(restClientMock.exchange(eq(sdcBeProtocol + "://" + sdcBeEndpoint + "/" + requestDto.getEndpoint()), + eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))).thenReturn(responseEntity); + + ResponseEntity<String> response = associationService.execute(USER_ID, requestDto, artifactMock); + assertEquals(200, response.getStatusCode().value()); + + } + + + @Test + public void shouldReturnStatusFailWhenNoParametersInitialized() { + associationService.setSdcBeEndpoint(null); + ResponseEntity<String> response = associationService.execute(USER_ID, requestDto, artifactMock); + assertEquals(417, response.getStatusCode().value()); + assertEquals(EROR_MSG, response.getBody()); + } + +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ExceptionsHandlerTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ExceptionsHandlerTest.java new file mode 100644 index 00000000..ee924007 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/ExceptionsHandlerTest.java @@ -0,0 +1,83 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.NOT_FOUND; +import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.onap.sdc.workflow.api.types.ErrorResponse; +import org.onap.sdc.workflow.api.types.UnexpectedErrorResponse; +import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException; +import org.onap.sdc.workflow.services.exceptions.VersionModificationException; +import org.onap.sdc.workflow.services.exceptions.VersionStateModificationMissingArtifactException; +import org.onap.sdc.workflow.services.types.WorkflowVersionState; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class ExceptionsHandlerTest { + + @InjectMocks + private ExceptionsHandler exceptionsHandler; + + @Test + public void handleNotFoundException() { + EntityNotFoundException exception = new EntityNotFoundException("message"); + ResponseEntity<ErrorResponse> response = exceptionsHandler.handleNotFoundException(exception); + + assertEquals(NOT_FOUND, response.getStatusCode()); + assertEquals(exception.getMessage(), response.getBody().getMessage()); + } + + @Test + public void handleUnprocessableEntityException() { + VersionModificationException exception = new VersionModificationException("1", "2"); + ResponseEntity<ErrorResponse> response = exceptionsHandler.handleUnprocessableEntityException(exception); + + assertEquals(UNPROCESSABLE_ENTITY, response.getStatusCode()); + assertEquals(exception.getMessage(), response.getBody().getMessage()); + } + + @Test + public void handleUnprocessableEntityVersionStateModificationMissingArtifactException() { + VersionStateModificationMissingArtifactException exception = + new VersionStateModificationMissingArtifactException("WF_ID", "Version_id", + WorkflowVersionState.DRAFT, WorkflowVersionState.CERTIFIED); + ResponseEntity<ErrorResponse> response = exceptionsHandler.handleUnprocessableEntityException(exception); + + assertEquals(UNPROCESSABLE_ENTITY, response.getStatusCode()); + assertEquals(exception.getMessage(), response.getBody().getMessage()); + } + + @Test + public void handleUnexpectedException() { + Exception exception = new Exception("message"); + ResponseEntity<UnexpectedErrorResponse> response = exceptionsHandler.handleUnexpectedException(exception); + + assertEquals(INTERNAL_SERVER_ERROR, response.getStatusCode()); + assertNotNull(response.getBody().getMessage()); + assertFalse(response.getBody().getMessage().contains(exception.getMessage())); + assertNotNull(response.getBody().getDevInfo()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowControllerTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowControllerTest.java new file mode 100644 index 00000000..5e0f61d0 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowControllerTest.java @@ -0,0 +1,311 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.onap.sdc.workflow.api; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.onap.sdc.workflow.TestUtil.createWorkflow; +import static org.onap.sdc.workflow.api.RestParams.USER_ID_HEADER; +import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_LIMIT; +import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_OFFSET; +import static org.onap.sdc.workflow.services.types.WorkflowValidationConstants.MAX_LENGTH; +import static org.onap.sdc.workflow.services.types.WorkflowValidationConstants.MIN_LENGTH; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.Item; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.workflow.RestPath; +import org.onap.sdc.workflow.server.resolvers.UserIdResolver; +import org.onap.sdc.workflow.services.WorkflowManager; +import org.onap.sdc.workflow.services.types.ArchivingStatus; +import org.onap.sdc.workflow.services.types.Page; +import org.onap.sdc.workflow.services.types.PagingRequest; +import org.onap.sdc.workflow.services.types.RequestSpec; +import org.onap.sdc.workflow.services.types.Sort; +import org.onap.sdc.workflow.services.types.Workflow; +import org.onap.sdc.workflow.services.utilities.JsonUtil; +import org.springframework.data.web.PageableHandlerMethodArgumentResolver; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +@RunWith(MockitoJUnitRunner.class) +public class WorkflowControllerTest { + + private static final String USER_ID = "userId"; + private static final String MISSING_USER_HEADER_ERROR = "Missing mandatory request header 'USER_ID'"; + private static final String DEFAULT_SORT_VALUE = "name:asc"; + + private MockMvc mockMvc; + + @Mock + private WorkflowManager workflowManagerMock; + @Captor + private ArgumentCaptor<RequestSpec> requestSpecArg; + @InjectMocks + private WorkflowController workflowController; + + @Before + public void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(workflowController) + .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()) + .setCustomArgumentResolvers(new UserIdResolver()) + .setControllerAdvice(new ExceptionsHandler()).build(); + } + + @Test + public void shouldReturnErrorWhenMissingUserIdInGetReqHeader() throws Exception { + Workflow workflowMock = createWorkflow(1, true, ArchivingStatus.ACTIVE); + mockMvc.perform(get(RestPath.getWorkflowPath(workflowMock.getId())).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", is(MISSING_USER_HEADER_ERROR))); + } + + @Test + public void shouldReturnWorkflowDataWhenRequestPathIsOk() throws Exception { + Workflow workflowMock = createWorkflow(1, true, ArchivingStatus.ACTIVE); + doReturn(workflowMock).when(workflowManagerMock).get(any(Workflow.class)); + mockMvc.perform(get(RestPath.getWorkflowPath(workflowMock.getId())).header(USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.id", is(workflowMock.getId()))) + .andExpect(jsonPath("$.name", is(workflowMock.getName()))); + } + + @Test + public void shouldReturnErrorWhenMissingUserIdInListReqHeader() throws Exception { + mockMvc.perform(get(RestPath.getWorkflowsPath()).contentType(APPLICATION_JSON)) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", is(MISSING_USER_HEADER_ERROR))); + } + + @Test + public void shouldReturnOkWhenArchivingWorkflow() throws Exception { + Workflow workflowMock = createWorkflow(1, true, ArchivingStatus.ACTIVE); + mockMvc.perform(post(RestPath.getArchiveWorkflowPath(workflowMock.getId())).header(USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON) + .content( + "{\"status\": \"ARCHIVED\"}")) + .andExpect(status().isOk()); + verify(workflowManagerMock).updateStatus(workflowMock.getId(), ArchivingStatus.ARCHIVED); + } + + @Test + public void shouldReturnOkWhenRestoringWorkflow() throws Exception { + Workflow workflowMock = createWorkflow(1, true, ArchivingStatus.ACTIVE); + mockMvc.perform(post(RestPath.getArchiveWorkflowPath(workflowMock.getId())).header(USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON) + .content("{\"status\": \"ACTIVE\"}")) + .andExpect(status().isOk()); + verify(workflowManagerMock).updateStatus(workflowMock.getId(), ArchivingStatus.ACTIVE); + } + + @Test + public void listWhenExist() throws Exception { + mockManagerList3(); + ResultActions result = mockMvc.perform( + get(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + for (int i = 0; i < 3; i++) { + result.andExpect(jsonPath(String.format("$.items[%s].id", i), is(String.valueOf(i + 1)))); + } + + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), DEFAULT_OFFSET, DEFAULT_LIMIT, Collections.emptyList()); + } + + @Test + public void listWhenPagingAndSortingAreSet() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathAllQueryParams(DEFAULT_SORT_VALUE, "2", "1")) + .header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), 1, 2, + Collections.singletonList(new Sort("name", true))); + } + + @Test + public void shouldReturnResultsWithDefaultWhenLimitIsNegative() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathAllQueryParams(DEFAULT_SORT_VALUE, "-2", "1")) + .header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), 1, DEFAULT_LIMIT, + Collections.singletonList(new Sort("name", true))); + } + + @Test + public void shouldFallbackOnDefaultOffsetWhenOffsetIsNegative() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathAllQueryParams(DEFAULT_SORT_VALUE, "2", "-1")) + .header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), DEFAULT_OFFSET, 2, + Collections.singletonList(new Sort("name", true))); + } + + @Test + public void shouldFallbackOnDefaultLimitWhenLimitIsNotAnInteger() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathAllQueryParams(DEFAULT_SORT_VALUE, "abc", "0")) + .header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), 0, DEFAULT_LIMIT, + Collections.singletonList(new Sort("name", true))); + } + + @Test + public void shouldFallbackOnDefaultOffsetWhenOffsetIsNotAnInteger() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathAllQueryParams(DEFAULT_SORT_VALUE, "2", "abc")) + .header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON)) + .andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), DEFAULT_OFFSET, 2, + Collections.singletonList(new Sort("name", true))); + } + + @Test + public void shouldReturnDefaultLimitOffsetAppliedWorkflowsWhenLimitIsNotSpecified() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathNoSortAndLimit("1")).header(USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON)) + .andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), 1, DEFAULT_LIMIT, Collections.emptyList()); + } + + @Test + public void shouldReturnDefaultOffsetAppliedWorkflowsWhenOffsetIsNotSpecified() throws Exception { + mockManagerList3(); + mockMvc.perform(get(RestPath.getWorkflowsPathNoSortAndOffset("1")).header(USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON)) + .andExpect(status().isOk()).andExpect(jsonPath("$.items", hasSize(3))); + verify(workflowManagerMock).list(any(), any(), any(), requestSpecArg.capture()); + assertRequestSpec(requestSpecArg.getValue(), DEFAULT_OFFSET, 1, Collections.emptyList()); + } + + @Test + public void shouldCreateWorkflowWhenCallingPostRestRequest() throws Exception { + Item item = new Item(); + item.setId(new Id("abc")); + Workflow reqWorkflow = createWorkflow(1, false, any()); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isCreated()); + verify(workflowManagerMock).create(reqWorkflow); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameInvalid() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName("Invalid workflow name %"); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()).andExpect( + jsonPath("$.message", is("Workflow name must contain only letters, digits and underscores."))); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameBlank() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName(" "); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameNull() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName(null); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameEmptyString() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName(""); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameMoreThanMax() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", + is("Workflow name must be at least " + MIN_LENGTH + " characters, and no more than " + MAX_LENGTH + + " characters."))); + } + + @Test + public void shouldThrowExceptionWhenWorkflowNameLessThanMin() throws Exception { + Workflow reqWorkflow = new Workflow(); + reqWorkflow.setName("AAA"); + mockMvc.perform(post(RestPath.getWorkflowsPath()).header(USER_ID_HEADER, USER_ID).contentType(APPLICATION_JSON) + .content(JsonUtil.object2Json(reqWorkflow))) + .andExpect(status().isBadRequest()).andExpect(jsonPath("$.message", + is("Workflow name must be at least " + MIN_LENGTH + " characters, and no more than " + MAX_LENGTH + + " characters."))); + } + + private void mockManagerList3() { + doReturn(new Page<>(Arrays.asList(createWorkflow(1, true, ArchivingStatus.ACTIVE), + createWorkflow(2, true, ArchivingStatus.ACTIVE), createWorkflow(3, true, ArchivingStatus.ACTIVE)), + new PagingRequest(DEFAULT_OFFSET, DEFAULT_LIMIT), 3)).when(workflowManagerMock) + .list(any(), any(), any(), any()); + } + + private static void assertRequestSpec(RequestSpec actual, int expectedOffset, int expectedLimit, + List<Sort> expectedSorts) { + assertEquals(Integer.valueOf(expectedOffset), actual.getPaging().getOffset()); + assertEquals(Integer.valueOf(expectedLimit), actual.getPaging().getLimit()); + if (expectedSorts.isEmpty()) { + assertEquals(expectedSorts, actual.getSorting().getSorts()); + } else { + for (int i = 0; i < expectedSorts.size(); i++) { + assertEquals(expectedSorts.get(i), actual.getSorting().getSorts().get(i)); + } + } + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowVersionControllerTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowVersionControllerTest.java new file mode 100644 index 00000000..a8813c05 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/WorkflowVersionControllerTest.java @@ -0,0 +1,165 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api; + +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.workflow.RestPath; +import org.onap.sdc.workflow.api.mappers.WorkflowVersionDtoMapper; +import org.onap.sdc.workflow.api.types.Parameter; +import org.onap.sdc.workflow.api.types.WorkflowVersionRequest; +import org.onap.sdc.workflow.api.types.WorkflowVersionResponse; +import org.onap.sdc.workflow.persistence.types.ParameterType; +import org.onap.sdc.workflow.services.WorkflowVersionManager; +import org.onap.sdc.workflow.services.types.WorkflowVersion; +import org.onap.sdc.workflow.services.utilities.JsonUtil; +import org.springframework.http.HttpStatus; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +@RunWith(MockitoJUnitRunner.class) +public class WorkflowVersionControllerTest { + + private static final String USER_ID = "cs0008"; + private static final String ITEM1_ID = "item_id_1"; + private static final String VERSION1_ID = "version_id_1"; + private static final String VERSION2_ID = "version_id_2"; + + private MockMvc mockMvc; + + @Mock + private WorkflowVersionManager workflowVersionManagerMock; + @Mock + private WorkflowVersionDtoMapper versionDtoMapperMock; + @InjectMocks + private WorkflowVersionController workflowVersionController; + + @Before + public void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(workflowVersionController).build(); + } + + @Test + public void shouldReturnWorkflowVersionListWhenCallingVersionGetREST() throws Exception { + WorkflowVersion version1 = new WorkflowVersion(VERSION1_ID); + WorkflowVersion version2 = new WorkflowVersion(VERSION2_ID); + doReturn(Arrays.asList(version1, version2)).when(workflowVersionManagerMock).list(ITEM1_ID, null); + + WorkflowVersionResponse response1 = new WorkflowVersionResponse(); + response1.setId(VERSION1_ID); + doReturn(response1).when(versionDtoMapperMock).workflowVersionToResponse(version1); + WorkflowVersionResponse response2 = new WorkflowVersionResponse(); + response2.setId(VERSION2_ID); + doReturn(response2).when(versionDtoMapperMock).workflowVersionToResponse(version2); + + mockMvc.perform(get(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$.items", hasSize(2))).andExpect(jsonPath("$.items[0].id", is(VERSION1_ID))) + .andExpect(jsonPath("$.items[1].id", is(VERSION2_ID))); + + verify(workflowVersionManagerMock).list(ITEM1_ID, null); + } + + @Test + public void shouldCreateWorkflowVersionWhenCallingVersionsPostREST() throws Exception { + + WorkflowVersionRequest request = new WorkflowVersionRequest(); + request.setDescription("Updated"); + WorkflowVersion version = new WorkflowVersion(); + version.setDescription("Updated"); + doReturn(version).when(versionDtoMapperMock).requestToWorkflowVersion(request); + + mockMvc.perform(post(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON).content(JsonUtil.object2Json(request))) + .andExpect(status().isCreated()); + + verify(workflowVersionManagerMock).create(ITEM1_ID, null, version); + } + + @Test + public void shouldFailCreateWorkflowVersionWhenCallingVersionsPostRESTWithDuplicateInput() throws Exception { + + WorkflowVersionRequest version = new WorkflowVersionRequest(); + Collection<Parameter> inputs = Arrays.asList(createParameter("name1"), createParameter("name1")); + version.setInputs(inputs); + version.setDescription("VersionDescription"); + mockMvc.perform(post(RestPath.getWorkflowVersions(ITEM1_ID)).header(RestParams.USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON).content(JsonUtil.object2Json(version))) + .andExpect(status().isBadRequest()); + } + + @Test + public void shouldReturnWorkflowVersionWhenExists() throws Exception { + WorkflowVersion version = new WorkflowVersion(VERSION1_ID); + doReturn(version).when(workflowVersionManagerMock).get(ITEM1_ID, VERSION1_ID); + WorkflowVersionResponse response = new WorkflowVersionResponse(); + response.setId(VERSION1_ID); + doReturn(response).when(versionDtoMapperMock).workflowVersionToResponse(version); + + mockMvc.perform( + get(RestPath.getWorkflowVersion(ITEM1_ID, VERSION1_ID)).header(RestParams.USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON)).andExpect(status().isOk()) + .andExpect(jsonPath("$.id", is(VERSION1_ID))); + verify(workflowVersionManagerMock).get(ITEM1_ID, VERSION1_ID); + } + + @Test + public void shouldUpdateWorkflowVersionWhenCallingPutREST() throws Exception { + WorkflowVersionRequest request = new WorkflowVersionRequest(); + request.setDescription("Updated"); + WorkflowVersion version = new WorkflowVersion(); + version.setDescription("Updated"); + doReturn(version).when(versionDtoMapperMock).requestToWorkflowVersion(request); + + MockHttpServletResponse result = mockMvc.perform( + put(RestPath.getWorkflowVersion(ITEM1_ID, VERSION1_ID)).header(RestParams.USER_ID_HEADER, USER_ID) + .contentType(APPLICATION_JSON).content(JsonUtil.object2Json(request))).andReturn() + .getResponse(); + + assertEquals(HttpStatus.OK.value(), result.getStatus()); + + verify(workflowVersionManagerMock).update(ITEM1_ID, version); + } + + private Parameter createParameter(String name) { + Parameter parameter = new Parameter(); + parameter.setName(name); + parameter.setMandatory(false); + parameter.setType(ParameterType.STRING); + return parameter; + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/swagger/UserIdReaderTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/swagger/UserIdReaderTest.java new file mode 100644 index 00000000..6899e984 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/swagger/UserIdReaderTest.java @@ -0,0 +1,81 @@ +/* + * Copyright © 2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.swagger; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.fasterxml.classmate.TypeResolver; +import com.google.common.base.Optional; +import java.lang.annotation.Annotation; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.sdc.workflow.services.annotations.UserId; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import springfox.documentation.builders.ParameterBuilder; +import springfox.documentation.service.ResolvedMethodParameter; +import springfox.documentation.spi.service.contexts.ParameterContext; + +@RunWith(SpringJUnit4ClassRunner.class) +public class UserIdReaderTest { + + private static final UserId USER_ID_ANNOTATION = new UserId() { + + @Override + public Class<? extends Annotation> annotationType() { + return UserId.class; + } + }; + + @Mock + TypeResolver resolver; // do not delete. this is used in the injection of UserIdReader constructor + @Mock + ResolvedMethodParameter resolvedMethodParameter; + @Mock + ParameterBuilder parameterBuilder; + @Mock + ParameterContext parameterContext; + @InjectMocks + UserIdReader userIdReader; + + @Test + public void shouldNotCallToParameterBuilderIfUserIdAnnotationNotFound() { + when(parameterContext.resolvedMethodParameter()).thenReturn(resolvedMethodParameter); + when(resolvedMethodParameter.findAnnotation(UserId.class)).thenReturn(Optional.absent()); + userIdReader.apply(parameterContext); + verify(parameterContext, times(0)).parameterBuilder(); + } + + @Test + public void shouldCallToParameterBuilderIfUserIdAnnotationFound() { + + doReturn(resolvedMethodParameter).when(parameterContext).resolvedMethodParameter(); + doReturn(parameterBuilder).when(parameterContext).parameterBuilder(); + doReturn(parameterBuilder).when(parameterBuilder).parameterType(any()); + doReturn(parameterBuilder).when(parameterBuilder).name(any()); + doReturn(parameterBuilder).when(parameterBuilder).type(any()); + doReturn(Optional.of(USER_ID_ANNOTATION)).when(resolvedMethodParameter).findAnnotation(UserId.class); + + userIdReader.apply(parameterContext); + verify(parameterContext, times(1)).parameterBuilder(); + } +}
\ No newline at end of file diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/PagingTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/PagingTest.java new file mode 100644 index 00000000..a0392eb5 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/PagingTest.java @@ -0,0 +1,87 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.types; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.sdc.workflow.services.types.PagingConstants.MAX_LIMIT; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class PagingTest { + + @InjectMocks + private Paging paging; + + @Test + public void setOffsetNotNumber() { + paging.setOffset("aaa"); + assertNull(paging.getOffset()); + } + + @Test + public void setOffsetNegative() { + paging.setOffset("-5"); + assertNull(paging.getOffset()); + } + + @Test + public void setOffsetZero() { + paging.setOffset("0"); + assertEquals(Integer.valueOf(0), paging.getOffset()); + } + + @Test + public void setOffsetPositive() { + paging.setOffset("8"); + assertEquals(Integer.valueOf(8), paging.getOffset()); + } + + @Test + public void setLimitNotNumber() { + paging.setLimit("aaa"); + assertNull(paging.getLimit()); + } + + @Test + public void setLimitNegative() { + paging.setLimit("-5"); + assertNull(paging.getLimit()); + } + + @Test + public void setLimitZero() { + paging.setLimit("0"); + assertNull(paging.getLimit()); + } + + @Test + public void setLimitPositive() { + paging.setLimit("8"); + assertEquals(Integer.valueOf(8), paging.getLimit()); + } + + @Test + public void setLimitGreaterThanMax() { + paging.setLimit("7000"); + assertEquals(Integer.valueOf(MAX_LIMIT), paging.getLimit()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/SortingTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/SortingTest.java new file mode 100644 index 00000000..9cd95a5d --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/SortingTest.java @@ -0,0 +1,67 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.types; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.Collections; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.onap.sdc.workflow.services.types.Sort; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class SortingTest { + + @InjectMocks + private Sorting sorting; + + @Test + public void setSortInvalid() { + sorting.setSort("name:asc:a,:,"); + assertEquals(Collections.emptyList(), sorting.getSorts()); + } + + @Test + public void setSortAscByDefault() { + sorting.setSort("name"); + assertEquals(Collections.singletonList(new Sort("name", true)), sorting.getSorts()); + } + + @Test + public void setSortAsc() { + sorting.setSort("name:asc"); + assertEquals(Collections.singletonList(new Sort("name", true)), sorting.getSorts()); + } + + @Test + public void setSortDesc() { + sorting.setSort("name:desc"); + assertEquals(Collections.singletonList(new Sort("name", false)), sorting.getSorts()); + } + + @Test + public void setSortMoreThanOne() { + sorting.setSort("name:asc,type,date:desc"); + assertEquals(Arrays.asList( + new Sort("name", true), + new Sort("type", true), + new Sort("date", false)), sorting.getSorts()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/VersionStatesFormatterTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/VersionStatesFormatterTest.java new file mode 100644 index 00000000..294577fe --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/types/VersionStatesFormatterTest.java @@ -0,0 +1,61 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.types; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.sdc.workflow.services.types.WorkflowVersionState.CERTIFIED; +import static org.onap.sdc.workflow.services.types.WorkflowVersionState.DRAFT; + +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class VersionStatesFormatterTest { + + @InjectMocks + private VersionStatesFormatter versionStateSet; + + @Test + public void setVersionStateInvalid() { + versionStateSet.setVersionState(",,a"); + assertEquals(Collections.emptySet() ,versionStateSet.getVersionStates()); + } + + @Test + public void setVersionStateDraft() { + versionStateSet.setVersionState("DRAFT"); + assertEquals(Collections.singleton(DRAFT), versionStateSet.getVersionStates()); + } + + @Test + public void setVersionStateCertified() { + versionStateSet.setVersionState("CERTIFIED"); + assertEquals(Collections.singleton(CERTIFIED), versionStateSet.getVersionStates()); + } + + @Test + public void setVersionStateBoth() { + versionStateSet.setVersionState("DRAFT,CERTIFIED"); + assertEquals(Stream.of(DRAFT, CERTIFIED).collect(Collectors.toSet()), versionStateSet.getVersionStates()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ActivitySpecParameterNameValidatorTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ActivitySpecParameterNameValidatorTest.java new file mode 100644 index 00000000..75fb5a29 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ActivitySpecParameterNameValidatorTest.java @@ -0,0 +1,128 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.validation.ConstraintValidatorContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class ActivitySpecParameterNameValidatorTest { + + class AnnotationWrapper { + + @ValidName(message = "test message") + public ActivitySpecParameter parameter; + } + + private String noSpacesMessage = "Input and output names must not contain any spaces"; + private String matchPatternMessage = "Input and output names must match the validation pattern"; + + @Mock + private ConstraintValidatorContext context; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder constraintViolationBuilder; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext nodeBuilderCustomizableContext; + + private ActivitySpecParameterNameValidator validator; + + + @Before + public void setup() throws NoSuchFieldException { + MockitoAnnotations.initMocks(this); + when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(constraintViolationBuilder); + when(constraintViolationBuilder.addPropertyNode(anyString())).thenReturn(nodeBuilderCustomizableContext); + validator = initializeValidator(ActivitySpecParameterNameValidatorTest.AnnotationWrapper.class); + } + + @Test + public void shouldPassIfNoSpaces() { + validator.setValidationRegex("^\\S*$"); + assertTrue(validator.isValid(createParameter("validName"), context)); + } + + @Test + public void shouldFailIfNameHasSpaces() { + validator.setValidationRegex("^\\S*$"); + validator.setValidationMessage(noSpacesMessage); + assertFalse(validator.isValid(createParameter("not a valid name"), context)); + verify(context).disableDefaultConstraintViolation(); + verify(context).buildConstraintViolationWithTemplate(noSpacesMessage); + } + + + @Test + public void shouldFailIfNameHasSpacesInStart() { + validator.setValidationRegex("^\\S*$"); + validator.setValidationMessage(noSpacesMessage); + assertFalse(validator.isValid(createParameter(" name"), context)); + verify(context).disableDefaultConstraintViolation(); + verify(context).buildConstraintViolationWithTemplate(noSpacesMessage); + } + + @Test + public void shouldFailIfNameHasSpacesInEnd() { + validator.setValidationRegex("^\\S*$"); + validator.setValidationMessage(noSpacesMessage); + assertFalse(validator.isValid(createParameter("name "), context)); + verify(context).disableDefaultConstraintViolation(); + verify(context).buildConstraintViolationWithTemplate(noSpacesMessage); + } + + @Test + public void shouldFailIfDoesNotMatchRegex() { + validator.setValidationRegex("^[a-zA-Z0-9-]*$"); + validator.setValidationMessage(matchPatternMessage); + assertFalse(validator.isValid(createParameter("NotValid$$##"), context)); + verify(context).disableDefaultConstraintViolation(); + verify(context).buildConstraintViolationWithTemplate(matchPatternMessage); + } + + @Test + public void shouldPassIfMatchRegex() { + validator.setValidationRegex("^[a-zA-Z0-9-]*$"); + assertTrue(validator.isValid(createParameter("validName"), context)); + } + + private ActivitySpecParameterNameValidator initializeValidator(Class<?> classWithAnnotation) + throws NoSuchFieldException { + ValidName constraint = classWithAnnotation.getField("parameter").getAnnotation(ValidName.class); + ActivitySpecParameterNameValidator validator = new ActivitySpecParameterNameValidator(); + validator.initialize(constraint); + return validator; + } + + private ActivitySpecParameter createParameter(String name) { + ActivitySpecParameter parameter = new ActivitySpecParameter(); + parameter.setName(name); + parameter.setValue("value"); + parameter.setType("type"); + return parameter; + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ArchivingStatusValidatorTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ArchivingStatusValidatorTest.java new file mode 100644 index 00000000..d5e5f20d --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/ArchivingStatusValidatorTest.java @@ -0,0 +1,91 @@ +/* + * Copyright © 2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.validation.ConstraintValidatorContext; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class ArchivingStatusValidatorTest { + + class AnnotationWrapper { + + @ValidName(message = "test message") + public String status; + } + + @Mock + private ConstraintValidatorContext context; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder constraintViolationBuilder; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext nodeBuilderCustomizableContext; + + private ArchivingStatusValidator validator; + + @Before + public void setup() throws NoSuchFieldException { + MockitoAnnotations.initMocks(this); + when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(constraintViolationBuilder); + when(constraintViolationBuilder.addPropertyNode(anyString())).thenReturn(nodeBuilderCustomizableContext); + validator = initializeValidator(ArchivingStatusValidatorTest.AnnotationWrapper.class); + } + + @Test + public void shouldFailIfValueIsNull() { + assertFalse(validator.isValid(null, context)); + } + + @Test + public void shouldFailIfValueInvalid() { + assertFalse(validator.isValid("blahblah", context)); + } + + @Test + public void shouldPassIfValueIsActive() { + assertTrue(validator.isValid("ACTIVE", context)); + } + + @Test + public void shouldPassIfValueIsArchived() { + assertTrue(validator.isValid("ARCHIVED", context)); + } + + + + + private ArchivingStatusValidator initializeValidator(Class<?> classWithAnnotation) + throws NoSuchFieldException { + ValidStatus constraint = classWithAnnotation.getField("status").getAnnotation(ValidStatus.class); + ArchivingStatusValidator validator = new ArchivingStatusValidator(); + validator.initialize(constraint); + return validator; + } + + +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/NoDuplicatesValidatorTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/NoDuplicatesValidatorTest.java new file mode 100644 index 00000000..f8f6b743 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/api/validation/NoDuplicatesValidatorTest.java @@ -0,0 +1,104 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.api.validation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import javax.validation.ConstraintValidatorContext; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.workflow.api.types.Parameter; + +public class NoDuplicatesValidatorTest { + + class AnnotationWrapper { + + @NoDuplicates(message = "test message") + public Collection<Parameter> collection; + } + + private NoDuplicatesValidator noDuplicatesValidator; + + @Mock + private ConstraintValidatorContext context; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder constraintViolationBuilder; + @Mock + private ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext + nodeBuilderCustomizableContext; + + @Before + public void init() throws NoSuchFieldException { + MockitoAnnotations.initMocks(this); + when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(constraintViolationBuilder); + when(constraintViolationBuilder.addPropertyNode(anyString())).thenReturn(nodeBuilderCustomizableContext); + noDuplicatesValidator = initializeValidator(AnnotationWrapper.class); + } + + @Test + public void shouldFailIfCollectionHaveMoreThen1ParameterEntityWithSameName() { + Collection<Parameter> inputs = Arrays.asList(createParameter("name1"), createParameter("name1")); + + assertFalse(noDuplicatesValidator.isValid(inputs, context)); + } + + @Test + public void shouldPassIfCollectionDontHaveMoreThen1ParameterEntityWithSameName() { + Collection<Parameter> inputs = Arrays.asList(createParameter("name2"), createParameter("name1")); + + assertTrue(noDuplicatesValidator.isValid(inputs, context)); + } + + @Test + public void shouldPassIfCollectionContainsOnlyOneObject() { + Collection<Parameter> inputs = Collections.singletonList(createParameter("name2")); + + assertTrue(noDuplicatesValidator.isValid(inputs, context)); + } + + @Test + public void shouldPassIfCollectionIsNull() { + assertTrue(noDuplicatesValidator.isValid(null, context)); + } + + @Test + public void shouldPassIfCollectionIsEmpty() { + assertTrue(noDuplicatesValidator.isValid(new ArrayList<>(), context)); + } + + private NoDuplicatesValidator initializeValidator(Class<?> classWithAnnotation) throws NoSuchFieldException { + NoDuplicates constraint = classWithAnnotation.getField("collection").getAnnotation(NoDuplicates.class); + NoDuplicatesValidator validator = new NoDuplicatesValidator(); + validator.initialize(constraint); + return validator; + } + + private Parameter createParameter(String name) { + Parameter parameter = new Parameter(); + parameter.setName(name); + return parameter; + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java new file mode 100644 index 00000000..e69d4984 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ActivitySpecRepositoryImplTest.java @@ -0,0 +1,180 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.persistence.impl; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.onap.sdc.common.zusammen.services.ZusammenElementUtil.ELEMENT_TYPE_PROPERTY; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.common.versioning.persistence.zusammen.ZusammenSessionContextCreator; +import org.onap.sdc.common.zusammen.services.ZusammenAdaptor; +import org.onap.sdc.workflow.persistence.impl.ActivitySpecRepositoryImpl.InfoPropertyName; +import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecData; +import org.onap.sdc.workflow.persistence.impl.types.ActivitySpecElementType; +import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity; +import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter; +import org.onap.sdc.workflow.services.utilities.JsonUtil; + +@RunWith(MockitoJUnitRunner.class) +public class ActivitySpecRepositoryImplTest { + + private static final String versionId = "1234"; + private static final String itemId = "5678"; + + @Mock + private ZusammenAdaptor zusammenAdaptor; + @Mock + private ZusammenSessionContextCreator contextCreator; + @InjectMocks + private ActivitySpecRepositoryImpl daoImpl; + + private ActivitySpecEntity entity; + private final Map<String, Element> elementMap = new HashMap<>(); + private String elementId; + + @Before + public void setUp() { + daoImpl = new ActivitySpecRepositoryImpl(zusammenAdaptor, contextCreator); + entity = new ActivitySpecEntity(); + entity = new ActivitySpecEntity(); + + entity.setId(itemId); + entity.setVersionId(versionId); + entity.setName("activitySpec"); + List<String> categoryList = new ArrayList<>(); + categoryList.add("category1"); + entity.setCategoryList(categoryList); + ActivitySpecParameter inputParams = new ActivitySpecParameter("dbhost", "String", null); + inputParams.setValue("localhost"); + List<ActivitySpecParameter> inputs = new ArrayList<>(); + inputs.add(inputParams); + entity.setInputs(inputs); + + + mockZusammenAdapter(); + } + + @Test + public void testCreate() { + ItemVersion itemVersionmock = new ItemVersion(); + itemVersionmock.setId(new Id()); + + daoImpl.create(entity); + ElementContext elementContext = new ElementContext(entity.getId(), entity.getVersionId()); + Optional<ElementInfo> testElementInfo = zusammenAdaptor + .getElementInfoByName(contextCreator.create(), elementContext, + Id.ZERO, ActivitySpecElementType.ACTIVITYSPEC.name()); + Assert.assertTrue(testElementInfo.isPresent()); + Assert.assertEquals(testElementInfo.get().getInfo().getName(), ActivitySpecElementType.ACTIVITYSPEC.name()); + Assert.assertEquals(testElementInfo.get().getInfo() + .getProperty(ActivitySpecRepositoryImpl.InfoPropertyName.DESCRIPTION.getValue()), + entity.getDescription()); + Assert.assertEquals(testElementInfo.get().getInfo().getProperty(InfoPropertyName.CATEGORY.getValue()), + entity.getCategoryList()); + Assert.assertEquals(testElementInfo.get().getInfo() + .getProperty(ActivitySpecRepositoryImpl.InfoPropertyName.NAME.getValue()), + entity.getName()); + + final Optional<Element> testElement = + zusammenAdaptor.getElement(contextCreator.create(), elementContext, new Id(elementId)); + final InputStream data = testElement.get().getData(); + final ActivitySpecData activitySpecData = JsonUtil.json2Object(data, ActivitySpecData.class); + Assert.assertEquals(activitySpecData.getInputs().get(0).getName(), entity.getInputs().get(0).getName()); + } + + @Test + public void testGet() { + final ActivitySpecEntity retrieved = daoImpl.get(entity); + Assert.assertEquals(retrieved.getName(), entity.getName()); + Assert.assertEquals(retrieved.getDescription(), entity.getDescription()); + Assert.assertEquals(retrieved.getCategoryList(), entity.getCategoryList()); + } + + @Test + public void testUpdate() { + entity.setDescription("Update AS version1"); + daoImpl.update(entity); + final ActivitySpecEntity retrieved = daoImpl.get(entity); + Assert.assertEquals(retrieved.getName(), entity.getName()); + Assert.assertEquals(retrieved.getDescription(), entity.getDescription()); + Assert.assertEquals(retrieved.getCategoryList(), entity.getCategoryList()); + } + + + private void mockZusammenAdapter() { + + doAnswer(invocationOnMock -> { + Id elementId = invocationOnMock.getArgument(2); + return Optional.of(elementMap.get(elementId.getValue())); + }).when(zusammenAdaptor).getElement(any(), any(), any()); + + doAnswer(invocationOnMock -> { + ZusammenElement element = new ZusammenElement(); + Info info = new Info(); + element.setElementId(Id.ZERO); + info.addProperty("name", entity.getName()); + info.addProperty("description", entity.getDescription()); + info.addProperty("category", entity.getCategoryList()); + element.setInfo(info); + return Optional.of(element); + }).when(zusammenAdaptor).getElementByName(any(), any(), any(), any()); + + doAnswer(invocationOnMock -> { + String elementName = invocationOnMock.getArgument(3); + return elementMap.values().stream() + .filter(element -> elementName.equals(element.getInfo().getProperty(ELEMENT_TYPE_PROPERTY))) + .map(element -> { + ElementInfo elementInfo = new ElementInfo(); + elementInfo.setId(element.getElementId()); + elementInfo.setInfo(element.getInfo()); + return elementInfo; + }).findAny(); + }).when(zusammenAdaptor).getElementInfoByName(any(), any(), any(), any()); + + doAnswer(invocationOnMock -> { + ZusammenElement element = invocationOnMock.getArgument(2); + if (element.getAction().equals(Action.CREATE) || element.getAction().equals(Action.UPDATE)) { + element.setElementId(new Id(UUID.randomUUID().toString())); + } + elementMap.put(element.getElementId().getValue(), element); + elementId = element.getElementId().getValue(); + return element; + }).when(zusammenAdaptor).saveElement(any(), any(), any(), any()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ArtifactRepositoryTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ArtifactRepositoryTest.java new file mode 100644 index 00000000..96f74d58 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ArtifactRepositoryTest.java @@ -0,0 +1,148 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.persistence.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.onap.sdc.common.zusammen.services.ZusammenElementUtil.buildStructuralElement; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Info; +import java.io.IOException; +import java.io.InputStream; +import java.util.Optional; +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.common.versioning.persistence.zusammen.ZusammenSessionContextCreator; +import org.onap.sdc.common.zusammen.services.ZusammenAdaptor; +import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType; +import org.onap.sdc.workflow.persistence.types.ArtifactEntity; + +@RunWith(MockitoJUnitRunner.class) +public class ArtifactRepositoryTest { + + private static final String FILE_NAME_PROPERTY = "fileName"; + private static final String FILE_NAME = "fileName.txt"; + private static final String ITEM1_ID = "item_id_1"; + private static final String VERSION1_ID = "version_id_1"; + private static final SessionContext SESSION_CONTEXT = new SessionContext(); + + + @Mock + private ZusammenAdaptor zusammenAdaptorMock; + @Mock + private ZusammenSessionContextCreator contextCreatorMock; + @InjectMocks + private ArtifactRepositoryImpl artifactRepository; + + @Before + public void setUp() { + doReturn(SESSION_CONTEXT).when(contextCreatorMock).create(); + } + + @Test + public void shouldUpdateArtifact() throws IOException { + + InputStream inputStreamMock = IOUtils.toInputStream("some test data for my input stream", "UTF-8"); + ArtifactEntity artifactMock = new ArtifactEntity(FILE_NAME, inputStreamMock); + + artifactRepository.update(ITEM1_ID, VERSION1_ID, artifactMock); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Update WorkflowVersion Artifact Element")); + } + + @Test + public void shouldGetArtifactWhenExist() throws IOException { + + ZusammenElement artifactElement = buildStructuralElement(WorkflowElementType.ARTIFACT.name(), Action.UPDATE); + artifactElement.setData(IOUtils.toInputStream("some test data for my input stream", "UTF-8")); + artifactElement.getInfo().addProperty(FILE_NAME_PROPERTY, FILE_NAME); + Optional<Element> elementOptional = Optional.of(artifactElement); + + doReturn(elementOptional).when(zusammenAdaptorMock) + .getElementByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.ARTIFACT.name())); + + Optional<ArtifactEntity> result = artifactRepository.get(ITEM1_ID, VERSION1_ID); + assertTrue(result.isPresent()); + assertEquals(FILE_NAME,result.get().getFileName()); + verify(zusammenAdaptorMock).getElementByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.ARTIFACT.name())); + } + + @Test + public void shouldReturnOptionalEmptyWhenDoesNotExist() { + + doReturn(Optional.empty()).when(zusammenAdaptorMock) + .getElementByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.ARTIFACT.name())); + + Optional<ArtifactEntity> result = artifactRepository.get(ITEM1_ID, VERSION1_ID); + verify(zusammenAdaptorMock).getElementByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.ARTIFACT.name())); + assertFalse(result.isPresent()); + } + + @Test + public void shouldCreateArtifactStructure() { + artifactRepository.createStructure(ITEM1_ID, VERSION1_ID); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Create WorkflowVersion Artifact Element")); + } + + @Test + public void shouldDeleteArtifact() { + artifactRepository.delete(ITEM1_ID,VERSION1_ID); + verify(zusammenAdaptorMock).saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Delete WorkflowVersion Artifact Data")); + } + + @Test + public void shouldReturnTrueIfExists() { + ElementInfo elementInfo = new ElementInfo(); + elementInfo.setId(new Id("test_id")); + Info info = new Info(); + info.addProperty(FILE_NAME_PROPERTY, "test_fileName"); + elementInfo.setInfo(info); + + doReturn(Optional.of(elementInfo)).when(zusammenAdaptorMock) + .getElementInfoByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.ARTIFACT.name())); + + assertTrue(artifactRepository.isExist(ITEM1_ID, VERSION1_ID)); + } + +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ParameterRepositoryTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ParameterRepositoryTest.java new file mode 100644 index 00000000..4112ab4e --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/persistence/impl/ParameterRepositoryTest.java @@ -0,0 +1,214 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.persistence.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Info; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mapstruct.ap.internal.util.Collections; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.common.versioning.persistence.zusammen.ZusammenSessionContextCreator; +import org.onap.sdc.common.zusammen.services.ZusammenAdaptor; +import org.onap.sdc.workflow.persistence.impl.types.ParameterPropertyName; +import org.onap.sdc.workflow.persistence.impl.types.WorkflowElementType; +import org.onap.sdc.workflow.persistence.types.ParameterEntity; +import org.onap.sdc.workflow.persistence.types.ParameterRole; +import org.onap.sdc.workflow.persistence.types.ParameterType; + +@RunWith(MockitoJUnitRunner.class) +public class ParameterRepositoryTest { + + private static final String ITEM1_ID = "item_id_1"; + private static final String VERSION1_ID = "version_id_1"; + private static final String PARAMETER1_ID = "parameter_id_1"; + private static final String PARAMETER2_ID = "parameter_id_2"; + private static final String PARAMETERS_PARENT_ID = "parameters_id"; + private static final SessionContext SESSION_CONTEXT = new SessionContext(); + + @Mock + private ZusammenAdaptor zusammenAdaptorMock; + @Mock + private ZusammenSessionContextCreator contextCreatorMock; + @Spy + @InjectMocks + private ParameterRepositoryImpl parameterRepository; + + @Before + public void setUp() { + doReturn(SESSION_CONTEXT).when(contextCreatorMock).create(); + } + + @Test + public void shouldGetParameterById() { + + ElementInfo element = new ElementInfo(); + element.setId(new Id(PARAMETER1_ID)); + Info info = new Info(); + info.setName("testInput"); + info.addProperty(ParameterPropertyName.TYPE.name(), ParameterType.FLOAT.name()); + info.addProperty(ParameterPropertyName.MANDATORY.name(), true); + element.setInfo(info); + doReturn(Optional.of(element)).when(zusammenAdaptorMock) + .getElementInfo(eq(SESSION_CONTEXT), any(ElementContext.class), + eq(new Id(PARAMETER1_ID))); + ParameterEntity result = parameterRepository.get(ITEM1_ID, VERSION1_ID, PARAMETER1_ID); + verify(zusammenAdaptorMock) + .getElementInfo(eq(SESSION_CONTEXT), any(ElementContext.class), eq(new Id(PARAMETER1_ID))); + assertEquals("testInput", result.getName()); + + } + + + @Test + public void shouldUpdateParameter() { + ParameterEntity parameterEntityToUpdate = new ParameterEntity(); + parameterEntityToUpdate.setId(PARAMETER1_ID); + parameterEntityToUpdate.setName("Input1"); + parameterEntityToUpdate.setMandatory(true); + parameterEntityToUpdate.setType(ParameterType.STRING); + + parameterRepository.update(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT, parameterEntityToUpdate); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Update WorkflowVersion Parameter")); + + } + + @Test + public void shouldCreateParameterStructure() { + parameterRepository.createStructure(ITEM1_ID, VERSION1_ID); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Create WorkflowVersion INPUTS Element")); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Create WorkflowVersion OUTPUTS Element")); + } + + @Test + public void shouldDeleteParameter() { + parameterRepository.delete(ITEM1_ID, VERSION1_ID, PARAMETER1_ID); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Delete Parameter with id parameter_id_1")); + } + + + @Test + public void shouldListParametersByType() { + + ElementInfo parameter1 = new ElementInfo(); + parameter1.setId(new Id(PARAMETER1_ID)); + Info info1 = new Info(); + info1.setName("input1"); + info1.addProperty(ParameterPropertyName.TYPE.name(), "INTEGER"); + info1.addProperty(ParameterPropertyName.MANDATORY.name(), true); + parameter1.setInfo(info1); + ElementInfo parameter2 = new ElementInfo(); + parameter2.setId(new Id(PARAMETER2_ID)); + Info info2 = new Info(); + info2.setName("input2"); + info2.addProperty(ParameterPropertyName.TYPE.name(), "STRING"); + info2.addProperty(ParameterPropertyName.MANDATORY.name(), false); + parameter2.setInfo(info2); + Collection<ElementInfo> parameters = Collections.asSet(parameter1, parameter2); + doReturn(parameters).when(zusammenAdaptorMock) + .listElementsByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.INPUTS.name())); + Collection<ParameterEntity> results = parameterRepository.list(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT); + + verify(zusammenAdaptorMock).listElementsByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.INPUTS.name())); + assertTrue(results.stream().anyMatch(parameterEntity -> parameterEntity.getId().equals(PARAMETER1_ID))); + assertTrue(results.stream().anyMatch(parameterEntity -> parameterEntity.getId().equals(PARAMETER2_ID))); + } + + @Test + public void shouldDeleteAllParametersByType() { + ElementInfo parameterParentElement = new ElementInfo(); + parameterParentElement.setId(new Id(PARAMETERS_PARENT_ID)); + ElementInfo parameter1 = new ElementInfo(); + parameter1.setId(new Id(PARAMETER1_ID)); + ElementInfo parameter2 = new ElementInfo(); + parameter2.setId(new Id(PARAMETER2_ID)); + parameterParentElement.setSubElements(new ArrayList<>()); + parameterParentElement.getSubElements().add(parameter1); + parameterParentElement.getSubElements().add(parameter2); + + Optional<ElementInfo> elementOptional = Optional.of(parameterParentElement); + + doReturn(elementOptional).when(zusammenAdaptorMock) + .getElementInfoByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.INPUTS.name())); + + parameterRepository.deleteAll(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Delete all INPUT")); + } + + @Test(expected = IllegalStateException.class) + public void shouldFailIfParentElementDoesNotExist() { + doReturn(Optional.empty()).when(zusammenAdaptorMock) + .getElementInfoByName(eq(SESSION_CONTEXT), any(ElementContext.class), isNull(), + eq(WorkflowElementType.INPUTS.name())); + parameterRepository.deleteAll(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT); + } + + @Test + public void shouldCreateParameter() { + ZusammenElement zusammenParentElement = new ZusammenElement(); + zusammenParentElement.setElementId(new Id(PARAMETERS_PARENT_ID)); + ZusammenElement zusammenElement = new ZusammenElement(); + zusammenElement.setElementId(new Id(PARAMETER1_ID)); + zusammenParentElement.addSubElement(zusammenElement); + doReturn(zusammenParentElement).when(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), + any(ZusammenElement.class), eq("Create WorkflowVersion Parameter Element")); + ParameterEntity parameterEntity = new ParameterEntity("test_input_parameter"); + parameterEntity.setType(ParameterType.INTEGER); + parameterEntity.setMandatory(true); + + ParameterEntity returnedParameter = + parameterRepository.create(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT, parameterEntity); + verify(zusammenAdaptorMock) + .saveElement(eq(SESSION_CONTEXT), any(ElementContext.class), any(ZusammenElement.class), + eq("Create WorkflowVersion Parameter Element")); + assertEquals(PARAMETER1_ID, returnedParameter.getId()); + } + +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/server/resolvers/UserIdResolverTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/server/resolvers/UserIdResolverTest.java new file mode 100644 index 00000000..464af465 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/server/resolvers/UserIdResolverTest.java @@ -0,0 +1,92 @@ +/* + * Copyright © 2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.server.resolvers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.sdc.workflow.api.RestParams.USER_ID_HEADER; + +import javax.servlet.http.HttpServletRequest; +import org.junit.Test; +import org.onap.sdc.workflow.services.annotations.UserId; +import org.springframework.core.MethodParameter; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.context.request.NativeWebRequest; + +/** + * Tests injection of user ID from HTTP headers. + * + * @author evitaliy + * @since 21 Aug 2018 + */ +public class UserIdResolverTest { + + @Test + public void oneHeaderSelectedWhenMultipleUserIdHeadersSent() throws ServletRequestBindingException { + + final String headerValue = "UserIdValueFromHeader"; + + HttpServletRequest servletRequestMock = mock(HttpServletRequest.class); + when(servletRequestMock.getHeader(USER_ID_HEADER)).thenReturn(headerValue); + + NativeWebRequest webRequestMock = mock(NativeWebRequest.class); + when(webRequestMock.getNativeRequest(HttpServletRequest.class)).thenReturn(servletRequestMock); + + Object resolved = new UserIdResolver().resolveArgument(null, null, webRequestMock, null); + assertEquals(headerValue, resolved); + } + + @Test(expected = IllegalStateException.class) + public void illegalTypeErrorThrownWhenAnnotatedParameterIsNotOfTypeString() { + MethodParameter methodParameterMock = mock(MethodParameter.class); + when(methodParameterMock.hasParameterAnnotation(UserId.class)).thenReturn(true); + //noinspection unchecked + when(methodParameterMock.getParameterType()).thenReturn((Class)String[].class); + new UserIdResolver().supportsParameter(methodParameterMock); + } + + @Test(expected = ServletRequestBindingException.class) + public void missingHeaderErrorThrownWhenUserIdHeaderNotPopulated() throws ServletRequestBindingException { + NativeWebRequest webRequestMock = mock(NativeWebRequest.class); + when(webRequestMock.getNativeRequest(HttpServletRequest.class)).thenReturn(mock(HttpServletRequest.class)); + new UserIdResolver().resolveArgument(null, null, webRequestMock, null); + } + + @Test(expected = NullPointerException.class) + public void exceptionThrownWhenRequestTypeIsNotHttpRequest() throws ServletRequestBindingException { + NativeWebRequest webRequestMock = mock(NativeWebRequest.class); + new UserIdResolver().resolveArgument(null, null, webRequestMock, null); + } + + @Test + public void parameterNotSupportedWhenNotAnnotatedWithUserIdAnnotation() { + MethodParameter methodParameterMock = mock(MethodParameter.class); + assertFalse(new UserIdResolver().supportsParameter(methodParameterMock)); + } + + @Test + public void parameterSupportedWhenAnnotatedWithUserIdAnnotationAndOfTypeString() { + MethodParameter methodParameterMock = mock(MethodParameter.class); + when(methodParameterMock.hasParameterAnnotation(UserId.class)).thenReturn(true); + //noinspection unchecked + when(methodParameterMock.getParameterType()).thenReturn((Class) String.class); + assertTrue(new UserIdResolver().supportsParameter(methodParameterMock)); + } +}
\ No newline at end of file diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/UniqueValueServiceTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/UniqueValueServiceTest.java new file mode 100644 index 00000000..da2d8fa5 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/UniqueValueServiceTest.java @@ -0,0 +1,114 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.util.Optional; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.onap.sdc.workflow.persistence.UniqueValueRepository; +import org.onap.sdc.workflow.persistence.types.UniqueValueEntity; +import org.onap.sdc.workflow.services.exceptions.UniqueValueViolationException; + +public class UniqueValueServiceTest { + + private static final String TYPE = "ss"; + private static final String DUMMY_COMBINATION = "dummy"; + + @Mock + private UniqueValueRepository uniqueValueRepositoryMock; + + @Spy + @InjectMocks + private UniqueValueService uniqueValueService; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldCallRepositoryInsertIfValueUnique() { + doReturn(Optional.empty()).when(uniqueValueRepositoryMock).findById(any()); + uniqueValueService.createUniqueValue(TYPE, DUMMY_COMBINATION); + verify(uniqueValueRepositoryMock, times(1)).insert(any(UniqueValueEntity.class)); + } + + @Test + public void shouldNotCheckValueIfNoUniqueCombination() { + uniqueValueService.createUniqueValue(TYPE); + verify(uniqueValueRepositoryMock, never()).findById(any(UniqueValueEntity.class)); + } + + @Test(expected = UniqueValueViolationException.class) + public void shouldThrowExceptionIfValueIsNotUnique() { + doReturn(Optional.of("xxx")).when(uniqueValueRepositoryMock).findById(any()); + uniqueValueService.createUniqueValue(TYPE, DUMMY_COMBINATION); + } + + @Test + public void shouldCallRepositoryDeleteIfValueValid() { + uniqueValueService.deleteUniqueValue(TYPE, DUMMY_COMBINATION); + verify(uniqueValueRepositoryMock, times(1)).delete(any(UniqueValueEntity.class)); + } + + @Test + public void shouldNotCallRepositoryDeleteIfValueNouniqueCombination() { + uniqueValueService.deleteUniqueValue(TYPE); + verify(uniqueValueRepositoryMock, never()).delete(any(UniqueValueEntity.class)); + } + + @Test + public void shouldNotUpdateIfNewAndOldValueAreEqualsCaseIgnore() { + String value = "value"; + uniqueValueService.updateUniqueValue(TYPE, value, value.toUpperCase()); + verify(uniqueValueService, never()).createUniqueValue(anyString(), any()); + } + + @Test + public void shouldUpdateIfNewAndOldValueAreNotEqualsCaseIgnore() { + String oldValue = "oldValue"; + String newValue = "newValue"; + uniqueValueService.updateUniqueValue(TYPE, oldValue, newValue); + verify(uniqueValueService, times(1)).createUniqueValue(anyString(), any()); + verify(uniqueValueService, times(1)).deleteUniqueValue(anyString(), any()); + } + + @Test + public void shouldReturnTrueIfValueExist() { + doReturn(Optional.of("xxx")).when(uniqueValueRepositoryMock).findById(any()); + assertTrue(uniqueValueService.isUniqueValueOccupied(TYPE, DUMMY_COMBINATION)); + } + + @Test + public void shouldReturnFalseIfValueNotExist() { + doReturn(Optional.empty()).when(uniqueValueRepositoryMock).findById(any()); + assertFalse(uniqueValueService.isUniqueValueOccupied(TYPE, DUMMY_COMBINATION)); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java new file mode 100644 index 00000000..3166e06f --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/ActivitySpecManagerImplTest.java @@ -0,0 +1,293 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.onap.sdc.workflow.TestUtil.createRetrievedVersion; +import static org.onap.sdc.workflow.services.ActivitySpecConstant.ACTIVITY_SPEC_NOT_FOUND; +import static org.onap.sdc.workflow.services.ActivitySpecConstant.VERSION_ID_DEFAULT_VALUE; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.onap.sdc.common.versioning.persistence.types.InternalItem; +import org.onap.sdc.common.versioning.persistence.types.InternalVersion; +import org.onap.sdc.common.versioning.services.ItemManager; +import org.onap.sdc.common.versioning.services.VersioningManager; +import org.onap.sdc.common.versioning.services.types.Item; +import org.onap.sdc.common.versioning.services.types.Version; +import org.onap.sdc.common.versioning.services.types.VersionCreationMethod; +import org.onap.sdc.common.versioning.services.types.VersionStatus; +import org.onap.sdc.workflow.api.types.activityspec.ActivitySpecAction; +import org.onap.sdc.workflow.persistence.ActivitySpecRepository; +import org.onap.sdc.workflow.persistence.types.ActivitySpecEntity; +import org.onap.sdc.workflow.persistence.types.ActivitySpecParameter; +import org.onap.sdc.workflow.services.UniqueValueService; +import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException; +import org.onap.sdc.workflow.services.exceptions.VersionStatusModificationException; +import org.onap.sdc.workflow.services.impl.mappers.ActivitySpecMapper; + +public class ActivitySpecManagerImplTest { + + private static final String STRING_TYPE = "String"; + private static final String TEST_ERROR_MSG = "Test Error"; + private static final String ID = "ID1"; + private String version01 = "12345"; + private ActivitySpecEntity input; + + @Spy + @InjectMocks + private ActivitySpecManagerImpl activitySpecManager; + @Mock + private ItemManager itemManagerMock; + @Mock + private VersioningManager versionManagerMock; + @Mock + private ActivitySpecRepository activitySpecRepositoryMock; + @Mock + private UniqueValueService uniqueValueServiceMock; + @Mock + private ActivitySpecMapper activitySpecMapperMock; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + + @After + public void tearDown() { + activitySpecManager = null; + } + + @Test + public void testCreate() { + ActivitySpecEntity activitySpecToCreate = new ActivitySpecEntity(); + activitySpecToCreate.setName("startserver"); + activitySpecToCreate.setDescription("start the server"); + activitySpecToCreate.setVersionId(version01); + + List<String> categoryList = new ArrayList<>(); + categoryList.add("category1"); + categoryList.add("category2"); + activitySpecToCreate.setCategoryList(categoryList); + + ActivitySpecParameter inputParams = new ActivitySpecParameter("dbhost", STRING_TYPE, null); + inputParams.setValue("localhost"); + ActivitySpecParameter inputParams1 = new ActivitySpecParameter("dbname", STRING_TYPE, null); + inputParams.setValue("prod"); + List<ActivitySpecParameter> inputs = new ArrayList<>(); + inputs.add(inputParams); + inputs.add(inputParams1); + activitySpecToCreate.setInputs(inputs); + + ActivitySpecParameter outputParams = new ActivitySpecParameter("status", STRING_TYPE, null); + outputParams.setValue("started"); + List<ActivitySpecParameter> outputs = new ArrayList<>(); + outputs.add(outputParams); + activitySpecToCreate.setOutputs(outputs); + + activitySpecToCreate.setVersionId(version01); + + String itemId = "ID1"; + + InternalItem createdItem = new InternalItem(); + createdItem.setId(itemId); + doReturn(createdItem).when(itemManagerMock).create(any()); + + doReturn(createRetrievedVersion(version01, VersionStatus.Draft)).when(versionManagerMock) + .create(eq(itemId), isNull(), any(Version.class), eq(VersionCreationMethod.major)); + + ActivitySpecEntity activitySpec = activitySpecManager.createActivitySpec(activitySpecToCreate); + + Assert.assertNotNull(activitySpec); + activitySpec.setId(itemId); + activitySpec.setStatus(VersionStatus.Draft.name()); + assertActivitySpecEquals(activitySpec, activitySpecToCreate); + } + + private void assertActivitySpecEquals(ActivitySpecEntity actual, ActivitySpecEntity expected) { + Assert.assertEquals(actual.getId(), expected.getId()); + Assert.assertEquals(actual.getName(), expected.getName()); + Assert.assertEquals(actual.getDescription(), expected.getDescription()); + Assert.assertEquals(actual.getCategoryList(), expected.getCategoryList()); + Assert.assertEquals(actual.getInputs(), expected.getInputs()); + Assert.assertEquals(actual.getOutputs(), expected.getOutputs()); + } + + @Test + public void testList() { + Item item = new Item(); + doReturn(Collections.singletonList(item)).when(itemManagerMock).list(any()); + doReturn(new ActivitySpecEntity(ID, null)).when(activitySpecMapperMock).itemToActivitySpec(item); + + final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list("Certified"); + Assert.assertEquals(1, activitySpecs.size()); + Assert.assertEquals(ID, activitySpecs.iterator().next().getId()); + } + + @Test + public void testListInvalidFilter() { + final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list("invalid_status"); + Assert.assertEquals(0, activitySpecs.size()); + } + + @Test + public void testListNoFilter() { + final Collection<ActivitySpecEntity> activitySpecs = activitySpecManager.list(null); + Assert.assertEquals(0, activitySpecs.size()); + } + + @Test + public void testGet() { + input = new ActivitySpecEntity(); + input.setId(ID); + input.setVersionId(version01); + + mockListVersions(); + doReturn(input).when(activitySpecRepositoryMock).get(any()); + doReturn(createRetrievedVersion(version01,VersionStatus.Draft)).when(versionManagerMock).get(any(), any()); + ActivitySpecEntity retrieved = activitySpecManager.get(input); + assertActivitySpecEquals(retrieved, input); + Assert.assertEquals(retrieved.getStatus(), VersionStatus.Draft.name()); + + + retrieved = activitySpecManager.get(input); + assertActivitySpecEquals(retrieved, input); + Assert.assertEquals(retrieved.getStatus(), VersionStatus.Draft.name()); + } + + private void mockListVersions() { + doReturn(Collections.singletonList((Version)createRetrievedVersion(version01,VersionStatus.Draft))).when(versionManagerMock).list(any()); + } + + @Test + public void testGetActivitySpecDaoFail() { + input = new ActivitySpecEntity(); + input.setId(ID); + input.setVersionId(version01); + mockListVersions(); + doReturn(input).when(activitySpecRepositoryMock).get(any()); + Mockito.doThrow(new RuntimeException(TEST_ERROR_MSG)).when(activitySpecRepositoryMock).get(any()); + try { + activitySpecManager.get(input); + Assert.fail(); + } catch (EntityNotFoundException exception) { + Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage()); + } + } + + @Test + public void testListVersionFail() { + input = new ActivitySpecEntity(); + input.setId(ID); + input.setVersionId(VERSION_ID_DEFAULT_VALUE); + Mockito.doThrow(new RuntimeException(TEST_ERROR_MSG)).when(versionManagerMock).list(any()); + try { + activitySpecManager.get(input); + Assert.fail(); + } catch (EntityNotFoundException exception) { + Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage()); + } + } + + @Test(expected = VersionStatusModificationException.class) + public void testInvalidDeprecate() { + InternalVersion version = createRetrievedVersion(version01, VersionStatus.Draft); + doReturn(version).when(versionManagerMock).get(ID, version01); + activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.DEPRECATE); + } + + @Test(expected = VersionStatusModificationException.class) + public void testInvalidDelete() { + mockCertifiedVersion(); + activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.DELETE); + } + + private void mockCertifiedVersion() { + InternalVersion version = createRetrievedVersion(version01, VersionStatus.Certified); + doReturn(version).when(versionManagerMock).get(ID, version01); + } + + @Test(expected = VersionStatusModificationException.class) + public void testInvalidCertify() { + mockCertifiedVersion(); + activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY); + } + + @Test + public void testCertify() { + InternalVersion retrievedVersion = createRetrievedVersion(version01, VersionStatus.Draft); + doReturn(Collections.singletonList(retrievedVersion)).when(versionManagerMock).list(any()); + doReturn(retrievedVersion).when(versionManagerMock).get(any(), any()); + + activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY); + + verify(versionManagerMock).updateStatus(eq(ID), eq(version01), eq(VersionStatus.Certified), anyString()); + } + + @Test + public void testGetVersionFailOnStatusChangeAction() { + mockListVersions(); + try { + activitySpecManager.actOnAction(new ActivitySpecEntity(ID, version01), ActivitySpecAction.CERTIFY); + Assert.fail(); + } catch (EntityNotFoundException exception) { + Assert.assertEquals(ACTIVITY_SPEC_NOT_FOUND, exception.getMessage()); + } + } + + @Test + public void testDeprecate() { + InternalVersion retrievedVersion = createRetrievedVersion(version01, VersionStatus.Certified); + mockListVersions(); + doReturn(retrievedVersion).when(versionManagerMock).get(any(), any()); + activitySpecManager + .actOnAction(new ActivitySpecEntity(ID, VERSION_ID_DEFAULT_VALUE), ActivitySpecAction.DEPRECATE); + + verify(versionManagerMock).updateStatus(eq(ID), eq(version01), eq(VersionStatus.Deprecated), anyString()); + } + + @Test + public void testDelete() { + ActivitySpecEntity activitySpec = new ActivitySpecEntity(); + activitySpec.setName("stopServer"); + activitySpec.setVersionId(version01); + + mockListVersions(); + doReturn(createRetrievedVersion(version01, VersionStatus.Deprecated)).when(versionManagerMock).get(any(), any()); + doReturn(activitySpec).when(activitySpecRepositoryMock).get(any()); + activitySpecManager + .actOnAction(new ActivitySpecEntity(ID, VERSION_ID_DEFAULT_VALUE), ActivitySpecAction.DELETE); + + verify(versionManagerMock).updateStatus(eq(ID), eq(version01), eq(VersionStatus.Deleted), anyString()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowManagerImplTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowManagerImplTest.java new file mode 100644 index 00000000..1db24092 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowManagerImplTest.java @@ -0,0 +1,359 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.onap.sdc.common.versioning.services.types.VersionStatus.Certified; +import static org.onap.sdc.workflow.TestUtil.createItem; +import static org.onap.sdc.workflow.TestUtil.createWorkflow; +import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_LIMIT; +import static org.onap.sdc.workflow.services.types.PagingConstants.DEFAULT_OFFSET; +import static org.onap.sdc.workflow.services.types.PagingConstants.MAX_LIMIT; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.sdc.common.versioning.services.ItemManager; +import org.onap.sdc.common.versioning.services.types.Item; +import org.onap.sdc.common.versioning.services.types.ItemStatus; +import org.onap.sdc.workflow.services.UniqueValueService; +import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException; +import org.onap.sdc.workflow.services.impl.mappers.VersionStateMapper; +import org.onap.sdc.workflow.services.impl.mappers.WorkflowMapper; +import org.onap.sdc.workflow.services.types.ArchivingStatus; +import org.onap.sdc.workflow.services.types.Page; +import org.onap.sdc.workflow.services.types.Paging; +import org.onap.sdc.workflow.services.types.PagingRequest; +import org.onap.sdc.workflow.services.types.RequestSpec; +import org.onap.sdc.workflow.services.types.Sort; +import org.onap.sdc.workflow.services.types.SortingRequest; +import org.onap.sdc.workflow.services.types.Workflow; +import org.onap.sdc.workflow.services.types.WorkflowVersionState; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +public class WorkflowManagerImplTest { + + + private static final String ITEM1_ID = "1"; + private static final String WORKFLOW_TYPE = "WORKFLOW"; + private static final String WORKFLOW_NAME_UNIQUE_TYPE = "WORKFLOW_NAME"; + private static final List<Item> ITEMS; + private static final List<Workflow> MAPPED_WORKFLOWS; + private static final String SORT_FIELD_NAME = "name"; + + static { + List<Item> items = new ArrayList<>(); + List<Workflow> mappedWorkflows = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + items.add(createItem(i, true, true, ItemStatus.ACTIVE)); + mappedWorkflows.add(createWorkflow(i, true, ArchivingStatus.ACTIVE)); + } + ITEMS = Collections.unmodifiableList(items); + MAPPED_WORKFLOWS = Collections.unmodifiableList(mappedWorkflows); + } + + @Mock + private ItemManager itemManagerMock; + @Mock + private UniqueValueService uniqueValueServiceMock; + @Mock + private WorkflowMapper workflowMapperMock; + @Mock + private VersionStateMapper versionStateMapperMock; + @InjectMocks + private WorkflowManagerImpl workflowManager; + + @Test + public void shouldReturnWorkflowVersionList() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + RequestSpec requestSpec = createRequestSpec(0, 20, true); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + Map<String, Workflow> workflowById = + workflows.getItems().stream().collect(Collectors.toMap(Workflow::getId, Function.identity())); + assertEquals(ITEMS.size(), workflows.getItems().size()); + for (int i = 0; i < ITEMS.size(); i++) { + assertTrue(workflowById.containsKey(String.valueOf(i))); + } + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWithVersionStateFilter() { + doReturn(Certified).when(versionStateMapperMock) + .workflowVersionStateToVersionStatus(WorkflowVersionState.CERTIFIED); + doReturn(Arrays.asList(ITEMS.get(0), ITEMS.get(2))).when(itemManagerMock).list(any()); + doReturn(MAPPED_WORKFLOWS.get(0)).when(workflowMapperMock).fromItem(ITEMS.get(0)); + doReturn(MAPPED_WORKFLOWS.get(2)).when(workflowMapperMock).fromItem(ITEMS.get(2)); + + RequestSpec requestSpec = createRequestSpec(0, 20, true); + Page<Workflow> workflows = + workflowManager.list(null, null, Collections.singleton(WorkflowVersionState.CERTIFIED), requestSpec); + + Map<String, Workflow> workflowById = + workflows.getItems().stream().collect(Collectors.toMap(Workflow::getId, Function.identity())); + assertEquals(2, workflows.getItems().size()); + assertTrue(workflowById.containsKey("0")); + assertTrue(workflowById.containsKey("2")); + + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), 2); + } + + @Test(expected = EntityNotFoundException.class) + public void shouldThrowExceptionWhenWorkflowDontExist() { + Workflow nonExistingWorkflow = new Workflow(); + nonExistingWorkflow.setId(ITEM1_ID); + doReturn(null).when(itemManagerMock).get(ITEM1_ID); + workflowManager.get(nonExistingWorkflow); + verify(workflowMapperMock, times(3)).fromItem(any(Item.class)); + } + + @Test + public void shouldReturnWorkflow() { + Item retrievedItem = createItem(1, true, true, ItemStatus.ACTIVE); + doReturn(retrievedItem).when(itemManagerMock).get(ITEM1_ID); + Workflow workflow = createWorkflow(1, true, ArchivingStatus.ACTIVE); + workflowManager.get(workflow); + verify(itemManagerMock).get(ITEM1_ID); + verify(workflowMapperMock).fromItem(retrievedItem); + } + + @Test + public void shouldCreateWorkflowItemFromWorkflow() { + Workflow workflowToBeCreated = createWorkflow(1, false, ArchivingStatus.ACTIVE); + workflowManager.create(workflowToBeCreated); + verify(itemManagerMock).create(any(Item.class)); + verify(uniqueValueServiceMock).validateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, workflowToBeCreated.getName()); + } + + @Test + public void shouldUpdateWorkflow() { + Item workflowItem = createItem(1, true, true, ItemStatus.ACTIVE); + doReturn(workflowItem).when(itemManagerMock).get(ITEM1_ID); + Workflow workflowToBeUpdated = createWorkflow(1, true, ArchivingStatus.ACTIVE); + workflowManager.update(workflowToBeUpdated); + verify(itemManagerMock).update(eq(ITEM1_ID),any(Item.class)); + verify(uniqueValueServiceMock) + .updateUniqueValue(WORKFLOW_NAME_UNIQUE_TYPE, workflowItem.getName(), workflowToBeUpdated.getName()); + + } + + @Test(expected = EntityNotFoundException.class) + public void shouldThrowExceptionWhenWorkflowToUpdateNotFound() { + doReturn(null).when(itemManagerMock).get(ITEM1_ID); + workflowManager.update(createWorkflow(1, true, ArchivingStatus.ACTIVE)); + } + + @Test + public void listWhenRequestSpecIsNull() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, null); + + assertEquals(ITEMS.size(), workflows.getItems().size()); + assertPaging(workflows.getPaging(), DEFAULT_OFFSET, DEFAULT_LIMIT, ITEMS.size()); + + // verify sorted ascending by name + for (int i = DEFAULT_OFFSET; i < ITEMS.size(); i++) { + assertEquals("Workflow_" + i, workflows.getItems().get(i).getName()); + } + } + + @Test + public void listWhenPagingIsNull() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, + new RequestSpec(null, SortingRequest.builder().sort(new Sort(SORT_FIELD_NAME, true)).build())); + + assertEquals(ITEMS.size(), workflows.getItems().size()); + assertPaging(workflows.getPaging(), DEFAULT_OFFSET, DEFAULT_LIMIT, ITEMS.size()); + } + + @Test + public void listWhenOffsetAndLimitAreNull() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + RequestSpec requestSpec = new RequestSpec(new PagingRequest(-2, -8), + SortingRequest.builder().sort(new Sort(SORT_FIELD_NAME, true)).build()); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + assertEquals(ITEMS.size(), workflows.getItems().size()); + assertPaging(workflows.getPaging(), DEFAULT_OFFSET, DEFAULT_LIMIT, ITEMS.size()); + } + + @Test + public void listWhenSortingIsNull() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + RequestSpec requestSpec = new RequestSpec(new PagingRequest(2, 8), null); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + assertEquals(3, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + + // verify sorted ascending by name + assertEquals("Workflow_2", workflows.getItems().get(0).getName()); + assertEquals("Workflow_3", workflows.getItems().get(1).getName()); + assertEquals("Workflow_4", workflows.getItems().get(2).getName()); + } + + @Test + public void listWhenSortingIsEmpty() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + RequestSpec requestSpec = new RequestSpec(new PagingRequest(2, 8), SortingRequest.builder().build()); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + assertEquals(3, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + + // verify sorted ascending by name + assertEquals("Workflow_2", workflows.getItems().get(0).getName()); + assertEquals("Workflow_3", workflows.getItems().get(1).getName()); + assertEquals("Workflow_4", workflows.getItems().get(2).getName()); + } + + @Test + public void listWhenRequestSpecIsValid() { + RequestSpec requestSpec = createRequestSpec(0, 5, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + assertEquals(5, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWhenLimitIsLessThanTotal() { + RequestSpec requestSpec = createRequestSpec(0, 3, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(3, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + + @Test + public void listWhenOffsetIsNotFirst() { + RequestSpec requestSpec = createRequestSpec(3, 1, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(1, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWhenLimitIsMoreThanTotal() { + RequestSpec requestSpec = createRequestSpec(0, 10, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(5, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWhenOffsetIsMoreThanTotal() { + RequestSpec requestSpec = createRequestSpec(6, 3, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(0, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWhenOffsetIsMoreThanMax() { + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + RequestSpec requestSpec = createRequestSpec(0, 5555, true); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + + assertEquals(ITEMS.size(), workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), MAX_LIMIT, ITEMS.size()); + } + + @Test + public void listWhenOffsetAndLimitAreMoreThanTotal() { + RequestSpec requestSpec = createRequestSpec(10, 10, true); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(0, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + } + + @Test + public void listWhenSortedDesc() { + RequestSpec requestSpec = createRequestSpec(2, 1, false); + doReturn(ITEMS).when(itemManagerMock).list(any()); + mockItemToWorkflowMaps(); + Page<Workflow> workflows = workflowManager.list(null, null, null, requestSpec); + assertEquals(1, workflows.getItems().size()); + assertPaging(workflows.getPaging(), requestSpec.getPaging().getOffset(), requestSpec.getPaging().getLimit(), + ITEMS.size()); + Iterator<Workflow> workflowIterator = workflows.getItems().iterator(); + assertEquals("Workflow_2", workflowIterator.next().getName()); + } + + private void mockItemToWorkflowMaps() { + for (int i = 0; i < ITEMS.size(); i++) { + doReturn(MAPPED_WORKFLOWS.get(i)).when(workflowMapperMock).fromItem(ITEMS.get(i)); + } + } + + private static RequestSpec createRequestSpec(int offset, int limit, boolean isAscending) { + return new RequestSpec(new PagingRequest(offset, limit), + SortingRequest.builder().sort(new Sort(SORT_FIELD_NAME, isAscending)).build()); + } + + private static void assertPaging(Paging paging, int expectedOffset, int expectedLimit, int expectedTotal) { + assertEquals(expectedOffset, paging.getOffset()); + assertEquals(expectedLimit, paging.getLimit()); + assertEquals(expectedTotal, paging.getTotal()); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowVersionManagerImplTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowVersionManagerImplTest.java new file mode 100644 index 00000000..6648f376 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/WorkflowVersionManagerImplTest.java @@ -0,0 +1,441 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.onap.sdc.workflow.TestUtil.createRetrievedVersion; +import static org.onap.sdc.workflow.services.types.WorkflowVersionState.CERTIFIED; +import static org.onap.sdc.workflow.services.types.WorkflowVersionState.DRAFT; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import org.apache.commons.io.IOUtils; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.sdc.common.versioning.persistence.types.InternalItem; +import org.onap.sdc.common.versioning.persistence.types.InternalVersion; +import org.onap.sdc.common.versioning.services.ItemManager; +import org.onap.sdc.common.versioning.services.VersioningManager; +import org.onap.sdc.common.versioning.services.types.ItemStatus; +import org.onap.sdc.common.versioning.services.types.Version; +import org.onap.sdc.common.versioning.services.types.VersionCreationMethod; +import org.onap.sdc.common.versioning.services.types.VersionState; +import org.onap.sdc.common.versioning.services.types.VersionStatus; +import org.onap.sdc.workflow.persistence.ArtifactRepository; +import org.onap.sdc.workflow.persistence.ParameterRepository; +import org.onap.sdc.workflow.persistence.types.ArtifactEntity; +import org.onap.sdc.workflow.persistence.types.ParameterEntity; +import org.onap.sdc.workflow.persistence.types.ParameterRole; +import org.onap.sdc.workflow.services.exceptions.EntityNotFoundException; +import org.onap.sdc.workflow.services.exceptions.VersionCreationException; +import org.onap.sdc.workflow.services.exceptions.VersionModificationException; +import org.onap.sdc.workflow.services.exceptions.VersionStateModificationException; +import org.onap.sdc.workflow.services.exceptions.VersionStateModificationMissingArtifactException; +import org.onap.sdc.workflow.services.exceptions.WorkflowModificationException; +import org.onap.sdc.workflow.services.impl.mappers.VersionMapper; +import org.onap.sdc.workflow.services.impl.mappers.VersionStateMapper; +import org.onap.sdc.workflow.services.types.WorkflowVersion; +import org.onap.sdc.workflow.services.types.WorkflowVersionState; +import org.springframework.mock.web.MockMultipartFile; + +@RunWith(MockitoJUnitRunner.class) +public class WorkflowVersionManagerImplTest { + + private static final String ITEM1_ID = "item_id_1"; + private static final String VERSION1_ID = "version_id_1"; + private static final String VERSION2_ID = "version_id_2"; + + @Mock + private ItemManager itemManagerMock; + @Mock + private VersioningManager versioningManagerMock; + @Mock + private ParameterRepository parameterRepositoryMock; + @Mock + private ArtifactRepository artifactRepositoryMock; + @Mock + private VersionMapper versionMapperMock; + @Mock + private VersionStateMapper versionStateMapperMock; + @Rule + public ExpectedException exceptionRule = ExpectedException.none(); + @Spy + @InjectMocks + private WorkflowVersionManagerImpl workflowVersionManager; + + @Test(expected = EntityNotFoundException.class) + public void shouldThrowExceptionWhenVersionDontExist() { + doThrow(new RuntimeException()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + workflowVersionManager.get(ITEM1_ID, VERSION1_ID); + } + + @Test(expected = WorkflowModificationException.class) + public void shouldThrowExceptionWhenCreatingVersionForArchivedWorkflow() { + InternalItem mockItem = new InternalItem(); + mockItem.setId(ITEM1_ID); + mockItem.setStatus(ItemStatus.ARCHIVED); + doReturn(mockItem).when(itemManagerMock).get(ITEM1_ID); + workflowVersionManager.create(ITEM1_ID, null, new WorkflowVersion(VERSION1_ID)); + } + + @Test(expected = WorkflowModificationException.class) + public void shouldThrowExceptionWhenUpdatingVersionForArchivedWorkflow() { + InternalItem mockItem = new InternalItem(); + mockItem.setId(ITEM1_ID); + mockItem.setStatus(ItemStatus.ARCHIVED); + doReturn(mockItem).when(itemManagerMock).get(ITEM1_ID); + workflowVersionManager.update(ITEM1_ID, new WorkflowVersion(VERSION1_ID)); + } + + @Test(expected = WorkflowModificationException.class) + public void shouldThrowExceptionWhenUploadingArtifactForArchivedWorkflow() { + InternalItem mockItem = new InternalItem(); + mockItem.setId(ITEM1_ID); + mockItem.setStatus(ItemStatus.ARCHIVED); + doReturn(mockItem).when(itemManagerMock).get(ITEM1_ID); + MockMultipartFile mockFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes()); + workflowVersionManager.uploadArtifact(ITEM1_ID, VERSION1_ID, mockFile); + } + + @Test(expected = WorkflowModificationException.class) + public void shouldThrowExceptionWhenDeletingArtifactForArchivedWorkflow() { + InternalItem mockItem = new InternalItem(); + mockItem.setId(ITEM1_ID); + mockItem.setStatus(ItemStatus.ARCHIVED); + doReturn(mockItem).when(itemManagerMock).get(ITEM1_ID); + workflowVersionManager.deleteArtifact(ITEM1_ID, VERSION1_ID); + } + + @Test + public void shouldReturnWorkflowVersionWhenExist() { + WorkflowVersion workflowVersion = new WorkflowVersion(VERSION1_ID); + doReturn(workflowVersion).when(versionMapperMock).fromVersion(any(Version.class)); + doReturn(new Version()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(eq(ITEM1_ID), eq(VERSION1_ID), any(ParameterRole.class)); + workflowVersionManager.get(ITEM1_ID, VERSION1_ID); + verify(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + } + + @Test + public void shouldReturnWorkflowVersionList() { + InternalVersion version1 = createRetrievedVersion(VERSION1_ID, VersionStatus.Certified); + InternalVersion version2 = createRetrievedVersion(VERSION2_ID, VersionStatus.Draft); + List<Version> versionList = Arrays.asList(version1, version2); + doReturn(versionList).when(versioningManagerMock).list(ITEM1_ID); + + WorkflowVersion workflowVersion1 = new WorkflowVersion(); + workflowVersion1.setId(VERSION1_ID); + workflowVersion1.setName(VERSION1_ID); + doReturn(workflowVersion1).when(versionMapperMock).fromVersion(version1); + + WorkflowVersion workflowVersion2 = new WorkflowVersion(); + workflowVersion2.setId(VERSION2_ID); + workflowVersion2.setName(VERSION2_ID); + doReturn(workflowVersion2).when(versionMapperMock).fromVersion(version2); + + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(eq(ITEM1_ID), anyString(), eq(ParameterRole.INPUT)); + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(eq(ITEM1_ID), anyString(), eq(ParameterRole.OUTPUT)); + + workflowVersionManager.list(ITEM1_ID, null); + verify(versioningManagerMock).list(ITEM1_ID); + verify(versionMapperMock, times(2)).fromVersion(any(Version.class)); + } + + @Test + public void shouldReturnCertifiedWorkflowVersionList() { + InternalVersion version1 = createRetrievedVersion(VERSION1_ID, VersionStatus.Certified); + InternalVersion version2 = createRetrievedVersion(VERSION2_ID, VersionStatus.Draft); + List<Version> versionList = Arrays.asList(version1, version2); + + doReturn(versionList).when(versioningManagerMock).list(ITEM1_ID); + WorkflowVersion workflowVersion1 = new WorkflowVersion(); + workflowVersion1.setId(VERSION1_ID); + workflowVersion1.setName(VERSION1_ID); + doReturn(workflowVersion1).when(versionMapperMock).fromVersion(version1); + + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(eq(ITEM1_ID), anyString(), eq(ParameterRole.INPUT)); + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(eq(ITEM1_ID), anyString(), eq(ParameterRole.OUTPUT)); + doReturn(VersionStatus.Certified).when(versionStateMapperMock) + .workflowVersionStateToVersionStatus(WorkflowVersionState.CERTIFIED); + + assertEquals(1, + workflowVersionManager.list(ITEM1_ID, Collections.singleton(WorkflowVersionState.CERTIFIED)).size()); + verify(versioningManagerMock).list(ITEM1_ID); + verify(versionMapperMock, times(1)).fromVersion(any(Version.class)); + + } + + @Test + public void shouldUpdateWorkflowVersion() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + String updatedDescription = "WorkflowVersion description updated"; + InternalVersion retrievedVersion = new InternalVersion(); + retrievedVersion.setId(VERSION1_ID); + retrievedVersion.setName("1.0"); + retrievedVersion.setDescription("WorkflowVersion description"); + retrievedVersion.setStatus(VersionStatus.Draft); + VersionState versionState = new VersionState(); + versionState.setDirty(true); + retrievedVersion.setState(versionState); + doReturn(retrievedVersion).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(DRAFT).when(versionStateMapperMock).versionStatusToWorkflowVersionState(retrievedVersion.getStatus()); + doReturn(Collections.emptyList()).when(parameterRepositoryMock) + .list(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT); + + WorkflowVersion inputVersion = new WorkflowVersion(VERSION1_ID); + inputVersion.setName("1.0"); + inputVersion.setDescription(updatedDescription); + ParameterEntity toBeCreated = new ParameterEntity("Input1"); + inputVersion.setInputs(Collections.singleton(toBeCreated)); + ParameterEntity toBeUpdated = new ParameterEntity("Output1"); + inputVersion.setOutputs(Collections.singleton(toBeUpdated)); + + ParameterEntity toBeDeleted = new ParameterEntity("Output2"); + toBeDeleted.setId("parameter_id_1"); + Collection<ParameterEntity> currentOutputs = Arrays.asList(toBeDeleted, toBeUpdated); + doReturn(currentOutputs).when(parameterRepositoryMock).list(ITEM1_ID, VERSION1_ID, ParameterRole.OUTPUT); + + doAnswer(invocationOnMock -> { + WorkflowVersion workflowVersion = invocationOnMock.getArgument(0); + Version version = invocationOnMock.getArgument(1); + version.setDescription(workflowVersion.getDescription()); + return null; + }).when(versionMapperMock).toVersion(inputVersion, retrievedVersion); + + ArgumentCaptor<Version> versionArgCaptor = ArgumentCaptor.forClass(Version.class); + workflowVersionManager.update(ITEM1_ID, inputVersion); + + verify(versioningManagerMock).update(eq(ITEM1_ID), eq(VERSION1_ID), versionArgCaptor.capture()); + Version captorVersion = versionArgCaptor.getValue(); + assertEquals("1.0", captorVersion.getName()); + assertEquals(updatedDescription, captorVersion.getDescription()); + assertEquals(VersionStatus.Draft, captorVersion.getStatus()); + verify(versioningManagerMock).publish(ITEM1_ID, VERSION1_ID, "Update version"); + + verify(parameterRepositoryMock).delete(ITEM1_ID, VERSION1_ID, "parameter_id_1"); + verify(parameterRepositoryMock).create(ITEM1_ID, VERSION1_ID, ParameterRole.INPUT, toBeCreated); + verify(parameterRepositoryMock).update(ITEM1_ID, VERSION1_ID, ParameterRole.OUTPUT, toBeUpdated); + + } + + + @Test + public void shouldCreateWorkflowVersion() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + Version version = createRetrievedVersion(VERSION1_ID, VersionStatus.Draft); + doReturn(version).when(versioningManagerMock) + .create(eq(ITEM1_ID), isNull(), any(Version.class), eq(VersionCreationMethod.major)); + + WorkflowVersion versionRequest = new WorkflowVersion(); + versionRequest.setDescription("version desc"); + versionRequest.setInputs(Collections.emptyList()); + versionRequest.setOutputs(Collections.emptyList()); + WorkflowVersion workflowVersion = new WorkflowVersion(VERSION1_ID); + doReturn(workflowVersion).when(workflowVersionManager).get(ITEM1_ID, VERSION1_ID); + + workflowVersionManager.create(ITEM1_ID, null, versionRequest); + } + + @Test(expected = VersionCreationException.class) + public void shouldTrowExceptionWhenDraftVersionExists() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + WorkflowVersion versionRequestDto = new WorkflowVersion(); + + Version baseVersion = createRetrievedVersion(VERSION2_ID, VersionStatus.Draft); + List<Version> versions = Collections.singletonList(baseVersion); + doReturn(versions).when(versioningManagerMock).list(ITEM1_ID); + + workflowVersionManager.create(ITEM1_ID, VERSION2_ID, versionRequestDto); + } + + @Test(expected = VersionCreationException.class) + public void shouldTrowExceptionWhenInputsSupplied() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + WorkflowVersion versionRequestDto = new WorkflowVersion(); + versionRequestDto.setInputs(Collections.singleton(new ParameterEntity())); + InternalVersion baseVersion = createRetrievedVersion(VERSION2_ID, VersionStatus.Draft); + List<Version> versions = Collections.singletonList(baseVersion); + doReturn(versions).when(versioningManagerMock).list(ITEM1_ID); + + workflowVersionManager.create(ITEM1_ID, VERSION2_ID, versionRequestDto); + } + + + @Test(expected = EntityNotFoundException.class) + public void getStateOfNonExisting() { + doThrow(new RuntimeException()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + workflowVersionManager.getState(ITEM1_ID, VERSION1_ID); + } + + @Test + public void getState() { + InternalVersion version = createRetrievedVersion(VERSION1_ID, VersionStatus.Certified); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(CERTIFIED).when(versionStateMapperMock).versionStatusToWorkflowVersionState(version.getStatus()); + + WorkflowVersionState state = workflowVersionManager.getState(ITEM1_ID, VERSION1_ID); + assertEquals(CERTIFIED, state); + } + + @Test(expected = EntityNotFoundException.class) + public void updateStateOfNonExisting() { + doThrow(new RuntimeException()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + workflowVersionManager.updateState(ITEM1_ID, VERSION1_ID, CERTIFIED); + } + + @Test(expected = VersionStateModificationException.class) + public void updateStateToCurrentState() { + InternalVersion version = createRetrievedVersion(VERSION1_ID, VersionStatus.Draft); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(DRAFT).when(versionStateMapperMock).versionStatusToWorkflowVersionState(version.getStatus()); + + workflowVersionManager.updateState(ITEM1_ID, VERSION1_ID, DRAFT); + } + + @Test(expected = VersionStateModificationMissingArtifactException.class) + public void updateStateWhenCertified() { + InternalVersion version = createRetrievedVersion(VERSION1_ID, VersionStatus.Certified); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(CERTIFIED).when(versionStateMapperMock).versionStatusToWorkflowVersionState(version.getStatus()); + + workflowVersionManager.updateState(ITEM1_ID, VERSION1_ID, CERTIFIED); + } + + @Test + public void shouldFailUpdateStateWhenNoArtifact() { + InternalVersion retrievedVersion = createRetrievedVersion(VERSION1_ID, VersionStatus.Draft); + doReturn(retrievedVersion).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(DRAFT).when(versionStateMapperMock).versionStatusToWorkflowVersionState(VersionStatus.Draft); + + exceptionRule.expect(VersionStateModificationMissingArtifactException.class); + exceptionRule.expectMessage(String.format( + VersionStateModificationMissingArtifactException.WORKFLOW_MODIFICATION_STATE_MISSING_ARTIFACT_TEMPLATE, + ITEM1_ID, VERSION1_ID, DRAFT, CERTIFIED)); + workflowVersionManager.updateState(ITEM1_ID, VERSION1_ID, CERTIFIED); + + verify(versioningManagerMock).updateStatus(ITEM1_ID, VERSION1_ID, VersionStatus.Certified, anyString()); + } + + @Test + public void shouldSuccessUpdateStateWhenArtifactExist() { + InternalVersion retrievedVersion = createRetrievedVersion(VERSION1_ID, VersionStatus.Draft); + doReturn(retrievedVersion).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(DRAFT).when(versionStateMapperMock).versionStatusToWorkflowVersionState(VersionStatus.Draft); + doReturn(true).when(artifactRepositoryMock).isExist(ITEM1_ID, VERSION1_ID); + workflowVersionManager.updateState(ITEM1_ID, VERSION1_ID, CERTIFIED); + verify(versioningManagerMock) + .updateStatus(eq(ITEM1_ID), eq(VERSION1_ID), eq(VersionStatus.Certified), anyString()); + } + + @Test + public void shouldUploadArtifact() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + InternalVersion version = createRetrievedVersion(VERSION1_ID, VersionStatus.Draft); + VersionState versionState = new VersionState(); + versionState.setDirty(false); + version.setState(versionState); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + doReturn(DRAFT).when(versionStateMapperMock).versionStatusToWorkflowVersionState(version.getStatus()); + + MockMultipartFile mockFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes()); + workflowVersionManager.uploadArtifact(ITEM1_ID, VERSION1_ID, mockFile); + + verify(artifactRepositoryMock).update(eq(ITEM1_ID), eq(VERSION1_ID), any(ArtifactEntity.class)); + } + + @Test(expected = EntityNotFoundException.class) + public void shouldThrowExceptionWhenArtifactNotFound() { + doReturn(new Version()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + + doReturn(Optional.empty()).when(artifactRepositoryMock).get(ITEM1_ID, VERSION1_ID); + workflowVersionManager.getArtifact(ITEM1_ID, VERSION1_ID); + } + + @Test + public void shouldReturnArtifact() throws IOException { + doReturn(new Version()).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + + InputStream inputStreamMock = IOUtils.toInputStream("some test data for my input stream", "UTF-8"); + ArtifactEntity artifactMock = new ArtifactEntity("fileName.txt", inputStreamMock); + doReturn(Optional.of(artifactMock)).when(artifactRepositoryMock).get(ITEM1_ID, VERSION1_ID); + ArtifactEntity returnedArtifact = workflowVersionManager.getArtifact(ITEM1_ID, VERSION1_ID); + assertEquals(artifactMock, returnedArtifact); + } + + @Test(expected = VersionModificationException.class) + public void shouldThrowExceptionInDeleteArtifactWhenVersionIsCertified() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + Version version = new Version(); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + WorkflowVersion workflowVersion = new WorkflowVersion(VERSION1_ID); + workflowVersion.setState(WorkflowVersionState.CERTIFIED); + doReturn(workflowVersion).when(versionMapperMock).fromVersion(version); + workflowVersionManager.deleteArtifact(ITEM1_ID, VERSION1_ID); + } + + @Test + public void shouldNotDeleteArtifactIfNotExist() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + Version version = new Version(); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + WorkflowVersion workflowVersion = new WorkflowVersion(VERSION1_ID); + doReturn(workflowVersion).when(versionMapperMock).fromVersion(version); + workflowVersionManager.deleteArtifact(ITEM1_ID, VERSION1_ID); + verify(artifactRepositoryMock, times(0)).delete(ITEM1_ID, VERSION1_ID); + verify(versioningManagerMock, times(0)).publish(ITEM1_ID, VERSION1_ID, "Delete Artifact"); + } + + @Test + public void shouldDeleteArtifactIfExist() { + doNothing().when(workflowVersionManager).validateWorkflowStatus(ITEM1_ID); + Version version = new Version(); + doReturn(version).when(versioningManagerMock).get(ITEM1_ID, VERSION1_ID); + WorkflowVersion workflowVersion = new WorkflowVersion(VERSION1_ID); + doReturn(true).when(artifactRepositoryMock).isExist(ITEM1_ID, VERSION1_ID); + doReturn(workflowVersion).when(versionMapperMock).fromVersion(version); + workflowVersionManager.deleteArtifact(ITEM1_ID, VERSION1_ID); + verify(artifactRepositoryMock, times(1)).delete(ITEM1_ID, VERSION1_ID); + verify(versioningManagerMock, times(1)).publish(ITEM1_ID, VERSION1_ID, "Delete Artifact"); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionMapperTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionMapperTest.java new file mode 100644 index 00000000..8bffc3e1 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionMapperTest.java @@ -0,0 +1,93 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl.mappers; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.sdc.common.versioning.persistence.types.InternalVersion; +import org.onap.sdc.common.versioning.services.types.Version; +import org.onap.sdc.common.versioning.services.types.VersionStatus; +import org.onap.sdc.workflow.services.types.WorkflowVersion; +import org.onap.sdc.workflow.services.types.WorkflowVersionState; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@ContextConfiguration(classes = VersionMapperTest.VersionMapperSpringTestConfig.class) +@RunWith(SpringJUnit4ClassRunner.class) +public class VersionMapperTest { + + @Configuration + @ComponentScan(basePackageClasses = {VersionMapper.class, VersionStateMapper.class}) + public static class VersionMapperSpringTestConfig { } + + @Autowired + VersionMapper versionMapper; + + @Test + public void shouldMapVersionToWorkflowVersion() { + Version version = createVersion(); + WorkflowVersion mappedWorkflowVersion = versionMapper.fromVersion(version); + assertEquals(mappedWorkflowVersion.getId(), version.getId()); + assertEquals(mappedWorkflowVersion.getBaseId(), version.getBaseId()); + assertEquals(mappedWorkflowVersion.getDescription(), version.getDescription()); + assertEquals(mappedWorkflowVersion.getName(), version.getName()); + assertEquals(mappedWorkflowVersion.getCreationTime(), version.getCreationTime()); + assertEquals(mappedWorkflowVersion.getModificationTime(), version.getModificationTime()); + } + + @Test + public void shouldMapWorkflowVersionToVersion() { + WorkflowVersion workflowVersion = createWorkflowVersion(); + Version mappedVersion = new Version(); + versionMapper.toVersion(workflowVersion, mappedVersion); + assertEquals(mappedVersion.getDescription(), workflowVersion.getDescription()); + + } + + private Version createVersion() { + InternalVersion version = new InternalVersion(); + version.setId("version_id"); + version.setBaseId("base_version_id"); + version.setName("1.0"); + version.setCreationTime(new Date()); + version.setModificationTime(new Date()); + version.setDescription("version_description"); + version.setStatus(VersionStatus.Draft); + + return version; + + } + + private WorkflowVersion createWorkflowVersion() { + WorkflowVersion workflowVersion = new WorkflowVersion(); + workflowVersion.setId("wf_version_id"); + workflowVersion.setBaseId("wf_base_version_id"); + workflowVersion.setName("1.0"); + workflowVersion.setCreationTime(new Date()); + workflowVersion.setModificationTime(new Date()); + workflowVersion.setDescription("version_description"); + workflowVersion.setState(WorkflowVersionState.CERTIFIED); + + return workflowVersion; + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionStateMapperTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionStateMapperTest.java new file mode 100644 index 00000000..c0804eb8 --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/VersionStateMapperTest.java @@ -0,0 +1,84 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl.mappers; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.sdc.workflow.services.types.WorkflowVersionState; +import org.onap.sdc.common.versioning.services.types.VersionStatus; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@ContextConfiguration(classes = VersionStateMapperTest.VersionStatusMapperSpringTestConfig.class) +@RunWith(SpringJUnit4ClassRunner.class) +public class VersionStateMapperTest { + + @Configuration + @ComponentScan(basePackageClasses = {VersionStateMapper.class}) + public static class VersionStatusMapperSpringTestConfig { } + + + @Autowired + VersionStateMapper versionStateMapper; + + @Test + public void shouldMapCertifiedVersionStatusToWorkflowVersionStatus() { + WorkflowVersionState mappedVersionStatus = + versionStateMapper.versionStatusToWorkflowVersionState(VersionStatus.Certified); + assertEquals(WorkflowVersionState.CERTIFIED, mappedVersionStatus); + } + + @Test + public void shouldMapDraftVersionStatusToWorkflowVersionStatus() { + WorkflowVersionState mappedVersionStatus = + versionStateMapper.versionStatusToWorkflowVersionState(VersionStatus.Draft); + assertEquals(WorkflowVersionState.DRAFT, mappedVersionStatus); + } + + @Test + public void shouldMapDeletedVersionStatusToWorkflowVersionStatus() { + WorkflowVersionState mappedVersionStatus = + versionStateMapper.versionStatusToWorkflowVersionState(VersionStatus.Deleted); + assertEquals(WorkflowVersionState.DRAFT, mappedVersionStatus); + } + + @Test + public void shouldMapDeprecatedVersionStatusToWorkflowVersionStatus() { + WorkflowVersionState mappedVersionStatus = + versionStateMapper.versionStatusToWorkflowVersionState(VersionStatus.Deprecated); + assertEquals(WorkflowVersionState.DRAFT, mappedVersionStatus); + } + + @Test + public void shouldMapCertifiedWorkflowVersionStatusToVersionStatus() { + VersionStatus mappedVersionStatus = + versionStateMapper.workflowVersionStateToVersionStatus(WorkflowVersionState.CERTIFIED); + assertEquals(VersionStatus.Certified, mappedVersionStatus); + } + + @Test + public void shouldMapDraftWorkflowVersionStatusToVersionStatus() { + VersionStatus mappedVersionStatus = + versionStateMapper.workflowVersionStateToVersionStatus(WorkflowVersionState.DRAFT); + assertEquals(VersionStatus.Draft, mappedVersionStatus); + } +} diff --git a/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/WorkflowMapperTest.java b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/WorkflowMapperTest.java new file mode 100644 index 00000000..ef84190a --- /dev/null +++ b/sdc-workflow-designer-be/src/test/java/org/onap/sdc/workflow/services/impl/mappers/WorkflowMapperTest.java @@ -0,0 +1,70 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.onap.sdc.workflow.services.impl.mappers; + + +import static org.junit.Assert.assertEquals; +import static org.onap.sdc.workflow.TestUtil.createItem; +import static org.onap.sdc.workflow.TestUtil.createWorkflow; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.sdc.common.versioning.services.types.Item; +import org.onap.sdc.common.versioning.services.types.ItemStatus; +import org.onap.sdc.workflow.services.impl.ItemType; +import org.onap.sdc.workflow.services.types.ArchivingStatus; +import org.onap.sdc.workflow.services.types.Workflow; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@ContextConfiguration(classes = WorkflowMapperTest.WorkflowMapperSpringTestConfig.class) +@RunWith(SpringJUnit4ClassRunner.class) +public class WorkflowMapperTest { + + @Configuration + @ComponentScan(basePackageClasses = {WorkflowMapper.class}) + public static class WorkflowMapperSpringTestConfig { } + + @Autowired + WorkflowMapper workflowMapper; + + @Test + public void shouldMapItemToWorkflow() { + + Item item = createItem(1, false, true, ItemStatus.ACTIVE); + Workflow mappedWorkflow = workflowMapper.fromItem(item); + assertEquals(mappedWorkflow.getId(), item.getId()); + assertEquals(mappedWorkflow.getDescription(), item.getDescription()); + assertEquals(mappedWorkflow.getName(), item.getName()); + assertEquals(mappedWorkflow.getArchiving().name(), item.getStatus().name()); + } + + @Test + public void shouldMapWorkflowToItem() { + + Workflow workflow = createWorkflow(1, true, ArchivingStatus.ARCHIVED); + Item mappedItem = new Item(); + workflowMapper.toItem(workflow, mappedItem); + assertEquals(ItemType.WORKFLOW.name(), mappedItem.getType()); + assertEquals(workflow.getDescription(), mappedItem.getDescription()); + assertEquals(workflow.getName(), mappedItem.getName()); + } + +} |