2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.requesthandler;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.HttpResponseFactory;
31 import org.apache.http.HttpStatus;
32 import org.apache.http.HttpVersion;
33 import org.apache.http.client.protocol.HttpClientContext;
34 import org.apache.http.entity.BasicHttpEntity;
35 import org.apache.http.impl.DefaultHttpResponseFactory;
36 import org.apache.http.message.BasicStatusLine;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.junit.runner.RunWith;
40 import org.mockito.Mockito;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.onap.appc.domainmodel.lcm.ActionIdentifiers;
44 import org.onap.appc.domainmodel.lcm.CommonHeader;
45 import org.onap.appc.domainmodel.lcm.Flags;
46 import org.onap.appc.domainmodel.lcm.RequestContext;
47 import org.onap.appc.domainmodel.lcm.ResponseContext;
48 import org.onap.appc.domainmodel.lcm.RuntimeContext;
49 import org.onap.appc.domainmodel.lcm.Status;
50 import org.onap.appc.domainmodel.lcm.TransactionRecord;
51 import org.onap.appc.domainmodel.lcm.VNFContext;
52 import org.onap.appc.domainmodel.lcm.VNFOperation;
53 import org.onap.appc.exceptions.InvalidInputException;
54 import org.onap.appc.lockmanager.api.LockManager;
55 import org.onap.appc.requesthandler.exceptions.DuplicateRequestException;
56 import org.onap.appc.requesthandler.exceptions.LCMOperationsDisabledException;
57 import org.onap.appc.requesthandler.exceptions.RequestValidationException;
58 import org.onap.appc.requesthandler.impl.RequestHandlerImpl;
59 import org.onap.appc.requesthandler.impl.RequestValidatorImpl;
60 import org.onap.appc.requesthandler.objects.RequestHandlerInput;
61 import org.onap.appc.rest.client.RestClientInvoker;
62 import org.onap.appc.transactionrecorder.TransactionRecorder;
63 import org.onap.appc.validationpolicy.RequestValidationPolicy;
64 import org.onap.appc.validationpolicy.executors.ActionInProgressRuleExecutor;
65 import org.onap.appc.validationpolicy.objects.RuleResult;
66 import org.onap.appc.workflow.WorkFlowManager;
67 import org.onap.appc.workflow.objects.WorkflowExistsOutput;
68 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
69 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
70 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
71 import org.osgi.framework.Bundle;
72 import org.osgi.framework.BundleContext;
73 import org.osgi.framework.FrameworkUtil;
74 import org.osgi.framework.ServiceReference;
75 import org.powermock.api.mockito.PowerMockito;
76 import org.powermock.core.classloader.annotations.PrepareForTest;
77 import org.powermock.modules.junit4.PowerMockRunner;
79 import java.io.ByteArrayInputStream;
80 import java.io.InputStream;
81 import java.util.Date;
82 import java.util.UUID;
84 import static junit.framework.TestCase.assertNotNull;
85 import static org.junit.Assert.assertNull;
86 import static org.mockito.Matchers.anyBoolean;
87 import static org.mockito.Matchers.anyList;
88 import static org.mockito.Matchers.anyObject;
89 import static org.mockito.Matchers.anyString;
91 @RunWith(PowerMockRunner.class)
92 @PrepareForTest({FrameworkUtil.class, TransactionRecorder.class,
93 RequestHandlerImpl.class, RequestValidatorImpl.class, TransactionRecorder.class})
94 public class RequestValidatorTest {
96 private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestHandlerTest.class);
98 private RequestValidatorImpl requestValidator;
100 private AAIService aaiAdapter;
101 private WorkFlowManager workflowManager;
102 private LCMStateManager lcmStateManager;
103 private TransactionRecorder transactionRecorder;
104 private LockManager lockManager;
105 private RestClientInvoker client;
106 private RequestValidationPolicy requestValidationPolicy;
108 private final BundleContext bundleContext = Mockito.mock(BundleContext.class);
109 private final Bundle bundleService = Mockito.mock(Bundle.class);
110 private final ServiceReference sref = Mockito.mock(ServiceReference.class);
113 public void init() throws Exception {
114 AAIService aaiService = Mockito.mock(AAIService.class);
115 PowerMockito.mockStatic(FrameworkUtil.class);
116 PowerMockito.when(FrameworkUtil.getBundle(AAIService.class)).thenReturn(bundleService);
117 PowerMockito.when(bundleService.getBundleContext()).thenReturn(bundleContext);
118 PowerMockito.when(bundleContext.getServiceReference(AAIService.class.getName())).thenReturn(sref);
119 PowerMockito.when(bundleContext.getService(sref)).thenReturn(aaiService);
120 PowerMockito.when(aaiService.query(
121 anyString(), anyBoolean(), anyString(), anyString(), anyString(), anyString(), anyObject()))
122 .thenAnswer(new Answer<SvcLogicResource.QueryStatus>() {
124 public SvcLogicResource.QueryStatus answer(InvocationOnMock invocation) throws Exception {
125 Object[] args = invocation.getArguments();
126 SvcLogicContext ctx = (SvcLogicContext) args[6];
127 String prefix = (String) args[4];
128 String key = (String) args[3];
129 if (key.contains("'28'")) {
130 return SvcLogicResource.QueryStatus.FAILURE;
131 } else if (key.contains("'8'")) {
132 return SvcLogicResource.QueryStatus.NOT_FOUND;
134 ctx.setAttribute(prefix + ".vnf-type", "FIREWALL");
135 ctx.setAttribute(prefix + ".orchestration-status", "Instantiated");
137 return SvcLogicResource.QueryStatus.SUCCESS;
140 PowerMockito.when(aaiService.update(anyString(), anyString(), anyObject(), anyString(), anyObject()))
141 .thenReturn(SvcLogicResource.QueryStatus.SUCCESS);
143 aaiAdapter = Mockito.mock(AAIService.class);
144 workflowManager = Mockito.mock(WorkFlowManager.class);
145 lcmStateManager = Mockito.mock(LCMStateManager.class);
146 transactionRecorder=Mockito.mock(TransactionRecorder.class);
147 lockManager=Mockito.mock(LockManager.class);
148 client=Mockito.mock(RestClientInvoker.class);
149 requestValidationPolicy=Mockito.mock(RequestValidationPolicy.class);
151 requestValidator = new RequestValidatorImpl();
152 requestValidator.setWorkflowManager(workflowManager);
153 requestValidator.setLcmStateManager(lcmStateManager);
154 requestValidator.setTransactionRecorder(transactionRecorder);
155 requestValidator.setLockManager(lockManager);
156 requestValidator.setClient(client);
157 requestValidator.setRequestValidationPolicy(requestValidationPolicy);
159 Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(true);
163 public AAIService getAaiadapter() {
164 return this.aaiAdapter;
167 private RequestHandlerInput getRequestHandlerInput(String vnfID,
175 String API_VERSION = "2.0.0";
176 RequestHandlerInput input = new RequestHandlerInput();
177 RuntimeContext runtimeContext = createRuntimeContextWithSubObjects();
178 RequestContext requestContext = runtimeContext.getRequestContext();
179 input.setRequestContext(requestContext);
180 requestContext.getActionIdentifiers().setVnfId(vnfID);
181 requestContext.setAction(action);
182 if (action != null) {
183 input.setRpcName(convertActionNameToUrl(action.name()));
185 input.setRpcName(null);
187 requestContext.getCommonHeader().setRequestId(requestId);
188 requestContext.getCommonHeader().setSubRequestId(subRequestId);
189 requestContext.getCommonHeader().setOriginatorId(originatorId);
190 requestContext.getCommonHeader().getFlags().setTtl(ttl);
191 requestContext.getCommonHeader().getFlags().setForce(force);
192 requestContext.getCommonHeader().getTimeStamp();
193 requestContext.getCommonHeader().setApiVer(API_VERSION);
194 requestContext.getCommonHeader().setTimestamp(timeStamp);
199 public void testNullVnfID() throws Exception {
200 logger.debug("=====================testNullVnfID=============================");
201 Mockito.when(workflowManager.workflowExists(anyObject()))
202 .thenReturn(new WorkflowExistsOutput(true, true));
203 RequestHandlerInput input = this.getRequestHandlerInput(null, VNFOperation.Configure, 30,
204 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
205 UUID.randomUUID().toString(), new Date());
207 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
209 requestValidator.validateRequest(runtimeContext);
210 } catch (InvalidInputException e) {
214 logger.debug("=====================testNullVnfID=============================");
217 public void testPositiveFlowWithConfigure() throws Exception {
218 logger.debug("=====================testPositiveFlowWithConfigure=============================");
219 Mockito.when(workflowManager.workflowExists(anyObject()))
220 .thenReturn(new WorkflowExistsOutput(true, true));
221 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
222 Mockito.when(lockManager.getLockOwner(anyString())).thenReturn(null);
223 ActionInProgressRuleExecutor action=Mockito.mock(ActionInProgressRuleExecutor.class);
225 Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(action);
226 Mockito.when(action.executeRule(anyString(),anyList())).thenReturn(RuleResult.ACCEPT);
227 HttpResponseFactory factory = new DefaultHttpResponseFactory();
228 HttpResponse response=factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null),new HttpClientContext());
229 /*String jsonResponse="{\n" +
230 "\t\"status\" : \"success\",\n" +
231 "\t\"scope-overlap\" : true\n" +
234 String jsonResponse= "{\"output\":{\"status\":{\"message\":\"success\",\"code\":\"400\"},\"response-info\":{\"requestId\":\"AnynonRepetitiveNumber/String\",\"block\":{\"requestOverlap\":\"true\"}}}}";
236 InputStream stream= new ByteArrayInputStream(jsonResponse.getBytes());
237 BasicHttpEntity a=new BasicHttpEntity();
238 a.setContent(stream);
239 response.setEntity(a);
240 Mockito.when(client.doPost(anyString(),anyString())).thenReturn(response);
241 RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30,
242 false, UUID.randomUUID().toString(), "123",
243 UUID.randomUUID().toString(), new Date());
245 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
247 requestValidator.validateRequest(runtimeContext);
248 } catch (Exception e) {
252 logger.debug("testPositiveFlowWithConfigure");
253 logger.debug("=====================testPositiveFlowWithConfigure=============================");
256 //@Test(expected= RequestValidationException.class)
257 public void testWithRuleResultAsReject() throws Exception {
258 logger.debug("=====================testWithRuleResultAsReject=============================");
259 Mockito.when(workflowManager.workflowExists(anyObject()))
260 .thenReturn(new WorkflowExistsOutput(true, true));
261 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(false);
262 Mockito.when(lockManager.getLockOwner(anyString())).thenReturn(null);
263 ActionInProgressRuleExecutor action=Mockito.mock(ActionInProgressRuleExecutor.class);
265 Mockito.when(requestValidationPolicy.getInProgressRuleExecutor()).thenReturn(action);
266 Mockito.when(action.executeRule(anyString(),anyList())).thenReturn(RuleResult.REJECT);
267 HttpResponseFactory factory = new DefaultHttpResponseFactory();
268 HttpResponse response=factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null),new HttpClientContext());
269 /*String jsonResponse="{\n" +
270 "\t\"status\" : \"success\",\n" +
271 "\t\"scope-overlap\" : true\n" +
273 String jsonResponse= "{\"output\":{\"status\":{\"message\":\"success\",\"code\":\"400\"},\"response-info\":{\"requestId\":\"AnynonRepetitiveNumber/String\",\"block\":{\"requestOverlap\":\"true\"}}}}";
274 InputStream stream= new ByteArrayInputStream(jsonResponse.getBytes());
275 BasicHttpEntity a=new BasicHttpEntity();
276 a.setContent(stream);
277 response.setEntity(a);
278 Mockito.when(client.doPost(anyString(),anyString())).thenReturn(response);
279 RequestHandlerInput input = this.getRequestHandlerInput("1", VNFOperation.Configure, 30,
280 false, UUID.randomUUID().toString(), "200",
281 UUID.randomUUID().toString(), new Date());
283 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
285 requestValidator.validateRequest(runtimeContext);
286 logger.debug("testWithRuleResultAsReject");
287 logger.debug("=====================testWithRuleResultAsReject=============================");
291 public void testVnfNotFound() throws Exception {
292 logger.debug("=====================testVnfNotFound=============================");
293 Mockito.when(workflowManager.workflowExists(anyObject()))
294 .thenReturn(new WorkflowExistsOutput(true, true));
295 RequestHandlerInput input = this.getRequestHandlerInput("8", VNFOperation.Configure, 30,
296 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
297 UUID.randomUUID().toString(), new Date());
299 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
301 requestValidator.validateRequest(runtimeContext);
302 } catch (Exception e) {
306 logger.debug("=====================testVnfNotFound=============================");
311 public void testNullCommand() throws Exception {
312 logger.debug("=====================testNullCommand=============================");
313 Mockito.when(workflowManager.workflowExists(anyObject()))
314 .thenReturn(new WorkflowExistsOutput(true, true));
315 RequestHandlerInput input = this.getRequestHandlerInput("7", null, 30,
316 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
317 UUID.randomUUID().toString(), new Date());
319 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
321 requestValidator.validateRequest(runtimeContext);
322 } catch (InvalidInputException e) {
326 logger.debug("=====================testNullCommand=============================");
330 public void testNullVnfIDAndCommand() throws Exception {
331 logger.debug("=====================testNullVnfIDAndCommand=============================");
332 Mockito.when(workflowManager.workflowExists(anyObject()))
333 .thenReturn(new WorkflowExistsOutput(true, true));
334 RequestHandlerInput input = this.getRequestHandlerInput(null, null, 30,
335 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
336 UUID.randomUUID().toString(), new Date());
338 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
340 requestValidator.validateRequest(runtimeContext);
341 } catch (InvalidInputException e) {
345 logger.debug("=====================testNullVnfIDAndCommand=============================");
349 public void testWorkflowNotFound() throws Exception {
350 logger.debug("=====================testWorkflowNotFound=============================");
351 Mockito.when(workflowManager.workflowExists(anyObject()))
352 .thenReturn(new WorkflowExistsOutput(false, false));
353 RequestHandlerInput input = this.getRequestHandlerInput("10", VNFOperation.Configure, 30,
354 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
355 UUID.randomUUID().toString(), new Date());
357 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
359 requestValidator.validateRequest(runtimeContext);
360 } catch (Exception e) {
364 logger.debug("=====================testWorkflowNotFound=============================");
368 public void testAAIDown() throws Exception {
369 logger.debug("=====================testAAIDown=============================");
370 RequestHandlerInput input = this.getRequestHandlerInput("28", VNFOperation.Configure, 30,
371 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
372 UUID.randomUUID().toString(), new Date());
374 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
376 requestValidator.validateRequest(runtimeContext);
378 } catch (Exception e) {
382 logger.debug("=====================testAAIDown=============================");
386 public void testNegativeFlowWithTimeStamp() throws Exception {
387 logger.debug("=====================testNegativeFlowWithTimeStamp=============================");
388 Date now = new Date();
389 Date past = new Date();
390 past.setTime(now.getTime() - 1000000);
391 RequestHandlerInput input = this.getRequestHandlerInput("35", VNFOperation.Configure, 30,
392 false, UUID.randomUUID().toString(), UUID.randomUUID().toString(),
393 UUID.randomUUID().toString(), past);
395 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
398 requestValidator.validateRequest(runtimeContext);
399 } catch (Exception e) {
403 logger.debug("testNegativeFlowWithTimeStamp");
404 logger.debug("=====================testNegativeFlowWithTimeStamp=============================");
407 //@Test(expected= DuplicateRequestException.class)
408 public void rejectDuplicateRequest() throws Exception {
409 String originatorID = UUID.randomUUID().toString();
410 String requestID = UUID.randomUUID().toString();
411 String subRequestID = UUID.randomUUID().toString();
412 Mockito.when(transactionRecorder.isTransactionDuplicate(anyObject())).thenReturn(true);
413 Mockito.when(workflowManager.workflowExists(anyObject()))
414 .thenReturn(new WorkflowExistsOutput(true, true));
415 RequestHandlerInput input = this.getRequestHandlerInput("301", VNFOperation.Configure, 0,
416 false, originatorID, requestID, subRequestID, new Date());
418 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
419 requestValidator.validateRequest(runtimeContext);
424 public void testLockOperation() throws Exception {
426 testOperation("no-matter", VNFOperation.Lock);
429 //TODO needs to be fixed
431 public void testUnlockOperation() throws Exception {
432 testOperation("no-matter", VNFOperation.Unlock);
435 //TODO needs to be fixed
437 public void testCheckLockOperation() throws Exception {
438 testOperation("no-matter", VNFOperation.CheckLock);
442 //@Test(expected = LCMOperationsDisabledException.class)
443 public void testLCMOperationsDisabled() throws Exception {
444 Mockito.when(lcmStateManager.isLCMOperationEnabled()).thenReturn(false);
445 testOperation("no-matter", VNFOperation.Configure);
448 private void testOperation(String resource, VNFOperation operation) throws Exception {
449 String originatorID = UUID.randomUUID().toString();
450 String requestID = UUID.randomUUID().toString();
451 String subRequestID = UUID.randomUUID().toString();
452 RequestHandlerInput input = this.getRequestHandlerInput(resource, operation, 0,
453 false, originatorID, requestID, subRequestID, new Date());
454 RuntimeContext runtimeContext = putInputToRuntimeContext(input);
455 requestValidator.validateRequest(runtimeContext);
458 private RuntimeContext createRuntimeContextWithSubObjects() {
459 RuntimeContext runtimeContext = new RuntimeContext();
460 RequestContext requestContext = new RequestContext();
461 runtimeContext.setRequestContext(requestContext);
462 ResponseContext responseContext = createResponseContextWithSuObjects();
463 runtimeContext.setResponseContext(responseContext);
464 CommonHeader commonHeader = new CommonHeader();
465 requestContext.setCommonHeader(commonHeader);
466 Flags flags = new Flags();
467 commonHeader.setFlags(flags);
468 ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
469 requestContext.setActionIdentifiers(actionIdentifiers);
470 VNFContext vnfContext = new VNFContext();
471 runtimeContext.setVnfContext(vnfContext);
472 return runtimeContext;
475 private ResponseContext createResponseContextWithSuObjects() {
476 ResponseContext responseContext = new ResponseContext();
477 CommonHeader commonHeader = new CommonHeader();
478 Flags flags = new Flags();
479 Status status = new Status();
480 responseContext.setCommonHeader(commonHeader);
481 responseContext.setStatus(status);
482 commonHeader.setFlags(flags);
483 return responseContext;
486 private String convertActionNameToUrl(String action) {
487 String regex = "([a-z])([A-Z]+)";
488 String replacement = "$1-$2";
489 return action.replaceAll(regex, replacement)
493 private RuntimeContext putInputToRuntimeContext(RequestHandlerInput input) {
494 RuntimeContext runtimeContext = createRuntimeContextWithSubObjects();
495 runtimeContext.setRequestContext(input.getRequestContext());
496 runtimeContext.setRpcName(input.getRpcName());
497 runtimeContext.getVnfContext().setId(input.getRequestContext().getActionIdentifiers().getVnfId());
498 runtimeContext.getRequestContext().getActionIdentifiers().setServiceInstanceId(UUID.randomUUID().toString());
499 TransactionRecord record= new TransactionRecord();
500 record.setTargetId(input.getRequestContext().getActionIdentifiers().getVnfId());
501 record.setOriginatorId(input.getRequestContext().getCommonHeader().getOriginatorId());
502 record.setRequestId(input.getRequestContext().getCommonHeader().getRequestId());
503 record.setSubRequestId(input.getRequestContext().getCommonHeader().getSubRequestId());
504 record.setOriginTimestamp(input.getRequestContext().getCommonHeader().getTimeStamp().toInstant());
505 record.setServiceInstanceId(UUID.randomUUID().toString());
506 record.setOperation(input.getRequestContext().getAction());
507 runtimeContext.setTransactionRecord(record);
509 return runtimeContext;