2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2020 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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdp.xacml.application.common.std;
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;
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;
46 import java.nio.file.Path;
47 import java.util.HashSet;
48 import java.util.Properties;
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.mockito.Mock;
57 import org.mockito.MockitoAnnotations;
58 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
59 import org.onap.policy.models.decisions.concepts.DecisionRequest;
60 import org.onap.policy.models.decisions.concepts.DecisionResponse;
61 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
62 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
63 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
64 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
65 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 public class StdXacmlApplicationServiceProviderTest {
70 private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
72 private static final String TEMP_DIR_NAME = "src/test/resources/temp";
73 private static File TEMP_DIR = new File(TEMP_DIR_NAME);
74 private static Path TEMP_PATH = TEMP_DIR.toPath();
75 private static File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
76 private static File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
77 private static final String EXPECTED_EXCEPTION = "expected exception";
78 private static final String POLICY_NAME = "my-name";
79 private static final String POLICY_VERSION = "1.2.3";
80 private static final String POLICY_TYPE = "my-type";
81 private static final RestServerParameters apiRestParameters = new RestServerParameters();
84 private ToscaPolicyTranslator trans;
87 private PDPEngineFactory engineFactory;
90 private PDPEngine engine;
96 private Response resp;
98 private ToscaPolicy policy;
99 private PolicyType internalPolicy;
101 private StdXacmlApplicationServiceProvider prov;
104 * Creates the temp directory.
107 public static void setUpBeforeClass() {
108 assertTrue(TEMP_DIR.mkdir());
112 * Deletes the temp directory and its contents.
115 public static void tearDownAfterClass() {
116 for (File file : TEMP_DIR.listFiles()) {
117 if (!file.delete()) {
118 logger.warn("cannot delete: {}", file);
122 if (!TEMP_DIR.delete()) {
123 logger.warn("cannot delete: {}", TEMP_DIR);
128 * Initializes objects, including the provider.
130 * @throws Exception if an error occurs
133 public void setUp() throws Exception {
134 MockitoAnnotations.initMocks(this);
136 policy = new ToscaPolicy();
137 policy.setType(POLICY_TYPE);
138 policy.setName(POLICY_NAME);
139 policy.setVersion(POLICY_VERSION);
141 internalPolicy = new PolicyType();
142 internalPolicy.setPolicyId(POLICY_NAME);
143 internalPolicy.setVersion(POLICY_VERSION);
145 when(engineFactory.newEngine(any())).thenReturn(engine);
147 when(engine.decide(req)).thenReturn(resp);
149 when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
153 Files.copy(SOURCE_PROP_FILE, PROP_FILE);
157 public void testApplicationName() {
158 assertNotNull(prov.applicationName());
162 public void testActionDecisionsSupported() {
163 assertTrue(prov.actionDecisionsSupported().isEmpty());
167 public void testInitialize_testGetXxx() throws XacmlApplicationException {
168 prov.initialize(TEMP_PATH, apiRestParameters);
170 assertEquals(TEMP_PATH, prov.getDataPath());
171 assertNotNull(prov.getEngine());
173 Properties props = prov.getProperties();
174 assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
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");
184 public void testSupportedPolicyTypes() {
185 assertThat(prov.supportedPolicyTypes()).isEmpty();
189 public void testCanSupportPolicyType() {
190 assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
194 public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
195 when(trans.convertPolicy(policy)).thenReturn(null);
197 assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
201 public void testLoadPolicy_testUnloadPolicy() throws Exception {
202 prov.initialize(TEMP_PATH, apiRestParameters);
205 final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
208 prov.loadPolicy(policy);
210 // policy file should have been created
211 File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
212 assertTrue(policyFile.exists());
214 // new property file should have been created
215 assertTrue(PROP_FILE.exists());
217 // should have re-created the engine
218 verify(engineFactory, times(2)).newEngine(any());
220 final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
221 assertEquals(set.size() + 1, set2.size());
223 Set<String> set3 = new HashSet<>(set2);
225 assertEquals("[root1]", set3.toString());
229 * Prepare for unload.
233 assertTrue(prov.unloadPolicy(policy));
235 // policy file should have been removed
236 assertFalse(policyFile.exists());
238 // new property file should have been created
239 assertTrue(PROP_FILE.exists());
241 // should have re-created the engine
242 verify(engineFactory, times(3)).newEngine(any());
244 set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
245 assertEquals(set.toString(), set3.toString());
249 public void testUnloadPolicy_NotDeployed() throws Exception {
250 prov.initialize(TEMP_PATH, apiRestParameters);
252 assertFalse(prov.unloadPolicy(policy));
254 // no additional calls
255 verify(engineFactory, times(1)).newEngine(any());
259 public void testMakeDecision() throws ToscaPolicyConversionException {
260 prov.createEngine(null);
262 DecisionRequest decreq = mock(DecisionRequest.class);
263 when(trans.convertRequest(decreq)).thenReturn(req);
265 DecisionResponse decresp = mock(DecisionResponse.class);
266 when(trans.convertResponse(resp)).thenReturn(decresp);
268 Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
269 assertSame(decresp, result.getKey());
270 assertSame(resp, result.getValue());
272 verify(trans).convertRequest(decreq);
273 verify(trans).convertResponse(resp);
277 public void testGetTranslator() {
278 assertSame(trans, prov.getTranslator());
282 public void testCreateEngine() throws FactoryException {
284 prov.createEngine(null);
285 assertSame(engine, prov.getEngine());
287 // null - should be unchanged
288 when(engineFactory.newEngine(any())).thenReturn(null);
289 prov.createEngine(null);
290 assertSame(engine, prov.getEngine());
292 // exception - should be unchanged
293 when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
294 prov.createEngine(null);
295 assertSame(engine, prov.getEngine());
299 public void testXacmlDecision() throws PDPException {
300 prov.createEngine(null);
303 assertSame(resp, prov.xacmlDecision(req));
306 when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
307 assertNull(prov.xacmlDecision(req));
311 public void testGetPdpEngineFactory() throws XacmlApplicationException {
312 // use the real engine factory
313 engineFactory = null;
316 prov.initialize(TEMP_PATH, apiRestParameters);
318 assertNotNull(prov.getEngine());
321 private class MyProv extends StdXacmlApplicationServiceProvider {
324 protected ToscaPolicyTranslator getTranslator(String type) {
329 protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
330 return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());