a2c3ec360ac213f02d81a7660fb63b121ad42038
[appc.git] / appc-dispatcher / appc-request-handler / appc-request-handler-core / src / test / java / org / onap / appc / requesthandler / impl / AbstractRequestHandlerImplTest.java
1 /*
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2018-2019 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6  * file except in compliance with the License. You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software distributed under the License
11  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12  * or implied. See the License for the specific language governing permissions and limitations under
13  * the License.
14  *
15  * SPDX-License-Identifier: Apache-2.0
16  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.appc.requesthandler.impl;
20
21 import static org.mockito.Matchers.anyString;
22 import static org.mockito.Mockito.doNothing;
23 import static org.mockito.Mockito.doThrow;
24 import static org.mockito.Mockito.mock;
25 import static org.mockito.Mockito.spy;
26 import static org.mockito.Mockito.times;
27 import java.util.Arrays;
28 import java.util.Date;
29 import java.util.List;
30 import org.junit.Assert;
31 import org.junit.Before;
32 import org.junit.Rule;
33 import org.junit.Test;
34 import org.junit.rules.ExpectedException;
35 import org.junit.runner.RunWith;
36 import org.mockito.Mockito;
37 import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
38 import org.onap.appc.domainmodel.lcm.CommonHeader;
39 import org.onap.appc.domainmodel.lcm.RequestContext;
40 import org.onap.appc.domainmodel.lcm.RequestStatus;
41 import org.onap.appc.domainmodel.lcm.ResponseContext;
42 import org.onap.appc.domainmodel.lcm.RuntimeContext;
43 import org.onap.appc.domainmodel.lcm.Status;
44 import org.onap.appc.domainmodel.lcm.TransactionRecord;
45 import org.onap.appc.domainmodel.lcm.VNFOperation;
46 import org.onap.appc.exceptions.APPCException;
47 import org.onap.appc.exceptions.InvalidInputException;
48 import org.onap.appc.executor.objects.LCMCommandStatus;
49 import org.onap.appc.lockmanager.api.LockException;
50 import org.onap.appc.messageadapter.MessageAdapter;
51 import org.onap.appc.metricservice.MetricRegistry;
52 import org.onap.appc.metricservice.MetricService;
53 import org.onap.appc.metricservice.impl.MetricRegistryImpl;
54 import org.onap.appc.metricservice.metric.DispatchingFunctionCounterBuilder;
55 import org.onap.appc.metricservice.metric.DispatchingFuntionMetric;
56 import org.onap.appc.metricservice.metric.MetricBuilderFactory;
57 import org.onap.appc.metricservice.metric.MetricType;
58 import org.onap.appc.metricservice.metric.impl.DispatchingFuntionMetricImpl;
59 import org.onap.appc.metricservice.policy.PolicyBuilderFactory;
60 import org.onap.appc.metricservice.policy.PublishingPolicy;
61 import org.onap.appc.metricservice.policy.ScheduledPolicyBuilder;
62 import org.onap.appc.requesthandler.exceptions.RequestValidationException;
63 import org.onap.appc.requesthandler.helper.RequestValidator;
64 import org.onap.appc.requesthandler.objects.RequestHandlerInput;
65 import org.onap.appc.requesthandler.objects.RequestHandlerOutput;
66 import org.onap.appc.transactionrecorder.TransactionRecorder;
67 import org.osgi.framework.Bundle;
68 import org.osgi.framework.BundleContext;
69 import org.osgi.framework.FrameworkUtil;
70 import org.osgi.framework.ServiceReference;
71 import org.powermock.api.mockito.PowerMockito;
72 import org.powermock.core.classloader.annotations.PrepareForTest;
73 import org.powermock.modules.junit4.PowerMockRunner;
74 import org.powermock.reflect.Whitebox;
75 import com.att.eelf.configuration.EELFLogger;
76 import com.att.eelf.configuration.EELFLogger.Level;
77 import com.att.eelf.configuration.EELFManager;
78
79 @RunWith(PowerMockRunner.class)
80 @PrepareForTest({FrameworkUtil.class})
81 public class AbstractRequestHandlerImplTest implements LocalRequestHanlderTestHelper {
82
83     private AbstractRequestHandlerImpl requestHandler;
84     private TransactionRecorder recorder;
85     private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
86     private final Bundle bundleService = Mockito.mock(Bundle.class);
87     private final ServiceReference sref = Mockito.mock(ServiceReference.class);
88     private final MetricService metricService = Mockito.mock(MetricService.class);
89
90     @Rule
91     public ExpectedException expectedEx = ExpectedException.none();
92
93     @Before
94     public void setUp() throws Exception {
95         setupForHandlerImplTests();
96         requestHandler = spy(new LocalRequestHandlerImpl());
97         recorder = mock(TransactionRecorder.class);
98         requestHandler.setTransactionRecorder(recorder);
99         List<RequestStatus> result = Arrays.asList(RequestStatus.ACCEPTED);
100         PowerMockito.when(recorder.getRecords(anyString(), anyString(), anyString(), anyString())).thenReturn(result);
101         final EELFLogger logger = EELFManager.getInstance().getLogger(AbstractRequestHandlerImpl.class);
102         logger.setLevel(Level.TRACE);
103         Whitebox.setInternalState(requestHandler, "logger", logger);
104     }
105
106     @Test
107     public void testHandleRequestAbstractRequestHandler() {
108         RequestHandlerInput rhi = setupTestForHandleRequest();
109         RequestValidator rv = mock(RequestValidator.class);
110         doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class));
111         requestHandler.setRequestValidator(rv);
112         Assert.assertTrue(requestHandler.handleRequest(rhi) instanceof RequestHandlerOutput);
113     }
114
115     @Test
116     public void testHandleRequestAbstractRequestHandlerRequestValidationException() throws Exception {
117         RequestHandlerInput rhi = setupTestForHandleRequest();
118         RequestValidator rv = mock(RequestValidator.class);
119         RequestValidationException rve = new RequestValidationException("TEST");
120         rve.setTargetEntity("TEST_TARGET_ENTITY");
121         rve.setTargetService("TEST_TARGET_SERVICE");
122         rve.setLogMessage("TEST_LOG_MESSAGE");
123         rve.setLcmCommandStatus(LCMCommandStatus.SUCCESS);
124         rve.setParams(null);
125         RequestHandlerOutput output = null;
126         doThrow(rve).when(rv).validateRequest(Mockito.any(RuntimeContext.class));
127         doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class));
128         requestHandler.setRequestValidator(rv);
129         output = requestHandler.handleRequest(rhi);
130         Assert.assertEquals(LCMCommandStatus.SUCCESS.getResponseCode(),
131                 output.getResponseContext().getStatus().getCode());
132     }
133
134     @Test
135     public void testHandleRequestAbstractRequestHandlerInvalidInputException() throws Exception {
136         RequestHandlerInput rhi = setupTestForHandleRequest();
137         RequestValidator rv = mock(RequestValidator.class);
138         InvalidInputException iie = new InvalidInputException("TEST");
139         RequestHandlerOutput output = null;
140         doThrow(iie).when(rv).validateRequest(Mockito.any(RuntimeContext.class));
141         doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class));
142         requestHandler.setRequestValidator(rv);
143         output = requestHandler.handleRequest(rhi);
144         Assert.assertEquals(LCMCommandStatus.INVALID_INPUT_PARAMETER.getResponseCode(),
145                 output.getResponseContext().getStatus().getCode());
146     }
147
148     @Test
149     public void testHandleRequestAbstractRequestHandlerLockException() throws Exception {
150         RequestHandlerInput rhi = setupTestNoMetric();
151         RequestValidator rv = mock(RequestValidator.class);
152         LockException le = new LockException("TEST");
153         RequestHandlerOutput output = null;
154         doThrow(le).when(rv).validateRequest(Mockito.any(RuntimeContext.class));
155         doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class));
156         requestHandler.setRequestValidator(rv);
157         output = requestHandler.handleRequest(rhi);
158         Assert.assertEquals(LCMCommandStatus.LOCKED_VNF_ID.getResponseCode(),
159                 output.getResponseContext().getStatus().getCode());
160     }
161
162     @Test
163     public void testHandleRequestAbstractRequestHandlerException() throws Exception {
164         RequestHandlerInput rhi = setupTestNoMetric();
165         RequestValidator rv = mock(RequestValidator.class);
166         Exception exception = new Exception("TEST");
167         RequestHandlerOutput output = null;
168         doThrow(exception).when(rv).validateRequest(Mockito.any(RuntimeContext.class));
169         doNothing().when(requestHandler).handleRequest(Mockito.any(RuntimeContext.class));
170         requestHandler.setRequestValidator(rv);
171         output = requestHandler.handleRequest(rhi);
172         Assert.assertEquals(LCMCommandStatus.UNEXPECTED_ERROR.getResponseCode(),
173                 output.getResponseContext().getStatus().getCode());
174     }
175
176     @Test
177     public void testOnRequestExecutionEnd() {
178         RuntimeContext runtimeContext = spy(new RuntimeContext());
179         TransactionRecord record = new TransactionRecord();
180         record.setRequestState(RequestStatus.ACCEPTED);
181         runtimeContext.setTransactionRecord(record);
182         MessageAdapter messageAdapter = mock(MessageAdapter.class);
183         requestHandler.setMessageAdapter(messageAdapter);
184         RequestContext rc = mock(RequestContext.class);
185         Status status = new Status();
186         status.setCode(100);
187         ResponseContext responseContext = spy(new ResponseContext());
188         Mockito.doReturn(status).when(responseContext).getStatus();
189         Mockito.doReturn(VNFOperation.ActionStatus).when(rc).getAction();
190         Mockito.doReturn(rc).when(runtimeContext).getRequestContext();
191         Mockito.doReturn(responseContext).when(runtimeContext).getResponseContext();
192         requestHandler.onRequestExecutionEnd(runtimeContext);
193         Mockito.verify(runtimeContext, times(3)).getTransactionRecord();
194     }
195
196     @Test
197     public void testGetInprogressRequestCount() throws APPCException {
198         int i = 0;
199         Mockito.doReturn(19).when(recorder).getInProgressRequestsCount();
200         i = requestHandler.getInprogressRequestCount();
201         Assert.assertEquals(19, i);
202     }
203
204     @Test
205     public void testMetric() throws Exception {
206         PowerMockito.mockStatic(FrameworkUtil.class);
207         PowerMockito.when(FrameworkUtil.getBundle(MetricService.class)).thenReturn(bundleService);
208         PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
209         PowerMockito.when(bundleContext.getServiceReference(MetricService.class.getName())).thenReturn(sref);
210         PowerMockito.when(bundleContext.getService(sref)).thenReturn(metricService);
211         MetricRegistry metricRegistry = Mockito.mock(MetricRegistry.class);
212         DispatchingFuntionMetric dispatchingFunctionMetric = Mockito.mock(DispatchingFuntionMetric.class);
213         DispatchingFunctionCounterBuilder dispatchingFunctionCounterBuilder = Mockito.mock(DispatchingFunctionCounterBuilder.class);
214         MetricBuilderFactory metricBuilderFactory = Mockito.mock(MetricBuilderFactory.class);
215         Mockito.when(dispatchingFunctionCounterBuilder.withName("DISPATCH_FUNCTION")).thenReturn(dispatchingFunctionCounterBuilder);
216         Mockito.when(dispatchingFunctionCounterBuilder.withType(MetricType.COUNTER)).thenReturn(dispatchingFunctionCounterBuilder);
217         Mockito.when(dispatchingFunctionCounterBuilder.withAcceptRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
218         Mockito.when(dispatchingFunctionCounterBuilder.withRejectRequestValue(0)).thenReturn(dispatchingFunctionCounterBuilder);
219         Mockito.when(dispatchingFunctionCounterBuilder.build()).thenReturn(dispatchingFunctionMetric);
220         Mockito.when(metricBuilderFactory.dispatchingFunctionCounterBuilder()).thenReturn(dispatchingFunctionCounterBuilder);
221         Mockito.when(metricRegistry.metricBuilderFactory()).thenReturn(metricBuilderFactory);
222         Mockito.when(metricService.createRegistry("APPC")).thenReturn(metricRegistry);
223         Mockito.when(metricRegistry.register(dispatchingFunctionMetric)).thenReturn(true);
224
225         PublishingPolicy publishingPolicy = Mockito.mock(PublishingPolicy.class);
226         PolicyBuilderFactory policyBuilderFactory = Mockito.mock(PolicyBuilderFactory.class);
227         ScheduledPolicyBuilder scheduledPolicyBuilder = Mockito.mock(ScheduledPolicyBuilder.class);
228         Mockito.when(policyBuilderFactory.scheduledPolicyBuilder()).thenReturn(scheduledPolicyBuilder);
229         Mockito.when(scheduledPolicyBuilder.withPublishers(Mockito.any())).thenReturn(scheduledPolicyBuilder);
230         Mockito.when(scheduledPolicyBuilder.withMetrics(Mockito.any())).thenReturn(scheduledPolicyBuilder);
231         Mockito.when(scheduledPolicyBuilder.build()).thenReturn(publishingPolicy);
232         Mockito.when(metricRegistry.policyBuilderFactory()).thenReturn(policyBuilderFactory);
233         Whitebox.invokeMethod(requestHandler, "initMetric");
234         Mockito.verify(publishingPolicy).init();
235     }
236
237     @Test
238     public void testMetricNullMetricService() throws Exception {
239         expectedEx.expect(NullPointerException.class);
240         expectedEx.expectMessage("org.onap.appc.metricservice.MetricService is null. " +
241                     "Failed to init Metric");
242         Whitebox.invokeMethod(requestHandler, "initMetric");
243     }
244
245     private RequestHandlerInput setupTestForHandleRequest() {
246         Whitebox.setInternalState(requestHandler, "isMetricEnabled", true);
247         MetricRegistry metricRegistry = spy(new MetricRegistryImpl("TEST_METRIC_REGISTRY"));
248         DispatchingFuntionMetricImpl metric =
249                 spy(new DispatchingFuntionMetricImpl("DISPATCH_FUNCTION", MetricType.COUNTER, 0, 0));
250         metricRegistry.register(metric);
251         doNothing().when(metric).incrementAcceptedRequest();
252         Whitebox.setInternalState(RequestHandlerImpl.class, "metricRegistry", metricRegistry);
253         RequestHandlerInput rhi = new RequestHandlerInput();
254         RequestContext rc = new RequestContext();
255         CommonHeader ch = new CommonHeader();
256         rc.setCommonHeader(ch);
257         ch.setRequestId("TEST");
258         ch.setTimestamp(new Date(System.currentTimeMillis()));
259         VNFOperation vo = VNFOperation.findByString("ActionStatus");
260         rc.setAction(vo);
261         ActionIdentifiers ai = new ActionIdentifiers();
262         rc.setActionIdentifiers(ai);
263         rhi.setRequestContext(rc);
264         return rhi;
265     }
266
267     private RequestHandlerInput setupTestNoMetric() {
268         RequestHandlerInput rhi = new RequestHandlerInput();
269         RequestContext rc = new RequestContext();
270         CommonHeader ch = new CommonHeader();
271         rc.setCommonHeader(ch);
272         ch.setRequestId("TEST");
273         ch.setTimestamp(new Date(System.currentTimeMillis()));
274         VNFOperation vo = VNFOperation.findByString("ActionStatus");
275         rc.setAction(vo);
276         ActionIdentifiers ai = new ActionIdentifiers();
277         rc.setActionIdentifiers(ai);
278         rhi.setRequestContext(rc);
279         return rhi;
280     }
281 }