From 3a5484cadba6a7d33e7c85930c52541687fd2c92 Mon Sep 17 00:00:00 2001 From: root Date: Wed, 13 Jun 2018 12:37:59 +0100 Subject: Unit tests APPC-443 Unit test for request-handler Change-Id: Ida894d4c9ba920a6b8b7e105caab7952bd3be420 Signed-off-by: Joss Armstrong Issue-ID: APPC-443 --- .../appc-request-handler-core/pom.xml | 5 + .../impl/AbstractRequestHandlerImplTest.java | 225 +++++++++++++ .../impl/LocalRequestHandlerImplTest.java | 120 ++++--- .../impl/LocalRequestHanlderTestHelper.java | 51 ++- .../impl/LocalRequestValidatorImplTest.java | 50 ++- .../impl/RequestHandlerImplTest.java | 272 ++++++++++++++++ .../impl/RequestValidatorImplTest.java | 354 ++++++++++++++++++++- 7 files changed, 991 insertions(+), 86 deletions(-) create mode 100755 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java create mode 100755 appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java (limited to 'appc-dispatcher/appc-request-handler') diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/pom.xml b/appc-dispatcher/appc-request-handler/appc-request-handler-core/pom.xml index 00f0daa30..6bf2335de 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/pom.xml +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/pom.xml @@ -77,6 +77,11 @@ appc-workflow-management-api ${project.version} + + org.onap.appc + appc-workflow-management-core + ${project.version} + org.onap.appc appc-request-handler-api diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java new file mode 100755 index 000000000..226c670da --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/AbstractRequestHandlerImplTest.java @@ -0,0 +1,225 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RequestStatus; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.Status; +import org.onap.appc.domainmodel.lcm.TransactionRecord; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.messageadapter.MessageAdapter; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.impl.MetricRegistryImpl; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.impl.DispatchingFuntionMetricImpl; +import org.onap.appc.requesthandler.exceptions.RequestValidationException; +import org.onap.appc.requesthandler.helper.RequestValidator; +import org.onap.appc.requesthandler.objects.RequestHandlerInput; +import org.onap.appc.requesthandler.objects.RequestHandlerOutput; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class AbstractRequestHandlerImplTest implements LocalRequestHanlderTestHelper { + + private AbstractRequestHandlerImpl requestHandler; + private TransactionRecorder recorder; + + @Before + public void setUp() throws Exception { + setupForHandlerImplTests(); + requestHandler = spy(new LocalRequestHandlerImpl()); + recorder = mock(TransactionRecorder.class); + requestHandler.setTransactionRecorder(recorder); + List result = Arrays.asList(RequestStatus.ACCEPTED); + PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result); + final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(requestHandler, "logger", logger); + } + + @Test + public void testHandleRequestAbstractRequestHandler() { + RequestHandlerInput rhi = setupTestForHandleRequest(); + RequestValidator rv = mock(RequestValidator.class); + doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class)); + requestHandler.setRequestValidator(rv); + Assert.assertTrue(requestHandler.handleRequest(rhi) instanceof RequestHandlerOutput); + } + + @Test + public void testHandleRequestAbstractRequestHandlerRequestValidationException() throws Exception { + RequestHandlerInput rhi = setupTestForHandleRequest(); + RequestValidator rv = mock(RequestValidator.class); + RequestValidationException rve = new RequestValidationException("TEST"); + rve.setTargetEntity("TEST_TARGET_ENTITY"); + rve.setTargetService("TEST_TARGET_SERVICE"); + rve.setLogMessage("TEST_LOG_MESSAGE"); + rve.setLcmCommandStatus(LCMCommandStatus.SUCCESS); + rve.setParams(null); + RequestHandlerOutput output = null; + doThrow(rve).when(rv).validateRequest(Mockito.any(RuntimeContext.class)); + doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class)); + requestHandler.setRequestValidator(rv); + output = requestHandler.handleRequest(rhi); + Assert.assertEquals(LCMCommandStatus.SUCCESS.getResponseCode(), + output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testHandleRequestAbstractRequestHandlerInvalidInputException() throws Exception { + RequestHandlerInput rhi = setupTestForHandleRequest(); + RequestValidator rv = mock(RequestValidator.class); + InvalidInputException iie = new InvalidInputException("TEST"); + RequestHandlerOutput output = null; + doThrow(iie).when(rv).validateRequest(Mockito.any(RuntimeContext.class)); + doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class)); + requestHandler.setRequestValidator(rv); + output = requestHandler.handleRequest(rhi); + Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(), + output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testHandleRequestAbstractRequestHandlerLockException() throws Exception { + RequestHandlerInput rhi = setupTestNoMetric(); + RequestValidator rv = mock(RequestValidator.class); + LockException le = new LockException("TEST"); + RequestHandlerOutput output = null; + doThrow(le).when(rv).validateRequest(Mockito.any(RuntimeContext.class)); + doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class)); + requestHandler.setRequestValidator(rv); + output = requestHandler.handleRequest(rhi); + Assert.assertEquals(LCMCommandStatus.LOCKED_VNF_ID.getResponseCode(), + output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testHandleRequestAbstractRequestHandlerException() throws Exception { + RequestHandlerInput rhi = setupTestNoMetric(); + RequestValidator rv = mock(RequestValidator.class); + Exception exception = new Exception("TEST"); + RequestHandlerOutput output = null; + doThrow(exception).when(rv).validateRequest(Mockito.any(RuntimeContext.class)); + doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class)); + requestHandler.setRequestValidator(rv); + output = requestHandler.handleRequest(rhi); + Assert.assertEquals(LCMCommandStatus.UNEXPECTED_ERROR.getResponseCode(), + output.getResponseContext().getStatus().getCode()); + } + + @Test + public void testOnRequestExecutionEnd() { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + TransactionRecord record = new TransactionRecord(); + record.setRequestState(RequestStatus.ACCEPTED); + runtimeContext.setTransactionRecord(record); + MessageAdapter messageAdapter = mock(MessageAdapter.class); + requestHandler.setMessageAdapter(messageAdapter); + RequestContext rc = mock(RequestContext.class); + Status status = new Status(); + status.setCode(100); + ResponseContext responseContext = spy(new ResponseContext()); + Mockito.doReturn(status).when(responseContext).getStatus(); + Mockito.doReturn(VNFOperation.ActionStatus).when(rc).getAction(); + Mockito.doReturn(rc).when(runtimeContext).getRequestContext(); + Mockito.doReturn(responseContext).when(runtimeContext).getResponseContext(); + requestHandler.onRequestExecutionEnd(runtimeContext); + Mockito.verify(runtimeContext, times(3)).getTransactionRecord(); + } + + @Test + public void testGetInprogressRequestCount() throws APPCException { + int i = 0; + Mockito.doReturn(19).when(recorder).getInProgressRequestsCount(); + i = requestHandler.getInprogressRequestCount(); + Assert.assertEquals(19, i); + } + + private RequestHandlerInput setupTestForHandleRequest() { + Whitebox.setInternalState(requestHandler, "isMetricEnabled", true); + MetricRegistry metricRegistry = spy(new MetricRegistryImpl("TEST_METRIC_REGISTRY")); + DispatchingFuntionMetricImpl metric = + spy(new DispatchingFuntionMetricImpl("DISPATCH_FUNCTION", MetricType.COUNTER, 0, 0)); + metricRegistry.register(metric); + doNothing().when(metric).incrementAcceptedRequest(); + Whitebox.setInternalState(RequestHandlerImpl.class, "metricRegistry", metricRegistry); + RequestHandlerInput rhi = new RequestHandlerInput(); + RequestContext rc = new RequestContext(); + CommonHeader ch = new CommonHeader(); + rc.setCommonHeader(ch); + ch.setRequestId("TEST"); + ch.setTimestamp(new Date(System.currentTimeMillis())); + VNFOperation vo = VNFOperation.findByString("ActionStatus"); + rc.setAction(vo); + ActionIdentifiers ai = new ActionIdentifiers(); + rc.setActionIdentifiers(ai); + rhi.setRequestContext(rc); + return rhi; + } + + private RequestHandlerInput setupTestNoMetric() { + RequestHandlerInput rhi = new RequestHandlerInput(); + RequestContext rc = new RequestContext(); + CommonHeader ch = new CommonHeader(); + rc.setCommonHeader(ch); + ch.setRequestId("TEST"); + ch.setTimestamp(new Date(System.currentTimeMillis())); + VNFOperation vo = VNFOperation.findByString("ActionStatus"); + rc.setAction(vo); + ActionIdentifiers ai = new ActionIdentifiers(); + rc.setActionIdentifiers(ai); + rhi.setRequestContext(rc); + return rhi; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImplTest.java index f19eee14d..f44aa3907 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImplTest.java +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHandlerImplTest.java @@ -5,60 +5,54 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2017 Amdocs - * ============================================================================= + * ================================================================================ + * Copyright (C) 2018 Ericsson. 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.appc.requesthandler.impl; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.onap.appc.adapter.message.MessageAdapterFactory; -import org.onap.appc.adapter.message.Producer; -import org.onap.appc.domainmodel.lcm.ActionLevel; -import org.onap.appc.domainmodel.lcm.RequestContext; import org.onap.appc.domainmodel.lcm.RequestStatus; -import org.onap.appc.domainmodel.lcm.ResponseContext; import org.onap.appc.domainmodel.lcm.RuntimeContext; -import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.domainmodel.lcm.Status; import org.onap.appc.exceptions.APPCException; import org.onap.appc.requesthandler.exceptions.MultipleRecordsRetrievedException; import org.onap.appc.transactionrecorder.TransactionRecorder; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; -import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyCollection; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.powermock.api.mockito.PowerMockito.mockStatic; /** * Test class for LocalRequestHandlerImpl @@ -70,41 +64,24 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe private final String vnfId = "vnfId"; private final String subRequestId = "subRequestId"; private final String originatorId = "originatorId"; - private final String ACCEPTED_IN_PROGRESS_Response = "{\"status-reason\":\"ACCEPTED\"," + - "\"status\":\"IN_PROGRESS\"}"; - private final String SUCCESSFUL_SUCCESSFUL_Response = "{\"status-reason\":\"SUCCESSFUL\"," + - "\"status\":\"SUCCESSFUL\"}"; - private final String RECEIVED_IN_PROGRESS_Response = "{\"status-reason\":\"RECEIVED\"," + - "\"status\":\"IN_PROGRESS\"}"; - private final String UNKNOWN_FAILED_Response = "{\"status-reason\":\"UNKNOWN\"," + - "\"status\":\"FAILED\"}"; + private final String ACCEPTED_IN_PROGRESS_Response = "{\"status-reason\":\"ACCEPTED\"," + + "\"status\":\"IN_PROGRESS\"}"; + private final String SUCCESSFUL_SUCCESSFUL_Response = "{\"status-reason\":\"SUCCESSFUL\"," + + "\"status\":\"SUCCESSFUL\"}"; + private final String RECEIVED_IN_PROGRESS_Response = "{\"status-reason\":\"RECEIVED\"," + + "\"status\":\"IN_PROGRESS\"}"; + private final String UNKNOWN_FAILED_Response = "{\"status-reason\":\"UNKNOWN\"," + + "\"status\":\"FAILED\"}"; private LocalRequestHandlerImpl requestHandler; private TransactionRecorder recorder; @Before public void setUp() throws Exception { - mockStatic(FrameworkUtil.class); - Bundle myBundle = mock(Bundle.class); - PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); - - BundleContext myBundleContext = mock(BundleContext.class); - Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext); - - ServiceReference svcRef = mock(ServiceReference.class); - Mockito.when(myBundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(svcRef); - - Producer producer = mock(Producer.class); - MessageAdapterFactory factory = mock(MessageAdapterFactory.class); - Mockito.when(myBundleContext.getService(svcRef)).thenReturn(factory); - Mockito.when(factory.createProducer(anyCollection(), anyString(), anyString(), anyString())).thenReturn - (producer); - + setupForHandlerImplTests(); requestHandler = spy(new LocalRequestHandlerImpl()); - recorder = mock(TransactionRecorder.class); requestHandler.setTransactionRecorder(recorder); - List result = Arrays.asList(RequestStatus.ACCEPTED); PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result); } @@ -116,9 +93,9 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe */ @Test public void testHandleRequestSuccessfulWithSearchCriteriaOne() throws APPCException { - final String payload = "{\"request-id\":\"requestId\"," + - "\"sub-request-id\":\"subRequestId\"," + - "\"originator-id\":\"originatorId\"}"; + final String payload = "{\"request-id\":\"requestId\"," + + "\"sub-request-id\":\"subRequestId\"," + + "\"originator-id\":\"originatorId\"}"; List result = Arrays.asList(RequestStatus.SUCCESSFUL); PowerMockito.when(recorder.getRecords(requestId, subRequestId, originatorId, vnfId)).thenReturn(result); @@ -135,9 +112,9 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe */ @Test public void testHandleRequestReceivedWithSearchCriteriaOne() throws APPCException { - final String payload = "{\"request-id\":\"requestId\"," + - "\"sub-request-id\":\"subRequestId\"," + - "\"originator-id\":\"originatorId\"}"; + final String payload = "{\"request-id\":\"requestId\"," + + "\"sub-request-id\":\"subRequestId\"," + + "\"originator-id\":\"originatorId\"}"; List result = Arrays.asList(RequestStatus.RECEIVED); PowerMockito.when(recorder.getRecords(requestId, subRequestId, originatorId, vnfId)).thenReturn(result); @@ -154,8 +131,8 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe */ @Test public void testHandleRequestFailedWithSearchCriteriaTwo() throws APPCException { - final String payload = "{\"request-id\":\"requestId\"," + - "\"sub-request-id\":\"subRequestId\"}"; + final String payload = "{\"request-id\":\"requestId\"," + + "\"sub-request-id\":\"subRequestId\"}"; List result = Arrays.asList(RequestStatus.UNKNOWN); PowerMockito.when(recorder.getRecords(requestId, subRequestId, null, vnfId)).thenReturn(result); @@ -166,7 +143,6 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe } @Test - public void testSuccessHandleRequest() throws Exception { RuntimeContext runtimeContext = createRequestHandlerRuntimeContext("vnfId", "{\"request-id\":\"request-id\"}"); @@ -215,8 +191,28 @@ public class LocalRequestHandlerImplTest implements LocalRequestHanlderTestHelpe RequestStatus status = Whitebox.invokeMethod(requestHandler, "getStatusOfRequest", requestId, null, null, vnfId); - Assert.assertTrue(status.name().equals("NOT_FOUND")); + Assert.assertEquals("NOT_FOUND",status.name()); } - -} + @Test + public void testHandleRequestMultipleRecordException() throws Exception { + final EELFLogger logger = spy(EELFManager.getInstance().getLogger(LocalRequestHandlerImpl.class)); + Whitebox.setInternalState(requestHandler, "logger", logger); + RuntimeContext runtimeContext = createRequestHandlerRuntimeContext("vnfId", + "{\"request-id\":\"request-id\"}"); + RequestStatus rs1 = RequestStatus.ABORTED; + RequestStatus rs2 = RequestStatus.ACCEPTED; + List rqList = new ArrayList(2); + rqList.add(rs1); + rqList.add(rs2); + Mockito.when(recorder.getRecords(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString())).thenReturn(rqList); + requestHandler.handleRequest(runtimeContext); + Status status = new Status(); + status.setCode(315); + status.setMessage("MULTIPLE REQUESTS FOUND - using search criteria: request-id=request-id AND vnf-id=vnfId"); + Mockito.verify(logger).debug("RequestStatus is set to MULTIPLE_REQUESTS_FOUND due to " + + "MultipleRecordsRetrievedException", "MULTIPLE REQUESTS FOUND USING SEARCH CRITERIA: request-id=" + + "request-id AND vnf-id=vnfId"); + } +} \ No newline at end of file diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHanlderTestHelper.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHanlderTestHelper.java index 69f3b7b3e..a6bbe571a 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHanlderTestHelper.java +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestHanlderTestHelper.java @@ -17,21 +17,40 @@ * 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.appc.requesthandler.impl; +import org.mockito.Mockito; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.appc.adapter.message.Producer; import org.onap.appc.domainmodel.lcm.ActionIdentifiers; import org.onap.appc.domainmodel.lcm.ActionLevel; import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RequestStatus; import org.onap.appc.domainmodel.lcm.ResponseContext; import org.onap.appc.domainmodel.lcm.RuntimeContext; import org.onap.appc.domainmodel.lcm.VNFOperation; - +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.requesthandler.RequestHandler; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyCollectionOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import java.util.Arrays; import java.util.Date; +import java.util.List; /** * Creates RequestContextInput for ActionStatus JUnits @@ -79,4 +98,32 @@ public interface LocalRequestHanlderTestHelper { builder.setTimestamp(new Date(System.currentTimeMillis())); return builder; } + + default CommonHeader getCommonHeader(String requestId, Date date) { + CommonHeader builder = new CommonHeader(); + builder.setRequestId(requestId); + builder.setTimestamp(date); + Flags flags = new Flags(); + flags.setTtl(0); + builder.setFlags(flags); + return builder; + } + + default void setupForHandlerImplTests() { + mockStatic(FrameworkUtil.class); + Bundle myBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); + + BundleContext myBundleContext = mock(BundleContext.class); + Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext); + + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(myBundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(svcRef); + + Producer producer = mock(Producer.class); + MessageAdapterFactory factory = mock(MessageAdapterFactory.class); + Mockito.when(myBundleContext.getService(svcRef)).thenReturn(factory); + Mockito.when(factory.createProducer(anyCollectionOf(String.class), anyString(), anyString(), anyString())) + .thenReturn(producer); + } } diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImplTest.java index 51dfa6a1b..27f0897cc 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImplTest.java +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/LocalRequestValidatorImplTest.java @@ -22,34 +22,40 @@ package org.onap.appc.requesthandler.impl; -// import com.att.eelf.configuration.EELFLogger; -// import com.att.eelf.configuration.EELFManager; + +import static org.junit.Assert.fail; +import static org.powermock.api.mockito.PowerMockito.spy; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; + +import java.util.Date; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.Matchers; -import org.mockito.runners.MockitoJUnitRunner; import org.onap.appc.domainmodel.lcm.ActionIdentifiers; -import org.onap.appc.domainmodel.lcm.ActionLevel; import org.onap.appc.domainmodel.lcm.RuntimeContext; import org.onap.appc.domainmodel.lcm.VNFOperation; import org.onap.appc.exceptions.InvalidInputException; import org.onap.appc.requesthandler.LCMStateManager; import org.onap.appc.requesthandler.exceptions.DuplicateRequestException; import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.exceptions.RequestExpiredException; import org.onap.appc.transactionrecorder.TransactionRecorder; - -import static org.powermock.api.mockito.PowerMockito.spy; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; /** * Test class for LocalRequestValidatorImpl */ -@RunWith(MockitoJUnitRunner.class) -public class LocalRequestValidatorImplTest implements LocalRequestHanlderTestHelper { - // protected final EELFLogger logger = EELFManager.getInstance().getLogger(LocalRequestValidatorImplTest.class); +@RunWith(PowerMockRunner.class) +public class LocalRequestValidatorImplTest implements LocalRequestHanlderTestHelper { @Mock private LCMStateManager lcmStateManager; @@ -67,6 +73,9 @@ public class LocalRequestValidatorImplTest implements LocalRequestHanlderTestHel Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true); Mockito.when(transactionRecorder.isTransactionDuplicate(Matchers.anyObject())).thenReturn(false); + final EELFLogger logger = EELFManager.getInstance().getLogger(LocalRequestValidatorImpl.class); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(requestValidator, "logger", logger); } @Test(expected = LCMOperationsDisabledException.class) @@ -99,7 +108,6 @@ public class LocalRequestValidatorImplTest implements LocalRequestHanlderTestHel RuntimeContext context = createRequestValidatorInput(); ActionIdentifiers ai = context.getRequestContext().getActionIdentifiers(); ai.setVnfId(null); - // logger.warn("Set vnfId in ActionIdentifiers extracted from createRequestValidatorInput's RequestContext to null"); requestValidator.validateRequest(context); } @@ -110,6 +118,26 @@ public class LocalRequestValidatorImplTest implements LocalRequestHanlderTestHel requestValidator.validateRequest(context); } + @Test(expected = InvalidInputException.class) + public void validateRequestInvalidInputInvalidTime() throws Exception { + RuntimeContext context = createRequestValidatorInput(); + context.getResponseContext().getCommonHeader().setTimestamp(new Date(System.currentTimeMillis() + 999999)); + final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestValidatorImpl.class); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(requestValidator, "logger", logger); + requestValidator.validateRequest(context); + } + + @Test(expected = RequestExpiredException.class) + public void validateRequestRequestExpiredException() throws Exception { + RuntimeContext context = createRequestValidatorInput(); + context.getResponseContext().getCommonHeader().setTimestamp(new Date(System.currentTimeMillis() - 999999)); + final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestValidatorImpl.class); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(requestValidator, "logger", logger); + requestValidator.validateRequest(context); + } + private RuntimeContext createRequestValidatorInput() { return createRequestHandlerRuntimeContext("VSCP", "{\"request-id\":\"request-id\"}"); } diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java new file mode 100755 index 000000000..f163c6eab --- /dev/null +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestHandlerImplTest.java @@ -0,0 +1,272 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.requesthandler.impl; + +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; +import com.att.eelf.i18n.EELFResourceManager; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.RequestStatus; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.VNFContext; +import org.onap.appc.domainmodel.lcm.VNFOperation; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.executor.CommandExecutor; +import org.onap.appc.executor.objects.CommandExecutorInput; +import org.onap.appc.executor.objects.LCMCommandStatus; +import org.onap.appc.executor.objects.Params; +import org.onap.appc.i18n.Msg; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.logging.LoggingConstants; +import org.onap.appc.metricservice.MetricRegistry; +import org.onap.appc.metricservice.impl.MetricRegistryImpl; +import org.onap.appc.metricservice.metric.MetricType; +import org.onap.appc.metricservice.metric.impl.DispatchingFuntionMetricImpl; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ FrameworkUtil.class }) +public class RequestHandlerImplTest implements LocalRequestHanlderTestHelper { + + private RequestHandlerImpl requestHandler; + private TransactionRecorder recorder; + private LockManager lockManager; + + @Before + public void setUp() throws Exception { + setupForHandlerImplTests(); + requestHandler = PowerMockito.spy(new RequestHandlerImpl()); + recorder = mock(TransactionRecorder.class); + requestHandler.setTransactionRecorder(recorder); + lockManager = mock(LockManager.class); + requestHandler.setLockManager(lockManager); + List result = Arrays.asList(RequestStatus.ACCEPTED); + PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result); + final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerImpl.class); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(requestHandler, "logger", logger); + } + + @Test + public void testHandleRequestRuntimeContext() { + Whitebox.setInternalState(requestHandler, "isMetricEnabled", true); + MetricRegistry metricRegistry = spy(new MetricRegistryImpl("TEST_METRIC_REGISTRY")); + DispatchingFuntionMetricImpl metric = spy( + new DispatchingFuntionMetricImpl("DISPATCH_FUNCTION", MetricType.COUNTER, 0, 0)); + metricRegistry.register(metric); + doNothing().when(metric).incrementAcceptedRequest(); + Whitebox.setInternalState(RequestHandlerImpl.class, "metricRegistry", metricRegistry); + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = setupRequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(runtimeContext, LCMCommandStatus.ACCEPTED, null); + } + + @Test + public void testHandleRequestRuntimeContextNegativeTTL() { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = setupRequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis() - 100000)); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(runtimeContext, LCMCommandStatus.EXPIRED_REQUEST, null); + + } + + @Test + public void testHandleRequestRuntimeContextAPPCException() throws APPCException { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = setupRequestContext(); + runtimeContext.setRequestContext(requestContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doThrow(new APPCException("TEST_APPC_EXCEPTION")).when(commandExecutor) + .executeCommand(Mockito.any(CommandExecutorInput.class)); + doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any(Params.class)); + } + + @Test + public void testHandleRequestRuntimeContextCaseLock() throws LockException { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = new RequestContext(); + requestContext.setAction(VNFOperation.Lock); + runtimeContext.setRequestContext(requestContext); + VNFContext vnfContext = new VNFContext(); + vnfContext.setId("TEST_VNF_CONTEXT_ID"); + runtimeContext.setVnfContext(vnfContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doReturn(true).when(lockManager).acquireLock(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); + } + + @Test + public void testHandleRequestRuntimeContextLockError() throws LockException { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = new RequestContext(); + requestContext.setAction(VNFOperation.Lock); + runtimeContext.setRequestContext(requestContext); + VNFContext vnfContext = new VNFContext(); + vnfContext.setId("TEST_VNF_CONTEXT_ID"); + runtimeContext.setVnfContext(vnfContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doThrow(new LockException("TEST_LOCK_EXCEPTION")).when(lockManager).acquireLock(Mockito.anyString(), + Mockito.anyString(), Mockito.anyLong()); + doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).storeErrorMessageToLog(runtimeContext, LoggingConstants.TargetNames.APPC, + LoggingConstants.TargetNames.LOCK_MANAGER, + EELFResourceManager.format(Msg.VF_SERVER_BUSY, "TEST_VNF_CONTEXT_ID")); + } + + @Test + public void testHandleRequestRuntimeContextCaseUnlock() throws LockException { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = new RequestContext(); + requestContext.setAction(VNFOperation.Unlock); + runtimeContext.setRequestContext(requestContext); + VNFContext vnfContext = new VNFContext(); + vnfContext.setId("TEST_VNF_CONTEXT_ID"); + runtimeContext.setVnfContext(vnfContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doReturn(true).when(lockManager).acquireLock(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(runtimeContext, LCMCommandStatus.SUCCESS, null); + } + + @Test + public void testHandleRequestRuntimeContextUnlockError() throws LockException { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = new RequestContext(); + requestContext.setAction(VNFOperation.Unlock); + runtimeContext.setRequestContext(requestContext); + VNFContext vnfContext = new VNFContext(); + vnfContext.setId("TEST_VNF_CONTEXT_ID"); + runtimeContext.setVnfContext(vnfContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doThrow(new LockException("TEST_LOCK_EXCEPTION")).when(lockManager).releaseLock(Mockito.anyString(), + Mockito.anyString()); + doNothing().when(requestHandler).storeErrorMessageToLog(Mockito.any(RuntimeContext.class), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString()); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any(Params.class)); + } + + @Test + public void testHandleRequestRuntimeContextCaseCheckLock() { + RuntimeContext runtimeContext = spy(new RuntimeContext()); + RequestContext requestContext = new RequestContext(); + ResponseContext responseContext = spy(new ResponseContext()); + runtimeContext.setResponseContext(responseContext); + requestContext.setAction(VNFOperation.CheckLock); + runtimeContext.setRequestContext(requestContext); + VNFContext vnfContext = new VNFContext(); + vnfContext.setId("TEST_VNF_CONTEXT_ID"); + runtimeContext.setVnfContext(vnfContext); + CommonHeader ch = getCommonHeader("TEST", new Date(System.currentTimeMillis())); + requestContext.setCommonHeader(ch); + CommandExecutor commandExecutor = mock(CommandExecutor.class); + requestHandler.setCommandExecutor(commandExecutor); + doNothing().when(requestHandler).fillStatus(Mockito.any(RuntimeContext.class), + Mockito.any(LCMCommandStatus.class), Mockito.any()); + doReturn(true).when(lockManager).isLocked("TEST_VNF_CONTEXT_ID"); + requestHandler.handleRequest(runtimeContext); + Mockito.verify(responseContext).addKeyValueToAdditionalContext("locked", String.valueOf(true).toUpperCase()); + } + + private RequestContext setupRequestContext() { + RequestContext requestContext = new RequestContext(); + requestContext.setAction(VNFOperation.ActionStatus); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setVnfId("TEST_VNF_ID"); + requestContext.setActionIdentifiers(actionIdentifiers); + return requestContext; + } +} diff --git a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java index 8ecb08757..e1c10dae1 100644 --- a/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java +++ b/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/test/java/org/onap/appc/requesthandler/impl/RequestValidatorImplTest.java @@ -5,44 +5,144 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Copyright (C) 2017 Amdocs - * ============================================================================= + * ================================================================================ + * Copyright (C) 2018 Ericsson. 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.appc.requesthandler.impl; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFLogger.Level; +import com.att.eelf.configuration.EELFManager; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.apache.http.HttpResponse; +import org.apache.http.ProtocolVersion; +import org.apache.http.entity.BasicHttpEntity; +import org.apache.http.message.BasicHttpResponse; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.internal.util.reflection.Whitebox; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.onap.appc.configuration.Configuration; +import org.onap.appc.configuration.ConfigurationFactory; +import org.onap.appc.domainmodel.lcm.ActionIdentifiers; +import org.onap.appc.domainmodel.lcm.CommonHeader; +import org.onap.appc.domainmodel.lcm.Flags; +import org.onap.appc.domainmodel.lcm.Flags.Mode; +import org.onap.appc.domainmodel.lcm.RequestContext; +import org.onap.appc.domainmodel.lcm.ResponseContext; +import org.onap.appc.domainmodel.lcm.RuntimeContext; +import org.onap.appc.domainmodel.lcm.TransactionRecord; +import org.onap.appc.domainmodel.lcm.VNFOperation; import org.onap.appc.exceptions.APPCException; +import org.onap.appc.lockmanager.api.LockException; +import org.onap.appc.lockmanager.api.LockManager; +import org.onap.appc.requesthandler.LCMStateManager; +import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException; +import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException; +import org.onap.appc.requesthandler.exceptions.RequestValidationException; +import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException; +import org.onap.appc.rest.client.RestClientInvoker; +import org.onap.appc.transactionrecorder.TransactionRecorder; +import org.onap.appc.validationpolicy.RequestValidationPolicy; +import org.onap.appc.validationpolicy.executors.RuleExecutor; +import org.onap.appc.validationpolicy.objects.RuleResult; +import org.onap.appc.workflow.WorkFlowManager; +import org.onap.appc.workflow.impl.WorkFlowManagerImpl; +import org.onap.appc.workflow.objects.WorkflowExistsOutput; +import org.onap.appc.workflow.objects.WorkflowRequest; +import org.onap.ccsdk.sli.adaptors.aai.AAIService; +import org.onap.ccsdk.sli.core.sli.SvcLogicContext; +import org.onap.ccsdk.sli.core.sli.SvcLogicResource; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; -import java.util.Properties; - -import static org.mockito.Mockito.mock; - -public class RequestValidatorImplTest { - private Configuration mockConfig = mock(Configuration.class); +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper { + private Configuration mockConfig = ConfigurationFactory.getConfiguration(); private RequestValidatorImpl impl; + private final BundleContext bundleContext = Mockito.mock(BundleContext.class); + private final Bundle bundleService = Mockito.mock(Bundle.class); + private final ServiceReference sref = Mockito.mock(ServiceReference.class); + private EELFLogger logger; + private TransactionRecorder transactionRecorder; + private LockManager lockManager; + private LCMStateManager lcmStateManager; + @Before public void setUp() throws Exception { - impl = new RequestValidatorImpl(); + impl = PowerMockito.spy(new RequestValidatorImpl()); Whitebox.setInternalState(impl, "configuration", mockConfig); + logger = Mockito.spy(EELFManager.getInstance().getLogger(RequestHandlerImpl.class)); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(impl, "logger", logger); + lcmStateManager = new LCMStateManagerImpl(); + impl.setLcmStateManager(lcmStateManager); + AAIService aaiService = Mockito.mock(AAIService.class); + PowerMockito.when(aaiService.query( + anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject())) + .thenAnswer(new Answer() { + @Override + public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception { + Object[] args = invocation.getArguments(); + SvcLogicContext ctx = (SvcLogicContext) args[6]; + String prefix = (String) args[4]; + String key = (String) args[3]; + if (key.contains("'28'")) { + return SvcLogicResource.QueryStatus.FAILURE; + } else if (key.contains("'8'")) { + return SvcLogicResource.QueryStatus.NOT_FOUND; + } else { + ctx.setAttribute(prefix + ".vnf-type", "FIREWALL"); + ctx.setAttribute(prefix + ".orchestration-status", "Instantiated"); + } + return SvcLogicResource.QueryStatus.SUCCESS; + } + }); + PowerMockito.mockStatic(FrameworkUtil.class); + PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService); + PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext); + PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref); + PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService); + lockManager = mock(LockManager.class); + impl.setLockManager(lockManager); } // TODO: remove Ignore when initialize method actually throws APPCException @@ -72,4 +172,236 @@ public class RequestValidatorImplTest { Mockito.doReturn(mockProp).when(mockConfig).getProperties(); impl.initialize(); } + + @Test(expected = LCMOperationsDisabledException.class) + public void testValidateRequestLCMException() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + logger = Mockito.spy(EELFManager.getInstance().getLogger(LCMStateManager.class)); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(lcmStateManager, "logger", logger); + lcmStateManager.disableLCMOperations(); + impl.validateRequest(runtimeContext); + } + + + @Test(expected = RequestValidationException.class) + public void testValidateRequest() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + logger = Mockito.spy(EELFManager.getInstance().getLogger(LCMStateManager.class)); + logger.setLevel(Level.TRACE); + Whitebox.setInternalState(lcmStateManager, "logger", logger); + lcmStateManager.enableLCMOperations(); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + TransactionRecord transactionRecord = new TransactionRecord(); + transactionRecord.setMode(Mode.EXCLUSIVE); + runtimeContext.setTransactionRecord(transactionRecord); + impl.setTransactionRecorder(transactionRecorder); + WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true); + WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class); + Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))).thenReturn(workflowExistsOutput); + impl.setWorkflowManager(workflowManager); + ResponseContext responseContext = runtimeContext.getResponseContext(); + CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext); + RestClientInvoker client = mock(RestClientInvoker.class); + HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED"); + httpResponse.setEntity(getHttpEntity()); + Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse); + impl.setClient(client); + RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class); + RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class); + RuleResult ruleResult = RuleResult.REJECT; + Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor); + Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))).thenReturn(ruleResult); + impl.setRequestValidationPolicy(requestValidationPolicy); + impl.validateRequest(runtimeContext); + } + + @Test + public void testInitializeMalformed() throws Exception { + Properties properties = new Properties(); + properties.setProperty("appc.LCM.scopeOverlap.endpoint", "/not/a/URL"); + mockConfig.setProperties(properties); + Whitebox.setInternalState(impl, "configuration", mockConfig); + impl.initialize(); + Mockito.verify(logger).error(Mockito.anyString(), Mockito.any(MalformedURLException.class)); + } + + @Test + public void testInitialize() throws Exception { + Configuration mockConfigForInitTest = ConfigurationFactory.getConfiguration(new Properties()); + Whitebox.setInternalState(impl, "configuration", mockConfigForInitTest); + impl.initialize(); + Mockito.verify(logger).error("End point is not defined for scope over lap service in appc.properties."); + } + + @Test(expected = RequestValidationException.class) + public void testValidateRequestExclusiveRequestCount() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + lcmStateManager.enableLCMOperations(); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + List transactionRecordList = new ArrayList(1); + TransactionRecord inProgressTransaction = new TransactionRecord(); + inProgressTransaction.setMode(Mode.EXCLUSIVE); + transactionRecordList.add(inProgressTransaction); + Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class))) + .thenReturn(transactionRecordList); + runtimeContext.setTransactionRecord(inProgressTransaction); + impl.setTransactionRecorder(transactionRecorder); + WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true); + WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class); + Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))) + .thenReturn(workflowExistsOutput); + impl.setWorkflowManager(workflowManager); + ResponseContext responseContext = runtimeContext.getResponseContext(); + CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext); + impl.validateRequest(runtimeContext); + } + + @Test(expected = LockException.class) + public void testValidateLockException() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + lcmStateManager.enableLCMOperations(); + Mockito.when(lockManager.getLockOwner(Mockito.anyString())).thenReturn("TEST_LOCK_OWNER"); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + impl.setTransactionRecorder(transactionRecorder); + TransactionRecord inProgressTransaction = new TransactionRecord(); + runtimeContext.setTransactionRecord(inProgressTransaction); + impl.validateRequest(runtimeContext); + } + + @Test + public void testValidateRequestInProgressTransactionLoop() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + lcmStateManager.enableLCMOperations(); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + List transactionRecordList = new ArrayList(1); + TransactionRecord inProgressTransaction = new TransactionRecord(); + inProgressTransaction.setMode(Mode.NORMAL); + inProgressTransaction.setOperation(VNFOperation.ActionStatus); + transactionRecordList.add(inProgressTransaction); + runtimeContext.setTransactionRecord(inProgressTransaction); + Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class))) + .thenReturn(transactionRecordList); + impl.setTransactionRecorder(transactionRecorder); + WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true); + WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class); + Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))) + .thenReturn(workflowExistsOutput); + impl.setWorkflowManager(workflowManager); + ResponseContext responseContext = runtimeContext.getResponseContext(); + CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext); + RestClientInvoker client = mock(RestClientInvoker.class); + HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED"); + httpResponse.setEntity(getHttpEntity()); + Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse); + impl.setClient(client); + RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class); + RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class); + RuleResult ruleResult = RuleResult.ACCEPT; + Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor); + Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))) + .thenReturn(ruleResult); + impl.setRequestValidationPolicy(requestValidationPolicy); + RequestContext requestContext = new RequestContext(); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setServiceInstanceId("TEST_SERVICE_INSTANCE_ID"); + actionIdentifiers.setVfModuleId("TEST_VNF_MODULE_ID"); + actionIdentifiers.setVnfcName("TEST_VNFC_NAME"); + actionIdentifiers.setVnfId("TEST_VNF_ID"); + actionIdentifiers.setvServerId("TEST_SERVER_ID"); + requestContext.setActionIdentifiers(actionIdentifiers); + impl.validateRequest(runtimeContext); + Mockito.verify(logger).debug("Policy validation result ACCEPT"); + } + + @Test(expected = WorkflowNotFoundException.class) + public void testValidateRequestWorkflowNotFoundException() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + lcmStateManager.enableLCMOperations(); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + TransactionRecord transactionRecord = new TransactionRecord(); + transactionRecord.setMode(Mode.EXCLUSIVE); + runtimeContext.setTransactionRecord(transactionRecord); + impl.setTransactionRecorder(transactionRecorder); + WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true)); + WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class); + Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))) + .thenReturn(workflowExistsOutput); + Mockito.when(workflowExistsOutput.isMappingExist()).thenReturn(false); + impl.setWorkflowManager(workflowManager); + ResponseContext responseContext = runtimeContext.getResponseContext(); + CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext); + RestClientInvoker client = mock(RestClientInvoker.class); + HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");; + httpResponse.setEntity(getHttpEntity()); + Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse); + impl.setClient(client); + RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class); + RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class); + RuleResult ruleResult = RuleResult.REJECT; + Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor); + Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))) + .thenReturn(ruleResult); + impl.setRequestValidationPolicy(requestValidationPolicy); + impl.validateRequest(runtimeContext); + } + + @Test(expected = DGWorkflowNotFoundException.class) + public void testValidateRequestDGWorkflowNotFoundException() throws Exception { + RuntimeContext runtimeContext = createRequestValidatorInput(); + lcmStateManager.enableLCMOperations(); + transactionRecorder = Mockito.mock(TransactionRecorder.class); + Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false); + TransactionRecord transactionRecord = new TransactionRecord(); + transactionRecord.setMode(Mode.EXCLUSIVE); + runtimeContext.setTransactionRecord(transactionRecord); + impl.setTransactionRecorder(transactionRecorder); + WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true)); + WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class); + Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))) + .thenReturn(workflowExistsOutput); + Mockito.when(workflowExistsOutput.isDgExist()).thenReturn(false); + impl.setWorkflowManager(workflowManager); + ResponseContext responseContext = runtimeContext.getResponseContext(); + CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext); + RestClientInvoker client = mock(RestClientInvoker.class); + HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED"); + httpResponse.setEntity(getHttpEntity()); + Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse); + impl.setClient(client); + RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class); + RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class); + RuleResult ruleResult = RuleResult.REJECT; + Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor); + Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))) + .thenReturn(ruleResult); + impl.setRequestValidationPolicy(requestValidationPolicy); + impl.validateRequest(runtimeContext); + } + + private RuntimeContext createRequestValidatorInput() { + return createRequestHandlerRuntimeContext("VSCP", "{\"request-id\":\"request-id\"}"); + } + + private CommonHeader returnResponseContextCommonHeader(ResponseContext responseContext) { + CommonHeader commonHeader = responseContext.getCommonHeader(); + Flags flags = new Flags(); + flags.setForce(false); + commonHeader.setFlags(flags); + commonHeader.setRequestId("TEST_REQUEST_ID"); + return commonHeader; + } + + private BasicHttpEntity getHttpEntity() { + BasicHttpEntity httpEntity = new BasicHttpEntity(); + InputStream inputStream = new ByteArrayInputStream( + "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}".getBytes()); + httpEntity.setContent(inputStream); + return httpEntity; + } } -- cgit 1.2.3-korg