Added Xacml actor
[policy/models.git] / models-interactions / model-actors / actor.xacml / src / test / java / org / onap / policy / controlloop / actor / xacml / GuardOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.xacml;
22
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;
36
37 import java.util.Map;
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.OperationResult;
53 import org.onap.policy.controlloop.actorserviceprovider.Util;
54 import org.onap.policy.models.decisions.concepts.DecisionRequest;
55 import org.onap.policy.models.decisions.concepts.DecisionResponse;
56 import org.onap.policy.simulators.XacmlSimulatorJaxRs;
57
58 public class GuardOperationTest extends BasicHttpOperation {
59
60     @Mock
61     private Consumer<OperationOutcome> started;
62     @Mock
63     private Consumer<OperationOutcome> completed;
64
65     private DecisionConfig guardConfig;
66     private GuardOperation oper;
67
68     /**
69      * Starts the simulator.
70      */
71     @BeforeClass
72     public static void setUpBeforeClass() throws Exception {
73         org.onap.policy.simulators.Util.buildXacmlSim();
74
75         BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
76                         .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_SERVER_PORT)
77                         .build();
78         HttpClientFactoryInstance.getClientFactory().build(clientParams);
79     }
80
81     @AfterClass
82     public static void tearDownAfterClass() {
83         HttpClientFactoryInstance.getClientFactory().destroy();
84         HttpServletServerFactoryInstance.getServerFactory().destroy();
85     }
86
87     /**
88      * Sets up.
89      */
90     @Before
91     public void setUp() throws Exception {
92         super.setUpBasic();
93
94         guardConfig = mock(DecisionConfig.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");
101             return req;
102         });
103
104         config = guardConfig;
105         initConfig();
106
107         params = params.toBuilder().startCallback(started).completeCallback(completed).build();
108
109         oper = new GuardOperation(params, config);
110     }
111
112     /**
113      * Tests "success" case with simulator.
114      */
115     @Test
116     public void testSuccess() throws Exception {
117         DecisionParams opParams = DecisionParams.builder().clientName(MY_CLIENT).path("decision").build();
118         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
119
120         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
121         oper = new GuardOperation(params, config);
122
123         outcome = oper.start().get();
124         assertEquals(OperationResult.SUCCESS, outcome.getResult());
125         assertTrue(outcome.getResponse() instanceof DecisionResponse);
126     }
127
128     /**
129      * Tests "failure" case with simulator.
130      */
131     @Test
132     public void testFailure() throws Exception {
133         DecisionParams opParams = DecisionParams.builder().clientName(MY_CLIENT).path("decision").build();
134         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
135
136         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
137                         .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build();
138         oper = new GuardOperation(params, config);
139
140         outcome = oper.start().get();
141         assertEquals(OperationResult.FAILURE, outcome.getResult());
142         assertTrue(outcome.getResponse() instanceof DecisionResponse);
143     }
144
145     @Test
146     public void testConstructor() {
147         assertEquals(DEFAULT_ACTOR, oper.getActorName());
148         assertEquals(DEFAULT_OPERATION, oper.getName());
149     }
150
151     @Test
152     public void testGetPropertyNames() {
153         assertThat(oper.getPropertyNames()).isEmpty();
154     }
155
156     @Test
157     public void testStartOperationAsync() throws Exception {
158         CompletableFuture<OperationOutcome> future2 = oper.start();
159         executor.runAll(100);
160         assertFalse(future2.isDone());
161
162         DecisionResponse resp = new DecisionResponse();
163         resp.setStatus(GuardOperation.PERMIT);
164         when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
165
166         verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
167         callbackCaptor.getValue().completed(rawResponse);
168
169         executor.runAll(100);
170         assertTrue(future2.isDone());
171
172         outcome = future2.get();
173         assertEquals(OperationResult.SUCCESS, outcome.getResult());
174         assertEquals(resp, outcome.getResponse());
175
176         assertNotNull(oper.getSubRequestId());
177         assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
178     }
179
180     /**
181      * Tests startOperationAsync() when the guard is disabled.
182      */
183     @Test
184     public void testStartOperationAsyncDisabled() throws Exception {
185         // indicate that it's disabled
186         when(guardConfig.isDisabled()).thenReturn(true);
187
188         CompletableFuture<OperationOutcome> future2 = oper.start();
189         executor.runAll(100);
190
191         verify(client, never()).post(any(), any(), any(), any());
192
193         // should already be done
194         assertTrue(future2.isDone());
195
196         outcome = future2.get();
197         assertEquals(OperationResult.SUCCESS, outcome.getResult());
198         assertNull(outcome.getResponse());
199
200         // ensure callbacks were invoked
201         verify(started).accept(any());
202         verify(completed).accept(any());
203     }
204
205     @Test
206     public void testMakeRequest() throws CoderException {
207         oper.generateSubRequestId(2);
208
209         verifyPayload("makeReqStd.json", makePayload());
210         verifyPayload("makeReqDefault.json", new TreeMap<>());
211
212         // null payload - start with fresh parameters and operation
213         params = params.toBuilder().payload(null).build();
214         oper = new GuardOperation(params, config);
215         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
216     }
217
218     private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
219         params.getPayload().clear();
220         params.getPayload().putAll(payload);
221
222         DecisionRequest request = oper.makeRequest();
223
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());
230
231         verifyRequest(expectedJsonFile, request, "requestId");
232     }
233
234     @Test
235     public void testPostProcessResponse() {
236         DecisionResponse response = new DecisionResponse();
237
238         // null status
239         response.setStatus(null);
240         verifyOutcome(response, OperationResult.FAILURE, "response contains no status");
241
242         // permit, mixed case
243         response.setStatus("peRmit");
244         verifyOutcome(response, OperationResult.SUCCESS, "peRmit");
245
246         // indeterminate, mixed case
247         response.setStatus("inDETerminate");
248         verifyOutcome(response, OperationResult.SUCCESS, "inDETerminate");
249
250         // deny, mixed case
251         response.setStatus("deNY");
252         verifyOutcome(response, OperationResult.FAILURE, "deNY");
253
254         // unknown status
255         response.setStatus("unknown");
256         verifyOutcome(response, OperationResult.FAILURE, "unknown");
257     }
258
259     private void verifyOutcome(DecisionResponse response, OperationResult 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());
264     }
265
266     @Override
267     protected Map<String, Object> makePayload() {
268         return new TreeMap<>(Map.of("hello", "world", "abc", "123"));
269     }
270 }