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.assertTrue;
28 import static org.mockito.ArgumentMatchers.any;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.never;
31 import static org.mockito.Mockito.verify;
32 import static org.mockito.Mockito.when;
35 import java.util.TreeMap;
36 import java.util.concurrent.CompletableFuture;
37 import java.util.function.Consumer;
38 import org.junit.AfterClass;
39 import org.junit.Before;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.mockito.Mock;
43 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
44 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
45 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.controlloop.actor.test.BasicHttpOperation;
48 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
49 import org.onap.policy.controlloop.actorserviceprovider.Util;
50 import org.onap.policy.controlloop.policy.PolicyResult;
51 import org.onap.policy.models.decisions.concepts.DecisionRequest;
52 import org.onap.policy.models.decisions.concepts.DecisionResponse;
53 import org.onap.policy.simulators.GuardSimulatorJaxRs;
55 public class GuardOperationTest extends BasicHttpOperation<DecisionRequest> {
58 private Consumer<OperationOutcome> started;
60 private Consumer<OperationOutcome> completed;
62 private GuardConfig guardConfig;
63 private GuardOperation oper;
66 * Starts the simulator.
69 public static void setUpBeforeClass() throws Exception {
70 org.onap.policy.simulators.Util.buildGuardSim();
72 BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
73 .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.GUARDSIM_SERVER_PORT)
75 HttpClientFactoryInstance.getClientFactory().build(clientParams);
79 public static void tearDownAfterClass() {
80 HttpClientFactoryInstance.getClientFactory().destroy();
81 HttpServletServerFactoryInstance.getServerFactory().destroy();
88 public void setUp() throws Exception {
91 guardConfig = mock(GuardConfig.class);
92 when(guardConfig.makeRequest()).thenAnswer(args -> {
93 DecisionRequest req = new DecisionRequest();
94 req.setAction("guard");
95 req.setOnapComponent("my-onap-component");
96 req.setOnapInstance("my-onap-instance");
97 req.setOnapName("my-onap-name");
101 config = guardConfig;
104 params = params.toBuilder().startCallback(started).completeCallback(completed).build();
106 oper = new GuardOperation(params, config);
110 * Tests "success" case with simulator.
113 public void testSuccess() throws Exception {
114 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
115 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
117 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
118 oper = new GuardOperation(params, config);
120 outcome = oper.start().get();
121 assertEquals(PolicyResult.SUCCESS, outcome.getResult());
125 * Tests "failure" case with simulator.
128 public void testFailure() throws Exception {
129 GuardParams opParams = GuardParams.builder().clientName(MY_CLIENT).path("decision").build();
130 config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
132 params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
133 .payload(Map.of("clname", GuardSimulatorJaxRs.DENY_CLNAME)).build();
134 oper = new GuardOperation(params, config);
136 outcome = oper.start().get();
137 assertEquals(PolicyResult.FAILURE, outcome.getResult());
141 public void testConstructor() {
142 assertEquals(DEFAULT_ACTOR, oper.getActorName());
143 assertEquals(DEFAULT_OPERATION, oper.getName());
147 public void testStartOperationAsync() throws Exception {
148 CompletableFuture<OperationOutcome> future2 = oper.start();
149 executor.runAll(100);
150 assertFalse(future2.isDone());
152 DecisionResponse resp = new DecisionResponse();
153 resp.setStatus(GuardOperation.PERMIT);
154 when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
156 verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
157 callbackCaptor.getValue().completed(rawResponse);
159 executor.runAll(100);
160 assertTrue(future2.isDone());
162 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
164 assertEquals("1", future2.get().getSubRequestId());
168 * Tests startOperationAsync() when the guard is disabled.
171 public void testStartOperationAsyncDisabled() throws Exception {
172 // indicate that it's disabled
173 when(guardConfig.isDisabled()).thenReturn(true);
175 CompletableFuture<OperationOutcome> future2 = oper.start();
176 executor.runAll(100);
178 verify(client, never()).post(any(), any(), any(), any());
180 // should already be done
181 assertTrue(future2.isDone());
183 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
185 // ensure callbacks were invoked
186 verify(started).accept(any());
187 verify(completed).accept(any());
191 public void testMakeRequest() throws CoderException {
192 verifyPayload("makeReqStd.json", makePayload());
193 verifyPayload("makeReqDefault.json", new TreeMap<>());
195 // null payload - start with fresh parameters and operation
196 params = params.toBuilder().payload(null).build();
197 oper = new GuardOperation(params, config);
198 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
201 private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
202 params.getPayload().clear();
203 params.getPayload().putAll(payload);
205 DecisionRequest request = oper.makeRequest();
207 assertEquals("guard", request.getAction());
208 assertEquals("my-onap-component", request.getOnapComponent());
209 assertEquals("my-onap-instance", request.getOnapInstance());
210 assertEquals("my-onap-name", request.getOnapName());
211 assertNotNull(request.getRequestId());
212 assertEquals(Map.of("guard", payload), request.getResource());
214 verifyRequest(expectedJsonFile, request, "requestId");
218 public void testPostProcessResponse() {
219 DecisionResponse response = new DecisionResponse();
222 response.setStatus(null);
223 verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
225 // permit, mixed case
226 response.setStatus("peRmit");
227 verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
229 // indeterminate, mixed case
230 response.setStatus("inDETerminate");
231 verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
234 response.setStatus("deNY");
235 verifyOutcome(response, PolicyResult.FAILURE, "deNY");
238 response.setStatus("unknown");
239 verifyOutcome(response, PolicyResult.FAILURE, "unknown");
242 private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) {
243 oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
244 assertEquals(expectedResult, outcome.getResult());
245 assertEquals(expectedMessage, outcome.getMessage());
249 protected Map<String, Object> makePayload() {
250 return new TreeMap<>(Map.of("hello", "world", "abc", "123"));