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