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