diff options
Diffstat (limited to 'mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web')
13 files changed, 1802 insertions, 0 deletions
diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java new file mode 100644 index 0000000..c89b4dc --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/BaseMicroserviceControllerTest.java @@ -0,0 +1,165 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.exceptions.OperationNotAllowedException; +import org.onap.dcaegen2.platform.mod.model.exceptions.ResourceConflictException; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.BaseMicroserviceController; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsService; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.Arrays; + +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_NAME_CONFLICT_MESSAGE; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(BaseMicroserviceController.class) +class BaseMicroserviceControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private MsService mockBaseMsService; + + @BeforeEach + void setUp() { + } + + @Test + void test_GetAllBaseMicroservices_returnsListOfDTOs() throws Exception { + //arrange + BaseMicroservice ms1 = new BaseMicroservice(); + ms1.setName("HelloWorld1"); + BaseMicroservice ms2 = new BaseMicroservice(); + ms2.setName("HelloWorld2"); + + Mockito.when(mockBaseMsService.getAllMicroservices()).thenReturn(Arrays.asList(ms1, ms2)); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.get("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))); + } + + @Test + void test_addBaseMicroservice_returnsMicroservice() throws Exception { + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + + //response + BaseMicroservice microserviceDao = BaseMsObjectMother.createMockMsObject(); + + Mockito.when(mockBaseMsService.createMicroservice(microserviceRequest)).thenReturn(microserviceDao); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect((MockMvcResultMatchers.jsonPath("$.id", Matchers.equalTo(BaseMsObjectMother.BASE_MS_ID)))) + .andExpect(MockMvcResultMatchers.jsonPath("$.name", Matchers.equalTo(BaseMsObjectMother.BASE_MS_NAME))) + .andExpect(MockMvcResultMatchers.jsonPath("$.metadata.createdBy", Matchers.equalTo(BaseMsObjectMother.USER))); + } + + @Test + void test_addBaseMicroserviceWithDuplicateName_shouldThrowConflictError() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + Mockito.when(mockBaseMsService.createMicroservice(ArgumentMatchers.any())).thenThrow(new ResourceConflictException(MICROSERVICE_NAME_CONFLICT_MESSAGE)); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest))) + .andExpect(MockMvcResultMatchers.status().isConflict()); + } + + @Test + void test_updateBaseMicroserviceEndpoint() throws Exception{ + MicroserviceUpdateRequest microserviceRequest = BaseMsObjectMother.createUpdateMsRequest(); + String requestedMsId = "id-123"; + + mockMvc.perform(MockMvcRequestBuilders.patch(String.format(BaseMicroserviceController.API_BASE_MICROSERVICE + "/%s", requestedMsId)) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isNoContent()); + Mockito.verify(mockBaseMsService, Mockito.times(1)).updateMicroservice(requestedMsId, microserviceRequest); + } + + @Test + void test_OperationNotAllowedExceptionThrows409() throws Exception{ + MicroserviceUpdateRequest microserviceRequest = BaseMsObjectMother.createUpdateMsRequest(); + String requestedMsId = "id-123"; + Mockito.doThrow(new OperationNotAllowedException("")). + when(mockBaseMsService).updateMicroservice(requestedMsId, microserviceRequest); + + mockMvc.perform(MockMvcRequestBuilders.patch(String.format(BaseMicroserviceController.API_BASE_MICROSERVICE + "/%s", requestedMsId)) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest))) + .andExpect(MockMvcResultMatchers.status().isConflict()); + } + + @Test + void test_validateMsRequestShouldThrowCorrectResponse() throws Exception { + //arrange + MicroserviceCreateRequest microserviceRequest = BaseMsObjectMother.createMockMsRequest(); + microserviceRequest.setName(" "); + microserviceRequest.setTag("123"); + microserviceRequest.setServiceName("123"); + microserviceRequest.setUser(" "); + + //response + BaseMicroservice microserviceDao = BaseMsObjectMother.createMockMsObject(); + + Mockito.when(mockBaseMsService.createMicroservice(microserviceRequest)).thenReturn(microserviceDao); + + //act/assert + mockMvc.perform(MockMvcRequestBuilders.post("/api/base-microservice") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(microserviceRequest)) + .characterEncoding("utf-8")) + .andExpect(MockMvcResultMatchers.status().isBadRequest()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message", Matchers.equalTo("Validation failed."))) + .andExpect(MockMvcResultMatchers.jsonPath("$.errors", Matchers.hasSize(4))) + ; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java new file mode 100644 index 0000000..c8942b1 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/DeploymentArtifactControllerTest.java @@ -0,0 +1,170 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.BlueprintFileNameCreateException; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.DeploymentArtifactNotFound; +import org.onap.dcaegen2.platform.mod.model.restapi.DeploymentArtifactPatchRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.DeploymentArtifactController; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +import java.util.Arrays; +import java.util.List; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +@WebMvcTest(DeploymentArtifactController.class) +class DeploymentArtifactControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + DeploymentArtifactService service; + + @BeforeEach + void setUp() { + } + + @Test + void test_GenerateDeploymentArtifactEndpoint_returnsBlueprint() throws Exception{ + String url = String.format("/api/deployment-artifact/%s?user=%s", MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER); + DeploymentArtifact response = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + Mockito.when(service.generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER)).thenReturn(response); + + mockMvc.perform(post(url)) + .andExpect(MockMvcResultMatchers.status().isCreated()) + .andExpect(MockMvcResultMatchers.jsonPath("$.fileName").exists()) + .andExpect(MockMvcResultMatchers.jsonPath("$.content").exists()); + + Mockito.verify(service, Mockito.times(1)).generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER); + } + + @Test + void test_RaiseExceptionIfBlueprintNameCanNotBeCreated() throws Exception{ + String url = String.format("/api/deployment-artifact/%s?user=%s", MsInstanceObjectMother.MS_INSTANCE_ID, + MsInstanceObjectMother.USER); + DeploymentArtifact response = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + Mockito.when(service.generateDeploymentArtifact(MsInstanceObjectMother.MS_INSTANCE_ID, MsInstanceObjectMother.USER)).thenThrow(new BlueprintFileNameCreateException("")); + + mockMvc.perform(post(url)) + .andExpect(MockMvcResultMatchers.status().is4xxClientError()); + } + + @Test + void test_GetAllDeploymentArtifactsShouldReturnList() throws Exception{ + List<DeploymentArtifact> daos = createDaos(); + Mockito.when(service.getAllDeploymentArtifacts()).thenReturn(daos); + + mockMvc.perform(get("/api/deployment-artifact")) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(2))); + + } + + private List<DeploymentArtifact> createDaos() { + DeploymentArtifact dao1 = new DeploymentArtifact(); + dao1.setId("123"); + DeploymentArtifact dao2 = new DeploymentArtifact(); + dao2.setId("456"); + + return Arrays.asList(dao1, dao2); + } + + @Test + void test_GetAllDeploymentArtifactTestShouldReturnAList() throws Exception{ + + mockMvc.perform(get(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + DeploymentArtifactController.GET_STATUSES)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$", Matchers.hasSize(DeploymentArtifactStatus.values().length))); + } + + @Test + void test_ifUserIsNullRaiseException() throws Exception{ + String id = "id-123"; + String user = ""; + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + id + "?user=" + user) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(new DeploymentArtifactPatchRequest()))) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); + } + + @Test + void test_ChangeStatusOfDeploymentArtifact() throws Exception{ + + String id = "id-123"; + String user = "user1"; + DeploymentArtifactPatchRequest partialDto = new DeploymentArtifactPatchRequest(); + partialDto.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + id + "?user=" + user) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(partialDto))) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").exists()); + + Mockito.verify(service, Mockito.times(1)).updateDeploymentArtifact(id, partialDto, user); + + } + + @Test + void test_deploymentArtifactIdNotFound() throws Exception{ + String wrongId = "wrong-id"; + DeploymentArtifactPatchRequest partialDto = new DeploymentArtifactPatchRequest(); + partialDto.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); + + Mockito.doThrow(new DeploymentArtifactNotFound("")).when(service). + updateDeploymentArtifact(wrongId, partialDto, "user-1"); + + mockMvc.perform(patch(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + wrongId + "?user=" + "user-1") + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(partialDto))) + .andExpect(MockMvcResultMatchers.status().isBadRequest()); + } + + @Test + void test_deleteDeploymentArtifactEndpoint() throws Exception{ + String deploymentArtifactId = "id-123"; + String user = "user-1"; + mockMvc.perform(delete(DeploymentArtifactController.DEPLOYMENT_ARTIFACTS_BASE_URL + "/" + deploymentArtifactId + "?user=" + user)) + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.jsonPath("$.message").exists()); + Mockito.verify(service, Mockito.times(1)).deleteDeploymentArtifact(deploymentArtifactId); + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java new file mode 100644 index 0000000..852fb10 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MicroserviceInstanceControllerTest.java @@ -0,0 +1,145 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.controller.MicroserviceInstanceController; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(MicroserviceInstanceController.class) +class MicroserviceInstanceControllerTest { + + @MockBean + MsInstanceService service; + + @Autowired + MockMvc mockMvc; + + @BeforeEach + void setUp() { + } + + @Test + void getAll() throws Exception { + MsInstance instance_1 = MsInstance.builder().id("123").build(); + MsInstance instance_2 = MsInstance.builder().id("345").build(); + + when(service.getAll()).thenReturn(Arrays.asList(instance_1,instance_2)); + + mockMvc.perform(get("/api/microservice-instance") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$",hasSize(2))); + verify(service, times(1)).getAll(); + } + + @Test + void createMsInstance_shouldReturn201AndResponseBody() throws Exception { + + MsInstanceRequest request = getMsInstanceMockRequest(); + MsInstance msInstance = createMsInstance(); + + when(service.createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME, request)).thenReturn(msInstance); + + mockMvc.perform(MockMvcRequestBuilders.post("/api/microservice-instance/"+ BaseMsObjectMother.BASE_MS_NAME) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(request)).accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andExpect(jsonPath("$.name",equalTo(MS_INSTANCE_NAME))); + + verify(service, times(1)).createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME,request); + } + + @Test + void patchMsInstance_shouldReturn204NoContent() throws Exception{ + //given + String updatedVersion = "updatedVersion"; + String updatedRelease = "updatedRelease"; + + MsInstance mockedMsInstance = prepareMockMsInstance(updatedVersion, updatedRelease); + String msInstanceId = mockedMsInstance.getId(); + + MsInstanceUpdateRequest updateRequest = prepareMsInstanceUpdateRequest(updatedVersion, updatedRelease); + + when(service.updateMsInstance(updateRequest, msInstanceId)).thenReturn(mockedMsInstance); + + mockMvc.perform(patch("/api/microservice-instance/" + msInstanceId) + .contentType(MediaType.APPLICATION_JSON) + .content(BaseMsObjectMother.asJsonString(updateRequest))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.release", equalTo(updatedRelease))) + .andExpect(jsonPath("$.version", equalTo(updatedVersion))) + .andExpect(jsonPath("$.metadata.scrumLead", equalTo("updatedScrumLead"))); + + verify(service, times(1)).updateMsInstance(updateRequest, msInstanceId); + } + + private MsInstanceUpdateRequest prepareMsInstanceUpdateRequest(String updatedVersion, String updatedRelease) { + MsInstanceUpdateRequest updateRequest = new MsInstanceUpdateRequest(); + updateRequest.setRelease(updatedRelease); + updateRequest.setVersion(updatedVersion); + updateRequest.setMetadata(prepareMetadataToBeUpdated()); + return updateRequest; + } + + private Map<String, Object> prepareMetadataToBeUpdated() { + Map<String, Object> metadata = new HashMap<>(); + metadata.put("scrumLead", "updatedScrumLead"); + return metadata; + } + + private MsInstance prepareMockMsInstance(String updatedVersion, String updatedRelease) { + MsInstance msInstanceToBeUpdated = MsInstanceObjectMother.createMsInstance(); + msInstanceToBeUpdated.setVersion(updatedVersion); + msInstanceToBeUpdated.setRelease(updatedRelease); + msInstanceToBeUpdated.getMetadata().put("scrumLead", "updatedScrumLead"); + return msInstanceToBeUpdated; + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java new file mode 100644 index 0000000..d71f8dd --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/MsRequestValidationTest.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import java.util.Set; + +public class MsRequestValidationTest { + + public Validator validator; + private MicroserviceCreateRequest request; + + @BeforeEach + public void setup(){ + validator = Validation.buildDefaultValidatorFactory().getValidator(); + request = BaseMsObjectMother.createMockMsRequest(); + } + + @Test + void test_msNameShouldNotBeBlank(){ + request.setName(" "); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msTagShouldNotBeNull(){ + request.setTag(null); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + + } + + @Test + void test_msTagShouldFollowRegex() throws Exception{ + request.setTag("ms-1"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msTagSizeValidation() throws Exception { + request.setTag("core-name-should-not-exceed-fifty-chars-core-name-should-not-exceed-fifty-chars"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_msServiceNameShouldFollowRegex() throws Exception{ + request.setServiceName("ms-1"); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } + + @Test + void test_userShouldNotBeBlank(){ + request.setUser(" "); + Set<ConstraintViolation<MicroserviceCreateRequest>> violations = validator.validate(request); + Assertions.assertThat(violations.size()).isEqualTo(1); + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java new file mode 100644 index 0000000..64f9c00 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/SpecificationControllerTest.java @@ -0,0 +1,79 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.restapi.SpecificationRequest; +import org.onap.dcaegen2.platform.mod.model.specification.Specification; +import org.onap.dcaegen2.platform.mod.web.controller.SpecificationController; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.asJsonString; +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.MS_INSTANCE_ID; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getMockSpecification; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getSpecificationRequest; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(SpringExtension.class) +@WebMvcTest(SpecificationController.class) +public class SpecificationControllerTest { + + @Autowired + MockMvc mockMvc; + + @MockBean + private SpecificationService mockSpecificationService; + + @BeforeEach + void setup() { + } + + @Test + void test_addSpecification_returnsSpecification() throws Exception { + //arrange + SpecificationRequest specificationRequest = getSpecificationRequest(); + Specification specification = getMockSpecification(DeploymentType.DOCKER); + + when(mockSpecificationService.createSpecification(MS_INSTANCE_ID, specificationRequest)).thenReturn(specification); + + //act/assert + mockMvc.perform(post("/api/specification/" + MS_INSTANCE_ID) + .contentType(MediaType.APPLICATION_JSON) + .content(asJsonString(specificationRequest)).accept(MediaType.APPLICATION_JSON)) + .andExpect(jsonPath("$.id", notNullValue())) + .andExpect(status().isCreated()); + verify(mockSpecificationService, times(1)).createSpecification(MS_INSTANCE_ID, specificationRequest); + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java new file mode 100644 index 0000000..1d84b60 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceServiceImplTest.java @@ -0,0 +1,209 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.MsInstanceInfo; +import org.onap.dcaegen2.platform.mod.model.exceptions.msinstance.MsInstanceNotFoundException; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.MsInstanceRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsService; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceGateway; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceStatusChangeHandler; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsInstanceServiceImplTest { + + @Spy + private MsInstanceServiceImpl service = new MsInstanceServiceImpl(); + + @Mock + private MsInstanceGateway msInstanceRepository; + + @Mock + private MsService msService; + + @Mock + private SpecificationService specificationService; + + @Mock + private DeploymentArtifactService deploymentArtifactService; + + @Mock + private MsInstanceStatusChangeHandler msInstanceStatusChangeHandler; + + + @BeforeEach + void setUp() { + service.setMsService(msService); + service.setSpecificationService(specificationService); + service.setDeploymentArtifactService(deploymentArtifactService); + service.setMsInstanceRepository(msInstanceRepository); + service.setMsInstanceStatusChangeHandler(msInstanceStatusChangeHandler); + } + + @Test + void getAll() { + MsInstance instance_1 = MsInstance.builder().id("123").build(); + MsInstance instance_2 = MsInstance.builder().id("345").build(); + + when(msInstanceRepository.findAll()).thenReturn(Arrays.asList(instance_1, instance_2)); + + List<MsInstance> instances = service.getAll(); + + assertThat(instances.size()).isEqualTo(2); + verify(msInstanceRepository, times(1)).findAll(); + } + + @Test + void test_getMsInstanceById() throws Exception{ + MsInstance expected = MsInstanceObjectMother.createMsInstance(); + + when(msInstanceRepository.findById(MS_INSTANCE_ID)).thenReturn(Optional.of(expected)); + + MsInstance original = service.getMsInstanceById(MS_INSTANCE_ID); + + assertThat(original.getId()).isEqualTo(expected.getId()); + } + + @Test + void test_msIntanceNotFound_willRaiseException() throws Exception{ + when(msInstanceRepository.findById(MS_INSTANCE_ID)).thenReturn(Optional.empty()); + assertThatExceptionOfType(MsInstanceNotFoundException.class).isThrownBy( + () -> service.getMsInstanceById(MS_INSTANCE_ID)); + } + + //TODO require cleaning and more assertions + @Test + void createMicroserviceInstance() { + + BaseMicroservice microservice = BaseMsObjectMother.createMockMsObject(); + MsInstanceRequest request = getMsInstanceMockRequest(); + MsInstance msInstanceMockDao = createMsInstance(); + + when(msService.getMicroserviceByName(BaseMsObjectMother.BASE_MS_NAME)).thenReturn(microservice); + when(msInstanceRepository.findByNameAndRelease(request.getName(), request.getRelease())) + .thenReturn(Optional.empty()); + when(msInstanceRepository.save(any())).thenReturn(msInstanceMockDao); + + MsInstance msInstance = service.createMicroserviceInstance(BaseMsObjectMother.BASE_MS_NAME,request); + + assertThat(msInstance.getId()).isEqualTo(msInstance.getId()); + assertThat(msInstance.getName()).isEqualTo(msInstance.getName()); + assertThat(msInstance.getMsInfo().keySet()).isEqualTo(msInstanceMockDao.getMsInfo().keySet()); + + verify(msService, times(1)).getMicroserviceByName(BaseMsObjectMother.BASE_MS_NAME); + verify(msInstanceRepository, times(1)).save(any(MsInstance.class)); + verify(msService, times(1)). + saveMsInstanceReferenceToMs(microservice, msInstance); + + } + + @Test + void test_updateMsInstance() { + + } + + @Test + void updateStatusBasedOnDeploymentArtifactsStatuses() { + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceRepository.findById(msInstance.getId())).thenReturn(Optional.of(msInstance)); + + service.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance.getId()); + + verify(msInstanceStatusChangeHandler, times(1)).updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + verify(service, times(1)).updateMsInstance(msInstance); + + } + + @Test + void test_removeDeploymentArtifactFromMsInstance() { + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + DeploymentArtifact deploymentArtifact = createDeploymentArtifact(msInstance); + + when(msInstanceRepository.findById(msInstance.getId())).thenReturn(Optional.of(msInstance)); + //when(msInstanceStatusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(any())).thenReturn(msInstance); + + service.removeDeploymentArtifactFromMsInstance(deploymentArtifact); + + assertThat(msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts().contains(deploymentArtifact.getId())).isFalse(); + verify(msInstanceStatusChangeHandler, times(1)).updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + verify(service, times(1)).updateMsInstance(msInstance); + + } + + @Test + void updateMicroserviceReference() throws Exception{ + BaseMicroservice microservice = BaseMsObjectMother.createMockMsObject(); + MsInstance msInstance_1 = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + msInstance_1.setId("instance-1"); + msInstance_1.getMsInfo().put("name", "old-ms"); + MsInstance msInstance_2 = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + msInstance_2.setId("instance-2"); + msInstance_2.getMsInfo().put("name", "old-ms"); + + when(msInstanceRepository.findById("instance-1")).thenReturn(Optional.of(msInstance_1)); + when(msInstanceRepository.findById("instance-2")).thenReturn(Optional.of(msInstance_2)); + + service.updateMicroserviceReference(microservice); + + assertThat(msInstance_1.getName()).isEqualTo(microservice.getName()); + assertThat(msInstance_2.getName()).isEqualTo(microservice.getName()); + + assertThat(msInstance_1.getMsInfo().get("name")).isEqualTo(microservice.getName()); + assertThat(msInstance_2.getMsInfo().get("name")).isEqualTo(microservice.getName()); + + verify(service, times(2)).getMsInstanceById(anyString()); + verify(msInstanceRepository, times(2)).save(any(MsInstance.class)); + } + + private DeploymentArtifact createDeploymentArtifact(MsInstance msInstance) { + DeploymentArtifact deploymentArtifact = new DeploymentArtifact(); + deploymentArtifact.setId(msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts().get(0)); + + MsInstanceInfo msInstanceInfo = new MsInstanceInfo(); + msInstanceInfo.setId(msInstance.getId()); + deploymentArtifact.setMsInstanceInfo(msInstanceInfo); + return deploymentArtifact; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java new file mode 100644 index 0000000..9339b26 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsInstanceStatusChangeHandlerTest.java @@ -0,0 +1,92 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstanceStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.deploymentartifact.DeploymentArtifactService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceStatusChangeHandler; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsInstanceStatusChangeHandlerTest { + + MsInstanceStatusChangeHandler statusChangeHandler; + + @Mock + MsInstanceService msInstanceService; + + @Mock + DeploymentArtifactService deploymentArtifactService; + + @BeforeEach + void setup() throws Exception{ + statusChangeHandler = new MsInstanceStatusChangeHandler(); + statusChangeHandler.setMsInstanceService(msInstanceService); + statusChangeHandler.setDeploymentArtifactService(deploymentArtifactService); + } + + @Test + void handleStatusChangeFromDeploymentArtifactsWithDevComplete() { + //arrange + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + + when(deploymentArtifactService.findByMsInstanceId(msInstance.getId())).thenReturn( + DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true) + ); + + //act + statusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + + //assert + assertThat(msInstance.getStatus()).isEqualTo(MsInstanceStatus.DEV_COMPLETE); + verify(deploymentArtifactService, times(1)).findByMsInstanceId(msInstance.getId()); + } + + @Test + void handleStatusChangeFromDeploymentArtifactsWithoutDevComplete() { + //arrange + MsInstance msInstance = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + + //when(msInstanceService.getMsInstanceById(msInstance.getId())).thenReturn(msInstance); + when(deploymentArtifactService.findByMsInstanceId(msInstance.getId())).thenReturn( + DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(false) + ); + + //act + statusChangeHandler.updateStatusBasedOnDeploymentArtifactsStatuses(msInstance); + + //assert + assertThat(msInstance.getStatus()).isEqualTo(MsInstanceStatus.IN_DEV); + verify(deploymentArtifactService, times(1)).findByMsInstanceId(msInstance.getId()); + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java new file mode 100644 index 0000000..8604f1a --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/MsServiceImplTest.java @@ -0,0 +1,217 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMicroservice; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsLocation; +import org.onap.dcaegen2.platform.mod.model.basemicroservice.BaseMsType; +import org.onap.dcaegen2.platform.mod.model.exceptions.ResourceConflictException; +import org.onap.dcaegen2.platform.mod.model.exceptions.basemicroservice.BaseMicroserviceNotFoundException; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceCreateRequest; +import org.onap.dcaegen2.platform.mod.model.restapi.MicroserviceUpdateRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.BaseMicroserviceGateway; +import org.onap.dcaegen2.platform.mod.web.service.basemicroservice.MsServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.*; + +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_NAME_CONFLICT_MESSAGE; +import static org.onap.dcaegen2.platform.mod.model.exceptions.ErrorMessages.MICROSERVICE_TAG_CONFLICT_MESSAGE; +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.createMockMsObject; +import static org.onap.dcaegen2.platform.mod.objectmothers.BaseMsObjectMother.createMockMsRequest; +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class MsServiceImplTest { + + @Mock + private BaseMicroserviceGateway repository; + + @Mock + private MsInstanceService msInstanceService; + + @Spy + private MsServiceImpl baseMsService = new MsServiceImpl(); + + @BeforeEach + void setup() throws Exception{ + baseMsService.setRepository(repository); + baseMsService.setMsInstanceService(msInstanceService); + } + + /**GET MICROSERVICE TESTS*/ + @Test + void getAll() { + //arrange + BaseMicroservice ms1 = new BaseMicroservice(); + ms1.setName("HelloWorld1"); + BaseMicroservice ms2 = new BaseMicroservice(); + ms2.setName("HelloWorld2"); + + when(repository.findAll()).thenReturn(Arrays.asList(ms1, ms2)); + + //act + List<BaseMicroservice> microservices = baseMsService.getAllMicroservices(); + + //assert + assertThat(microservices).hasSizeGreaterThan(0); + } + + @Test + void test_getMicroserviceById() throws Exception{ + BaseMicroservice expectedMicroservice = BaseMsObjectMother.createMockMsObject(); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.of(expectedMicroservice)); + + BaseMicroservice resultMicroservice = baseMsService.getMicroserviceById(baseMsId); + + assertThat(resultMicroservice).isEqualTo(expectedMicroservice); + verify(repository, times(1)).findById(baseMsId); + } + + @Test + void test_ifMicroserviceNotFoundRaiseException() throws Exception{ + BaseMicroservice expectedMicroservice = BaseMsObjectMother.createMockMsObject(); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.empty()); + + assertThatExceptionOfType(BaseMicroserviceNotFoundException.class).isThrownBy( + () -> baseMsService.getMicroserviceById(baseMsId) + ); + } + + /**CREATE MICROSERVICE TESTS*/ + @Test + void createMicroservice() { + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice expected = createMockMsObject(); + + when(repository.save(any())).thenReturn(expected); + + //act + BaseMicroservice actual = baseMsService.createMicroservice(microserviceRequest); + + //assert + assertThat(actual.getMetadata().getCreatedBy()).isEqualTo(microserviceRequest.getUser()); + assertThat(actual.getMetadata().getUpdatedBy()).isEqualTo(microserviceRequest.getUser()); + } + + @Test + void AddingMsWithDuplicateName_shouldThrowException() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice existedMicroservice = createMockMsObject(); + + when(repository.findByName(any())).thenReturn(Optional.of(existedMicroservice)); + + //act/assert + assertThatThrownBy(() -> baseMsService.createMicroservice((microserviceRequest))) + .isInstanceOf(ResourceConflictException.class) + .hasMessage(MICROSERVICE_NAME_CONFLICT_MESSAGE); + } + @Test + void AddingMsWithDuplicateTag_shouldThrowException() throws Exception{ + //arrange + MicroserviceCreateRequest microserviceRequest = createMockMsRequest(); + BaseMicroservice existedMicroservice = createMockMsObject(); + + when(repository.findByTag(any())).thenReturn(Optional.of(existedMicroservice)); + + //act/assert + assertThatThrownBy(() -> baseMsService.createMicroservice((microserviceRequest))) + .isInstanceOf(ResourceConflictException.class) + .hasMessage(MICROSERVICE_TAG_CONFLICT_MESSAGE); + } + + /**UPDATE MICROSERVICE TESTS*/ + @Test + void test_updateMicroservice() throws Exception{ + MicroserviceUpdateRequest updateRequest = createUpdateMsRequest(); + + BaseMicroservice msToBeUpdated = BaseMsObjectMother.createMockMsObject(); + Date updateTimeBefore = new Date(msToBeUpdated.getMetadata().getUpdatedOn().getTime()); + + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + when(repository.findById(baseMsId)).thenReturn(Optional.of(msToBeUpdated)); + + baseMsService.updateMicroservice(baseMsId, updateRequest); + + //assert + assertUpdatedMsFileds(updateRequest, msToBeUpdated, updateTimeBefore); + verify(baseMsService, times(1)).getMicroserviceById(baseMsId); + verify(msInstanceService, times(1)).updateMicroserviceReference(msToBeUpdated); + verify(repository, times(1)).save(msToBeUpdated); + } + +/* @Test + void test_msTagChangeShouldNotBeAllowed() throws Exception{ + MicroserviceCreateRequest updateRequest = new MicroserviceCreateRequest(); + updateRequest.setTag("updateTag"); + String baseMsId = BaseMsObjectMother.BASE_MS_ID; + + assertThatExceptionOfType(OperationNotAllowedException.class).isThrownBy( + () -> baseMsService.updateMicroservice(baseMsId, updateRequest) + ); + }*/ + + private void assertUpdatedMsFileds(MicroserviceUpdateRequest updateRequest, BaseMicroservice msToBeUpdated, + Date updateTimeBefore) { + assertThat(msToBeUpdated.getName()).isEqualTo(updateRequest.getName()); + assertThat(msToBeUpdated.getLocation()).isEqualTo(updateRequest.getLocation()); + assertThat(msToBeUpdated.getServiceName()).isEqualTo(updateRequest.getServiceName()); + assertThat(msToBeUpdated.getNamespace()).isEqualTo(updateRequest.getNamespace()); + assertThat(msToBeUpdated.getType()).isEqualTo(updateRequest.getType()); + + assertThat(msToBeUpdated.getMetadata().getUpdatedBy()).isEqualTo(updateRequest.getUser()); + assertThat(msToBeUpdated.getMetadata().getUpdatedOn()).isNotEqualTo(updateTimeBefore); + + assertThat(msToBeUpdated.getMetadata().getNotes()).isEqualTo(updateRequest.getMetadata().get("notes")); + assertThat(msToBeUpdated.getMetadata().getLabels()).isEqualTo(updateRequest.getMetadata().get("labels")); + } + + private MicroserviceUpdateRequest createUpdateMsRequest() { + MicroserviceUpdateRequest updateRequest = new MicroserviceUpdateRequest(); + updateRequest.setName("updatedName"); + updateRequest.setLocation(BaseMsLocation.EDGE); + updateRequest.setServiceName("updatedServiceName"); + updateRequest.setNamespace("updatedNameSpace"); + updateRequest.setType(BaseMsType.ANALYTIC); + updateRequest.setUser("updater"); + + Map<String, Object> metadata = new HashMap(); + metadata.put("notes", "updatedNote"); + metadata.put("labels", Arrays.asList("updatedLabel1", "updatedLabel2")); + updateRequest.setMetadata(metadata); + return updateRequest; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java new file mode 100644 index 0000000..dff0727 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/SpecificationServiceTest.java @@ -0,0 +1,103 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.SpecificationRequest; +import org.onap.dcaegen2.platform.mod.model.specification.Specification; +import org.onap.dcaegen2.platform.mod.model.specification.SpecificationStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationGateway; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationServiceImpl; +import org.onap.dcaegen2.platform.mod.web.service.specification.SpecificationValidatorService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.MS_INSTANCE_ID; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getMockSpecification; +import static org.onap.dcaegen2.platform.mod.objectmothers.SpecificationObjectMother.getSpecificationRequest; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith({MockitoExtension.class}) +public class SpecificationServiceTest { + + private SpecificationServiceImpl service; + + @Mock + private SpecificationGateway specRepo; + + @Mock + private MsInstanceService msInstanceService; + + @Mock + private SpecificationValidatorService validatorService; + + @BeforeEach + void setUp() { + service = new SpecificationServiceImpl(); + service.setMsInstanceService(msInstanceService); + service.setSpecificationValidatorService(validatorService); + service.setSpecificationGateway(specRepo); + } + + @Test + void createSpecificationTest() throws Exception { + //given + SpecificationRequest request = getSpecificationRequest(); + Specification specFromRepo = getMockSpecification(DeploymentType.K8S); + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + when(specRepo.save(any(Specification.class))).thenReturn(specFromRepo); + + //when + Specification spec = service.createSpecification(MS_INSTANCE_ID, request); + + //then + assertThatFieldsAreCorrect(request, spec); + verifyCalls(request, msInstance); + + } + + private void assertThatFieldsAreCorrect(SpecificationRequest request, Specification spec) { + assertThat(spec.getStatus()).isEqualTo(SpecificationStatus.ACTIVE); + assertThat(spec.getSpecContent()).isEqualTo(request.getSpecContent()); + assertThat(spec.getPolicyJson()).isEqualTo(request.getPolicyJson()); + assertThat(spec.getType()).isEqualTo(request.getType()); + assertThat(spec.getMetadata().get("createdBy")).isEqualTo(request.getUser()); + assertThat(spec.getMetadata().get("createdOn")).isNotNull(); + assertThat(spec.getMsInstanceInfo()).isNotNull(); + } + + private void verifyCalls(SpecificationRequest request, MsInstance msInstance) { + verify(msInstanceService, times(1)).getMsInstanceById(MS_INSTANCE_ID); + verify(validatorService, times(1)).validateSpecForRelease(request, msInstance.getRelease()); + verify(specRepo, times(2)).save(any(Specification.class)); + verify(msInstanceService, times(1)).updateMsInstance(msInstance); + } +} diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java new file mode 100644 index 0000000..12a7dd2 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/ArtifactFileNameCreatorTest.java @@ -0,0 +1,89 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.specification.DeploymentType; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.BlueprintFileNameCreateException; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; + +class ArtifactFileNameCreatorTest { + + private ArtifactFileNameCreator fileNameCreator; + + @BeforeEach + void setUp() { + fileNameCreator = new ArtifactFileNameCreator(); + } + + @Test + void test_createCorrectBlueprintFileName() throws Exception{ + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + String expectedName = createExpectedName(msInstance); + + //act + String fileName = fileNameCreator.createFileName(msInstance, 1); + + //assert + Assertions.assertThat(fileName).isEqualTo(expectedName); + } + + @Test + void test_missingTagForFileNameCreation_ShouldRaiseException() throws Exception{ + + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + msInstance.setMsInfo(new HashMap<>()); + + Assertions.assertThatExceptionOfType(BlueprintFileNameCreateException.class).isThrownBy( + () -> fileNameCreator.createFileName(msInstance, 1) + ); + } + + @Test + void test_missingSpecForFileNameCreation_ShouldRaiseException() throws Exception{ + + //arrange + MsInstance msInstance = MsInstanceObjectMother.createMsInstance(); + msInstance.setActiveSpec(null); + + Assertions.assertThatExceptionOfType(BlueprintFileNameCreateException.class).isThrownBy( + () -> fileNameCreator.createFileName(msInstance, 1) + ); + } + + + private String createExpectedName(MsInstance msInstance) { + String fileName = MsInstanceObjectMother.BASE_MS_TAG + "_" + + DeploymentType.DOCKER.toString().toLowerCase() + "_" + + msInstance.getRelease() + "_" + + "1" + + ".yaml"; + + return fileName; + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java new file mode 100644 index 0000000..749d8b1 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactServiceImplTest.java @@ -0,0 +1,250 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.DeploymentArtifactNotFound; +import org.onap.dcaegen2.platform.mod.model.microserviceinstance.MsInstance; +import org.onap.dcaegen2.platform.mod.model.restapi.DeploymentArtifactPatchRequest; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother; +import org.onap.dcaegen2.platform.mod.web.service.microserviceinstance.MsInstanceService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.onap.dcaegen2.platform.mod.objectmothers.MsInstanceObjectMother.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class DeploymentArtifactServiceImplTest { + + private DeploymentArtifactServiceImpl deploymentArtifactService; + + @Mock + private MsInstanceService msInstanceService; + + @Mock + private DeploymentArtifactGeneratorStrategy deploymentArtifactGeneratorStrategy; + + @Mock + private DeploymentArtifactGateway repository; + + @Mock + private ArtifactFileNameCreator fileNameCreator; + + @Mock + private DeploymentArtifactStatusChangeHandler deploymentArtifactStatusChangeHandler; + + private MsInstance msInstance; + + DeploymentArtifact deploymentArtifact; + + @BeforeEach + void setUp() { + //Initiated the deployment artifact core with mocks + deploymentArtifactService = new DeploymentArtifactServiceImpl(); + deploymentArtifactService.setDeploymentArtifactGeneratorStrategy(deploymentArtifactGeneratorStrategy); + deploymentArtifactService.setDeploymentArtifactGateway(repository); + deploymentArtifactService.setMsInstanceService(msInstanceService); + deploymentArtifactService.setFileNameCreator(fileNameCreator); + deploymentArtifactService.setStatusChangeHandler(deploymentArtifactStatusChangeHandler); + } + + private void setupMockBehaviours() { + //Mock methods + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + msInstance = MsInstanceObjectMother.createMsInstance(); + + when(deploymentArtifactGeneratorStrategy.generateForRelease(msInstance.getActiveSpec(), msInstance.getRelease())) + .thenReturn(DeploymentArtifactObjectMother.createBlueprintResponse()); + when(repository.save(any())).thenReturn(deploymentArtifact); + when(fileNameCreator.createFileName(any(MsInstance.class), any(Integer.class))).thenReturn(BASE_MS_TAG + "_" + + msInstance.getActiveSpec().getType().toString().toLowerCase() + "_" + msInstance.getRelease() + "_1.yaml"); + } + + @Test + void test_getAllDeploymentArtifactInstance() throws Exception{ + when(repository.findAll()).thenReturn(Arrays.asList(deploymentArtifact)); + List<DeploymentArtifact> deployments = deploymentArtifactService.getAllDeploymentArtifacts(); + assertThat(deployments.size()).isEqualTo(1); + } + + @Test + void test_GenerateBlueprint_shouldReturnCorrectBlueprint() throws Exception{ + + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + + //act + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + + //assert + verify(msInstanceService, atLeastOnce()).getMsInstanceById(MS_INSTANCE_ID); + verify(repository, times(1)).save(any()); + assertThat(resultDAO.getContent()).contains("tosca_definitions_version"); + assertThat(resultDAO.getId()).isNotEmpty(); + assertThat(resultDAO.getVersion()).isEqualTo(1); + assertThat(resultDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.IN_DEV); + assertThat(resultDAO.getMsInstanceInfo().getId()).isEqualTo(MS_INSTANCE_ID); + assertThat(resultDAO.getMsInstanceInfo().getName()).isEqualTo(msInstance.getName()); + assertThat(resultDAO.getMsInstanceInfo().getRelease()).isEqualTo(msInstance.getRelease()); + assertThat(resultDAO.getSpecificationInfo().get("id")).isNotNull(); + assertThat(resultDAO.getMetadata().get("createdBy")).isEqualTo(USER); + + } + + @Test + void test_deploymentVersionIsInitatedWith1() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(resultDAO.getVersion()).isEqualTo(1); + } + + @Test + void test_deploymentVersionIncrementsForEachAddForAnInstance() throws Exception{ + setupMockBehaviours(); + MsInstance msInstanceWithRef = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstanceWithRef); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + + assertThat(resultDAO.getVersion()).isEqualTo(2); + } + + @Test + void test_deploymentArtifactRefAddedToMsInstanceForFirstTime() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(msInstance.getDeploymentArtifactsInfo().getMostRecentVersion()).isEqualTo(1); + + List<String> deploymentArtifactList = msInstance.getDeploymentArtifactsInfo().getDeploymentArtifacts(); + assertThat(deploymentArtifactList.size()).isEqualTo(1); + assertThat(deploymentArtifactList.get(0)).isEqualTo(resultDAO.getId()); + } + + @Test + void test_deploymentArtifactRefAddedToMsInstanceForSecondTime() throws Exception{ + setupMockBehaviours(); + MsInstance msInstanceWithRef = MsInstanceObjectMother.getMsInstanceWithExistingDeploymentArtifactRef(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstanceWithRef); + + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + assertThat(msInstanceWithRef.getDeploymentArtifactsInfo().getMostRecentVersion()).isEqualTo(2); + + List<String> deploymentArtifactList = msInstanceWithRef.getDeploymentArtifactsInfo().getDeploymentArtifacts(); + assertThat(deploymentArtifactList.size()).isEqualTo(2); + assertThat(deploymentArtifactList.get(1)).isEqualTo(resultDAO.getId()); + } + + @Test + void test_ifMsInstanceIsPersistedAfterDeploymentArtifactCreation() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + verify(msInstanceService, times(1)).updateMsInstance(msInstance); + } + + @Test + void test_blueprintFileNameValidation() throws Exception{ + setupMockBehaviours(); + when(msInstanceService.getMsInstanceById(MS_INSTANCE_ID)).thenReturn(msInstance); + DeploymentArtifact resultDAO = deploymentArtifactService.generateDeploymentArtifact(MS_INSTANCE_ID, USER); + System.out.println(resultDAO.getFileName()); + assertThat(resultDAO.getFileName().contains(BASE_MS_TAG)).isTrue(); + } + + @Test + void test_updateStatusForDeploymentArtifact() throws Exception{ + //arrange + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + + DeploymentArtifactPatchRequest dtoWithStatus = new DeploymentArtifactPatchRequest(); + dtoWithStatus.setStatus(DeploymentArtifactStatus.NOT_NEEDED); + + when(repository.findById("id-123")).thenReturn(Optional.of(deploymentArtifact)); + + //Mocking void method from DeploymentArtifactStatusChangeHandler + doAnswer(invocation -> { + deploymentArtifact.setStatus(DeploymentArtifactStatus.NOT_NEEDED); + return null; + }).when(deploymentArtifactStatusChangeHandler).handleStatusChange(dtoWithStatus.getStatus(), deploymentArtifact); + + //act + deploymentArtifactService.updateDeploymentArtifact("id-123", dtoWithStatus, "user1"); + + //assert + assertThat(deploymentArtifact.getStatus()).isEqualTo(DeploymentArtifactStatus.NOT_NEEDED); + assertThat(deploymentArtifact.getMetadata().get("updatedBy")).isEqualTo("user1"); + assertThat(deploymentArtifact.getMetadata().get("updatedOn")).isNotNull(); + + verify(deploymentArtifactStatusChangeHandler, times(1)).handleStatusChange(dtoWithStatus.getStatus(), + deploymentArtifact); + verify(msInstanceService, times(1)). + updateStatusBasedOnDeploymentArtifactsStatuses(deploymentArtifact.getMsInstanceInfo().getId()); + verify(repository, times(1)).save(deploymentArtifact); + } + + @Test + void test_findDeploymentArtifactById() throws Exception{ + //arrange + deploymentArtifact = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + when(repository.findById("id-123")).thenReturn(Optional.of(deploymentArtifact)); + + DeploymentArtifact result = deploymentArtifactService.findDeploymentArtifactById("id-123"); + + assertThat(result).isEqualTo(deploymentArtifact); + } + + @Test + void test_findByIdWithInvalidId() throws Exception{ + when(repository.findById("invalid-id")).thenReturn(Optional.empty()); + assertThatExceptionOfType(DeploymentArtifactNotFound.class).isThrownBy( + () -> deploymentArtifactService.findDeploymentArtifactById("invalid-id")); + } + + @Test + void test_deleteDeploymentArtifact() throws Exception{ + DeploymentArtifact deploymentArtifact = + DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + String id = deploymentArtifact.getId(); + + when(repository.findById(id)).thenReturn(Optional.of(deploymentArtifact)); + + deploymentArtifactService.deleteDeploymentArtifact(id); + verify(msInstanceService, times(1)) + .removeDeploymentArtifactFromMsInstance(deploymentArtifact); + verify(repository, times(1)).deleteById(id); + } +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java new file mode 100644 index 0000000..5e9acfa --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/DeploymentArtifactStatusChangeHandlerTest.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.model.exceptions.deploymentartifact.StatusChangeNotValidException; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class DeploymentArtifactStatusChangeHandlerTest { + + DeploymentArtifactStatusChangeHandler artifactStatusChangeHandler; + + @Mock + DeploymentArtifactService deploymentArtifactService; + + @BeforeEach + void setUp() { + artifactStatusChangeHandler = new DeploymentArtifactStatusChangeHandler(); + artifactStatusChangeHandler.setDeploymentArtifactService(deploymentArtifactService); + } + + @Test + void test_DevCompleteToNotNeeded() throws Exception{ + //arrange + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true); + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + String msInstaneId = givenDAO.getMsInstanceInfo().getId(); + + when(deploymentArtifactService.findByMsInstanceId(msInstaneId)).thenReturn(mockDeploymentArticats); + + //act + artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.NOT_NEEDED, givenDAO); + + assertThat(givenDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.NOT_NEEDED); +// verify(msInstanceStatusChangeHandler, times(1)) +// .updateStatusBasedOnDeploymentArtifactsStatuses(msInstaneId); + + } + + @Test + void test_ValidateIfArtifactWithDevCompleteStatusNotFoundForTheSameInstance() throws Exception{ + //arrange + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + String msInstaneId = givenDAO.getMsInstanceInfo().getId(); + + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(false); + when(deploymentArtifactService.findByMsInstanceId(msInstaneId)).thenReturn(mockDeploymentArticats); + + //act + artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.DEV_COMPLETE, givenDAO); + + //assert + assertThat(givenDAO.getStatus()).isEqualTo(DeploymentArtifactStatus.DEV_COMPLETE); + verify(deploymentArtifactService, times(1)). + findByMsInstanceId(givenDAO.getMsInstanceInfo().getId()); +// verify(msInstanceStatusChangeHandler, times(1)) +// .updateStatusBasedOnDeploymentArtifactsStatuses(msInstaneId); + + } + + @Test + void DoesntValidateIfArtifactWithDevCompleteStatusAlreadyExistsForTheSameInstance() throws Exception{ + //arrange + DeploymentArtifact givenDAO = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + List<DeploymentArtifact> mockDeploymentArticats = DeploymentArtifactObjectMother.createMockDeploymentArtifactsWithDifferentStatuses(true); + when(deploymentArtifactService.findByMsInstanceId("id-123")).thenReturn(mockDeploymentArticats); + + //act/assert + assertThatExceptionOfType(StatusChangeNotValidException.class).isThrownBy( + () -> artifactStatusChangeHandler.handleStatusChange(DeploymentArtifactStatus.DEV_COMPLETE, givenDAO) + ); + + } + +}
\ No newline at end of file diff --git a/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java new file mode 100644 index 0000000..bc1a3a0 --- /dev/null +++ b/mod2/catalog-service/src/test/java/org/onap/dcaegen2/platform/mod/web/service/deploymentartifact/SearchDeploymentArtifactsTest.java @@ -0,0 +1,90 @@ +/* + * ============LICENSE_START======================================================= + * org.onap.dcae + * ================================================================================ + * Copyright (c) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.dcaegen2.platform.mod.web.service.deploymentartifact; + +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifact; +import org.onap.dcaegen2.platform.mod.model.deploymentartifact.DeploymentArtifactStatus; +import org.onap.dcaegen2.platform.mod.objectmothers.DeploymentArtifactObjectMother; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class SearchDeploymentArtifactsTest { + + private DeploymentArtifactServiceImpl service; + + @Mock + private DeploymentArtifactGateway repository; + + private DeploymentArtifact artifact_1; + private DeploymentArtifact artifact_2; + private DeploymentArtifact artifact_3; + + @BeforeEach + void setUp() { + service = new DeploymentArtifactServiceImpl(); + service.setDeploymentArtifactGateway(repository); + + //given + artifact_1 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.IN_DEV); + artifact_1.getMsInstanceInfo().setRelease("2008"); + artifact_2 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + artifact_2.getMsInstanceInfo().setRelease("2010"); + artifact_3 = DeploymentArtifactObjectMother.createDeploymentArtifactDAO(DeploymentArtifactStatus.DEV_COMPLETE); + artifact_3.getMsInstanceInfo().setRelease("2008"); + + } + +// @Test +// void findArtifacts_filteredWithRelease() throws Exception { +// List<DeploymentArtifact> artifacts = Arrays.asList(artifact_1, artifact_3); +// when(repository.findByReleaseOrStatusOfMsInstance("2008", null)).thenReturn(artifacts); +// +// //when +// DeploymentArtifactSearch search = new DeploymentArtifactSearch(); +// DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); +// filter.setRelease("2008"); +// search.setFilter(filter); +// +// List<DeploymentArtifact> result = core.searchDeploymentArtifacts(search); +// +// //assert +// assertThat(result.size()).isEqualTo(2); +// } +// +// @Test +// void findArtifacts_filteredWithStatus() throws Exception{ +// List<DeploymentArtifact> artifacts = Arrays.asList(artifact_2, artifact_3); +// when(repository.findByReleaseOrStatusOfMsInstance(null, DeploymentArtifactStatus.DEV_COMPLETE)) +// .thenReturn(artifacts); +// +// DeploymentArtifactSearch search = new DeploymentArtifactSearch(); +// DeploymentArtifactFilter filter = new DeploymentArtifactFilter(); +// filter.setStatus(DeploymentArtifactStatus.DEV_COMPLETE); +// search.setFilter(filter); +// +// List<DeploymentArtifact> result = core.searchDeploymentArtifacts(search); +// assertThat(result.size()).isEqualTo(2); +// +// } +} |