2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ============LICENSE_END=========================================================
24 package org.onap.appc.requesthandler;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.HttpResponseFactory;
30 import org.apache.http.HttpStatus;
31 import org.apache.http.HttpVersion;
32 import org.apache.http.client.protocol.HttpClientContext;
33 import org.apache.http.entity.BasicHttpEntity;
34 import org.apache.http.impl.DefaultHttpResponseFactory;
35 import org.apache.http.message.BasicStatusLine;
36 import org.junit.Before;
37 import org.junit.Test;
38 import org.junit.runner.RunWith;
39 import org.mockito.Mockito;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
43 import org.onap.appc.domainmodel.lcm.CommonHeader;
44 import org.onap.appc.domainmodel.lcm.Flags;
45 import org.onap.appc.domainmodel.lcm.RequestContext;
46 import org.onap.appc.domainmodel.lcm.ResponseContext;
47 import org.onap.appc.domainmodel.lcm.RuntimeContext;
48 import org.onap.appc.domainmodel.lcm.Status;
49 import org.onap.appc.domainmodel.lcm.TransactionRecord;
50 import org.onap.appc.domainmodel.lcm.VNFContext;
51 import org.onap.appc.domainmodel.lcm.VNFOperation;
52 import org.onap.appc.exceptions.InvalidInputException;
53 import org.onap.appc.lockmanager.api.LockManager;
54 import org.onap.appc.requesthandler.exceptions.DuplicateRequestException;
55 import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
56 import org.onap.appc.requesthandler.exceptions.RequestValidationException;
57 import org.onap.appc.requesthandler.impl.RequestHandlerImpl;
58 import org.onap.appc.requesthandler.impl.RequestValidatorImpl;
59 import org.onap.appc.requesthandler.objects.RequestHandlerInput;
60 import org.onap.appc.rest.client.RestClientInvoker;
61 import org.onap.appc.transactionrecorder.TransactionRecorder;
62 import org.onap.appc.validationpolicy.RequestValidationPolicy;
63 import org.onap.appc.validationpolicy.executors.ActionInProgressRuleExecutor;
64 import org.onap.appc.validationpolicy.objects.RuleResult;
65 import org.onap.appc.workflow.WorkFlowManager;
66 import org.onap.appc.workflow.objects.WorkflowExistsOutput;
67 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
68 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
69 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
70 import org.osgi.framework.Bundle;
71 import org.osgi.framework.BundleContext;
72 import org.osgi.framework.FrameworkUtil;
73 import org.osgi.framework.ServiceReference;
74 import org.powermock.api.mockito.PowerMockito;
75 import org.powermock.core.classloader.annotations.PrepareForTest;
76 import org.powermock.modules.junit4.PowerMockRunner;
78 import java.io.ByteArrayInputStream;
79 import java.io.InputStream;
80 import java.util.Date;
81 import java.util.UUID;
83 import static junit.framework.TestCase.assertNotNull;
84 import static org.junit.Assert.assertNull;
85 import static org.mockito.Matchers.anyBoolean;
86 import static org.mockito.Matchers.anyList;
87 import static org.mockito.Matchers.anyObject;
88 import static org.mockito.Matchers.anyString;
90 @RunWith(PowerMockRunner.class)
91 @PrepareForTest({FrameworkUtil.class, TransactionRecorder.class,
92 RequestHandlerImpl.class, RequestValidatorImpl.class, TransactionRecorder.class})
93 public class RequestValidatorTest {
95 private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerTest.class);
97 private RequestValidatorImpl requestValidator;
99 private AAIService aaiAdapter;
100 private WorkFlowManager workflowManager;
101 private LCMStateManager lcmStateManager;
102 private TransactionRecorder transactionRecorder;
103 private LockManager lockManager;
104 private RestClientInvoker client;
105 private RequestValidationPolicy requestValidationPolicy;
107 private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
108 private final Bundle bundleService = Mockito.mock(Bundle.class);
109 private final ServiceReference sref = Mockito.mock(ServiceReference.class);
112 public void init() throws Exception {
113 AAIService aaiService = Mockito.mock(AAIService.class);
114 PowerMockito.mockStatic(FrameworkUtil.class);
115 PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
116 PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
117 PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref);
118 PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService);
119 PowerMockito.when(aaiService.query(
120 anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject()))
121 .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
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;
133 ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
134 ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
136 return SvcLogicResource.QueryStatus.SUCCESS;
139 PowerMockito.when(aaiService.update(anyString(), anyString(), anyObject(), anyString(), anyObject()))
140 .thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
142 aaiAdapter = Mockito.mock(AAIService.class);
143 workflowManager = Mockito.mock(WorkFlowManager.class);
144 lcmStateManager = Mockito.mock(LCMStateManager.class);
145 transactionRecorder=Mockito.mock(TransactionRecorder.class);
146 lockManager=Mockito.mock(LockManager.class);
147 client=Mockito.mock(RestClientInvoker.class);
148 requestValidationPolicy=Mockito.mock(RequestValidationPolicy.class);
150 requestValidator = new RequestValidatorImpl();
151 requestValidator.setWorkflowManager(workflowManager);
152 requestValidator.setLcmStateManager(lcmStateManager);
153 requestValidator.setTransactionRecorder(transactionRecorder);
154 requestValidator.setLockManager(lockManager);
155 requestValidator.setClient(client);
156 requestValidator.setRequestValidationPolicy(requestValidationPolicy);
158 Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true);
162 public AAIService getAaiadapter() {
163 return this.aaiAdapter;
166 private RequestHandlerInput getRequestHandlerInput(String vnfID,
174 String API_VERSION = "2.0.0";
175 RequestHandlerInput input = new RequestHandlerInput();
176 RuntimeContext runtimeContext = createRuntimeContextWithSubObjects();
177 RequestContext requestContext = runtimeContext.getRequestContext();
178 input.setRequestContext(requestContext);
179 requestContext.getActionIdentifiers().setVnfId(vnfID);
180 requestContext.setAction(action);
181 if (action != null) {
182 input.setRpcName(convertActionNameToUrl(action.name()));
184 input.setRpcName(null);
186 requestContext.getCommonHeader().setRequestId(requestId);
187 requestContext.getCommonHeader().setSubRequestId(subRequestId);
188 requestContext.getCommonHeader().setOriginatorId(originatorId);
189 requestContext.getCommonHeader().getFlags().setTtl(ttl);
190 requestContext.getCommonHeader().getFlags().setForce(force);
191 requestContext.getCommonHeader().getTimeStamp();
192 requestContext.getCommonHeader().setApiVer(API_VERSION);
193 requestContext.getCommonHeader().setTimestamp(timeStamp);
198 public void testNullVnfID() throws Exception {
199 logger.debug("=====================testNullVnfID=============================");
200 Mockito.when(workflowManager.workflowExists(anyObject()))
201 .thenReturn(new WorkflowExistsOutput(true, true));
202 RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30,
203 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
204 UUID.randomUUID().toString(), new Date());
206 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
208 requestValidator.validateRequest(runtimeContext);
209 } catch (InvalidInputException e) {
213 logger.debug("=====================testNullVnfID=============================");
216 public void testPositiveFlowWithConfigure() throws Exception {
217 logger.debug("=====================testPositiveFlowWithConfigure=============================");
218 Mockito.when(workflowManager.workflowExists(anyObject()))
219 .thenReturn(new WorkflowExistsOutput(true, true));
220 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
221 Mockito.when(lockManager.getLockOwner(anyString())).thenReturn(null);
222 ActionInProgressRuleExecutor action=Mockito.mock(ActionInProgressRuleExecutor.class);
224 Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(action);
225 Mockito.when(action.executeRule(anyString(),anyList())).thenReturn(RuleResult.ACCEPT);
226 HttpResponseFactory factory = new DefaultHttpResponseFactory();
227 HttpResponse response=factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null),new HttpClientContext());
228 /*String jsonResponse="{\n" +
229 "\t\"status\" : \"success\",\n" +
230 "\t\"scope-overlap\" : true\n" +
233 String jsonResponse= "{\"output\":{\"status\":{\"message\":\"success\",\"code\":\"400\"},\"response-info\":{\"requestId\":\"AnynonRepetitiveNumber/String\",\"block\":{\"requestOverlap\":\"true\"}}}}";
235 InputStream stream= new ByteArrayInputStream(jsonResponse.getBytes());
236 BasicHttpEntity a=new BasicHttpEntity();
237 a.setContent(stream);
238 response.setEntity(a);
239 Mockito.when(client.doPost(anyString(),anyString())).thenReturn(response);
240 RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30,
241 false, UUID.randomUUID().toString(), "123",
242 UUID.randomUUID().toString(), new Date());
244 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
246 requestValidator.validateRequest(runtimeContext);
247 } catch (Exception e) {
251 logger.debug("testPositiveFlowWithConfigure");
252 logger.debug("=====================testPositiveFlowWithConfigure=============================");
255 //@Test(expected= RequestValidationException.class)
256 public void testWithRuleResultAsReject() throws Exception {
257 logger.debug("=====================testWithRuleResultAsReject=============================");
258 Mockito.when(workflowManager.workflowExists(anyObject()))
259 .thenReturn(new WorkflowExistsOutput(true, true));
260 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
261 Mockito.when(lockManager.getLockOwner(anyString())).thenReturn(null);
262 ActionInProgressRuleExecutor action=Mockito.mock(ActionInProgressRuleExecutor.class);
264 Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(action);
265 Mockito.when(action.executeRule(anyString(),anyList())).thenReturn(RuleResult.REJECT);
266 HttpResponseFactory factory = new DefaultHttpResponseFactory();
267 HttpResponse response=factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null),new HttpClientContext());
268 /*String jsonResponse="{\n" +
269 "\t\"status\" : \"success\",\n" +
270 "\t\"scope-overlap\" : true\n" +
272 String jsonResponse= "{\"output\":{\"status\":{\"message\":\"success\",\"code\":\"400\"},\"response-info\":{\"requestId\":\"AnynonRepetitiveNumber/String\",\"block\":{\"requestOverlap\":\"true\"}}}}";
273 InputStream stream= new ByteArrayInputStream(jsonResponse.getBytes());
274 BasicHttpEntity a=new BasicHttpEntity();
275 a.setContent(stream);
276 response.setEntity(a);
277 Mockito.when(client.doPost(anyString(),anyString())).thenReturn(response);
278 RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30,
279 false, UUID.randomUUID().toString(), "200",
280 UUID.randomUUID().toString(), new Date());
282 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
284 requestValidator.validateRequest(runtimeContext);
285 logger.debug("testWithRuleResultAsReject");
286 logger.debug("=====================testWithRuleResultAsReject=============================");
290 public void testVnfNotFound() throws Exception {
291 logger.debug("=====================testVnfNotFound=============================");
292 Mockito.when(workflowManager.workflowExists(anyObject()))
293 .thenReturn(new WorkflowExistsOutput(true, true));
294 RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30,
295 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
296 UUID.randomUUID().toString(), new Date());
298 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
300 requestValidator.validateRequest(runtimeContext);
301 } catch (Exception e) {
305 logger.debug("=====================testVnfNotFound=============================");
310 public void testNullCommand() throws Exception {
311 logger.debug("=====================testNullCommand=============================");
312 Mockito.when(workflowManager.workflowExists(anyObject()))
313 .thenReturn(new WorkflowExistsOutput(true, true));
314 RequestHandlerInput input = this.getRequestHandlerInput("7", null, 30,
315 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
316 UUID.randomUUID().toString(), new Date());
318 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
320 requestValidator.validateRequest(runtimeContext);
321 } catch (InvalidInputException e) {
325 logger.debug("=====================testNullCommand=============================");
329 public void testNullVnfIDAndCommand() throws Exception {
330 logger.debug("=====================testNullVnfIDAndCommand=============================");
331 Mockito.when(workflowManager.workflowExists(anyObject()))
332 .thenReturn(new WorkflowExistsOutput(true, true));
333 RequestHandlerInput input = this.getRequestHandlerInput(null, null, 30,
334 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
335 UUID.randomUUID().toString(), new Date());
337 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
339 requestValidator.validateRequest(runtimeContext);
340 } catch (InvalidInputException e) {
344 logger.debug("=====================testNullVnfIDAndCommand=============================");
348 public void testWorkflowNotFound() throws Exception {
349 logger.debug("=====================testWorkflowNotFound=============================");
350 Mockito.when(workflowManager.workflowExists(anyObject()))
351 .thenReturn(new WorkflowExistsOutput(false, false));
352 RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30,
353 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
354 UUID.randomUUID().toString(), new Date());
356 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
358 requestValidator.validateRequest(runtimeContext);
359 } catch (Exception e) {
363 logger.debug("=====================testWorkflowNotFound=============================");
367 public void testAAIDown() throws Exception {
368 logger.debug("=====================testAAIDown=============================");
369 RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30,
370 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
371 UUID.randomUUID().toString(), new Date());
373 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
375 requestValidator.validateRequest(runtimeContext);
377 } catch (Exception e) {
381 logger.debug("=====================testAAIDown=============================");
385 public void testNegativeFlowWithTimeStamp() throws Exception {
386 logger.debug("=====================testNegativeFlowWithTimeStamp=============================");
387 Date now = new Date();
388 Date past = new Date();
389 past.setTime(now.getTime() - 1000000);
390 RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30,
391 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
392 UUID.randomUUID().toString(), past);
394 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
397 requestValidator.validateRequest(runtimeContext);
398 } catch (Exception e) {
402 logger.debug("testNegativeFlowWithTimeStamp");
403 logger.debug("=====================testNegativeFlowWithTimeStamp=============================");
406 //@Test(expected= DuplicateRequestException.class)
407 public void rejectDuplicateRequest() throws Exception {
408 String originatorID = UUID.randomUUID().toString();
409 String requestID = UUID.randomUUID().toString();
410 String subRequestID = UUID.randomUUID().toString();
411 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(true);
412 Mockito.when(workflowManager.workflowExists(anyObject()))
413 .thenReturn(new WorkflowExistsOutput(true, true));
414 RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure, 0,
415 false, originatorID, requestID, subRequestID, new Date());
417 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
418 requestValidator.validateRequest(runtimeContext);
423 public void testLockOperation() throws Exception {
425 testOperation("no-matter", VNFOperation.Lock);
428 //TODO needs to be fixed
430 public void testUnlockOperation() throws Exception {
431 testOperation("no-matter", VNFOperation.Unlock);
434 //TODO needs to be fixed
436 public void testCheckLockOperation() throws Exception {
437 testOperation("no-matter", VNFOperation.CheckLock);
441 //@Test(expected = LCMOperationsDisabledException.class)
442 public void testLCMOperationsDisabled() throws Exception {
443 Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false);
444 testOperation("no-matter", VNFOperation.Configure);
447 private void testOperation(String resource, VNFOperation operation) throws Exception {
448 String originatorID = UUID.randomUUID().toString();
449 String requestID = UUID.randomUUID().toString();
450 String subRequestID = UUID.randomUUID().toString();
451 RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0,
452 false, originatorID, requestID, subRequestID, new Date());
453 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
454 requestValidator.validateRequest(runtimeContext);
457 private RuntimeContext createRuntimeContextWithSubObjects() {
458 RuntimeContext runtimeContext = new RuntimeContext();
459 RequestContext requestContext = new RequestContext();
460 runtimeContext.setRequestContext(requestContext);
461 ResponseContext responseContext = createResponseContextWithSuObjects();
462 runtimeContext.setResponseContext(responseContext);
463 CommonHeader commonHeader = new CommonHeader();
464 requestContext.setCommonHeader(commonHeader);
465 Flags flags = new Flags();
466 commonHeader.setFlags(flags);
467 ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
468 requestContext.setActionIdentifiers(actionIdentifiers);
469 VNFContext vnfContext = new VNFContext();
470 runtimeContext.setVnfContext(vnfContext);
471 return runtimeContext;
474 private ResponseContext createResponseContextWithSuObjects() {
475 ResponseContext responseContext = new ResponseContext();
476 CommonHeader commonHeader = new CommonHeader();
477 Flags flags = new Flags();
478 Status status = new Status();
479 responseContext.setCommonHeader(commonHeader);
480 responseContext.setStatus(status);
481 commonHeader.setFlags(flags);
482 return responseContext;
485 private String convertActionNameToUrl(String action) {
486 String regex = "([a-z])([A-Z]+)";
487 String replacement = "$1-$2";
488 return action.replaceAll(regex, replacement)
492 private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) {
493 RuntimeContext runtimeContext = createRuntimeContextWithSubObjects();
494 runtimeContext.setRequestContext(input.getRequestContext());
495 runtimeContext.setRpcName(input.getRpcName());
496 runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId());
497 runtimeContext.getRequestContext().getActionIdentifiers().setServiceInstanceId(UUID.randomUUID().toString());
498 TransactionRecord record= new TransactionRecord();
499 record.setTargetId(input.getRequestContext().getActionIdentifiers().getVnfId());
500 record.setOriginatorId(input.getRequestContext().getCommonHeader().getOriginatorId());
501 record.setRequestId(input.getRequestContext().getCommonHeader().getRequestId());
502 record.setSubRequestId(input.getRequestContext().getCommonHeader().getSubRequestId());
503 record.setOriginTimestamp(input.getRequestContext().getCommonHeader().getTimeStamp().toInstant());
504 record.setServiceInstanceId(UUID.randomUUID().toString());
505 record.setOperation(input.getRequestContext().getAction());
506 runtimeContext.setTransactionRecord(record);
508 return runtimeContext;