diff options
Diffstat (limited to 'vid-app-common/src/test/java/org')
14 files changed, 1809 insertions, 330 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java index 80c65935e..7bdd6b863 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controllers/MaintenanceControllerTest.java @@ -1,66 +1,340 @@ package org.onap.vid.controllers; -import javax.servlet.http.HttpServletRequest; +/*- + * ============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 static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +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; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import java.util.Collections; +import java.util.function.BiFunction; +import javax.ws.rs.ForbiddenException; +import org.apache.log4j.BasicConfigurator; +import org.codehaus.jackson.map.ObjectMapper; +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.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.springframework.http.ResponseEntity; +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; +@RunWith(MockitoJUnitRunner.class) public class MaintenanceControllerTest { - private MaintenanceController createTestSubject() { - return new MaintenanceController(); + 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 testAddCategoryOptions() throws Exception { - MaintenanceController testSubject; - HttpServletRequest request = null; - String categoryName = ""; - AddCategoryOptionsRequest option = null; - ResponseEntity result; + public void updateNameForOption_shouldReturnOk_whenNoErrorsExist() throws Exception { + String categoryName = "catName5"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id2", "name2"); + AddCategoryOptionResponse addCategoryOptionResponse = new AddCategoryOptionResponse(Collections.emptyList()); - // default test - testSubject = createTestSubject(); - result = testSubject.addCategoryOptions(request, categoryName, option); + 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 testUpdateNameForOption() throws Exception { - MaintenanceController testSubject; - HttpServletRequest request = null; - String categoryName = ""; - CategoryParameterOptionRep option = null; - ResponseEntity result; + public void updateNameForOption_shouldReturnForbidden_whenForbiddenExceptionIsThrown() throws Exception { + String categoryName = "catName6"; + CategoryParameterOptionRep categoryParameterOptionRep = new CategoryParameterOptionRep("id3", "name3"); - // default test - testSubject = createTestSubject(); - result = testSubject.updateNameForOption(request, categoryName, option); + 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 testGetCategoryParameter() throws Exception { - MaintenanceController testSubject; - HttpServletRequest request = null; - ResponseEntity result; + 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)); - // default test - testSubject = createTestSubject(); - result = testSubject.getCategoryParameter(request, null); + 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 testDeleteCategoryOption() throws Exception { - MaintenanceController testSubject; - HttpServletRequest request = null; - String categoryName = ""; - CategoryParameterOption option = null; - ResponseEntity result; - - // default test - testSubject = createTestSubject(); - result = testSubject.deleteCategoryOption(request, categoryName, option); + 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 <T> ArgumentMatcher<T> requestMatcher(T t) { + return new ArgumentMatcher<T>() { + @Override + public boolean matches(Object o) { + return t.equals(o); + } + }; + } + + private ResultActions prepareRequestExpectations( + BiFunction<String, String, MockHttpServletRequestBuilder> 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/job/command/InProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java new file mode 100644 index 000000000..bc623928c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusCommandTest.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.vid.job.command; + + +import io.joshworks.restclient.http.HttpResponse; +import org.mockito.Mock; +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import javax.ws.rs.ProcessingException; +import java.util.UUID; + + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class InProgressStatusCommandTest { + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; + + @Mock + private MsoInterface msoInterface; + + @Mock + private AuditService auditService; + + @Mock + private HttpResponse<AsyncRequestStatus> msoResponse; + + @Mock + private AsyncRequestStatus asyncRequestStatus; + + @Mock + private AsyncRequestStatus.Request request; + + private UUID uuid = UUID.randomUUID(); + + private InProgressStatusCommand inProgressStatusCommand; + + @BeforeMethod + public void setUp() { + initMocks(this); + + inProgressStatusCommand = new InProgressStatusCommand(asyncInstantiationBusinessLogic, msoInterface, auditService, uuid, "sampleRequestId"); + + when(asyncInstantiationBusinessLogic.getOrchestrationRequestsPath()).thenReturn("http://localhost:8080/samplePath"); + when(msoInterface.get("http://localhost:8080/samplePath/sampleRequestId", AsyncRequestStatus.class)).thenReturn(msoResponse); + when(msoResponse.getBody()).thenReturn(asyncRequestStatus); + } + + + @Test + public void whenSOReturnsErrorShouldSetProperFailureStateAndReturnRetryCommand() { + when(msoResponse.getStatus()).thenReturn(500); + + NextCommand call = inProgressStatusCommand.call(); + + assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); + assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); + + verify(auditService).setFailedAuditStatusFromMso(uuid, "sampleRequestId", 500, asyncRequestStatus.toString()); + } + + @Test + public void shouldProperlyHandleFailedInstantiation() { + when(msoResponse.getStatus()).thenReturn(200); + when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.FAILED); + asyncRequestStatus.request = request; + + NextCommand call = inProgressStatusCommand.call(); + + assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); + assertThat(call.getStatus()).isEqualTo(Job.JobStatus.FAILED); + + verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid); + verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request); + } + + @Test + public void shouldRetryCommandWithPausedState() { + when(msoResponse.getStatus()).thenReturn(200); + when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenReturn(Job.JobStatus.PAUSE); + asyncRequestStatus.request = request; + + NextCommand call = inProgressStatusCommand.call(); + + assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); + assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); + + verify(asyncInstantiationBusinessLogic).auditMsoStatus(uuid, request); + verify(asyncInstantiationBusinessLogic).updateServiceInfoAndAuditStatus(uuid, Job.JobStatus.PAUSE); + } + + @Test + public void shouldRetryCommandExitedWithProcessingException() { + when(msoResponse.getStatus()).thenReturn(200); + when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new ProcessingException("")); + + NextCommand call = inProgressStatusCommand.call(); + + assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); + assertThat(call.getStatus()).isEqualTo(Job.JobStatus.IN_PROGRESS); + } + + @Test + public void shouldSetStoppedStatusWhenRuntimeExceptionOccurs() { + when(msoResponse.getStatus()).thenReturn(200); + when(asyncInstantiationBusinessLogic.calcStatus(asyncRequestStatus)).thenThrow(new RuntimeException()); + + NextCommand call = inProgressStatusCommand.call(); + + assertThat(call.getCommand()).isEqualTo(inProgressStatusCommand); + assertThat(call.getStatus()).isEqualTo(Job.JobStatus.STOPPED); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java new file mode 100644 index 000000000..e7ab4f098 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInstantiationCommandTest.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.vid.job.command; + + +import io.joshworks.restclient.http.HttpResponse; +import org.mockito.Mock; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.exceptions.InvalidAAIResponseException; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.domain.mso.RequestReferences; +import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.job.Job; +import org.onap.vid.job.NextCommand; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class ServiceInstantiationCommandTest { + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; + + @Mock + private MsoInterface msoInterface; + + @Mock + private AuditService auditService; + + @Mock + private ServiceInstantiation serviceInstantiation; + + @Mock + private HttpResponse<RequestReferencesContainer> msoResponse; + + @Mock + private RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper; + + @Mock + private AaiResponse aaiResponse; + + @Mock + private RequestReferencesContainer requestReferencesContainer; + + + private UUID uuid = UUID.randomUUID(); + + + private ServiceInstantiationCommand serviceInstantiationCommand; + + @BeforeMethod + public void setUp() { + initMocks(this); + serviceInstantiationCommand = new ServiceInstantiationCommand(asyncInstantiationBusinessLogic, auditService, msoInterface, uuid, serviceInstantiation, "sampleUserId"); + } + + + @Test + public void shouldProperlyHandleMaxRetriesException() { + when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenThrow(new MaxRetriesException("", 2)); + + NextCommand call = serviceInstantiationCommand.call(); + + assertThat(call.getCommand(), is(nullValue())); + assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED))); + + verify(asyncInstantiationBusinessLogic).handleFailedInstantiation(uuid); + } + + @Test + public void shouldProperlyHandleInvalidAAIResponseException() { + doThrow(new InvalidAAIResponseException(aaiResponse)).when(asyncInstantiationBusinessLogic).generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId"); + + NextCommand call = serviceInstantiationCommand.call(); + + assertThat(call.getCommand(), is(serviceInstantiationCommand)); + assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS))); + } + + + @Test + public void shouldProperlyHandleInvalidSOResponse() { + when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper); + when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath"); + when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse); + when(msoResponse.getStatus()).thenReturn(500); + when(msoResponse.getBody()).thenReturn(requestReferencesContainer); + + NextCommand call = serviceInstantiationCommand.call(); + + assertThat(call.getCommand(), is(nullValue())); + assertThat(call.getStatus(), is(equalTo(Job.JobStatus.FAILED))); + + verify(auditService).setFailedAuditStatusFromMso(uuid, null, 500, requestReferencesContainer.toString()); + } + + + @Test + public void shouldProperlyUpdateServiceStatusAndReturnInProgressCommand() { + RequestReferences requestReferences = createRequestReferences(); + + when(asyncInstantiationBusinessLogic.generateServiceInstantiationRequest(uuid, serviceInstantiation, "sampleUserId")).thenReturn(requestDetailsWrapper); + when(asyncInstantiationBusinessLogic.getServiceInstantiationPath(serviceInstantiation)).thenReturn("samplePath"); + when(msoInterface.post("samplePath", requestDetailsWrapper, RequestReferencesContainer.class)).thenReturn(msoResponse); + when(msoResponse.getStatus()).thenReturn(200); + when(msoResponse.getBody()).thenReturn(requestReferencesContainer); + when(requestReferencesContainer.getRequestReferences()).thenReturn(requestReferences); + + + NextCommand call = serviceInstantiationCommand.call(); + + assertThat(call.getCommand(), instanceOf(InProgressStatusCommand.class)); + assertThat(call.getStatus(), is(equalTo(Job.JobStatus.IN_PROGRESS))); + + } + + private RequestReferences createRequestReferences() { + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setInstanceId("sampleInstanceId"); + requestReferences.setRequestId("sampleRequestId"); + return requestReferences; + } +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java new file mode 100644 index 000000000..dc2eafc9b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterImplTest.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.vid.job.impl; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.mockito.Mock; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobType; +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.UUID; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class JobAdapterImplTest { + + + private static final int SAMPLE_INDEX = 10; + private static final String SAMPLE_USER_ID = "sampleUserId"; + + @Mock + private Job job; + + @Mock + private JobAdapter.AsyncJobRequest asyncJobRequest; + + private UUID sampleUuid=UUID.randomUUID(); + + private JobAdapterImpl jobAdapter = new JobAdapterImpl(); + + @BeforeMethod + public void setUp() { + initMocks(this); + + when(job.getUuid()).thenReturn(sampleUuid); + when(job.getStatus()).thenReturn(Job.JobStatus.IN_PROGRESS); + when(job.getTemplateId()).thenReturn(sampleUuid); + } + + @Test + public void shouldConvertJobToJobModel() { + + + JobModel convertedJob = jobAdapter.toModel(job); + + assertThat(convertedJob.getUuid()).isEqualByComparingTo(sampleUuid); + assertThat(convertedJob.getStatus()).isEqualByComparingTo(Job.JobStatus.IN_PROGRESS); + assertThat(convertedJob.getTemplateId()).isEqualByComparingTo(sampleUuid); + } + + + @Test + public void shouldProperlyCreateJob() { + UUID uuid = UUID.randomUUID(); + + Job createdJob = jobAdapter.createJob(JobType.ServiceInstantiation, asyncJobRequest, uuid, SAMPLE_USER_ID, SAMPLE_INDEX); + + assertThat(createdJob.getStatus()).isEqualByComparingTo(Job.JobStatus.PENDING); + assertThat(createdJob.getTemplateId()).isEqualByComparingTo(uuid); + assertThat(createdJob.getType()).isEqualByComparingTo(JobType.ServiceInstantiation); + assertThat(createdJob.getData()).isEqualTo(ImmutableMap.of("request", asyncJobRequest, "userId", SAMPLE_USER_ID)); + } + + @Test + public void shouldProperlyCreateBulkOfJobs(){ + List<Job> bulkOfJobs = jobAdapter.createBulkOfJobs(ImmutableMap.of("count", 5, "type", JobType.InProgressStatus.name())); + + + assertThat(bulkOfJobs).hasSize(5); + + Stream<Job> jobStream = bulkOfJobs.stream().filter(x -> JobType.InProgressStatus.equals(x.getType()) && Job.JobStatus.PENDING.equals(x.getStatus())); + + assertThat(jobStream).hasSize(5); + } + + + @Test + public void shouldConvertListToBulkJob(){ + JobBulk jobBulk = jobAdapter.toModelBulk(ImmutableList.of(job, job)); + + assertThat(jobBulk.getJobs()).hasSize(2); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java new file mode 100644 index 000000000..93afd1709 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobSchedulerInitializerTest.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia 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.vid.job.impl; + + +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.JobCommandFactory; +import org.onap.vid.properties.Features; +import org.quartz.JobDetail; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.Trigger; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +public class JobSchedulerInitializerTest { + + @Mock + private JobsBrokerService brokerService; + + @Mock + private SchedulerFactoryBean schedulerFactoryBean; + + @Mock + private FeatureManager featureManager; + + @Mock + private JobCommandFactory commandFactory; + + @Mock + private Scheduler scheduler; + + @InjectMocks + private JobSchedulerInitializer jobSchedulerInitializer; + + @BeforeMethod + public void setUp() { + initMocks(this); + } + + + @Test + public void shouldNotInitializeSchedulerWhenAsyncJobsAreDisabled() { + when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(false); + + jobSchedulerInitializer.init(); + + verifyZeroInteractions(schedulerFactoryBean); + } + + + @Test + public void shouldInitializeSchedulerWhenAsyncJobsAreEnabled() throws SchedulerException { + ArgumentCaptor<JobDetail> jobDetailArgumentCaptor = ArgumentCaptor.forClass(JobDetail.class); + ArgumentCaptor<Trigger> triggerArgumentCaptor = ArgumentCaptor.forClass(Trigger.class); + when(featureManager.isActive(Features.FLAG_ASYNC_JOBS)).thenReturn(true); + when(schedulerFactoryBean.getScheduler()).thenReturn(scheduler); + + jobSchedulerInitializer.init(); + + verify(scheduler, times(2)).scheduleJob(jobDetailArgumentCaptor.capture(), triggerArgumentCaptor.capture()); + + List<Object> topics = extractTopics(jobDetailArgumentCaptor); + + List<String> descriptions = extractDescription(triggerArgumentCaptor); + + assertThat(topics, containsInAnyOrder(org.onap.vid.job.Job.JobStatus.IN_PROGRESS, org.onap.vid.job.Job.JobStatus.PENDING)); + assertThat(descriptions, containsInAnyOrder("Trigger to run async worker for PENDING", "Trigger to run async worker for IN_PROGRESS")); + } + + private List<Object> extractTopics(ArgumentCaptor<JobDetail> jobDetailArgumentCaptor) { + return jobDetailArgumentCaptor + .getAllValues() + .stream() + .map(JobDetail::getJobDataMap) + .map(x -> x.get("topic")) + .collect(Collectors.toList()); + } + + private List<String> extractDescription(ArgumentCaptor<Trigger> triggerArgumentCaptor) { + return triggerArgumentCaptor + .getAllValues() + .stream() + .map(Trigger::getDescription) + .collect(Collectors.toList()); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 36f4bdd43..461673224 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -1,153 +1,306 @@ +/* + * ============LICENSE_START========================================== + * =================================================================== + * Modifications Copyright (C) 2018 Nokia. 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.vid.mso; -import org.mockito.InjectMocks; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentMatcher; import org.mockito.Mock; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.onap.vid.properties.Features; -import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.http.HttpStatus; 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.annotations.BeforeTest; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.togglz.core.manager.FeatureManager; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.onap.vid.controllers.MsoController.SVC_INSTANCE_ID; -import static org.onap.vid.controllers.MsoController.VNF_INSTANCE_ID; -import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; - @ContextConfiguration(classes = {SystemProperties.class}) -@WebAppConfiguration -public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +public class MsoBusinessLogicImplTest { - @InjectMocks - private MsoBusinessLogicImpl msoBusinessLogic; + private static final ObjectMapper objectMapper = new ObjectMapper(); @Mock - private FeatureManager featureManagerMock; + private FeatureManager featureManager; @Mock - private MsoInterface msoInterfaceMock; + private MsoInterface msoInterface; + private MsoBusinessLogicImpl msoBusinessLogic; - @BeforeTest - public void initMocks(){ + @Before + public void setUp() { MockitoAnnotations.initMocks(this); + msoBusinessLogic = new MsoBusinessLogicImpl(msoInterface, featureManager); } @Test - public void validateEndpointPath_endPointIsNotEmptyAndVaild_returnProperty(){ - System.setProperty("TestEnv","123"); - String foundEndPoint = validateEndpointPath("TestEnv"); - Assert.assertEquals("123",foundEndPoint); - } + public void createConfigurationInstance_shouldCallMsoInterface_withCorrectServiceInstanceId() throws Exception { + // given + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String endpointTemplate = String.format("/serviceInstances/v6/%s/configurations", serviceInstanceId); + RequestDetailsWrapper requestDetailsWrapper = createRequestDetails("mso_request_create_configuration.json"); + MsoResponseWrapper expectedResponse = createOkResponse(); + given(msoInterface.createConfigurationInstance(requestDetailsWrapper, endpointTemplate)) + .willReturn(expectedResponse); - @Test(expectedExceptions = RuntimeException.class) - public void validateEndpointPath_endPointIsNull_throwRuntimeException(){ - validateEndpointPath("NotExists"); - } + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .createConfigurationInstance(requestDetailsWrapper, serviceInstanceId); - @Test(expectedExceptions = RuntimeException.class) - public void validateEndpointPath_endPointIsNotEmptyButDoesntExists_throwRuntimeException(){ - System.setProperty("EmptyEndPoint",""); - validateEndpointPath("EmptyEndPoint"); + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); } + private RequestDetailsWrapper createRequestDetails(String bodyFileName) throws Exception { + final URL resource = this.getClass().getResource("/payload_jsons/" + bodyFileName); + RequestDetails requestDetails = objectMapper.readValue(resource, RequestDetails.class); + return new RequestDetailsWrapper(requestDetails); + } - //@Test(dataProvider = "unAssignOrDeleteParams") - public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOffOrUnAssignFlagIsFalse(boolean isAssignFlag,String status) { - Mockito.reset(msoInterfaceMock); - String endpoint = validateEndpointPath(isAssignFlag ? MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE : MsoProperties.MSO_REST_API_SVC_INSTANCE); - RequestDetails requestDetails = new RequestDetails(); - - when(featureManagerMock.isActive(Features.FLAG_UNASSIGN_SERVICE)).thenReturn(isAssignFlag); - - msoBusinessLogic.deleteSvcInstance(requestDetails, "tempId", status); + @Test + public void validateEndpointPath_endPointIsNotEmptyAndVaild_returnProperty() { + System.setProperty("TestEnv", "123"); + String foundEndPoint = validateEndpointPath("TestEnv"); + assertEquals("123", foundEndPoint); + } - verify(msoInterfaceMock).deleteSvcInstance(requestDetails, endpoint + "/tempId"); + @Test + public void validateEndpointPath_endPointIsNull_throwRuntimeException() { + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> validateEndpointPath("NotExists")); } - @DataProvider - public Object[][] unAssignOrDeleteParams() { - return new Object[][]{ - {Boolean.FALSE, "active"}, - {Boolean.FALSE, "created"}, - {Boolean.TRUE, "Active"}, - {Boolean.TRUE, "unexpected-status"}, - }; + @Test + public void validateEndpointPath_endPointIsNotEmptyButDoesntExists_throwRuntimeException() { + String endPoint = "EmptyEndPoint"; + System.setProperty(endPoint, ""); + assertThatExceptionOfType(GenericUncheckedException.class) + .isThrownBy(() -> validateEndpointPath(endPoint)) + .withMessage(endPoint + " env variable is not defined"); } - //@Test(dataProvider = "unAssignStatus") - public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOnAndUnAssignFlagIsTrue(String status) { - Mockito.reset(msoInterfaceMock); - // in the test Features.FLAG_UNASSIGN_SERVICE is active so the endpoint should be MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE - String endpoint = validateEndpointPath(MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE); + @Test + public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOffOrUnAssignFlagIsFalse() { + // given + String endpointTemplate = "/serviceInstances/v5/%s"; + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String svcEndpoint = String.format(endpointTemplate, serviceInstanceId); RequestDetails requestDetails = new RequestDetails(); + MsoResponseWrapper expectedResponse = createOkResponse(); + given(msoInterface.deleteSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse); + given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(false); - when(featureManagerMock.isActive(Features.FLAG_UNASSIGN_SERVICE)).thenReturn(true); + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .deleteSvcInstance(requestDetails, serviceInstanceId, "unAssignOrDeleteParams"); - msoBusinessLogic.deleteSvcInstance(requestDetails, "tempId", status); - - verify(msoInterfaceMock).unassignSvcInstance(requestDetails, endpoint + "/tempId/unassign"); + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); } - @DataProvider - public Object[][] unAssignStatus() { - return new Object[][]{ - {"Created"}, - {"Pendingdelete"}, - {"pending-Delete"}, - {"Assigned"} - }; + @Test + public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOnAndUnAssignFlagIsTrue() { + // given + String endpointTemplate = "/serviceInstantiation/v5/serviceInstances/%s/unassign"; + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String svcEndpoint = String.format(endpointTemplate, serviceInstanceId); + RequestDetails requestDetails = new RequestDetails(); + MsoResponseWrapper expectedResponse = createOkResponse(); + given(msoInterface.unassignSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse); + given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(true); + + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .deleteSvcInstance(requestDetails, serviceInstanceId, "assigned"); + + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); } @Test public void deleteVnf_verifyEndPointPathConstructing() { - String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); + // when + String endpointTemplate = "/serviceInstances/v5/%s/vnfs/%s"; + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String vnfInstanceId = "testVnfInstanceTempId"; + String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId); RequestDetails requestDetails = new RequestDetails(); + MsoResponseWrapper expectedResponse = createOkResponse(); + given(msoInterface.deleteVnf(requestDetails, vnfEndpoint)).willReturn(expectedResponse); - String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, "serviceInstanceTempId"); + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .deleteVnf(requestDetails, serviceInstanceId, vnfInstanceId); - msoBusinessLogic.deleteVnf(requestDetails, "serviceInstanceTempId","vnfInstanceTempId"); - verify(msoInterfaceMock).deleteVnf(requestDetails, vnf_endpoint + "/vnfInstanceTempId"); + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); } @Test public void deleteVfModule_verifyEndPointPathConstructing() { - String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + // when + String endpointTemplate = "/serviceInstances/v7/%s/vnfs/%s/vfModules/%s"; + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String vnfInstanceId = "testVnfInstanceTempId"; + String vfModuleId = "testVfModuleId"; + String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId, vfModuleId); RequestDetails requestDetails = new RequestDetails(); + MsoResponseWrapper expectedResponse = createOkResponse(); + given(msoInterface.deleteVfModule(requestDetails, vnfEndpoint)).willReturn(expectedResponse); + + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .deleteVfModule(requestDetails, serviceInstanceId, vnfInstanceId, vfModuleId); + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); + } + + @Test + public void shouldSendProperScaleOutRequest() throws IOException { + // given + String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; + String vnfInstanceId = "testVnfInstanceTempId"; + String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s/vfModules/scaleOut"; + String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId); + org.onap.vid.changeManagement.RequestDetails requestDetails = readRequest( + "scaleOutVfModulePayload.json"); + org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest = readExpectedRequest( + "scaleOutVfModulePayloadToMso.json"); + MsoResponseWrapper expectedMsoResponseWrapper = createOkResponse(); + given( + msoInterface + .scaleOutVFModuleInstance(argThat(new MsoRequestWrapperMatcher(expectedRequest)), + eq(vnfEndpoint))) + .willReturn(expectedMsoResponseWrapper); + + // when + MsoResponseWrapper msoResponseWrapper = msoBusinessLogic + .scaleOutVfModuleInstance(requestDetails, serviceInstanceId, vnfInstanceId); + + // then + assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedMsoResponseWrapper); + } - String vf__modules_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, "serviceInstanceTempId").replaceFirst(VNF_INSTANCE_ID, "vnfInstanceTempId"); + private org.onap.vid.changeManagement.RequestDetails readRequest(String requestJsonFilename) throws IOException { + Path path = Paths.get("payload_jsons", requestJsonFilename); + URL url = this.getClass().getClassLoader().getResource(path.toString()); + return objectMapper.readValue(url, org.onap.vid.changeManagement.RequestDetails.class); + } - msoBusinessLogic.deleteVfModule(requestDetails, "serviceInstanceTempId","vnfInstanceTempId", "vfModuleTempId"); - verify(msoInterfaceMock).deleteVfModule(requestDetails, vf__modules_endpoint + "/vfModuleTempId" ); + private org.onap.vid.changeManagement.RequestDetailsWrapper readExpectedRequest(String requestJsonFilename) + throws IOException { + Path path = Paths.get("payload_jsons", requestJsonFilename); + URL url = this.getClass().getClassLoader().getResource(path.toString()); + return objectMapper.readValue(url, + new TypeReference<org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails>>() { + }); + } + + private MsoResponseWrapper createOkResponse() { + HttpStatus expectedStatus = HttpStatus.ACCEPTED; + String expectedBody = " \"body\": {\n" + + " \"requestReferences\": {\n" + + " \"instanceId\": \" 123456 \",\n" + + " \"requestId\": \"b6dc9806-b094-42f7-9386-a48de8218ce8\"\n" + + " }"; + MsoResponseWrapper responseWrapper = new MsoResponseWrapper(); + responseWrapper.setEntity(expectedBody); + responseWrapper.setStatus(expectedStatus.value()); + return responseWrapper; } @Test - public void insertServiceInstantiationToDB_StartJob() { - -// broker = new JobsBrokerServiceInDatabaseImpl(dataAccessServiceMock, sessionFactory); -// ((JobsBrokerServiceInDatabaseImpl)broker).deleteAll(); -// -//// msoBusinessLogic.setDataAccessService(dataAccessServiceMock); -//// msoBusinessLogic.setJobsBrokerService(broker); -//// msoBusinessLogic.setJobAdapter(jobAdapter); -// -// ServiceInstantiation serviceInstantiation = new ServiceInstantiation(); -// serviceInstantiation.setCount(2); -// serviceInstantiation.setInstanceName("TestName"); -// -// msoBusinessLogic.pushBulkJob(serviceInstantiation, "testUserId"); -// -// List<ServiceInfo> serviceInfoList = dataAccessServiceMock.getList(ServiceInfo.class, null); -// int k = 9; -// Assert.assertEquals(serviceInstantiation, containsInAnyOrder(serviceInfoList.toArray())); + public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws IOException { + //given + String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json"); + String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json"); + + MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class); + given(msoInterface + .getOrchestrationRequestsForDashboard(any(String.class), any(String.class), any(String.class), + any(RestObject.class))) + .willReturn(msoResponseWrapperMock); + given(msoResponseWrapperMock.getEntity()) + .willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests); + + //when + List<Request> filteredOrchestrationReqs = msoBusinessLogic.getOrchestrationRequestsForDashboard(); + + //then + assertThat(filteredOrchestrationReqs).hasSize(3); + assertThat(MsoBusinessLogicImpl.DASHBOARD_ALLOWED_TYPES) + .containsAll(filteredOrchestrationReqs + .stream() + .map(el -> el.getRequestType().toUpperCase()) + .collect(Collectors.toList())); + assertThat(filteredOrchestrationReqs) + .extracting(org.onap.vid.domain.mso.Request::getRequestScope) + .containsOnly("vnf", "vfModule"); + } + + private String getFileContentAsString(String resourceName) throws IOException { + URL url = this.getClass().getClassLoader().getResource("."); + Path path = Paths.get(url.getPath(), "payload_jsons", resourceName); + return new String(Files.readAllBytes(path)); + } + + private static class MsoRequestWrapperMatcher extends + ArgumentMatcher<org.onap.vid.changeManagement.RequestDetailsWrapper> { + + private final org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest; + + public MsoRequestWrapperMatcher(org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest) { + this.expectedRequest = expectedRequest; + } + + @Override + public boolean matches(Object argument) { + org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = (org.onap.vid.changeManagement.RequestDetailsWrapper) argument; + return expectedRequest.requestDetails.equals(requestDetailsWrapper.requestDetails); + } } } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java deleted file mode 100644 index af7f74b3d..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.onap.vid.mso; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.vid.mso.MsoBusinessLogicImpl; -import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.MsoResponseWrapper; -import org.onap.vid.mso.rest.RequestDetails; -import org.onap.vid.mso.rest.RequestDetailsWrapper; -import org.testng.annotations.Test; - -import java.net.URL; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -@RunWith(MockitoJUnitRunner.class) -public class MsoBusinessLogicTest { - - @InjectMocks - private MsoBusinessLogicImpl msoBusinessLogic; - - @Mock - private MsoInterface msoClient; - - @Test - public void testCreateInstance() throws Exception { - String instanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; - final RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - requestDetailsWrapper.requestDetails = setRequestDetails("mso_request_create_configuration.json"); - Mockito.doReturn(getOkResponse(instanceId)).when(msoClient).createConfigurationInstance(requestDetailsWrapper, "/serviceInstances/v6/3f93c7cb-2fd0-4557-9514-e189b7b04f9d/configurations"); - final MsoResponseWrapper msoResponseWrapper = msoBusinessLogic.createConfigurationInstance(requestDetailsWrapper, instanceId); - - assertNotNull(msoResponseWrapper); - assertEquals(202, msoResponseWrapper.getStatus()); - } - - private MsoResponseWrapper getOkResponse(String instanceId){ - MsoResponseWrapper responseWrapper = new MsoResponseWrapper(); - String entity = " \"body\": {\n" + - " \"requestReferences\": {\n" + - " \"instanceId\": \""+instanceId+"\",\n" + - " \"requestId\": \"b6dc9806-b094-42f7-9386-a48de8218ce8\"\n" + - " }"; - responseWrapper.setEntity(entity); - responseWrapper.setStatus(202); - return responseWrapper; - } - - private RequestDetails setRequestDetails(String bodyFileName)throws Exception { - final URL resource = this.getClass().getResource("/payload_jsons/" + bodyFileName); - ObjectMapper mapper = new ObjectMapper(); - RequestDetails requestDetails = mapper.readValue(resource, RequestDetails.class); - return requestDetails; - - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index 402386a50..bfc82ce2a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -21,17 +21,12 @@ package org.onap.vid.mso.rest; import com.xebialabs.restito.server.StubServer; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Properties; -import java.util.UUID; import org.glassfish.grizzly.http.util.HttpStatus; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; +import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.client.SyncRestClient; import org.onap.vid.controllers.MsoController; import org.onap.vid.mso.MsoInterface; @@ -39,16 +34,30 @@ import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.RestObject; +import org.springframework.test.context.ContextConfiguration; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; +import java.util.UUID; + +import static org.onap.vid.controllers.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controllers.MsoController.VNF_INSTANCE_ID; + +@ContextConfiguration(classes = {SystemProperties.class}) public class MsoRestClientNewTest { private static StubServer server; private static StubServer securedServer; private static Properties props = new Properties(); private static String msoCreateServiceInstanceJson; + private static String msoScaleOutVfModule; private final static String CREATE_INSTANCE_RESPONSE_STR = - "{\"requestReferences\":{\"instanceId\":\"baa13544-0e95-4644-9565-9a198a29a294\"," - + "\"requestId\":\"a42a1a35-3d63-4629-bbe0-4989fa7414cb\"}}"; + "{\"requestReferences\":{\"instanceId\":\"baa13544-0e95-4644-9565-9a198a29a294\"," + + "\"requestId\":\"a42a1a35-3d63-4629-bbe0-4989fa7414cb\"}}"; private final static String SERVICE_INSTANCE_ID = "12345"; private static final String SAMPLE_VNF_INSTANCE_ID = "111"; private static final String SAMPLE_VNF_MODULE_ID = "987"; @@ -63,15 +72,19 @@ public class MsoRestClientNewTest { securedServer = new StubServer().secured().run(); Path resourceDirectory = - Paths.get("src", "test", "resources", "WEB-INF", "conf", "system.properties"); - try(InputStream is = Files.newInputStream(resourceDirectory)) { + Paths.get("src", "test", "resources", "WEB-INF", "conf", "system.properties"); + try (InputStream is = Files.newInputStream(resourceDirectory)) { props.load(is); } Path msoServiceInstantiationJsonFilePath = - Paths.get("src", "test", "resources", "payload_jsons", "mso_service_instantiation.json"); + Paths.get("src", "test", "resources", "payload_jsons", "mso_service_instantiation.json"); + + Path scaleOutJsonFilePath = Paths.get("src", "test", "resources", "payload_jsons", "scaleOutVfModulePayloadToMso.json"); msoCreateServiceInstanceJson = - String.join("\n", Files.readAllLines(msoServiceInstantiationJsonFilePath)); + String.join("\n", Files.readAllLines(msoServiceInstantiationJsonFilePath)); + msoScaleOutVfModule = String.join("\n", Files.readAllLines(scaleOutJsonFilePath)); + } @AfterClass @@ -89,11 +102,11 @@ public class MsoRestClientNewTest { public void testCreateSvcInstance() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_CONFIGURATIONS); endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - endpoint, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createSvcInstance); } } @@ -102,12 +115,12 @@ public class MsoRestClientNewTest { public void testCreateVnf() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - endpoint, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { - + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVnf); } } @@ -116,11 +129,11 @@ public class MsoRestClientNewTest { public void testCreateNwInstance() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); String nw_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - nw_endpoint, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + nw_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createNwInstance); } } @@ -130,11 +143,11 @@ public class MsoRestClientNewTest { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); vnf_endpoint = vnf_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - vnf_endpoint, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + vnf_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVolumeGroupInstance); } } @@ -144,14 +157,14 @@ public class MsoRestClientNewTest { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); String partial_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String vf_module_endpoint = - partial_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + partial_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - vf_module_endpoint, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + vf_module_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVfModuleInstance); } } @@ -170,36 +183,38 @@ public class MsoRestClientNewTest { } catch (Exception e) { } } - + @Ignore @Test public void testDeleteSvcInstance() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - endpoint, - HttpStatus.NO_CONTENT_204, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteSvcInstance); } } + @Ignore @Test public void testDeleteVnf() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - endpoint, - HttpStatus.NO_CONTENT_204, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVnf); } } + @Ignore @Test public void testDeleteVfModule() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); @@ -207,15 +222,16 @@ public class MsoRestClientNewTest { String vf_modules_endpoint = part_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); String delete_vf_endpoint = vf_modules_endpoint + '/' + SAMPLE_VNF_MODULE_ID; - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - delete_vf_endpoint, - HttpStatus.NO_CONTENT_204, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + delete_vf_endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVfModule); } } + @Ignore @Test public void testDeleteVolumeGroupInstance() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); @@ -223,15 +239,16 @@ public class MsoRestClientNewTest { String vnf_endpoint = svc_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); String delete_volume_group_endpoint = vnf_endpoint + "/" + SAMPLE_VNF_MODULE_ID; - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - delete_volume_group_endpoint, - HttpStatus.NO_CONTENT_204, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + delete_volume_group_endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVolumeGroupInstance); } } + @Ignore @Test public void testDeleteNwInstance() throws Exception { String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); @@ -410,11 +427,11 @@ public class MsoRestClientNewTest { String serviceEndpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); String removeRelationshipsPath = serviceEndpoint + "/" + SERVICE_INSTANCE_ID + "/removeRelationships"; - try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( - server, - removeRelationshipsPath, - HttpStatus.ACCEPTED_202, - CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + removeRelationshipsPath, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::removeRelationshipFromServiceInstance); } } @@ -433,6 +450,20 @@ public class MsoRestClientNewTest { } catch (Exception e) { } } + @Test + public void testScaleOutVfModule() throws IOException { + String serviceEndpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_SCALE_OUT); + String partial_endpoint = serviceEndpoint.replaceFirst(SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + String vf_module_endpoint = partial_endpoint.replaceFirst(VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + vf_module_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR, CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePostCall(msoScaleOutVfModule, msoRestClient()::scaleOutVFModuleInstance); + } + + } private MsoRestClientNew msoRestClient() { return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), baseUrl()); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java index e8f556999..c81fa16fd 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java @@ -20,11 +20,13 @@ import java.util.function.BiFunction; import java.util.function.Function; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; + import org.glassfish.grizzly.http.Method; import org.glassfish.grizzly.http.util.HttpStatus; import org.json.JSONObject; import org.junit.Assert; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.mso.MsoResponseWrapper; class MsoRestClientTestUtil implements AutoCloseable { @@ -60,6 +62,21 @@ class MsoRestClientTestUtil implements AutoCloseable { verifyServer(server, endpoint, Method.POST); } + void executePostCall(String jsonPayload, BiFunction<RequestDetailsWrapper, String, MsoResponseWrapper> func) throws IOException { + whenHttp(server) + .match(post(endpoint)) + .then(status(expectedStatus), jsonContent(responsePayload), contentType(MediaType.APPLICATION_JSON)); + + RequestDetailsWrapper sampleRequestDetails = + new ObjectMapper().readValue(jsonPayload, RequestDetailsWrapper.class); + + MsoResponseWrapper response = func.apply(sampleRequestDetails, endpoint); + JSONObject actualJson = new JSONObject(response.getEntity()); + + Assert.assertEquals(expectedStatus.getStatusCode(), response.getStatus()); + Assert.assertEquals(expectedResponseStr, actualJson.toString()); + verifyServer(server, endpoint, Method.POST); + } void executeDelete(String jsonPayload, BiFunction<RequestDetails, String, MsoResponseWrapper> func) throws IOException { diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java new file mode 100644 index 000000000..3d2a20b63 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.vid.services; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.UUID; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class AuditServiceImplTest { + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @InjectMocks + private AuditServiceImpl auditService; + + @BeforeClass + public void init() { + initMocks(this); + } + + @Test + public void setFailedAuditStatusFromMsoTest() { + + UUID jobUuid = UUID.randomUUID(); + String requestId = "1"; + int statusCode = HttpStatus.OK_200.getStatusCode(); + String msoResponse = "{}"; + + auditService.setFailedAuditStatusFromMso(jobUuid, requestId, statusCode, msoResponse); + + verify(asyncInstantiationBL, times(1)) + .auditMsoStatus( + Mockito.any(UUID.class), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString()); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java new file mode 100644 index 000000000..6677da357 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/BulkInstantiationServiceImplTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.vid.services; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.ws.rs.NotFoundException; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.model.JobBulk; +import org.onap.vid.model.JobModel; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +public class BulkInstantiationServiceImplTest { + + @Mock + private JobsBrokerService jobsBrokerService; + + @Mock + private JobAdapter jobAdapter; + + @InjectMocks + private BulkInstantiationServiceImpl testSubject; + + @BeforeSuite + public void before() { + initMocks(this); + } + + @BeforeMethod + public void resetMocks() { + reset(jobsBrokerService); + reset(jobAdapter); + } + + @Test + public void saveBulkTest() { + UUID uuid = UUID.randomUUID(); + Map<String, Object> bulkRequest = new HashMap<>(); + List<Job> jobList = new ArrayList<>(); + jobList.add(createJob(uuid)); + when(jobAdapter.createBulkOfJobs(bulkRequest)).thenReturn(jobList); + + JobBulk jobBulk = createJobBulk(jobList); + when(jobAdapter.toModelBulk(jobList)).thenReturn(jobBulk); + + JobBulk result = testSubject.saveBulk(bulkRequest); + + Assert.assertEquals(result.getJobs().size(), jobList.size()); + Assert.assertEquals(result.getJobs().get(0).getUuid(), uuid); + } + + @Test + public void getJobTest() { + UUID uuid = UUID.randomUUID(); + Job job = createJob(uuid); + doReturn(job).when(jobsBrokerService).peek(uuid); + JobModel jobModel = createJobModel(uuid); + when(jobAdapter.toModel(job)).thenReturn(jobModel); + + JobModel response = testSubject.getJob(uuid); + Assert.assertEquals(response.getUuid(), uuid); + } + + @Test(expectedExceptions = {NotFoundException.class}) + public void getJobTest_throwsExceptionOnEmptyUUID() { + UUID uuid = null; + Job job = createJob(uuid); + doReturn(job).when(jobsBrokerService).peek(uuid); + JobModel response = testSubject.getJob(uuid); + Assert.fail(); + } + + @Test(expectedExceptions = {NotFoundException.class}) + public void getJobTest_throwsExceptionCauseJobDoesNotExists() { + UUID uuid = UUID.randomUUID(); + doReturn(null).when(jobsBrokerService).peek(uuid); + JobModel response = testSubject.getJob(uuid); + Assert.fail(); + } + + private Job createJob(UUID uuid) { + Job job = new JobDaoImpl(); + job.setUuid(uuid); + return job; + } + + private JobModel createJobModel(UUID uuid) { + JobModel jobModel = new JobModel(); + jobModel.setUuid(uuid); + return jobModel; + } + + private JobBulk createJobBulk(List<Job> jobList) { + List<JobModel> jobBulkList = new ArrayList<>(); + jobList.stream().forEach(job -> { + JobModel jm = new JobModel(); + jm.setUuid(job.getUuid()); + jobBulkList.add(jm); + }); + return new JobBulk(jobBulkList); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/CategoryParameterServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/CategoryParameterServiceImplTest.java index 440a2a7bf..6ac7b5447 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/CategoryParameterServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/CategoryParameterServiceImplTest.java @@ -1,80 +1,262 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 Nokia. 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.vid.services; -import org.junit.Test; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.ws.rs.ForbiddenException; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.portalsdk.core.service.DataAccessService; 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.CategoryParameter.Family; import org.onap.vid.model.CategoryParameterOption; +import org.onap.vid.services.CategoryParameterServiceImpl.AlreadyExistOptionNameException; +import org.onap.vid.services.CategoryParameterServiceImpl.UnfoundedCategoryException; +import org.onap.vid.services.CategoryParameterServiceImpl.UnfoundedCategoryOptionException; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; public class CategoryParameterServiceImplTest { - private CategoryParameterServiceImpl createTestSubject() { - return new CategoryParameterServiceImpl(); + private static final String CATEGORY_NAME = "SAMPLE_CATEGORY_NAME"; + private static final String OPTION_NAME = "SAMPLE_OPTION_NAME"; + private static final String UNIQUE_OPTION_NAME = "UNIQUE_OPTION_NAME"; + private static final String APP_ID_VID = "VID"; + private static final String APP_ID_SDC = "SDC"; + private static final String QUERY_STRING_FOR_CATEGORY_NAME = String.format(" where name = '%s' ", CATEGORY_NAME); + + + @Mock + private DataAccessService dataAccessService; + + @InjectMocks + private CategoryParameterServiceImpl testSubject; + + @BeforeSuite + public void before() { + initMocks(this); + } + + @BeforeMethod + public void resetMocks() { + reset(dataAccessService); } @Test - public void testCreateCategoryParameterOptions() throws Exception { - CategoryParameterServiceImpl testSubject; - String categoryName = ""; - AddCategoryOptionsRequest optionsRequest = null; - AddCategoryOptionResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createCategoryParameterOptions(categoryName, optionsRequest); - } catch ( - - Exception e) { - } + public void createCategoryParameterOptions_happyPath() { + AddCategoryOptionsRequest optionsRequest = new AddCategoryOptionsRequest(); + optionsRequest.options.add(UNIQUE_OPTION_NAME); + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.createCategoryParameterOptions(CATEGORY_NAME, optionsRequest); + + Assert.assertTrue(result.getErrors().isEmpty());; + verify(dataAccessService, times(1)) + .saveDomainObject(anyObject(), anyObject()); } @Test - public void testDeleteCategoryOption() throws Exception { - CategoryParameterServiceImpl testSubject; - String categoryName = ""; + public void createCategoryParameterOptions_existingOptionsForCategory() { + AddCategoryOptionsRequest optionsRequest = new AddCategoryOptionsRequest(); + optionsRequest.options.add(OPTION_NAME); + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + categoryParameter.getOptions().add(new CategoryParameterOption(APP_ID_VID, OPTION_NAME, categoryParameter)); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + String expectedError = String.format(CategoryParameterServiceImpl.OPTION_ALREADY_EXIST_FOR_CATEGORY + , OPTION_NAME, CATEGORY_NAME); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.createCategoryParameterOptions(CATEGORY_NAME, optionsRequest); + + Assert.assertFalse(result.getErrors().isEmpty()); + Assert.assertEquals(result.getErrors().size(), 1); + Assert.assertTrue(result.getErrors().stream().allMatch(expectedError::equals)); + } + + private List<CategoryParameter> createCategoryParametersList(CategoryParameter categoryParameter) { + List<CategoryParameter> aList = new ArrayList<>(); + aList.add(categoryParameter); + return aList; + } + + @Test + public void createCategoryParameterOptions_nonExistingOptionsForCategory() { + AddCategoryOptionsRequest optionsRequest = new AddCategoryOptionsRequest(); + + List<CategoryParameter> aList = createCategoryParametersList(new CategoryParameter()); + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.createCategoryParameterOptions(CATEGORY_NAME, optionsRequest); + + Assert.assertTrue(result.getErrors().isEmpty()); + } + + @Test(expectedExceptions = { UnfoundedCategoryException.class }) + public void createCategoryParameterOptions_wrongNumberOfCategoryParameters() { + AddCategoryOptionsRequest optionsRequest = new AddCategoryOptionsRequest(); + List<CategoryParameter> aList = Collections.emptyList(); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.createCategoryParameterOptions(CATEGORY_NAME, optionsRequest); + + Assert.fail(); + } + + @Test(expectedExceptions = { UnfoundedCategoryException.class }) + public void deleteCategoryOption_wrongNumberOfParameters() { CategoryParameterOption option = null; + List<CategoryParameter> aList = Collections.emptyList(); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + testSubject.deleteCategoryOption(CATEGORY_NAME, option); - // default test - try { - testSubject = createTestSubject(); - testSubject.deleteCategoryOption(categoryName, option); - } catch ( + Assert.fail(); + } + + @Test + public void deleteCategoryOption_happyPath() { + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + CategoryParameterOption categoryParameterOption = + new CategoryParameterOption(APP_ID_VID, OPTION_NAME, categoryParameter); + categoryParameter.getOptions().add(categoryParameterOption); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(anyObject(), anyString(), anyString(), anyObject()); - Exception e) { - } + testSubject.deleteCategoryOption(CATEGORY_NAME, categoryParameterOption); + + verify(dataAccessService, times(1)) + .deleteDomainObject(anyObject(), anyObject()); } @Test - public void testGetCategoryParameters() throws Exception { - CategoryParameterServiceImpl testSubject; - CategoryParametersResponse result; - - // default test - try { - testSubject = createTestSubject(); - testSubject.getCategoryParameters(null); - } catch ( - - Exception e) { - } + public void getCategoryParametersTest() { + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + CategoryParameterOption categoryParameterOption = + new CategoryParameterOption(APP_ID_VID, OPTION_NAME, categoryParameter); + categoryParameter.getOptions().add(categoryParameterOption); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(anyObject(), anyString(), anyString(), anyObject()); + + CategoryParametersResponse response = testSubject.getCategoryParameters(Family.PARAMETER_STANDARDIZATION); + + Assert.assertFalse(response.getCategoryParameters().isEmpty()); + Assert.assertTrue(response.getCategoryParameters().containsKey(CATEGORY_NAME)); + + verify(dataAccessService, times(1)) + .getList(anyObject(), anyString(), anyString(), anyObject()); } @Test - public void testUpdateCategoryParameterOption() throws Exception { - CategoryParameterServiceImpl testSubject; - String categoryName = ""; - CategoryParameterOptionRep option = null; - AddCategoryOptionResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.updateCategoryParameterOption(categoryName, option); - } catch ( - - Exception e) { - } + public void updateCategoryParameterOption_domainObjectGetsSavedSuccessfully() { + CategoryParameterOptionRep optionRepExisting = new CategoryParameterOptionRep(APP_ID_VID, OPTION_NAME); + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + categoryParameter.getOptions().add( + new CategoryParameterOption(APP_ID_VID, UNIQUE_OPTION_NAME, categoryParameter)); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.updateCategoryParameterOption(CATEGORY_NAME, optionRepExisting); + + verify(dataAccessService, times(1)) + .saveDomainObject(anyObject(), anyObject()); + } + + @Test(expectedExceptions = { ForbiddenException.class }) + public void updateCategoryParameterOption_shouldFailUpdateForbidden() { + CategoryParameterOptionRep optionRep = new CategoryParameterOptionRep("1", CATEGORY_NAME); + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, false); + categoryParameter.getOptions().add(new CategoryParameterOption(APP_ID_VID, OPTION_NAME, categoryParameter)); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.updateCategoryParameterOption(CATEGORY_NAME, optionRep); + + Assert.fail(); + } + + @Test(expectedExceptions = { UnfoundedCategoryOptionException.class }) + public void updateCategoryParameterOption_CategoryNotFound() { + CategoryParameterOptionRep optionRep = new CategoryParameterOptionRep("SOME_UNRELATED_ID", CATEGORY_NAME); + + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + categoryParameter.getOptions().add(new CategoryParameterOption(APP_ID_VID, OPTION_NAME, categoryParameter)); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.updateCategoryParameterOption(CATEGORY_NAME, optionRep); + + Assert.fail(); + } + + @Test(expectedExceptions = { AlreadyExistOptionNameException.class }) + public void updateCategoryParameterOption_OptionNameExists() { + CategoryParameterOptionRep optionRepExisting = new CategoryParameterOptionRep(APP_ID_VID, OPTION_NAME); + + CategoryParameter categoryParameter = createCategoryParameter(CATEGORY_NAME, true); + CategoryParameter anotherCategoryParameter = createCategoryParameter(CATEGORY_NAME, true); + categoryParameter.getOptions().add( + new CategoryParameterOption(APP_ID_VID, UNIQUE_OPTION_NAME, anotherCategoryParameter)); + categoryParameter.getOptions().add( + new CategoryParameterOption(APP_ID_SDC, OPTION_NAME, anotherCategoryParameter)); + List<CategoryParameter> aList = createCategoryParametersList(categoryParameter); + + doReturn(aList).when(dataAccessService).getList(CategoryParameter.class, QUERY_STRING_FOR_CATEGORY_NAME, null, null); + + AddCategoryOptionResponse result = testSubject.updateCategoryParameterOption(CATEGORY_NAME, optionRepExisting); + + Assert.fail(); + } + + private CategoryParameter createCategoryParameter(String categoryName, boolean idSupported) { + CategoryParameter categoryParameter = new CategoryParameter(); + categoryParameter.setName(categoryName); + categoryParameter.setIdSupported(idSupported); + return categoryParameter; } }
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/PombaServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/PombaServiceImplTest.java new file mode 100644 index 000000000..d0eec2619 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/PombaServiceImplTest.java @@ -0,0 +1,40 @@ +package org.onap.vid.services; + +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.vid.aai.PombaClientInterface; +import org.onap.vid.model.PombaInstance.PombaRequest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +public class PombaServiceImplTest { + + @Mock + private PombaClientInterface pombaClientInterface; + + @InjectMocks + private PombaServiceImpl testSubject; + + @BeforeClass + public void beforeClass() { + initMocks(this); + } + + @BeforeMethod + public void resetMocks() { + Mockito.reset(pombaClientInterface); + } + + @Test + public void testVerify() { + PombaRequest pombaRequest = new PombaRequest(); + testSubject.verify(pombaRequest); + verify(pombaClientInterface, times(1)) + .verify(pombaRequest); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java index 544a799a0..d7db4955c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java @@ -1,25 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2018 Nokia. 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.vid.services; -import static org.junit.Assert.*; -import java.util.*; -import org.junit.Assert; -import org.junit.Test; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.ArrayList; +import org.apache.commons.lang.StringUtils; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.ServiceSubscription; +import org.onap.vid.aai.ServiceSubscriptions; +import org.onap.vid.aai.Services; +import org.onap.vid.model.Subscriber; +import org.onap.vid.model.SubscriberList; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; public class RoleGenaratorServiceImplTest { - private RoleGenaratorServiceImpl createTestSubject() { - return new RoleGenaratorServiceImpl(); + private static final String GLOBAL_CUSTOMER_ID = "997"; + private static final String SUBSCRIBER_NAME = "name"; + private static final String SUBSCRIBER_TYPE = "subscriber_type"; + private static final String RESOURCE_VERSION = "1"; + private static final String SERVICE_TYPE = "service_type"; + + @Mock + private AaiClientInterface aaiClientInterface; + + @InjectMocks + private RoleGenaratorServiceImpl testSubject; + + @BeforeClass + public void beforeClass() { + initMocks(this); + } + + @BeforeMethod + public void resetMocks() { + Mockito.reset(aaiClientInterface); + } + + @Test + public void tenerateRoleScript_firstRun() { + boolean firstRun = true; + + Subscriber subscriber = createSubscriber(); + AaiResponse<SubscriberList> subscribers = createSubscriberListAaiResponse(subscriber); + doReturn(subscribers).when(aaiClientInterface).getAllSubscribers(); + + ServiceSubscription serviceSubscription = createServiceSubscription(); + AaiResponse<Services> subscriberResponse = createServicesAaiResponse(serviceSubscription); + doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId); + + String result = testSubject.generateRoleScript(firstRun); + Assert.assertTrue(StringUtils.isNotBlank(result)); } @Test - public void testGenerateRoleScript() throws Exception { - RoleGenaratorServiceImpl testSubject; - Boolean firstRun = null; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.generateRoleScript(firstRun); + public void tenerateRoleScript_notAFirstRun() { + boolean firstRun = false; + + Subscriber subscriber = createSubscriber(); + AaiResponse<SubscriberList> subscribers = createSubscriberListAaiResponse(subscriber); + doReturn(subscribers).when(aaiClientInterface).getAllSubscribers(); + + ServiceSubscription serviceSubscription = createServiceSubscription(); + AaiResponse<Services> subscriberResponse = createServicesAaiResponse(serviceSubscription); + doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId); + + String result = testSubject.generateRoleScript(firstRun); + Assert.assertTrue(StringUtils.isNotBlank(result)); + } + + @Test(expectedExceptions = { Exception.class }) + public void tenerateRoleScript_errorGettingDataFromAAIClient() { + boolean firstRun = false; + + doThrow(new Exception("This is expected.")).when(aaiClientInterface).getAllSubscribers(); + + String result = testSubject.generateRoleScript(firstRun); + Assert.fail(); + } + + private ServiceSubscription createServiceSubscription() { + ServiceSubscription serviceSubscription = new ServiceSubscription(); + serviceSubscription.serviceType = SERVICE_TYPE; + return serviceSubscription; + } + + private AaiResponse<SubscriberList> createSubscriberListAaiResponse(Subscriber subscriber) { + AaiResponse<SubscriberList> subscribers = new AaiResponse<>(new SubscriberList(new ArrayList<>()), "", 200); + subscribers.getT().customer.add(subscriber); + return subscribers; + } + + private AaiResponse<Services> createServicesAaiResponse(ServiceSubscription serviceSubscription) { + AaiResponse<Services> subscriberResponse = new AaiResponse<>(new Services(), "", 200); + subscriberResponse.getT().serviceSubscriptions = new ServiceSubscriptions(); + subscriberResponse.getT().serviceSubscriptions.serviceSubscription = new ArrayList<>(); + subscriberResponse.getT().serviceSubscriptions.serviceSubscription.add(serviceSubscription); + return subscriberResponse; + } + + private Subscriber createSubscriber() { + Subscriber subscriber = new Subscriber(); + subscriber.globalCustomerId = GLOBAL_CUSTOMER_ID; + subscriber.subscriberName = SUBSCRIBER_NAME; + subscriber.subscriberType = SUBSCRIBER_TYPE; + subscriber.resourceVersion = RESOURCE_VERSION; + return subscriber; } |