From 6ad41e3ccd398a2721f41ad61c80b7bb03f7d127 Mon Sep 17 00:00:00 2001 From: Ittay Stern Date: Mon, 31 Dec 2018 17:21:27 +0200 Subject: Merge from ECOMP's repository Main Features -------------- - Async-Instantiation jobs mechanism major update; still WIP (package `org.onap.vid.job`) - New features in View/Edit: Activate fabric configuration; show related networks; soft delete - Support AAI service-tree traversal (`AAIServiceTree`) - In-memory cache for SDC models and certain A&AI queries (`CacheProviderWithLoadingCache`) - Upgrade TOSCA Parser and add parsing options; fix malformed TOSCA models - Resolve Cloud-Owner values for MSO - Pass X-ONAP headers to MSO Infrastructure -------------- - Remove codehaus' jackson mapper; use soley fasterxml 2.9.7 - Surefire invokes both TestNG and JUnit tests - Support Kotlin source files - AaiController2 which handles errors in a "Spring manner" - Inline generated-sources and remove jsonschema2pojo Quality -------- - Cumulative bug fixes (A&AI API, UI timeouts, and many more) - Many Sonar issues cleaned-up - Some unused classes removed - Minor changes in vid-automation project, allowing some API verification to run Hard Merges ------------ - HTTP Clients (MSO, A&AI, WebConfig, OutgoingRequestHeadersTest) - Moved `package org.onap.vid.controllers` to `controller`, without plural -- just to keep semantic sync with ECOMP. Reference commit in ECOMP: 3d1141625 Issue-ID: VID-378 Change-Id: I9c8d1e74caa41815891d441fc0760bb5f29c5788 Signed-off-by: Ittay Stern --- .../org/onap/vid/controller/AaiControllerTest.java | 12 +- ...ServiceInstanceStandardQueryControllerTest.java | 120 ++++++ .../controller/ChangeManagementControllerTest.java | 448 +++++++++++++++++++++ .../controller/ClientCredentialsFilterTest.java | 1 - .../vid/controller/HealthCheckControllerTest.java | 101 +++++ .../org/onap/vid/controller/LocalWebConfig.java | 23 +- .../onap/vid/controller/LoggerControllerTest.java | 49 +++ .../vid/controller/MaintenanceControllerTest.java | 339 ++++++++++++++++ .../onap/vid/controller/MsoControllerNewTest.java | 394 ++++++++++++++++++ .../org/onap/vid/controller/MsoControllerTest.java | 17 +- .../vid/controller/PropertyControllerTest.java | 39 ++ .../controller/RoleGeneratorControllerTest.java | 26 ++ .../vid/controller/ServicePermissionsTest.java | 48 +++ .../onap/vid/controller/ToscaParserMockHelper.java | 37 +- .../onap/vid/controller/VersionControllerTest.java | 31 ++ .../org/onap/vid/controller/VidControllerTest.java | 204 ++++++++++ .../vid/controller/ViewEditSubControllerTest.java | 46 +++ 17 files changed, 1894 insertions(+), 41 deletions(-) create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java (limited to 'vid-app-common/src/test/java/org/onap/vid/controller') diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java index 4076b3de9..d86ab78ab 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -7,9 +7,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.vid.aai.AaiResponseTranslator; -import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; -import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; -import org.onap.vid.controllers.AaiController; import org.onap.vid.services.AaiService; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -19,7 +16,6 @@ import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; - public class AaiControllerTest { @InjectMocks @@ -36,9 +32,9 @@ public class AaiControllerTest { @Test public void getPortMirroringConfigData_givenThreeIds_ReturnsThreeResults() { - final PortMirroringConfigDataOk toBeReturnedForA = new PortMirroringConfigDataOk("foobar"); - final PortMirroringConfigDataError toBeReturnedForB = new PortMirroringConfigDataError("foo", "{ baz: qux }"); - final PortMirroringConfigDataOk toBeReturnedForC = new PortMirroringConfigDataOk("corge"); + final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForA = new AaiResponseTranslator.PortMirroringConfigDataOk("foobar"); + final AaiResponseTranslator.PortMirroringConfigDataError toBeReturnedForB = new AaiResponseTranslator.PortMirroringConfigDataError("foo", "{ baz: qux }"); + final AaiResponseTranslator.PortMirroringConfigDataOk toBeReturnedForC = new AaiResponseTranslator.PortMirroringConfigDataOk("corge"); Mockito .doReturn(toBeReturnedForA) @@ -57,4 +53,4 @@ public class AaiControllerTest { -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java new file mode 100644 index 000000000..9a5ee3ecb --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java @@ -0,0 +1,120 @@ +package org.onap.vid.controller; + +import org.mockito.Answers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.util.ServiceInstanceStandardQuery; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.model.Service; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.VidNotions.ModelCategory; +import org.onap.vid.properties.Features; +import org.onap.vid.services.VidService; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.UUID; + +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.*; + +public class AaiServiceInstanceStandardQueryControllerTest { + + @InjectMocks + private AaiServiceInstanceStandardQueryController aaiServiceInstanceStandardQueryController; + + @Mock + private FeatureManager featureManager; + + @Mock + private VidService sdcService; + + @Mock(answer = Answers.RETURNS_MOCKS) + private ServiceInstanceStandardQuery serviceInstanceStandardQuery; + + //Don't use initMocks with @BeforeMethod + //because AaiServiceInstanceStandardQueryController contains final members that can not be injected twice + //See https://stackoverflow.com/questions/20046210/mockito-injectmocks-strange-behaviour-with-final-fields?answertab=active#tab-top + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @AfterMethod + public void resetMocks() { + reset(sdcService, featureManager, serviceInstanceStandardQuery); + } + + @Test + public void getNetworksToVlansByServiceInstance_given5G_PROVIDER_NETWORK_aaiIsAccessed() throws AsdcCatalogException { + // - turn on FLAG_PRESENT_PROVIDER_NETWORKS + // - mock an model with 5G_PROVIDER_NETWORK + // - request it's AAI network->vlan mapping + // - assert that AAI was accessed + + when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true); + + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL, randomModelUuid); + + doGetNetworksToVlansByServiceInstance(randomModelUuid); + + verify(serviceInstanceStandardQuery).fetchServiceInstance(any(), any(), any()); + } + + @Test + public void getNetworksToVlansByServiceInstance_givenNon5G_PROVIDER_NETWORK_aaiIsNotAccessed() throws AsdcCatalogException { + // - turn on FLAG_PRESENT_PROVIDER_NETWORKS + // - mock an model without 5G_PROVIDER_NETWORK (i.e. OTHER) + // - request it's AAI network->vlan mapping + // - assert that AAI was not accessed + // - empty result was responded + + when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true); + + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.OTHER, randomModelUuid); + + assertThat(doGetNetworksToVlansByServiceInstance(randomModelUuid).serviceNetworks, hasSize(0)); + verifyZeroInteractions(serviceInstanceStandardQuery); + } + + @Test + public void isModelOf5g_givenServiceWithFabricConfiguration_returnTrue() throws AsdcCatalogException { + final UUID randomModelUuid = UUID.randomUUID(); + mockServiceModel(ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL, randomModelUuid, VidNotions.InstantiationUI.SERVICE_WITH_FABRIC_CONFIGURATION); + + assertTrue(aaiServiceInstanceStandardQueryController.isModelOf5g(randomModelUuid)); + } + + private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid) throws AsdcCatalogException { + mockServiceModel(modelCategory, randomModelUuid, VidNotions.InstantiationUI.LEGACY); + } + + private void mockServiceModel(ModelCategory modelCategory, UUID randomModelUuid, VidNotions.InstantiationUI instantiationUI) throws AsdcCatalogException { + ServiceModel mockedModel = mock(ServiceModel.class); + Service mockedService = mock(Service.class); + when(mockedModel.getService()).thenReturn(mockedService); + when(mockedService.getVidNotions()).thenReturn( + new VidNotions(instantiationUI, modelCategory, VidNotions.InstantiationUI.LEGACY) + ); + + when(sdcService.getService(randomModelUuid.toString())).thenReturn(mockedModel); + } + + private AaiServiceInstanceStandardQueryController.VlansByNetworksHierarchy doGetNetworksToVlansByServiceInstance(UUID randomModelUuid) throws AsdcCatalogException { + return aaiServiceInstanceStandardQueryController.getNetworksToVlansByServiceInstance( + new MockHttpServletRequest(), + randomModelUuid, + "my global customer id", + "my service type", + "my instance id"); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java new file mode 100644 index 000000000..420b61ed1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ChangeManagementControllerTest.java @@ -0,0 +1,448 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * 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.vid.controller; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.google.common.collect.ImmutableList; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.vid.changeManagement.*; +import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.model.ExceptionResponse; +import org.onap.vid.mso.rest.InstanceIds; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.rest.RequestStatus; +import org.onap.vid.services.ChangeManagementService; +import org.onap.vid.services.WorkflowService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.multipart.MultipartFile; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.Scanner; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.isA; +import static org.onap.vid.controller.ChangeManagementController.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class ChangeManagementControllerTest { + + private static final String FILE_NAME = "file"; + private static final String GET_VNF_WORKFLOW_RELATION_URL = + "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION; + private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow"; + private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}"; + private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso"; + private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile"; + private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler"; + private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID; + private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION; + private static final String VNFS = "vnfs"; + + private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf"; + private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation"; + private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations"; + private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private ChangeManagementController controller; + private MockMvc mockMvc; + @Mock + private WorkflowService workflowService; + @Mock + private ChangeManagementService changeManagementService; + @Mock + private Response mockResponse; + @Mock + private Response.StatusType statusType; + private ClassLoader classLoader = getClass().getClassLoader(); + private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json"); + private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent( + "get-vnf-workflow-relation-request.json"); + private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json"); + + @Before + public void setUp() { + controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception { + + Collection givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3"); + Collection resultWorkflows = ImmutableList.of("workflow1", "workflow2"); + + given( + workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other)))) + .willReturn(resultWorkflows); + + mockMvc.perform(get(WORKFLOW_URL) + .param(VNFS, StringUtils.join(givenVnfs, ","))) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows))); + } + + @Test + public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue() + throws Exception { + + Collection requests = ImmutableList.of( + createRequest("network-instance-id-1", "status-message-1"), + createRequest("network-instance-id-2", "status-message-2")); + + given(changeManagementService.getMSOChangeManagements()).willReturn(requests); + + mockMvc.perform(get(MSO_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(requests))); + } + + @Test + public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception { + + String vnfName = "vnfName1"; + String jsonBody = "{'param1': 'paramparam'}"; + + given(changeManagementService.doChangeManagement( + argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName))) + .willReturn(ResponseEntity.ok().body(jsonBody)); + + mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName) + .contentType(MediaType.APPLICATION_JSON) + .content(CHANGE_MANAGEMENT_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(jsonBody)); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception { + + String jsonString = "{'param1': 'paramparam'}"; + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + given(changeManagementService + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)))) + .willReturn(jsonString); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isOk()) + .andExpect(content().json(jsonString)); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException() + throws Exception { + + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value()); + given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value()); + given(mockResponse.getStatusInfo()).willReturn(statusType); + + WebApplicationException exception = new WebApplicationException(mockResponse); + + willThrow(exception).given(changeManagementService) + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isNotFound()) + .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); + } + + @Test + public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + + byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8); + MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent); + + RuntimeException exception = new RuntimeException("runtime exception message"); + + willThrow(exception).given(changeManagementService) + .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))); + + mockMvc.perform(MockMvcRequestBuilders + .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL) + .file(file)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception)))); + } + + @Test + public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception { + + ObjectMapper mapper = new ObjectMapper(); + ArrayNode array = mapper.createArrayNode(); + array.add("element1"); + array.add("element2"); + + given(changeManagementService.getSchedulerChangeManagements()).willReturn(array); + + mockMvc.perform(get(SCHEDULER_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(mapper.writeValueAsString(array))); + } + + @Test + public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + String id = "schedule-id-1"; + Pair pair = new ImmutablePair<>("myString", HttpStatus.OK.value()); + + given(changeManagementService.deleteSchedule(id)).willReturn(pair); + + mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) + .andExpect(status().isOk()); + } + + @Test + public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception { + + String id = "schedule-id-1"; + Pair pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value()); + + given(changeManagementService.deleteSchedule(id)).willReturn(pair); + + mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id)) + .andExpect(status().isNotFound()); + } + + @Test + public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + ImmutableList elements = ImmutableList.of("workflow1", "workflow2"); + GetWorkflowsResponse response = new GetWorkflowsResponse(); + response.setWorkflows(elements); + + given(changeManagementService + .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(elements); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception { + + String errorMsg = "not found"; + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg)); + + willThrow(new NotFoundException(errorMsg)) + .given(changeManagementService) + .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isNotFound()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class)); + + mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(); + + given(changeManagementService + .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(response); + + mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + + VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows(); + workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2")); + VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows)); + + given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response); + + mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).getAllVnfWorkflowRelations(); + + mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception { + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc")); + + given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON)))) + .willReturn(response); + + mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() + throws Exception { + VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG)); + + willThrow(new RuntimeException("runtime exception message")) + .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request, + VNF_WORKFLOW_RELATION_REQUEST_JSON))); + + mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL) + .contentType(MediaType.APPLICATION_JSON) + .content(VNF_WORKFLOW_RELATION_REQUEST_JSON)) + .andExpect(status().isInternalServerError()) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + private boolean matches(T request, String expectedJson) { + try { + return objectMapper.writeValueAsString(request).equals(expectedJson); + } catch (JsonProcessingException e) { + System.out.println("Exception occurred: " + e.getMessage()); + } + return false; + } + + private ArgumentMatcher multipartFileMatcher(MultipartFile otherFile) { + return other -> { + try { + return other.getName().equals(otherFile.getName()) + && other.getSize() == otherFile.getSize() + && Arrays.equals(other.getBytes(), otherFile.getBytes()); + } catch (IOException e) { + System.out.println("IOException occurred: " + e.getMessage()); + } + return false; + }; + } + + private Request createRequest(String networkInstanceId, String statusMessage) { + Request req = new Request(); + InstanceIds instanceIds = new InstanceIds(); + instanceIds.setNetworkInstanceId(networkInstanceId); + + RequestStatus requestStatus = new RequestStatus(); + requestStatus.setStatusMessage(statusMessage); + + req.setInstanceIds(instanceIds); + req.setRequestStatus(requestStatus); + + return req; + } + + private String getRequestContent(String filename) { + InputStream inputStream = classLoader.getResourceAsStream(filename); + return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", ""); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java index 113bf2bf9..1b22d7738 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java @@ -19,7 +19,6 @@ import static org.mockito.ArgumentMatchers.any; /** * Created by amichai on 16/05/2018. */ -@Test public class ClientCredentialsFilterTest { @DataProvider diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java new file mode 100644 index 000000000..4f915ec49 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/HealthCheckControllerTest.java @@ -0,0 +1,101 @@ +package org.onap.vid.controller; + +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.dao.FnAppDoaImpl; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.sql.SQLException; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; +import static org.springframework.http.HttpStatus.OK; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class HealthCheckControllerTest { + + private static final String ERROR_MESSAGE = "error message"; + private HealthCheckController testSubject; + private MockMvc mockMvc; + + @Mock + private FnAppDoaImpl fnAppDoa; + + @Before + public void setUp() { + testSubject = new HealthCheckController(fnAppDoa); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(testSubject).build(); + } + + @Test + public void getHealthCheckStatusForIDNS_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { + databaseConnectionEstablished(); + mockMvc.perform(get("/healthCheck") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(OK.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")); + } + + @Test + public void getHealthCheckStatusForIDNS_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { + databaseNotAccessible(); + mockMvc.perform(get("/healthCheck") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); + } + + @Test + public void getHealthCheck_shouldReturnSuccess_whenNoExceptionIsThrown() throws Exception { + databaseConnectionEstablished(); + mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(OK.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check succeeded")) + .andExpect(jsonPath("$.date").isString()); + } + + @Test + public void getHealthCheck_shouldReturnErrorCode_whenExceptionIsThrown() throws Exception { + databaseNotAccessible(); + mockMvc.perform(get("/rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", "userAgent", "requestId") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.statusCode").value(INTERNAL_SERVER_ERROR.value())) + .andExpect(jsonPath("$.detailedMsg").value("health check failed: " + ERROR_MESSAGE)); + } + + @Test + public void getCommitInfo_shouldReturnCommitData_whenCorrectPropertiesFileExists() throws Exception { + mockMvc.perform(get("/commitInfo") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.commitId").value("123")) + .andExpect(jsonPath("$.commitMessageShort").value("Test short commit message")) + .andExpect(jsonPath("$.commitTime").value("1999-09-12T13:48:55+0200")); + } + + private void databaseConnectionEstablished() throws SQLException { + given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) + .willReturn(0); + } + + private void databaseNotAccessible() throws SQLException { + given(fnAppDoa.getProfileCount(anyString(), anyString(), anyString())) + .willThrow(new SQLException(ERROR_MESSAGE)); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java index f63580d27..e0ab34cd1 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java @@ -29,6 +29,7 @@ import org.onap.vid.aai.model.PortDetailsTranslator; import org.onap.vid.aai.util.*; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.asdc.parser.VidNotionsBuilder; import org.onap.vid.services.AaiService; import org.onap.vid.services.AaiServiceImpl; import org.onap.vid.services.VidService; @@ -81,9 +82,14 @@ public class LocalWebConfig { } @Bean - public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider) { + public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext, SystemPropertyHelper systemPropertyHelper, SSLContextProvider sslContextProvider, FeatureManager featureManager) { final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); - return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider); + return new HttpsAuthClient(certFilePath, systemPropertyHelper, sslContextProvider, featureManager); + } + + @Bean + public CacheProvider cacheProvider() { + return new NonCachingCacheProvider(); } @Bean(name = "aaiRestInterface") @@ -92,13 +98,18 @@ public class LocalWebConfig { } @Bean - public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface")AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator) { - return new AaiClient(aaiRestInterface, portDetailsTranslator); + public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface") AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) { + return new AaiClient(aaiRestInterface, portDetailsTranslator, cacheProvider); + } + + @Bean + public VidNotionsBuilder vidNotionsBuilder(FeatureManager featureManager) { + return new VidNotionsBuilder(featureManager); } @Bean - public ToscaParserImpl2 getToscaParser() { - return new ToscaParserImpl2(); + public ToscaParserImpl2 getToscaParser(VidNotionsBuilder vidNotionsBuilder) { + return new ToscaParserImpl2(vidNotionsBuilder); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java new file mode 100644 index 000000000..b79f84ad8 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java @@ -0,0 +1,49 @@ +package org.onap.vid.controller; + +import org.junit.Test; + +import javax.ws.rs.NotAuthorizedException; + + +public class LoggerControllerTest { + + private LoggerController createTestSubject() { + return new LoggerController(); + } + + /*@Test + public void testGetLog() throws Exception { + LoggerController testSubject; + String loggerName = ""; + HttpServletRequest request = null; + Integer limit = 0; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getLog(loggerName, request, limit); + }*/ + + + @Test + public void testNotAuthorizedHandler() throws Exception { + LoggerController testSubject; + NotAuthorizedException e = null; + String result; + + // default test + testSubject = createTestSubject(); + result = testSubject.notAuthorizedHandler(e); + } + + /*@Test + public void testIoExceptionHandler() throws Exception { + LoggerController testSubject; + Exception e = null; + ExceptionResponse result; + + // default test + testSubject = createTestSubject(); + result = testSubject.ioExceptionHandler(e); + }*/ +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java new file mode 100644 index 000000000..6933a2f8d --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MaintenanceControllerTest.java @@ -0,0 +1,339 @@ +package org.onap.vid.controller; + +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright © 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * 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========================================================= + */ + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.log4j.BasicConfigurator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.category.AddCategoryOptionResponse; +import org.onap.vid.category.AddCategoryOptionsRequest; +import org.onap.vid.category.CategoryParameterOptionRep; +import org.onap.vid.category.CategoryParametersResponse; +import org.onap.vid.model.CategoryParameter; +import org.onap.vid.model.CategoryParameterOption; +import org.onap.vid.services.CategoryParameterService; +import org.onap.vid.services.CategoryParameterServiceImpl; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import javax.ws.rs.ForbiddenException; +import java.util.Collections; +import java.util.function.BiFunction; + +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.times; +import static org.onap.vid.model.CategoryParameter.Family.PARAMETER_STANDARDIZATION; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class MaintenanceControllerTest { + + final private String MAINTENANCE_CATEGORY_PATH = "/maintenance/category_parameter"; + final private String CATEGORY_PARAMETER_PATH = MAINTENANCE_CATEGORY_PATH + "/{name}"; + final private String DELETE_CATEGORY_PATH = "/maintenance/delete_category_parameter/{name}"; + + @Mock + private CategoryParameterService service; + private MaintenanceController maintenanceController; + private MockMvc mockMvc; + private ObjectMapper objectMapper; + + @Before + public void setUp() { + maintenanceController = new MaintenanceController(service); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(maintenanceController).build(); + objectMapper = new ObjectMapper(); + } + + @Test + public void addCategoryOptions_shouldReturnMultiStatus_whenErrorsExist() throws Exception { + String categoryName = "catName1"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option", "second option"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( + ImmutableList.of("error one", "error two")); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willReturn(addCategoryOptionResponse); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isMultiStatus()) + .andExpect( + content().json(objectMapper + .writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void addCategoryOptions_shouldReturnOk_whenNoErrorsExist() throws Exception { + String categoryName = "catName2"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option", "second option", "third option"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willReturn(addCategoryOptionResponse); + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isOk()) + .andExpect(content().json( + objectMapper.writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void addCategoryOptions_shouldReturnNotFound_whenUnfoundedCategoryExceptionIsThrown() throws Exception { + String unfoundedMsg = "unfounded category exception message"; + String categoryName = "catName3"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("first option"); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); + } + + @Test + public void addCategoryOptions_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName13"; + AddCategoryOptionsRequest req = new AddCategoryOptionsRequest(); + req.options = ImmutableList.of("option second", "first option"); + + given(service.createCategoryParameterOptions(eq(categoryName), argThat(requestMatcher(req)))) + .willThrow(new RuntimeException()); + + prepareRequestExpectations(MockMvcRequestBuilders::post, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(req)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void updateNameForOption_shouldReturnMultiStatus_whenErrorsExist() throws Exception { + String categoryName = "catName4"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id1", "name1"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse( + ImmutableList.of("error one", "error two")); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willReturn(addCategoryOptionResponse); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isMultiStatus()) + .andExpect( + content().json(objectMapper + .writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void updateNameForOption_shouldReturnOk_whenNoErrorsExist() throws Exception { + String categoryName = "catName5"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id2", "name2"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willReturn(addCategoryOptionResponse); + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isOk()) + .andExpect(content().json( + objectMapper.writeValueAsString(addCategoryOptionResponse))); + } + + @Test + public void updateNameForOption_shouldReturnForbidden_whenForbiddenExceptionIsThrown() throws Exception { + String categoryName = "catName6"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id3", "name3"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new ForbiddenException()); + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isForbidden()) + .andExpect(content().json( + objectMapper + .writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of("HTTP 403 Forbidden"))))); + } + + @Test + public void updateNameForOption_shouldReturnNotFound_whenUnfoundedIsThrown() throws Exception { + String unfoundedOptionMsg = "unfounded category option exception message"; + String categoryName = "catName7"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id4", "name4"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryOptionException(unfoundedOptionMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedOptionMsg))))); + } + + @Test + public void updateNameForOption_shouldReturnConflict_whenAlreadyExistOptionNameIsThrown() throws Exception { + String conflictMsg = "already exists option name exception message"; + String categoryName = "catName8"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id5", "name5"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new CategoryParameterServiceImpl.AlreadyExistOptionNameException(conflictMsg)); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isConflict()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(conflictMsg))))); + } + + @Test + public void updateNameForOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName18"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id6", "name6"); + + given(service + .updateCategoryParameterOption(eq(categoryName), argThat(requestMatcher(categoryParameterOptionRep)))) + .willThrow(new RuntimeException()); + + prepareRequestExpectations(MockMvcRequestBuilders::put, CATEGORY_PARAMETER_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOptionRep)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void getCategoryParameter_shouldReturnExistingMap() throws Exception { + CategoryParametersResponse categoryParametersResponse = + new CategoryParametersResponse( + ImmutableMap.of( + "key1", ImmutableList.of( + new CategoryParameterOptionRep("testId", "testName")))); + + given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) + .willReturn(categoryParametersResponse); + + mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) + .param("familyName", "PARAMETER_STANDARDIZATION") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(categoryParametersResponse))); + } + + @Test + public void getCategoryParameter_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + given(service.getCategoryParameters(PARAMETER_STANDARDIZATION)) + .willThrow(new RuntimeException()); + + mockMvc.perform(get(MAINTENANCE_CATEGORY_PATH) + .param("familyName", "PARAMETER_STANDARDIZATION") + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isInternalServerError()); + } + + @Test + public void deleteCategoryOption_shouldReturnOk_whenNoExceptionIsThrown() throws Exception { + String categoryName = "catName9"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id1", "name1", + new CategoryParameter()); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isOk()); + + then(service).should(times(1)) + .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + } + + @Test + public void deleteCategoryOption_shouldReturnNotFound_whenUnfoundedExceptionIsThrown() throws Exception { + String unfoundedMsg = "unfounded category exception message"; + String categoryName = "catName10"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id2", "name2", + new CategoryParameter()); + + willThrow(new CategoryParameterServiceImpl.UnfoundedCategoryException(unfoundedMsg)) + .given(service).deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isNotFound()) + .andExpect(content().json( + objectMapper.writeValueAsString(new AddCategoryOptionResponse(ImmutableList.of(unfoundedMsg))))); + } + + @Test + public void deleteCategoryOption_shouldReturnInternalServerError_whenExceptionIsThrown() throws Exception { + String categoryName = "catName19"; + CategoryParameterOption categoryParameterOption = new CategoryParameterOption("id3", "name3", + new CategoryParameter()); + + willThrow(new RuntimeException()).given(service) + .deleteCategoryOption(eq(categoryName), argThat(requestMatcher(categoryParameterOption))); + + prepareRequestExpectations(MockMvcRequestBuilders::delete, DELETE_CATEGORY_PATH, categoryName, + objectMapper.writeValueAsString(categoryParameterOption)) + .andExpect(status().isInternalServerError()); + } + + private ArgumentMatcher requestMatcher(T t) { + return new ArgumentMatcher() { + @Override + public boolean matches(Object o) { + return t.equals(o); + } + }; + } + + private ResultActions prepareRequestExpectations( + BiFunction httpMethod, + String path, String name, String jsonContent) throws Exception { + return mockMvc.perform(httpMethod.apply(path, name) + .contentType(MediaType.APPLICATION_JSON) + .content(jsonContent)); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java new file mode 100644 index 000000000..747783d52 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java @@ -0,0 +1,394 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; +import org.onap.vid.services.CloudOwnerServiceImpl; +import org.springframework.http.ResponseEntity; +import org.togglz.core.manager.FeatureManager; + +import javax.servlet.http.HttpServletRequest; + +import static org.mockito.Mockito.mock; + +public class MsoControllerNewTest { + + private MsoController createTestSubject() { + try { + return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class),mock(FeatureManager.class)), new CloudOwnerServiceImpl(null, null)); + } catch (Exception e) { + return null; + } + } + + @Test + public void testCreateSvcInstance() throws Exception { + MsoController testSubject; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createSvcInstance(request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVnf() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVnf(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateNwInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createNwInstance(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVolumeGroupInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVolumeGroupInstance(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateVfModuleInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createVfModuleInstance(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testCreateConfigurationInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetailsWrapper mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.createConfigurationInstance(serviceInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteSvcInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + String result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteSvcInstance(serviceInstanceId, request, mso_request, ""); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVnf() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVnf(serviceInstanceId, vnfInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetailsWrapper mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testActivateConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.activateConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeactivateConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deactivateConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDisablePortOnConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.disablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testEnablePortOnConfiguration() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String configurationId = ""; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.enablePortOnConfiguration(serviceInstanceId, configurationId, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVfModule() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + String vfModuleId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVfModule(serviceInstanceId, vnfInstanceId, vfModuleId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteVolumeGroupInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String vnfInstanceId = ""; + String volumeGroupId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteVolumeGroupInstance(serviceInstanceId, vnfInstanceId, volumeGroupId, request, + mso_request); + } catch (Exception e) { + } + } + + @Test + public void testDeleteNwInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + String networkInstanceId = ""; + HttpServletRequest request = null; + RequestDetails mso_request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deleteNwInstance(serviceInstanceId, networkInstanceId, request, mso_request); + } catch (Exception e) { + } + } + + @Test + public void testGetOrchestrationRequest() throws Exception { + MsoController testSubject; + String requestId = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.getOrchestrationRequest(requestId, request); + } catch (Exception e) { + } + } + + @Test + public void testGetOrchestrationRequests() throws Exception { + MsoController testSubject; + String filterString = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.getOrchestrationRequests(filterString, request); + } catch (Exception e) { + } + } + + @Test + public void testActivateServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.activateServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testDeactivateServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.deactivateServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testManualTaskComplete() throws Exception { + MsoController testSubject; + String taskId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.manualTaskComplete(taskId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testRemoveRelationshipFromServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.removeRelationshipFromServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } + + @Test + public void testAddRelationshipToServiceInstance() throws Exception { + MsoController testSubject; + String serviceInstanceId = ""; + RequestDetails requestDetails = null; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.addRelationshipToServiceInstance(serviceInstanceId, requestDetails); + } catch (Exception e) { + } + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java index 4645a83ad..c69bce32b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -2,10 +2,8 @@ package org.onap.vid.controller; import org.apache.commons.lang.StringEscapeUtils; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.controllers.MsoConfig; -import org.onap.vid.controllers.MsoController; -import org.onap.vid.domain.mso.RequestInfo; import org.onap.vid.factories.MsoRequestFactory; +import org.onap.vid.mso.model.RequestInfo; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.Task; @@ -15,7 +13,6 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; import org.testng.Assert; -import org.testng.Assert.*; import org.testng.annotations.Test; import java.util.List; @@ -32,7 +29,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreationNew() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); //TODO: make ths test to really test something //ResponseEntity responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails); ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); @@ -44,7 +41,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreationLocalWithRest() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntityNew = msoController.createSvcInstance(null, requestDetails); //TODO: make ths test to really test something // ResponseEntity responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails); @@ -57,7 +54,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { public void testInstanceCreation() throws Exception { RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntity = msoController.createSvcInstance(null, requestDetails); @@ -72,7 +69,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { @Test(enabled = false) public void testGetOrchestrationRequestsForDashboard() throws Exception { - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); List orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard(); Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2); @@ -80,7 +77,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { @Test(enabled = false) public void testGetManualTasksByRequestId() throws Exception { - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); List orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335"); Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c"); @@ -94,7 +91,7 @@ public class MsoControllerTest extends AbstractTestNGSpringContextTests { requestInfo.setSource("VID"); RequestDetails requestDetails = new RequestDetails(); requestDetails.setRequestInfo(requestInfo); - MsoController msoController = new MsoController(null); + MsoController msoController = new MsoController(null, null); ResponseEntity responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails); String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" + " \" \\\"taskRequestReference\\\": {\\n\" +\n" + diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java new file mode 100644 index 000000000..e9d2cfd44 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/PropertyControllerTest.java @@ -0,0 +1,39 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.springframework.http.ResponseEntity; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; + +public class PropertyControllerTest { + + private PropertyController createTestSubject() { + return new PropertyController(); + } + + @Test + public void testWelcome() throws Exception { + PropertyController testSubject; + HttpServletRequest request = null; + ModelAndView result; + + // default test + testSubject = createTestSubject(); + result = testSubject.welcome(request); + } + + + @Test + public void testGetProperty() throws Exception { + PropertyController testSubject; + String name = ""; + String defaultvalue = ""; + HttpServletRequest request = null; + ResponseEntity result; + + // default test + testSubject = createTestSubject(); + result = testSubject.getProperty(name, defaultvalue, request); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java new file mode 100644 index 000000000..c19b810d0 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/RoleGeneratorControllerTest.java @@ -0,0 +1,26 @@ +package org.onap.vid.controller; + +import org.junit.Test; +import org.springframework.http.ResponseEntity; + +public class RoleGeneratorControllerTest { + + private RoleGeneratorController createTestSubject() { + return new RoleGeneratorController(); + } + + @Test + public void testGenerateRoleScript() throws Exception { + RoleGeneratorController testSubject; + boolean firstRun = false; + ResponseEntity result; + + // default test + try { + testSubject = createTestSubject(); + result = testSubject.generateRoleScript(firstRun); + } catch (Exception e) { + + } + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java new file mode 100644 index 000000000..f9f80d1b7 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java @@ -0,0 +1,48 @@ +package org.onap.vid.controller; + +import org.jetbrains.annotations.NotNull; +import org.onap.vid.aai.model.Permissions; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.roles.RoleValidator; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ServicePermissionsTest { + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][]{{TRUE}, {FALSE}}; + } + + + @Test(dataProvider = "trueAndFalse") + public void servicePermissions_responseMatchesMockedRoleValidator(boolean expected) { + String subscriberId = randomAlphanumeric(8); + String serviceType = randomAlphanumeric(8); + + RoleProvider roleProvider = mock(RoleProvider.class); + RoleValidator roleValidator = mock(RoleValidator.class); + when(roleProvider.getUserRolesValidator(any())).thenReturn(roleValidator); + when(roleValidator.isServicePermitted(subscriberId, serviceType)).thenReturn(expected); + + AaiController2 aaiController2 = new AaiController2(null, roleProvider, null); + + Permissions permissions = aaiController2.servicePermissions(unimportantRequest(), subscriberId, serviceType); + assertThat(permissions, is(new Permissions(expected))); + } + + @NotNull + private MockHttpServletRequest unimportantRequest() { + return new MockHttpServletRequest("", ""); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java index 36a179109..5751852af 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java @@ -1,42 +1,47 @@ package org.onap.vid.controller; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.module.kotlin.KotlinModule; +import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; import org.onap.vid.model.NewServiceModel; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + /** * Created by moriya1 on 04/07/2017. */ public class ToscaParserMockHelper { + private static final Logger logger = LogManager.getLogger(ToscaParserMockHelper.class); - private String uuid; - private String filePath; - private NewServiceModel newServiceModel; + private static final ObjectMapper om = new ObjectMapper(); + private final String uuid; + private final String filePath; + private final NewServiceModel newServiceModel; - public ToscaParserMockHelper(String uuid, String filePath) { + public ToscaParserMockHelper(String uuid, String filePath) throws IOException { this.uuid = uuid; this.filePath = filePath; + + InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(getFilePath()); + logger.info(jsonFile); + String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); + om.registerModule(new KotlinModule()); + this.newServiceModel = om.readValue(expectedJsonAsString, NewServiceModel.class); } public String getUuid() { return uuid; } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getFilePath() { return filePath; } - public void setFilePath(String filePath) { - this.filePath = filePath; - } - public NewServiceModel getNewServiceModel() { return newServiceModel; } - - public void setNewServiceModel(NewServiceModel newServiceModel) { - this.newServiceModel = newServiceModel; - } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java new file mode 100644 index 000000000..f57ba8a7f --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/VersionControllerTest.java @@ -0,0 +1,31 @@ +package org.onap.vid.controller; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + + +public class VersionControllerTest { + + @DataProvider + public static Object[][] majorVersionContainer() { + return new Object[][]{ + {"features.properties", "1.0.2000", "features.properties.2000"}, + {"", "1.0.2000", ".2000"}, + {"kuku", "1.0.2000", "kuku.2000"}, + {"/kuku", "1.0.2000", "kuku.2000"}, + {"1810p.features.properties", "1.0.2000", "1810p.2000"}, + {"/opt/app/dev.features.properties", "1.0.2000", "dev.2000"}, + {"foo", "2000", "foo.2000"}, + }; + } + + final VersionController versionController = new VersionController(null); + + @Test(dataProvider = "majorVersionContainer") + public void testGetDisplayVersion(String majorVersionContainer, String buildNumberContainer, String expected) { + assertThat(versionController.getDisplayVersion(majorVersionContainer, buildNumberContainer), is(expected)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java new file mode 100644 index 000000000..aeb03b60c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java @@ -0,0 +1,204 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Modifications Copyright 2018 Nokia + * ================================================================================ + * 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.vid.controller; + + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.apache.log4j.BasicConfigurator; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.SecureServices; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.asdc.beans.ServiceBuilder; +import org.onap.vid.model.*; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.onap.vid.model.PombaInstance.ServiceInstance; +import org.onap.vid.roles.RoleProvider; +import org.onap.vid.services.AaiService; +import org.onap.vid.services.PombaService; +import org.onap.vid.services.VidService; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import javax.ws.rs.core.MediaType; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.IntStream; + +import static java.util.stream.Collectors.toMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.not; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.times; +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.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(MockitoJUnitRunner.class) +public class VidControllerTest { + + public static final String REST_MODELS_SERVICES = "/rest/models/services"; + public static final String REST_MODELS_SERVICES_UUID = "/rest/models/services/{uuid}"; + public static final String REST_MODELS_RESET = "/rest/models/reset"; + public static final String REST_MODELS_SERVICES_VERIFY_SERVICE = "/rest/models/services/verifyService"; + @Mock + private VidService vidService; + @Mock + private AaiService aaiService; + @Mock + private RoleProvider roleProvider; + @Mock + private PombaService pombaService; + + private VidController vidController; + private MockMvc mockMvc; + private ObjectMapper objectMapper; + + private String uuid1; + private String uuid2; + private String uuid3; + + @Before + public void setUp() { + vidController = new VidController(vidService, aaiService, roleProvider, pombaService); + BasicConfigurator.configure(); + mockMvc = MockMvcBuilders.standaloneSetup(vidController).build(); + objectMapper = new ObjectMapper(); + + uuid1 = UUID.randomUUID().toString(); + uuid2 = UUID.randomUUID().toString(); + uuid3 = UUID.randomUUID().toString(); + } + + @Test + public void getServices_shouldReturnService_whenServiceExists() throws Exception { + List services = ImmutableList.of(createService(uuid1, 1), createService(uuid2, 2), createService(uuid3, 3)); + + given(aaiService.getServicesByDistributionStatus()).willReturn(services); + + SecureServices secureServices = new SecureServices(); + secureServices.setServices(services); + secureServices.setReadOnly(false); + + mockMvc.perform(get(REST_MODELS_SERVICES) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(secureServices))); + } + + @Test + public void getService_shouldReturnService_whenNoExceptionIsThrown() throws Exception { + ServiceModel model = expectedServiceModel(uuid1); + + given(vidService.getService(uuid1)).willReturn(model); + + mockMvc.perform(get(REST_MODELS_SERVICES_UUID, uuid1) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().json(objectMapper.writeValueAsString(model))); + } + + @Test + public void getService_shouldThrow_whenAsdcCatalogExceptionIsThrown() throws Exception { + String testUuid = UUID.randomUUID().toString(); + + given(vidService.getService(testUuid)).willThrow(new AsdcCatalogException("error msg")); + + mockMvc.perform(get(REST_MODELS_SERVICES_UUID, testUuid) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isServiceUnavailable()); + } + + @Test + public void invalidateServiceModelCache_shouldReturnAccepted() throws Exception { + mockMvc.perform(post(REST_MODELS_RESET) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isAccepted()); + + then(vidService).should(times(1)).invalidateServiceCache(); + } + + @Test + public void verifyServiceInstance_shouldReturnOk() throws Exception { + PombaRequest pombaRequest = new PombaRequest(); + pombaRequest.serviceInstanceList = ImmutableList.of(new ServiceInstance()); + + mockMvc.perform(post(REST_MODELS_SERVICES_VERIFY_SERVICE) + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(pombaRequest))) + .andExpect(status().isOk()); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(PombaRequest.class); + then(pombaService).should(times(1)).verify(argumentCaptor.capture()); + + assertThat(pombaRequest).isEqualToComparingFieldByFieldRecursively(argumentCaptor.getValue()); + } + + private ServiceModel expectedServiceModel(String uuid) { + final ServiceModel serviceModel = getModelsByUuid().get(uuid); + Assert.assertThat(serviceModel, is(not(nullValue()))); + return serviceModel; + } + + private Service createService(String uuid, int i) { + return new ServiceBuilder().setUuid(uuid).setInvariantUUID("invariantUUID" + i) + .setCategory("category" + i).setVersion("version" + i).setName("name" + i) + .setDistributionStatus("distStatus" + i).setToscaModelURL("toscaModelUrl" + i).build(); + } + + private ServiceModel createServiceModel(int i) { + ServiceModel model = new ServiceModel(); + + model.setCollectionResource(ImmutableMap.of("resKey" + i, new CR())); + model.setNetworks(ImmutableMap.of("network" + i, new Network())); + model.setPnfs(ImmutableMap.of("pnf" + i, new Node())); + model.setServiceProxies(ImmutableMap.of("servProxy" + i, new ServiceProxy())); + model.setVfModules(ImmutableMap.of("vfmod" + i, new VfModule())); + model.setVnfs(ImmutableMap.of("vnf" + i, new VNF())); + model.setVolumeGroups(ImmutableMap.of("volgroup" + i, new VolumeGroup())); + model.setService(new org.onap.vid.model.Service()); + return model; + } + + private Map getModelsByUuid() { + ServiceModel serviceModel1 = createServiceModel(1); + ServiceModel serviceModel2 = createServiceModel(2); + ServiceModel serviceModel3 = createServiceModel(3); + + List pseudoServiceModels = ImmutableList.of(serviceModel1, serviceModel2, serviceModel3); + List uuids = ImmutableList.of(uuid1, uuid2, uuid3); + return IntStream.range(0, pseudoServiceModels.size()).boxed() + .collect(toMap(i -> uuids.get(i), i -> pseudoServiceModels.get(i))); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java new file mode 100644 index 000000000..9729c4e7b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ViewEditSubControllerTest.java @@ -0,0 +1,46 @@ +package org.onap.vid.controller; +//package org.onap.vid.controller; +// +//import javax.servlet.http.HttpServletRequest; +// +//import org.junit.Test; +//import org.springframework.web.servlet.ModelAndView; +// +//public class ViewEditSubControllerTest { +// +// private ViewEditSubController createTestSubject() { +// return new ViewEditSubController(); +// } +// +// @Test +// public void testWelcome() throws Exception { +// ViewEditSubController testSubject; +// HttpServletRequest request = null; +// ModelAndView result; +// +// // default test +// testSubject = createTestSubject(); +// result = testSubject.welcome(request); +// } +// +// +// @Test +// public void testGetViewName() throws Exception { +// ViewEditSubController testSubject; +// String result; +// +// // default test +// testSubject = createTestSubject(); +// result = testSubject.getViewName(); +// } +// +// @Test +// public void testSetViewName() throws Exception { +// ViewEditSubController testSubject; +// String viewName = ""; +// +// // default test +// testSubject = createTestSubject(); +// testSubject.setViewName(viewName); +// } +//} \ No newline at end of file -- cgit 1.2.3-korg