Change RestServerParameters to BusTopicParams
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / std / StdXacmlApplicationServiceProviderTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdp.xacml.application.common.std;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
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.times;
34 import static org.mockito.Mockito.verify;
35 import static org.mockito.Mockito.when;
36
37 import com.att.research.xacml.api.Request;
38 import com.att.research.xacml.api.Response;
39 import com.att.research.xacml.api.pdp.PDPEngine;
40 import com.att.research.xacml.api.pdp.PDPEngineFactory;
41 import com.att.research.xacml.api.pdp.PDPException;
42 import com.att.research.xacml.util.FactoryException;
43 import com.att.research.xacml.util.XACMLProperties;
44 import com.google.common.io.Files;
45 import java.io.File;
46 import java.nio.file.Path;
47 import java.util.HashSet;
48 import java.util.Properties;
49 import java.util.Set;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
51 import org.apache.commons.lang3.tuple.Pair;
52 import org.junit.AfterClass;
53 import org.junit.Before;
54 import org.junit.BeforeClass;
55 import org.junit.Test;
56 import org.junit.runner.RunWith;
57 import org.mockito.Mock;
58 import org.mockito.junit.MockitoJUnitRunner;
59 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
60 import org.onap.policy.models.decisions.concepts.DecisionRequest;
61 import org.onap.policy.models.decisions.concepts.DecisionResponse;
62 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
63 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
64 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
65 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
66 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 @RunWith(MockitoJUnitRunner.class)
71 public class StdXacmlApplicationServiceProviderTest {
72     private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
73
74     private static final String TEMP_DIR_NAME = "src/test/resources/temp";
75     private static File TEMP_DIR = new File(TEMP_DIR_NAME);
76     private static Path TEMP_PATH = TEMP_DIR.toPath();
77     private static File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
78     private static File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
79     private static final String EXPECTED_EXCEPTION = "expected exception";
80     private static final String POLICY_NAME = "my-name";
81     private static final String POLICY_VERSION = "1.2.3";
82     private static final String POLICY_TYPE = "my-type";
83     private static final BusTopicParams apiRestParameters = new BusTopicParams();
84
85     @Mock
86     private ToscaPolicyTranslator trans;
87
88     @Mock
89     private PDPEngineFactory engineFactory;
90
91     @Mock
92     private PDPEngine engine;
93
94     @Mock
95     private Request req;
96
97     @Mock
98     private Response resp;
99
100     private ToscaPolicy policy;
101     private PolicyType internalPolicy;
102
103     private StdXacmlApplicationServiceProvider prov;
104
105     /**
106      * Creates the temp directory.
107      */
108     @BeforeClass
109     public static void setUpBeforeClass() {
110         assertTrue(TEMP_DIR.mkdir());
111     }
112
113     /**
114      * Deletes the temp directory and its contents.
115      */
116     @AfterClass
117     public static void tearDownAfterClass() {
118         for (File file : TEMP_DIR.listFiles()) {
119             if (!file.delete()) {
120                 logger.warn("cannot delete: {}", file);
121             }
122         }
123
124         if (!TEMP_DIR.delete()) {
125             logger.warn("cannot delete: {}", TEMP_DIR);
126         }
127     }
128
129     /**
130      * Initializes objects, including the provider.
131      *
132      * @throws Exception if an error occurs
133      */
134     @Before
135     public void setUp() throws Exception {
136         policy = new ToscaPolicy();
137         policy.setType(POLICY_TYPE);
138         policy.setName(POLICY_NAME);
139         policy.setVersion(POLICY_VERSION);
140
141         internalPolicy = new PolicyType();
142         internalPolicy.setPolicyId(POLICY_NAME);
143         internalPolicy.setVersion(POLICY_VERSION);
144
145         when(engineFactory.newEngine(any())).thenReturn(engine);
146
147         when(engine.decide(req)).thenReturn(resp);
148
149         when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
150
151         prov = new MyProv();
152
153         Files.copy(SOURCE_PROP_FILE, PROP_FILE);
154     }
155
156     @Test
157     public void testApplicationName() {
158         assertNotNull(prov.applicationName());
159     }
160
161     @Test
162     public void testActionDecisionsSupported() {
163         assertTrue(prov.actionDecisionsSupported().isEmpty());
164     }
165
166     @Test
167     public void testInitialize_testGetXxx() throws XacmlApplicationException {
168         prov.initialize(TEMP_PATH, apiRestParameters);
169
170         assertEquals(TEMP_PATH, prov.getDataPath());
171         assertNotNull(prov.getEngine());
172
173         Properties props = prov.getProperties();
174         assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
175     }
176
177     @Test
178     public void testInitialize_Ex() throws XacmlApplicationException {
179         assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiRestParameters))
180                         .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
181     }
182
183     @Test
184     public void testSupportedPolicyTypes() {
185         assertThat(prov.supportedPolicyTypes()).isEmpty();
186     }
187
188     @Test
189     public void testCanSupportPolicyType() {
190         assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
191     }
192
193     @Test
194     public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
195         when(trans.convertPolicy(policy)).thenReturn(null);
196
197         assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
198     }
199
200     @Test
201     public void testLoadPolicy_testUnloadPolicy() throws Exception {
202         prov.initialize(TEMP_PATH, apiRestParameters);
203         PROP_FILE.delete();
204
205         final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
206
207         // Load policy
208         prov.loadPolicy(policy);
209
210         // policy file should have been created
211         File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
212         assertTrue(policyFile.exists());
213
214         // new property file should have been created
215         assertTrue(PROP_FILE.exists());
216
217         // should have re-created the engine
218         verify(engineFactory, times(2)).newEngine(any());
219
220         final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
221         assertEquals(set.size() + 1, set2.size());
222
223         Set<String> set3 = new HashSet<>(set2);
224         set3.removeAll(set);
225         assertEquals("[root1]", set3.toString());
226
227
228         /*
229          * Prepare for unload.
230          */
231         PROP_FILE.delete();
232
233         assertTrue(prov.unloadPolicy(policy));
234
235         // policy file should have been removed
236         assertFalse(policyFile.exists());
237
238         // new property file should have been created
239         assertTrue(PROP_FILE.exists());
240
241         // should have re-created the engine
242         verify(engineFactory, times(3)).newEngine(any());
243
244         set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
245         assertEquals(set.toString(), set3.toString());
246     }
247
248     @Test
249     public void testUnloadPolicy_NotDeployed() throws Exception {
250         prov.initialize(TEMP_PATH, apiRestParameters);
251
252         assertFalse(prov.unloadPolicy(policy));
253
254         // no additional calls
255         verify(engineFactory, times(1)).newEngine(any());
256     }
257
258     @Test
259     public void testMakeDecision() throws ToscaPolicyConversionException {
260         prov.createEngine(null);
261
262         DecisionRequest decreq = mock(DecisionRequest.class);
263         when(trans.convertRequest(decreq)).thenReturn(req);
264
265         DecisionResponse decresp = mock(DecisionResponse.class);
266         when(trans.convertResponse(resp)).thenReturn(decresp);
267
268         Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
269         assertSame(decresp, result.getKey());
270         assertSame(resp, result.getValue());
271
272         verify(trans).convertRequest(decreq);
273         verify(trans).convertResponse(resp);
274     }
275
276     @Test
277     public void testGetTranslator() {
278         assertSame(trans, prov.getTranslator());
279     }
280
281     @Test
282     public void testCreateEngine() throws FactoryException {
283         // success
284         prov.createEngine(null);
285         assertSame(engine, prov.getEngine());
286
287         // null - should be unchanged
288         when(engineFactory.newEngine(any())).thenReturn(null);
289         prov.createEngine(null);
290         assertSame(engine, prov.getEngine());
291
292         // exception - should be unchanged
293         when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
294         prov.createEngine(null);
295         assertSame(engine, prov.getEngine());
296     }
297
298     @Test
299     public void testXacmlDecision() throws PDPException {
300         prov.createEngine(null);
301
302         // success
303         assertSame(resp, prov.xacmlDecision(req));
304
305         // exception
306         when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
307         assertNull(prov.xacmlDecision(req));
308     }
309
310     @Test
311     public void testGetPdpEngineFactory() throws XacmlApplicationException {
312         // use the real engine factory
313         engineFactory = null;
314
315         prov = new MyProv();
316         prov.initialize(TEMP_PATH, apiRestParameters);
317
318         assertNotNull(prov.getEngine());
319     }
320
321     private class MyProv extends StdXacmlApplicationServiceProvider {
322
323         @Override
324         protected ToscaPolicyTranslator getTranslator(String type) {
325             return trans;
326         }
327
328         @Override
329         protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
330             return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());
331         }
332     }
333 }