da0ee95b5c5d31b567d3158dba6ee6346e6b4256
[policy/models.git] / models-interactions / model-actors / actor.guard / src / test / java / org / onap / policy / controlloop / actor / guard / DecisionOperationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
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.guard;
22
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;
35
36 import java.util.Map;
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;
56
57 public class DecisionOperationTest extends BasicHttpOperation<DecisionRequest> {
58
59     @Mock
60     private Consumer<OperationOutcome> started;
61     @Mock
62     private Consumer<OperationOutcome> completed;
63
64     private GuardConfig guardConfig;
65     private DecisionOperation oper;
66
67     /**
68      * Starts the simulator.
69      */
70     @BeforeClass
71     public static void setUpBeforeClass() throws Exception {
72         org.onap.policy.simulators.Util.buildGuardSim();
73
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)
76                         .build();
77         HttpClientFactoryInstance.getClientFactory().build(clientParams);
78     }
79
80     @AfterClass
81     public static void tearDownAfterClass() {
82         HttpClientFactoryInstance.getClientFactory().destroy();
83         HttpServletServerFactoryInstance.getServerFactory().destroy();
84     }
85
86     /**
87      * Sets up.
88      */
89     @Before
90     public void setUp() throws Exception {
91         super.setUpBasic();
92
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");
100             return req;
101         });
102
103         config = guardConfig;
104         initConfig();
105
106         params = params.toBuilder().startCallback(started).completeCallback(completed).build();
107
108         oper = new DecisionOperation(params, config);
109     }
110
111     /**
112      * Tests "success" case with simulator.
113      */
114     @Test
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());
118
119         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
120         oper = new DecisionOperation(params, config);
121
122         outcome = oper.start().get();
123         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
124         assertTrue(outcome.getResponse() instanceof DecisionResponse);
125     }
126
127     /**
128      * Tests "failure" case with simulator.
129      */
130     @Test
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());
134
135         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
136                         .payload(Map.of("clname", GuardSimulatorJaxRs.DENY_CLNAME)).build();
137         oper = new DecisionOperation(params, config);
138
139         outcome = oper.start().get();
140         assertEquals(PolicyResult.FAILURE, outcome.getResult());
141         assertTrue(outcome.getResponse() instanceof DecisionResponse);
142     }
143
144     @Test
145     public void testConstructor() {
146         assertEquals(DEFAULT_ACTOR, oper.getActorName());
147         assertEquals(DEFAULT_OPERATION, oper.getName());
148     }
149
150     @Test
151     public void testStartOperationAsync() throws Exception {
152         CompletableFuture<OperationOutcome> future2 = oper.start();
153         executor.runAll(100);
154         assertFalse(future2.isDone());
155
156         DecisionResponse resp = new DecisionResponse();
157         resp.setStatus(DecisionOperation.PERMIT);
158         when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class));
159
160         verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any());
161         callbackCaptor.getValue().completed(rawResponse);
162
163         executor.runAll(100);
164         assertTrue(future2.isDone());
165
166         outcome = future2.get();
167         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
168         assertEquals(resp, outcome.getResponse());
169
170         assertNotNull(oper.getSubRequestId());
171         assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId());
172     }
173
174     /**
175      * Tests startOperationAsync() when the guard is disabled.
176      */
177     @Test
178     public void testStartOperationAsyncDisabled() throws Exception {
179         // indicate that it's disabled
180         when(guardConfig.isDisabled()).thenReturn(true);
181
182         CompletableFuture<OperationOutcome> future2 = oper.start();
183         executor.runAll(100);
184
185         verify(client, never()).post(any(), any(), any(), any());
186
187         // should already be done
188         assertTrue(future2.isDone());
189
190         outcome = future2.get();
191         assertEquals(PolicyResult.SUCCESS, outcome.getResult());
192         assertNull(outcome.getResponse());
193
194         // ensure callbacks were invoked
195         verify(started).accept(any());
196         verify(completed).accept(any());
197     }
198
199     @Test
200     public void testMakeRequest() throws CoderException {
201         oper.generateSubRequestId(2);
202
203         verifyPayload("makeReqStd.json", makePayload());
204         verifyPayload("makeReqDefault.json", new TreeMap<>());
205
206         // null payload - start with fresh parameters and operation
207         params = params.toBuilder().payload(null).build();
208         oper = new DecisionOperation(params, config);
209         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
210     }
211
212     private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
213         params.getPayload().clear();
214         params.getPayload().putAll(payload);
215
216         DecisionRequest request = oper.makeRequest();
217
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());
224
225         verifyRequest(expectedJsonFile, request, "requestId");
226     }
227
228     @Test
229     public void testPostProcessResponse() {
230         DecisionResponse response = new DecisionResponse();
231
232         // null status
233         response.setStatus(null);
234         verifyOutcome(response, PolicyResult.FAILURE, "response contains no status");
235
236         // permit, mixed case
237         response.setStatus("peRmit");
238         verifyOutcome(response, PolicyResult.SUCCESS, "peRmit");
239
240         // indeterminate, mixed case
241         response.setStatus("inDETerminate");
242         verifyOutcome(response, PolicyResult.SUCCESS, "inDETerminate");
243
244         // deny, mixed case
245         response.setStatus("deNY");
246         verifyOutcome(response, PolicyResult.FAILURE, "deNY");
247
248         // unknown status
249         response.setStatus("unknown");
250         verifyOutcome(response, PolicyResult.FAILURE, "unknown");
251     }
252
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());
258     }
259
260     @Override
261     protected Map<String, Object> makePayload() {
262         return new TreeMap<>(Map.of("hello", "world", "abc", "123"));
263     }
264 }