2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.controlloop.actor.guard;
23 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertNull;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.ArgumentMatchers.any;
31 import static org.mockito.Mockito.mock;
32 import static org.mockito.Mockito.never;
33 import static org.mockito.Mockito.verify;
34 import static org.mockito.Mockito.when;
37 import java.util.TreeMap;
38 import java.util.concurrent.CompletableFuture;
39 import java.util.function.Consumer;
40 import org.junit.AfterClass;
41 import org.junit.Before;
42 import org.junit.BeforeClass;
43 import org.junit.Test;
44 import org.mockito.Mock;
45 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
46 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
50 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
51 import org.onap.policy.controlloop.actorserviceprovider.Util;
52 import org.onap.policy.controlloop.policy.PolicyResult;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.simulators.GuardSimulatorJaxRs;
57 public class GuardOperationTest extends BasicHttpOperation<DecisionRequest> {
60 private Consumer<OperationOutcome> started;
62 private Consumer<OperationOutcome> completed;
64 private GuardConfig guardConfig;
65 private GuardOperation oper;
68 * Starts the simulator.
71 public static void setUpBeforeClass() throws Exception {
72 org.onap.policy.simulators.Util.buildGuardSim();
74 BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
75 .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.GUARDSIM_SERVER_PORT)
77 HttpClientFactoryInstance.getClientFactory().build(clientParams);
81 public static void tearDownAfterClass() {
82 HttpClientFactoryInstance.getClientFactory().destroy();
83 HttpServletServerFactoryInstance.getServerFactory().destroy();
90 public void setUp() throws Exception {
93 guardConfig = mock(GuardConfig.class);
94 when(guardConfig.makeRequest()).thenAnswer(args -> {
95 DecisionRequest req = new DecisionRequest();
96 req.setAction("guard");
97 req.setOnapComponent("my-onap-component");
98 req.setOnapInstance("my-onap-instance");
99 req.setOnapName("my-onap-name");
103 config = guardConfig;
106 params = params.toBuilder().startCallback(started).completeCallback(completed).build();
108 oper = new GuardOperation(params, config);
112 * Tests "success" case with simulator.
115 public void testSuccess() throws Exception {
116 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
117 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
119 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
120 oper = new GuardOperation(params, config);
122 outcome = oper.start().get();
123 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
124 assertTrue(outcome.getResponse() instanceof DecisionResponse);
128 * Tests "failure" case with simulator.
131 public void testFailure() throws Exception {
132 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
133 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
135 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
136 .payload(Map.of("clname", GuardSimulatorJaxRs.DENY_CLNAME)).build();
137 oper = new GuardOperation(params, config);
139 outcome = oper.start().get();
140 assertEquals(PolicyResult.FAILURE, outcome.getResult());
141 assertTrue(outcome.getResponse() instanceof DecisionResponse);
145 public void testConstructor() {
146 assertEquals(DEFAULT_ACTOR, oper.getActorName());
147 assertEquals(DEFAULT_OPERATION, oper.getName());
151 public void testStartOperationAsync() throws Exception {
152 CompletableFuture<OperationOutcome> future2 = oper.start();
153 executor.runAll(100);
154 assertFalse(future2.isDone());
156 DecisionResponse resp = new DecisionResponse();
157 resp.setStatus(GuardOperation.PERMIT);
158 when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
160 verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
161 callbackCaptor.getValue().completed(rawResponse);
163 executor.runAll(100);
164 assertTrue(future2.isDone());
166 outcome = future2.get();
167 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
168 assertEquals(resp, outcome.getResponse());
170 assertNotNull(oper.getSubRequestId());
171 assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
175 * Tests startOperationAsync() when the guard is disabled.
178 public void testStartOperationAsyncDisabled() throws Exception {
179 // indicate that it's disabled
180 when(guardConfig.isDisabled()).thenReturn(true);
182 CompletableFuture<OperationOutcome> future2 = oper.start();
183 executor.runAll(100);
185 verify(client, never()).post(any(), any(), any(), any());
187 // should already be done
188 assertTrue(future2.isDone());
190 outcome = future2.get();
191 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
192 assertNull(outcome.getResponse());
194 // ensure callbacks were invoked
195 verify(started).accept(any());
196 verify(completed).accept(any());
200 public void testMakeRequest() throws CoderException {
201 oper.generateSubRequestId(2);
203 verifyPayload("makeReqStd.json", makePayload());
204 verifyPayload("makeReqDefault.json", new TreeMap<>());
206 // null payload - start with fresh parameters and operation
207 params = params.toBuilder().payload(null).build();
208 oper = new GuardOperation(params, config);
209 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
212 private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
213 params.getPayload().clear();
214 params.getPayload().putAll(payload);
216 DecisionRequest request = oper.makeRequest();
218 assertEquals("guard", request.getAction());
219 assertEquals("my-onap-component", request.getOnapComponent());
220 assertEquals("my-onap-instance", request.getOnapInstance());
221 assertEquals("my-onap-name", request.getOnapName());
222 assertNotNull(request.getRequestId());
223 assertEquals(Map.of("guard", payload), request.getResource());
225 verifyRequest(expectedJsonFile, request, "requestId");
229 public void testPostProcessResponse() {
230 DecisionResponse response = new DecisionResponse();
233 response.setStatus(null);
234 verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
236 // permit, mixed case
237 response.setStatus("peRmit");
238 verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
240 // indeterminate, mixed case
241 response.setStatus("inDETerminate");
242 verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
245 response.setStatus("deNY");
246 verifyOutcome(response, PolicyResult.FAILURE, "deNY");
249 response.setStatus("unknown");
250 verifyOutcome(response, PolicyResult.FAILURE, "unknown");
253 private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) {
254 oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
255 assertEquals(expectedResult, outcome.getResult());
256 assertEquals(expectedMessage, outcome.getMessage());
257 assertSame(response, outcome.getResponse());
261 protected Map<String, Object> makePayload() {
262 return new TreeMap<>(Map.of("hello", "world", "abc", "123"));