Set all cross references of policy/xacml-pdp
[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.http.client.HttpClient;
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
84     @Mock
85     private HttpClient apiClient;
86
87     @Mock
88     private ToscaPolicyTranslator trans;
89
90     @Mock
91     private PDPEngineFactory engineFactory;
92
93     @Mock
94     private PDPEngine engine;
95
96     @Mock
97     private Request req;
98
99     @Mock
100     private Response resp;
101
102     private ToscaPolicy policy;
103     private PolicyType internalPolicy;
104
105     private StdXacmlApplicationServiceProvider prov;
106
107     /**
108      * Creates the temp directory.
109      */
110     @BeforeClass
111     public static void setUpBeforeClass() {
112         assertTrue(TEMP_DIR.mkdir());
113     }
114
115     /**
116      * Deletes the temp directory and its contents.
117      */
118     @AfterClass
119     public static void tearDownAfterClass() {
120         for (File file : TEMP_DIR.listFiles()) {
121             if (!file.delete()) {
122                 logger.warn("cannot delete: {}", file);
123             }
124         }
125
126         if (!TEMP_DIR.delete()) {
127             logger.warn("cannot delete: {}", TEMP_DIR);
128         }
129     }
130
131     /**
132      * Initializes objects, including the provider.
133      *
134      * @throws Exception if an error occurs
135      */
136     @Before
137     public void setUp() throws Exception {
138         policy = new ToscaPolicy();
139         policy.setType(POLICY_TYPE);
140         policy.setName(POLICY_NAME);
141         policy.setVersion(POLICY_VERSION);
142
143         internalPolicy = new PolicyType();
144         internalPolicy.setPolicyId(POLICY_NAME);
145         internalPolicy.setVersion(POLICY_VERSION);
146
147         when(engineFactory.newEngine(any())).thenReturn(engine);
148
149         when(engine.decide(req)).thenReturn(resp);
150
151         when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
152
153         prov = new MyProv();
154
155         Files.copy(SOURCE_PROP_FILE, PROP_FILE);
156     }
157
158     @Test
159     public void testApplicationName() {
160         assertNotNull(prov.applicationName());
161     }
162
163     @Test
164     public void testActionDecisionsSupported() {
165         assertTrue(prov.actionDecisionsSupported().isEmpty());
166     }
167
168     @Test
169     public void testInitialize_testGetXxx() throws XacmlApplicationException {
170         prov.initialize(TEMP_PATH, apiClient);
171
172         assertEquals(TEMP_PATH, prov.getDataPath());
173         assertNotNull(prov.getEngine());
174
175         Properties props = prov.getProperties();
176         assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
177     }
178
179     @Test
180     public void testInitialize_Ex() throws XacmlApplicationException {
181         assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiClient))
182                         .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
183     }
184
185     @Test
186     public void testSupportedPolicyTypes() {
187         assertThat(prov.supportedPolicyTypes()).isEmpty();
188     }
189
190     @Test
191     public void testCanSupportPolicyType() {
192         assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
193     }
194
195     @Test
196     public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
197         when(trans.convertPolicy(policy)).thenReturn(null);
198
199         assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
200     }
201
202     @Test
203     public void testLoadPolicy_testUnloadPolicy() throws Exception {
204         prov.initialize(TEMP_PATH, apiClient);
205         PROP_FILE.delete();
206
207         final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
208
209         // Load policy
210         prov.loadPolicy(policy);
211
212         // policy file should have been created
213         File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
214         assertTrue(policyFile.exists());
215
216         // new property file should have been created
217         assertTrue(PROP_FILE.exists());
218
219         // should have re-created the engine
220         verify(engineFactory, times(2)).newEngine(any());
221
222         final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
223         assertEquals(set.size() + 1, set2.size());
224
225         Set<String> set3 = new HashSet<>(set2);
226         set3.removeAll(set);
227         assertEquals("[root1]", set3.toString());
228
229
230         /*
231          * Prepare for unload.
232          */
233         PROP_FILE.delete();
234
235         assertTrue(prov.unloadPolicy(policy));
236
237         // policy file should have been removed
238         assertFalse(policyFile.exists());
239
240         // new property file should have been created
241         assertTrue(PROP_FILE.exists());
242
243         // should have re-created the engine
244         verify(engineFactory, times(3)).newEngine(any());
245
246         set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
247         assertEquals(set.toString(), set3.toString());
248     }
249
250     @Test
251     public void testUnloadPolicy_NotDeployed() throws Exception {
252         prov.initialize(TEMP_PATH, apiClient);
253
254         assertFalse(prov.unloadPolicy(policy));
255
256         // no additional calls
257         verify(engineFactory, times(1)).newEngine(any());
258     }
259
260     @Test
261     public void testMakeDecision() throws ToscaPolicyConversionException {
262         prov.createEngine(null);
263
264         DecisionRequest decreq = mock(DecisionRequest.class);
265         when(trans.convertRequest(decreq)).thenReturn(req);
266
267         DecisionResponse decresp = mock(DecisionResponse.class);
268         when(trans.convertResponse(resp)).thenReturn(decresp);
269
270         Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
271         assertSame(decresp, result.getKey());
272         assertSame(resp, result.getValue());
273
274         verify(trans).convertRequest(decreq);
275         verify(trans).convertResponse(resp);
276     }
277
278     @Test
279     public void testGetTranslator() {
280         assertSame(trans, prov.getTranslator());
281     }
282
283     @Test
284     public void testCreateEngine() throws FactoryException {
285         // success
286         prov.createEngine(null);
287         assertSame(engine, prov.getEngine());
288
289         // null - should be unchanged
290         when(engineFactory.newEngine(any())).thenReturn(null);
291         prov.createEngine(null);
292         assertSame(engine, prov.getEngine());
293
294         // exception - should be unchanged
295         when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
296         prov.createEngine(null);
297         assertSame(engine, prov.getEngine());
298     }
299
300     @Test
301     public void testXacmlDecision() throws PDPException {
302         prov.createEngine(null);
303
304         // success
305         assertSame(resp, prov.xacmlDecision(req));
306
307         // exception
308         when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
309         assertNull(prov.xacmlDecision(req));
310     }
311
312     @Test
313     public void testGetPdpEngineFactory() throws XacmlApplicationException {
314         // use the real engine factory
315         engineFactory = null;
316
317         prov = new MyProv();
318         prov.initialize(TEMP_PATH, apiClient);
319
320         assertNotNull(prov.getEngine());
321     }
322
323     private class MyProv extends StdXacmlApplicationServiceProvider {
324
325         @Override
326         protected ToscaPolicyTranslator getTranslator(String type) {
327             return trans;
328         }
329
330         @Override
331         protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
332             return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());
333         }
334     }
335 }