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