e1c10dae1efea6a9008494fc97c37aad8e089995
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Copyright (C) 2018 Ericsson. All rights reserved.
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.requesthandler.impl;
27
28 import static org.mockito.Matchers.anyBoolean;
29 import static org.mockito.Matchers.anyObject;
30 import static org.mockito.Matchers.anyString;
31 import static org.mockito.Mockito.mock;
32
33 import com.att.eelf.configuration.EELFLogger;
34 import com.att.eelf.configuration.EELFLogger.Level;
35 import com.att.eelf.configuration.EELFManager;
36
37 import java.io.ByteArrayInputStream;
38 import java.io.InputStream;
39 import java.net.MalformedURLException;
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.util.Properties;
43
44 import org.apache.http.HttpResponse;
45 import org.apache.http.ProtocolVersion;
46 import org.apache.http.entity.BasicHttpEntity;
47 import org.apache.http.message.BasicHttpResponse;
48 import org.junit.Before;
49 import org.junit.Ignore;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.mockito.Mockito;
53 import org.mockito.internal.util.reflection.Whitebox;
54 import org.mockito.invocation.InvocationOnMock;
55 import org.mockito.stubbing.Answer;
56 import org.onap.appc.configuration.Configuration;
57 import org.onap.appc.configuration.ConfigurationFactory;
58 import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
59 import org.onap.appc.domainmodel.lcm.CommonHeader;
60 import org.onap.appc.domainmodel.lcm.Flags;
61 import org.onap.appc.domainmodel.lcm.Flags.Mode;
62 import org.onap.appc.domainmodel.lcm.RequestContext;
63 import org.onap.appc.domainmodel.lcm.ResponseContext;
64 import org.onap.appc.domainmodel.lcm.RuntimeContext;
65 import org.onap.appc.domainmodel.lcm.TransactionRecord;
66 import org.onap.appc.domainmodel.lcm.VNFOperation;
67 import org.onap.appc.exceptions.APPCException;
68 import org.onap.appc.lockmanager.api.LockException;
69 import org.onap.appc.lockmanager.api.LockManager;
70 import org.onap.appc.requesthandler.LCMStateManager;
71 import org.onap.appc.requesthandler.exceptions.DGWorkflowNotFoundException;
72 import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
73 import org.onap.appc.requesthandler.exceptions.RequestValidationException;
74 import org.onap.appc.requesthandler.exceptions.WorkflowNotFoundException;
75 import org.onap.appc.rest.client.RestClientInvoker;
76 import org.onap.appc.transactionrecorder.TransactionRecorder;
77 import org.onap.appc.validationpolicy.RequestValidationPolicy;
78 import org.onap.appc.validationpolicy.executors.RuleExecutor;
79 import org.onap.appc.validationpolicy.objects.RuleResult;
80 import org.onap.appc.workflow.WorkFlowManager;
81 import org.onap.appc.workflow.impl.WorkFlowManagerImpl;
82 import org.onap.appc.workflow.objects.WorkflowExistsOutput;
83 import org.onap.appc.workflow.objects.WorkflowRequest;
84 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
85 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
86 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
87 import org.osgi.framework.Bundle;
88 import org.osgi.framework.BundleContext;
89 import org.osgi.framework.FrameworkUtil;
90 import org.osgi.framework.ServiceReference;
91 import org.powermock.api.mockito.PowerMockito;
92 import org.powermock.core.classloader.annotations.PrepareForTest;
93 import org.powermock.modules.junit4.PowerMockRunner;
94
95 @RunWith(PowerMockRunner.class)
96 @PrepareForTest({FrameworkUtil.class})
97 public class RequestValidatorImplTest implements LocalRequestHanlderTestHelper {
98     private Configuration mockConfig = ConfigurationFactory.getConfiguration();
99     private RequestValidatorImpl impl;
100     private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
101     private final Bundle bundleService = Mockito.mock(Bundle.class);
102     private final ServiceReference sref = Mockito.mock(ServiceReference.class);
103     private EELFLogger logger;
104     private TransactionRecorder transactionRecorder;
105     private LockManager lockManager;
106     private LCMStateManager lcmStateManager;
107
108
109     @Before
110     public void setUp() throws Exception {
111         impl = PowerMockito.spy(new RequestValidatorImpl());
112         Whitebox.setInternalState(impl, "configuration", mockConfig);
113         logger = Mockito.spy(EELFManager.getInstance().getLogger(RequestHandlerImpl.class));
114         logger.setLevel(Level.TRACE);
115         Whitebox.setInternalState(impl, "logger", logger);
116         lcmStateManager = new LCMStateManagerImpl();
117         impl.setLcmStateManager(lcmStateManager);
118         AAIService aaiService = Mockito.mock(AAIService.class);
119         PowerMockito.when(aaiService.query(
120                 anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject()))
121         .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
122             @Override
123             public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
124                 Object[] args = invocation.getArguments();
125                 SvcLogicContext ctx = (SvcLogicContext) args[6];
126                 String prefix = (String) args[4];
127                 String key = (String) args[3];
128                 if (key.contains("'28'")) {
129                     return SvcLogicResource.QueryStatus.FAILURE;
130                 } else if (key.contains("'8'")) {
131                     return SvcLogicResource.QueryStatus.NOT_FOUND;
132                 } else {
133                     ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
134                     ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
135                 }
136                 return SvcLogicResource.QueryStatus.SUCCESS;
137             }
138         });
139         PowerMockito.mockStatic(FrameworkUtil.class);
140         PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
141         PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
142         PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref);
143         PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService);
144         lockManager = mock(LockManager.class);
145         impl.setLockManager(lockManager);
146     }
147
148     // TODO: remove Ignore when initialize method actually throws APPCException
149     @Ignore
150     @Test(expected = APPCException.class)
151     public void testInitializeWithNullConfigProps() throws Exception {
152         Mockito.doReturn(null).when(mockConfig).getProperties();
153         impl.initialize();
154     }
155
156     // TODO: remove Ignore when initialize method actually throws APPCException
157     @Ignore
158     @Test(expected = APPCException.class)
159     public void testInitializeWithoutEndpointProp() throws Exception {
160         Properties mockProp = mock(Properties.class);
161         Mockito.doReturn(null).when(mockProp).getProperty(RequestValidatorImpl.SCOPE_OVERLAP_ENDPOINT);
162         Mockito.doReturn(mockProp).when(mockConfig).getProperties();
163         impl.initialize();
164     }
165
166     // TODO: remove Ignore when initialize method actually throws APPCException
167     @Ignore
168     @Test(expected = APPCException.class)
169     public void testInitializeWithMalFormatEndpoint() throws Exception {
170         Properties mockProp = mock(Properties.class);
171         Mockito.doReturn("a/b/c").when(mockProp).getProperty(RequestValidatorImpl.SCOPE_OVERLAP_ENDPOINT);
172         Mockito.doReturn(mockProp).when(mockConfig).getProperties();
173         impl.initialize();
174     }
175
176     @Test(expected = LCMOperationsDisabledException.class)
177     public void testValidateRequestLCMException() throws Exception {
178         RuntimeContext runtimeContext = createRequestValidatorInput();
179         logger = Mockito.spy(EELFManager.getInstance().getLogger(LCMStateManager.class));
180         logger.setLevel(Level.TRACE);
181         Whitebox.setInternalState(lcmStateManager, "logger", logger);
182         lcmStateManager.disableLCMOperations();
183         impl.validateRequest(runtimeContext);
184     }
185
186
187     @Test(expected = RequestValidationException.class)
188     public void testValidateRequest() throws Exception {
189         RuntimeContext runtimeContext = createRequestValidatorInput();
190         logger = Mockito.spy(EELFManager.getInstance().getLogger(LCMStateManager.class));
191         logger.setLevel(Level.TRACE);
192         Whitebox.setInternalState(lcmStateManager, "logger", logger);
193         lcmStateManager.enableLCMOperations();
194         transactionRecorder = Mockito.mock(TransactionRecorder.class);
195         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
196         TransactionRecord transactionRecord = new TransactionRecord();
197         transactionRecord.setMode(Mode.EXCLUSIVE);
198         runtimeContext.setTransactionRecord(transactionRecord);
199         impl.setTransactionRecorder(transactionRecorder);
200         WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
201         WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
202         Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class))).thenReturn(workflowExistsOutput);
203         impl.setWorkflowManager(workflowManager);
204         ResponseContext responseContext = runtimeContext.getResponseContext();
205         CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext);
206         RestClientInvoker client = mock(RestClientInvoker.class);
207         HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
208         httpResponse.setEntity(getHttpEntity());
209         Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
210         impl.setClient(client);
211         RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class);
212         RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
213         RuleResult ruleResult = RuleResult.REJECT;
214         Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
215         Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class))).thenReturn(ruleResult);
216         impl.setRequestValidationPolicy(requestValidationPolicy);
217         impl.validateRequest(runtimeContext);
218     }
219
220     @Test
221     public void testInitializeMalformed() throws Exception {
222         Properties properties = new Properties();
223         properties.setProperty("appc.LCM.scopeOverlap.endpoint", "/not/a/URL");
224         mockConfig.setProperties(properties);
225         Whitebox.setInternalState(impl, "configuration", mockConfig);
226         impl.initialize();
227         Mockito.verify(logger).error(Mockito.anyString(), Mockito.any(MalformedURLException.class));
228     }
229
230     @Test
231     public void testInitialize() throws Exception {
232         Configuration mockConfigForInitTest = ConfigurationFactory.getConfiguration(new Properties());
233         Whitebox.setInternalState(impl, "configuration", mockConfigForInitTest);
234         impl.initialize();
235         Mockito.verify(logger).error("End point is not defined for scope over lap service in appc.properties.");
236     }
237
238     @Test(expected = RequestValidationException.class)
239     public void testValidateRequestExclusiveRequestCount() throws Exception {
240         RuntimeContext runtimeContext = createRequestValidatorInput();
241         lcmStateManager.enableLCMOperations();
242         transactionRecorder = Mockito.mock(TransactionRecorder.class);
243         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
244         List<TransactionRecord> transactionRecordList = new ArrayList<TransactionRecord>(1);
245         TransactionRecord inProgressTransaction = new TransactionRecord();
246         inProgressTransaction.setMode(Mode.EXCLUSIVE);
247         transactionRecordList.add(inProgressTransaction);
248         Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class)))
249             .thenReturn(transactionRecordList);
250         runtimeContext.setTransactionRecord(inProgressTransaction);
251         impl.setTransactionRecorder(transactionRecorder);
252         WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
253         WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
254         Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
255             .thenReturn(workflowExistsOutput);
256         impl.setWorkflowManager(workflowManager);
257         ResponseContext responseContext = runtimeContext.getResponseContext();
258         CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext);
259         impl.validateRequest(runtimeContext);
260     }
261
262     @Test(expected = LockException.class)
263     public void testValidateLockException() throws Exception {
264         RuntimeContext runtimeContext = createRequestValidatorInput();
265         lcmStateManager.enableLCMOperations();
266         Mockito.when(lockManager.getLockOwner(Mockito.anyString())).thenReturn("TEST_LOCK_OWNER");
267         transactionRecorder = Mockito.mock(TransactionRecorder.class);
268         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
269         impl.setTransactionRecorder(transactionRecorder);
270         TransactionRecord inProgressTransaction = new TransactionRecord();
271         runtimeContext.setTransactionRecord(inProgressTransaction);
272         impl.validateRequest(runtimeContext);
273     }
274
275     @Test
276     public void testValidateRequestInProgressTransactionLoop() throws Exception {
277         RuntimeContext runtimeContext = createRequestValidatorInput();
278         lcmStateManager.enableLCMOperations();
279         transactionRecorder = Mockito.mock(TransactionRecorder.class);
280         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
281         List<TransactionRecord> transactionRecordList = new ArrayList<TransactionRecord>(1);
282         TransactionRecord inProgressTransaction = new TransactionRecord();
283         inProgressTransaction.setMode(Mode.NORMAL);
284         inProgressTransaction.setOperation(VNFOperation.ActionStatus);
285         transactionRecordList.add(inProgressTransaction);
286         runtimeContext.setTransactionRecord(inProgressTransaction);
287         Mockito.when(transactionRecorder.getInProgressRequests(Mockito.any(TransactionRecord.class)))
288             .thenReturn(transactionRecordList);
289         impl.setTransactionRecorder(transactionRecorder);
290         WorkflowExistsOutput workflowExistsOutput = new WorkflowExistsOutput(true, true);
291         WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
292         Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
293             .thenReturn(workflowExistsOutput);
294         impl.setWorkflowManager(workflowManager);
295         ResponseContext responseContext = runtimeContext.getResponseContext();
296         CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext);
297         RestClientInvoker client = mock(RestClientInvoker.class);
298         HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
299         httpResponse.setEntity(getHttpEntity());
300         Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
301         impl.setClient(client);
302         RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class);
303         RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
304         RuleResult ruleResult = RuleResult.ACCEPT;
305         Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
306         Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
307             .thenReturn(ruleResult);
308         impl.setRequestValidationPolicy(requestValidationPolicy);
309         RequestContext requestContext = new RequestContext();
310         ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
311         actionIdentifiers.setServiceInstanceId("TEST_SERVICE_INSTANCE_ID");
312         actionIdentifiers.setVfModuleId("TEST_VNF_MODULE_ID");
313         actionIdentifiers.setVnfcName("TEST_VNFC_NAME");
314         actionIdentifiers.setVnfId("TEST_VNF_ID");
315         actionIdentifiers.setvServerId("TEST_SERVER_ID");
316         requestContext.setActionIdentifiers(actionIdentifiers);
317         impl.validateRequest(runtimeContext);
318         Mockito.verify(logger).debug("Policy validation result ACCEPT");
319     }
320
321     @Test(expected = WorkflowNotFoundException.class)
322     public void testValidateRequestWorkflowNotFoundException() throws Exception {
323         RuntimeContext runtimeContext = createRequestValidatorInput();
324         lcmStateManager.enableLCMOperations();
325         transactionRecorder = Mockito.mock(TransactionRecorder.class);
326         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
327         TransactionRecord transactionRecord = new TransactionRecord();
328         transactionRecord.setMode(Mode.EXCLUSIVE);
329         runtimeContext.setTransactionRecord(transactionRecord);
330         impl.setTransactionRecorder(transactionRecorder);
331         WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
332         WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
333         Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
334             .thenReturn(workflowExistsOutput);
335         Mockito.when(workflowExistsOutput.isMappingExist()).thenReturn(false);
336         impl.setWorkflowManager(workflowManager);
337         ResponseContext responseContext = runtimeContext.getResponseContext();
338         CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext);
339         RestClientInvoker client = mock(RestClientInvoker.class);
340         HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");;
341         httpResponse.setEntity(getHttpEntity());
342         Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
343         impl.setClient(client);
344         RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class);
345         RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
346         RuleResult ruleResult = RuleResult.REJECT;
347         Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
348         Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
349             .thenReturn(ruleResult);
350         impl.setRequestValidationPolicy(requestValidationPolicy);
351         impl.validateRequest(runtimeContext);
352     }
353
354     @Test(expected = DGWorkflowNotFoundException.class)
355     public void testValidateRequestDGWorkflowNotFoundException() throws Exception {
356         RuntimeContext runtimeContext = createRequestValidatorInput();
357         lcmStateManager.enableLCMOperations();
358         transactionRecorder = Mockito.mock(TransactionRecorder.class);
359         Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
360         TransactionRecord transactionRecord = new TransactionRecord();
361         transactionRecord.setMode(Mode.EXCLUSIVE);
362         runtimeContext.setTransactionRecord(transactionRecord);
363         impl.setTransactionRecorder(transactionRecorder);
364         WorkflowExistsOutput workflowExistsOutput = Mockito.spy(new WorkflowExistsOutput(true, true));
365         WorkFlowManager workflowManager = Mockito.mock(WorkFlowManagerImpl.class);
366         Mockito.when(workflowManager.workflowExists(Mockito.any(WorkflowRequest.class)))
367             .thenReturn(workflowExistsOutput);
368         Mockito.when(workflowExistsOutput.isDgExist()).thenReturn(false);
369         impl.setWorkflowManager(workflowManager);
370         ResponseContext responseContext = runtimeContext.getResponseContext();
371         CommonHeader commonHeader = returnResponseContextCommonHeader(responseContext);
372         RestClientInvoker client = mock(RestClientInvoker.class);
373         HttpResponse httpResponse = new BasicHttpResponse(new ProtocolVersion("HTTP",1,0), 200, "ACCEPTED");
374         httpResponse.setEntity(getHttpEntity());
375         Mockito.when(client.doPost(Mockito.anyString(), Mockito.anyString())).thenReturn(httpResponse);
376         impl.setClient(client);
377         RequestValidationPolicy requestValidationPolicy = Mockito.mock(RequestValidationPolicy.class);
378         RuleExecutor ruleExecutor = Mockito.mock(RuleExecutor.class);
379         RuleResult ruleResult = RuleResult.REJECT;
380         Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(ruleExecutor);
381         Mockito.when(ruleExecutor.executeRule(Mockito.anyString(), Mockito.anyListOf(VNFOperation.class)))
382             .thenReturn(ruleResult);
383         impl.setRequestValidationPolicy(requestValidationPolicy);
384         impl.validateRequest(runtimeContext);
385     }
386
387     private RuntimeContext createRequestValidatorInput() {
388         return createRequestHandlerRuntimeContext("VSCP", "{\"request-id\":\"request-id\"}");
389     }
390
391     private CommonHeader returnResponseContextCommonHeader(ResponseContext responseContext) {
392         CommonHeader commonHeader = responseContext.getCommonHeader();
393         Flags flags = new Flags();
394         flags.setForce(false);
395         commonHeader.setFlags(flags);
396         commonHeader.setRequestId("TEST_REQUEST_ID");
397         return commonHeader;
398     }
399
400     private BasicHttpEntity getHttpEntity() {
401         BasicHttpEntity httpEntity = new BasicHttpEntity();
402         InputStream inputStream = new ByteArrayInputStream(
403                 "{\"output\": {\"status\": {\"message\": \"test_messge\",\"code\": \"400\",\"status\":\"test_status\"},\"response-info\": { \"block\": \"true\"}}}".getBytes());
404         httpEntity.setContent(inputStream);
405         return httpEntity;
406     }
407 }