Upgrade and clean up dependencies
[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  * Modifications Copyright (C) 2023 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.xacml;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertNotNull;
28 import static org.junit.Assert.assertSame;
29 import static org.junit.Assert.assertTrue;
30 import static org.mockito.Mockito.mock;
31 import static org.mockito.Mockito.when;
32
33 import java.util.Map;
34 import java.util.TreeMap;
35 import java.util.function.Consumer;
36 import org.junit.AfterClass;
37 import org.junit.Before;
38 import org.junit.BeforeClass;
39 import org.junit.Test;
40 import org.junit.runner.RunWith;
41 import org.mockito.Mock;
42 import org.mockito.junit.MockitoJUnitRunner;
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.OperationResult;
50 import org.onap.policy.models.decisions.concepts.DecisionRequest;
51 import org.onap.policy.models.decisions.concepts.DecisionResponse;
52 import org.onap.policy.simulators.XacmlSimulatorJaxRs;
53
54 @RunWith(MockitoJUnitRunner.class)
55 public class GuardOperationTest extends BasicHttpOperation {
56
57     @Mock
58     private Consumer<OperationOutcome> started;
59     @Mock
60     private Consumer<OperationOutcome> completed;
61
62     private DecisionConfig 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.buildXacmlSim();
71
72         BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/")
73                         .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_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(DecisionConfig.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         DecisionParams opParams =
115                         DecisionParams.builder().clientName(MY_CLIENT).path("decision").action("guard").build();
116         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
117
118         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build();
119         oper = new GuardOperation(params, config);
120
121         outcome = oper.start().get();
122         assertEquals(OperationResult.SUCCESS, outcome.getResult());
123         assertTrue(outcome.getResponse() instanceof DecisionResponse);
124     }
125
126     /**
127      * Tests "failure" case with simulator.
128      */
129     @Test
130     public void testFailure() throws Exception {
131         DecisionParams opParams =
132                         DecisionParams.builder().clientName(MY_CLIENT).path("decision").action("guard").build();
133         config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory());
134
135         params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor)
136                         .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build();
137         oper = new GuardOperation(params, config);
138
139         outcome = oper.start().get();
140         assertEquals(OperationResult.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 testGetPropertyNames() {
152         assertThat(oper.getPropertyNames()).isEmpty();
153     }
154
155     @Test
156     public void testMakeRequest() throws CoderException {
157         oper.generateSubRequestId(2);
158
159         verifyPayload("makeReqStd.json", makePayload());
160         verifyPayload("makeReqDefault.json", new TreeMap<>());
161
162         // null payload - start with fresh parameters and operation
163         params = params.toBuilder().payload(null).build();
164         oper = new GuardOperation(params, config);
165         assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest());
166     }
167
168     private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException {
169         params.getPayload().clear();
170         params.getPayload().putAll(payload);
171
172         DecisionRequest request = oper.makeRequest();
173
174         assertEquals("guard", request.getAction());
175         assertEquals("my-onap-component", request.getOnapComponent());
176         assertEquals("my-onap-instance", request.getOnapInstance());
177         assertEquals("my-onap-name", request.getOnapName());
178         assertNotNull(request.getRequestId());
179         assertEquals(Map.of("guard", payload), request.getResource());
180
181         verifyRequest(expectedJsonFile, request, "requestId");
182     }
183
184     @Test
185     public void testPostProcessResponse() {
186         DecisionResponse response = new DecisionResponse();
187
188         // null status
189         response.setStatus(null);
190         verifyOutcome(response, OperationResult.FAILURE, "response contains no status");
191
192         // permit, mixed case
193         response.setStatus("peRmit");
194         verifyOutcome(response, OperationResult.SUCCESS, "peRmit");
195
196         // indeterminate, mixed case
197         response.setStatus("inDETerminate");
198         verifyOutcome(response, OperationResult.SUCCESS, "inDETerminate");
199
200         // deny, mixed case
201         response.setStatus("deNY");
202         verifyOutcome(response, OperationResult.FAILURE, "deNY");
203
204         // unknown status
205         response.setStatus("unknown");
206         verifyOutcome(response, OperationResult.FAILURE, "unknown");
207     }
208
209     private void verifyOutcome(DecisionResponse response, OperationResult expectedResult, String expectedMessage) {
210         oper.postProcessResponse(outcome, BASE_URI, rawResponse, response);
211         assertEquals(expectedResult, outcome.getResult());
212         assertEquals(expectedMessage, outcome.getMessage());
213         assertSame(response, outcome.getResponse());
214     }
215
216     @Override
217     protected Map<String, Object> makePayload() {
218         return new TreeMap<>(Map.of("hello", "world", "abc", "123"));
219     }
220 }