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
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.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;
70 @RunWith(MockitoJUnitRunner.class)
71 public class StdXacmlApplicationServiceProviderTest {
72 private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
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";
85 private HttpClient apiClient;
88 private ToscaPolicyTranslator trans;
91 private PDPEngineFactory engineFactory;
94 private PDPEngine engine;
100 private Response resp;
102 private ToscaPolicy policy;
103 private PolicyType internalPolicy;
105 private StdXacmlApplicationServiceProvider prov;
108 * Creates the temp directory.
111 public static void setUpBeforeClass() {
112 assertTrue(TEMP_DIR.mkdir());
116 * Deletes the temp directory and its contents.
119 public static void tearDownAfterClass() {
120 for (File file : TEMP_DIR.listFiles()) {
121 if (!file.delete()) {
122 logger.warn("cannot delete: {}", file);
126 if (!TEMP_DIR.delete()) {
127 logger.warn("cannot delete: {}", TEMP_DIR);
132 * Initializes objects, including the provider.
134 * @throws Exception if an error occurs
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);
143 internalPolicy = new PolicyType();
144 internalPolicy.setPolicyId(POLICY_NAME);
145 internalPolicy.setVersion(POLICY_VERSION);
147 when(engineFactory.newEngine(any())).thenReturn(engine);
149 when(engine.decide(req)).thenReturn(resp);
151 when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
155 Files.copy(SOURCE_PROP_FILE, PROP_FILE);
159 public void testApplicationName() {
160 assertNotNull(prov.applicationName());
164 public void testActionDecisionsSupported() {
165 assertTrue(prov.actionDecisionsSupported().isEmpty());
169 public void testInitialize_testGetXxx() throws XacmlApplicationException {
170 prov.initialize(TEMP_PATH, apiClient);
172 assertEquals(TEMP_PATH, prov.getDataPath());
173 assertNotNull(prov.getEngine());
175 Properties props = prov.getProperties();
176 assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
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");
186 public void testSupportedPolicyTypes() {
187 assertThat(prov.supportedPolicyTypes()).isEmpty();
191 public void testCanSupportPolicyType() {
192 assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
196 public void testLoadPolicy_ConversionError() throws XacmlApplicationException, ToscaPolicyConversionException {
197 when(trans.convertPolicy(policy)).thenReturn(null);
199 assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
203 public void testLoadPolicy_testUnloadPolicy() throws Exception {
204 prov.initialize(TEMP_PATH, apiClient);
207 final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
210 prov.loadPolicy(policy);
212 // policy file should have been created
213 File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
214 assertTrue(policyFile.exists());
216 // new property file should have been created
217 assertTrue(PROP_FILE.exists());
219 // should have re-created the engine
220 verify(engineFactory, times(2)).newEngine(any());
222 final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
223 assertEquals(set.size() + 1, set2.size());
225 Set<String> set3 = new HashSet<>(set2);
227 assertEquals("[root1]", set3.toString());
231 * Prepare for unload.
235 assertTrue(prov.unloadPolicy(policy));
237 // policy file should have been removed
238 assertFalse(policyFile.exists());
240 // new property file should have been created
241 assertTrue(PROP_FILE.exists());
243 // should have re-created the engine
244 verify(engineFactory, times(3)).newEngine(any());
246 set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
247 assertEquals(set.toString(), set3.toString());
251 public void testUnloadPolicy_NotDeployed() throws Exception {
252 prov.initialize(TEMP_PATH, apiClient);
254 assertFalse(prov.unloadPolicy(policy));
256 // no additional calls
257 verify(engineFactory, times(1)).newEngine(any());
261 public void testMakeDecision() throws ToscaPolicyConversionException {
262 prov.createEngine(null);
264 DecisionRequest decreq = mock(DecisionRequest.class);
265 when(trans.convertRequest(decreq)).thenReturn(req);
267 DecisionResponse decresp = mock(DecisionResponse.class);
268 when(trans.convertResponse(resp)).thenReturn(decresp);
270 Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
271 assertSame(decresp, result.getKey());
272 assertSame(resp, result.getValue());
274 verify(trans).convertRequest(decreq);
275 verify(trans).convertResponse(resp);
279 public void testGetTranslator() {
280 assertSame(trans, prov.getTranslator());
284 public void testCreateEngine() throws FactoryException {
286 prov.createEngine(null);
287 assertSame(engine, prov.getEngine());
289 // null - should be unchanged
290 when(engineFactory.newEngine(any())).thenReturn(null);
291 prov.createEngine(null);
292 assertSame(engine, prov.getEngine());
294 // exception - should be unchanged
295 when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
296 prov.createEngine(null);
297 assertSame(engine, prov.getEngine());
301 public void testXacmlDecision() throws PDPException {
302 prov.createEngine(null);
305 assertSame(resp, prov.xacmlDecision(req));
308 when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
309 assertNull(prov.xacmlDecision(req));
313 public void testGetPdpEngineFactory() throws XacmlApplicationException {
314 // use the real engine factory
315 engineFactory = null;
318 prov.initialize(TEMP_PATH, apiClient);
320 assertNotNull(prov.getEngine());
323 private class MyProv extends StdXacmlApplicationServiceProvider {
326 protected ToscaPolicyTranslator getTranslator(String type) {
331 protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
332 return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());