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.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertFalse;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertNull;
29 import static org.junit.Assert.assertSame;
30 import static org.junit.Assert.assertTrue;
31 import static org.mockito.ArgumentMatchers.any;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.never;
34 import static org.mockito.Mockito.verify;
35 import static org.mockito.Mockito.when;
38 import java.util.TreeMap;
39 import java.util.concurrent.CompletableFuture;
40 import java.util.function.Consumer;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.mockito.Mock;
46 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
47 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
51 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
52 import org.onap.policy.controlloop.actorserviceprovider.Util;
53 import org.onap.policy.controlloop.policy.PolicyResult;
54 import org.onap.policy.models.decisions.concepts.DecisionRequest;
55 import org.onap.policy.models.decisions.concepts.DecisionResponse;
56 import org.onap.policy.simulators.GuardSimulatorJaxRs;
58 public class DecisionOperationTest extends BasicHttpOperation {
61 private Consumer<OperationOutcome> started;
63 private Consumer<OperationOutcome> completed;
65 private GuardConfig guardConfig;
66 private DecisionOperation oper;
69 * Starts the simulator.
72 public static void setUpBeforeClass() throws Exception {
73 org.onap.policy.simulators.Util.buildGuardSim();
75 BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
76 .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.GUARDSIM_SERVER_PORT)
78 HttpClientFactoryInstance.getClientFactory().build(clientParams);
82 public static void tearDownAfterClass() {
83 HttpClientFactoryInstance.getClientFactory().destroy();
84 HttpServletServerFactoryInstance.getServerFactory().destroy();
91 public void setUp() throws Exception {
94 guardConfig = mock(GuardConfig.class);
95 when(guardConfig.makeRequest()).thenAnswer(args -> {
96 DecisionRequest req = new DecisionRequest();
97 req.setAction("guard");
98 req.setOnapComponent("my-onap-component");
99 req.setOnapInstance("my-onap-instance");
100 req.setOnapName("my-onap-name");
104 config = guardConfig;
107 params = params.toBuilder().startCallback(started).completeCallback(completed).build();
109 oper = new DecisionOperation(params, config);
113 * Tests "success" case with simulator.
116 public void testSuccess() throws Exception {
117 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
118 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
120 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
121 oper = new DecisionOperation(params, config);
123 outcome = oper.start().get();
124 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
125 assertTrue(outcome.getResponse() instanceof DecisionResponse);
129 * Tests "failure" case with simulator.
132 public void testFailure() throws Exception {
133 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
134 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
136 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
137 .payload(Map.of("clname", GuardSimulatorJaxRs.DENY_CLNAME)).build();
138 oper = new DecisionOperation(params, config);
140 outcome = oper.start().get();
141 assertEquals(PolicyResult.FAILURE, outcome.getResult());
142 assertTrue(outcome.getResponse() instanceof DecisionResponse);
146 public void testConstructor() {
147 assertEquals(DEFAULT_ACTOR, oper.getActorName());
148 assertEquals(DEFAULT_OPERATION, oper.getName());
152 public void testGetPropertyNames() {
153 assertThat(oper.getPropertyNames()).isEmpty();
157 public void testStartOperationAsync() throws Exception {
158 CompletableFuture<OperationOutcome> future2 = oper.start();
159 executor.runAll(100);
160 assertFalse(future2.isDone());
162 DecisionResponse resp = new DecisionResponse();
163 resp.setStatus(DecisionOperation.PERMIT);
164 when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
166 verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
167 callbackCaptor.getValue().completed(rawResponse);
169 executor.runAll(100);
170 assertTrue(future2.isDone());
172 outcome = future2.get();
173 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
174 assertEquals(resp, outcome.getResponse());
176 assertNotNull(oper.getSubRequestId());
177 assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
181 * Tests startOperationAsync() when the guard is disabled.
184 public void testStartOperationAsyncDisabled() throws Exception {
185 // indicate that it's disabled
186 when(guardConfig.isDisabled()).thenReturn(true);
188 CompletableFuture<OperationOutcome> future2 = oper.start();
189 executor.runAll(100);
191 verify(client, never()).post(any(), any(), any(), any());
193 // should already be done
194 assertTrue(future2.isDone());
196 outcome = future2.get();
197 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
198 assertNull(outcome.getResponse());
200 // ensure callbacks were invoked
201 verify(started).accept(any());
202 verify(completed).accept(any());
206 public void testMakeRequest() throws CoderException {
207 oper.generateSubRequestId(2);
209 verifyPayload("makeReqStd.json", makePayload());
210 verifyPayload("makeReqDefault.json", new TreeMap<>());
212 // null payload - start with fresh parameters and operation
213 params = params.toBuilder().payload(null).build();
214 oper = new DecisionOperation(params, config);
215 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
218 private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
219 params.getPayload().clear();
220 params.getPayload().putAll(payload);
222 DecisionRequest request = oper.makeRequest();
224 assertEquals("guard", request.getAction());
225 assertEquals("my-onap-component", request.getOnapComponent());
226 assertEquals("my-onap-instance", request.getOnapInstance());
227 assertEquals("my-onap-name", request.getOnapName());
228 assertNotNull(request.getRequestId());
229 assertEquals(Map.of("guard", payload), request.getResource());
231 verifyRequest(expectedJsonFile, request, "requestId");
235 public void testPostProcessResponse() {
236 DecisionResponse response = new DecisionResponse();
239 response.setStatus(null);
240 verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
242 // permit, mixed case
243 response.setStatus("peRmit");
244 verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
246 // indeterminate, mixed case
247 response.setStatus("inDETerminate");
248 verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
251 response.setStatus("deNY");
252 verifyOutcome(response, PolicyResult.FAILURE, "deNY");
255 response.setStatus("unknown");
256 verifyOutcome(response, PolicyResult.FAILURE, "unknown");
259 private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) {
260 oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
261 assertEquals(expectedResult, outcome.getResult());
262 assertEquals(expectedMessage, outcome.getMessage());
263 assertSame(response, outcome.getResponse());
267 protected Map<String, Object> makePayload() {
268 return new TreeMap<>(Map.of("hello", "world", "abc", "123"));