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 assertNotNull(oper.getSubRequestId());
165 assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
169 * Tests startOperationAsync() when the guard is disabled.
172 public void testStartOperationAsyncDisabled() throws Exception {
173 // indicate that it's disabled
174 when(guardConfig.isDisabled()).thenReturn(true);
176 CompletableFuture<OperationOutcome> future2 = oper.start();
177 executor.runAll(100);
179 verify(client, never()).post(any(), any(), any(), any());
181 // should already be done
182 assertTrue(future2.isDone());
184 assertEquals(PolicyResult.SUCCESS, future2.get().getResult());
186 // ensure callbacks were invoked
187 verify(started).accept(any());
188 verify(completed).accept(any());
192 public void testMakeRequest() throws CoderException {
193 oper.generateSubRequestId(2);
195 verifyPayload("makeReqStd.json", makePayload());
196 verifyPayload("makeReqDefault.json", new TreeMap<>());
198 // null payload - start with fresh parameters and operation
199 params = params.toBuilder().payload(null).build();
200 oper = new GuardOperation(params, config);
201 assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
204 private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
205 params.getPayload().clear();
206 params.getPayload().putAll(payload);
208 DecisionRequest request = oper.makeRequest();
210 assertEquals("guard", request.getAction());
211 assertEquals("my-onap-component", request.getOnapComponent());
212 assertEquals("my-onap-instance", request.getOnapInstance());
213 assertEquals("my-onap-name", request.getOnapName());
214 assertNotNull(request.getRequestId());
215 assertEquals(Map.of("guard", payload), request.getResource());
217 verifyRequest(expectedJsonFile, request, "requestId");
221 public void testPostProcessResponse() {
222 DecisionResponse response = new DecisionResponse();
225 response.setStatus(null);
226 verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
228 // permit, mixed case
229 response.setStatus("peRmit");
230 verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
232 // indeterminate, mixed case
233 response.setStatus("inDETerminate");
234 verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
237 response.setStatus("deNY");
238 verifyOutcome(response, PolicyResult.FAILURE, "deNY");
241 response.setStatus("unknown");
242 verifyOutcome(response, PolicyResult.FAILURE, "unknown");
245 private void verifyOutcome(DecisionResponse response, PolicyResult expectedResult, String expectedMessage) {
246 oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
247 assertEquals(expectedResult, outcome.getResult());
248 assertEquals(expectedMessage, outcome.getMessage());
252 protected Map<String, Object> makePayload() {
253 return new TreeMap<>(Map.of("hello", "world", "abc", "123"));