2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2021 Nordix Foundation.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.xacml.pdp.application.match;
26 import static org.assertj.core.api.Assertions.assertThat;
28 import com.att.research.xacml.api.Response;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.ResourceUtils;
48 import org.onap.policy.common.utils.resources.TextFileUtils;
49 import org.onap.policy.models.decisions.concepts.DecisionRequest;
50 import org.onap.policy.models.decisions.concepts.DecisionResponse;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
54 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
55 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
60 public class MatchPdpApplicationTest {
61 private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
62 private static Properties properties = new Properties();
63 private static File propertiesFile;
64 private static XacmlApplicationServiceProvider service;
65 private static StandardCoder gson = new StandardCoder();
66 private static DecisionRequest baseRequest;
69 public static final TemporaryFolder policyFolder = new TemporaryFolder();
72 * Copies the xacml.properties and policies files into
73 * temporary folder and loads the service provider saving
74 * instance of provider off for other tests to use.
77 public static void setUp() throws Exception {
79 // Load Single Decision Request
81 baseRequest = gson.decode(
84 "src/test/resources/decision.match.input.json"),
85 DecisionRequest.class);
87 // Setup our temporary folder
89 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
90 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
91 properties, myCreator);
93 // Copy the test policy types into data area
95 String policy = "onap.policies.match.Test";
96 String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
97 LOGGER.info("Copying {}", policyType);
98 Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
99 policyType.getBytes());
103 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
104 ServiceLoader.load(XacmlApplicationServiceProvider.class);
106 // Iterate through Xacml application services and find
107 // the optimization service. Save it for use throughout
108 // all the Junit tests.
110 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
111 for (XacmlApplicationServiceProvider application : applicationLoader) {
113 // Is it our service?
115 if (application instanceof MatchPdpApplication) {
117 // Should be the first and only one
119 assertThat(service).isNull();
120 service = application;
122 strDump.append(application.applicationName());
123 strDump.append(" supports ");
124 strDump.append(application.supportedPolicyTypes());
125 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
127 LOGGER.debug("{}", strDump);
128 assertThat(service).isNotNull();
130 // Tell it to initialize based on the properties file
131 // we just built for it.
133 service.initialize(propertiesFile.toPath().getParent(), null);
137 public void test01Basics() {
139 // Make sure there's an application name
141 assertThat(service.applicationName()).isNotEmpty();
145 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
146 assertThat(service.actionDecisionsSupported()).contains("match");
148 // Ensure it has the supported policy types and
149 // can support the correct policy types.
151 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
152 "onap.policies.match.Test", "1.0.0"))).isTrue();
153 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
154 "onap.foobar", "1.0.0"))).isFalse();
158 public void test02NoPolicies() throws CoderException {
160 // Ask for a decision when there are no policies loaded
162 LOGGER.info("Request {}", gson.encode(baseRequest));
163 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
164 LOGGER.info("Decision {}", decision.getKey());
166 assertThat(decision.getKey()).isNotNull();
167 assertThat(decision.getKey().getPolicies()).isEmpty();
171 public void test03Match() throws CoderException, FileNotFoundException, IOException,
172 XacmlApplicationException {
174 // Now load all the test match policies
176 TestUtils.loadPolicies("src/test/resources/test-match-policies.yaml", service);
178 // Ask for a decision
180 DecisionResponse response = makeDecision();
182 // There is no default policy
184 assertThat(response).isNotNull();
185 assertThat(response.getPolicies()).isEmpty();
187 // Match applications should not have this information returned
189 assertThat(response.getAdvice()).isNull();
190 assertThat(response.getObligations()).isNull();
191 assertThat(response.getAttributes()).isNull();
195 baseRequest.getResource().put("matchable", "foo");
199 response = makeDecision();
200 assertThat(response).isNotNull();
201 assertThat(response.getPolicies()).hasSize(1);
203 // Match applications should not have this information returned
205 assertThat(response.getAdvice()).isNull();
206 assertThat(response.getObligations()).isNull();
207 assertThat(response.getAttributes()).isNull();
211 validateDecision(response, baseRequest, "value1");
215 baseRequest.getResource().put("matchable", "bar");
219 response = makeDecision();
220 assertThat(response).isNotNull();
221 assertThat(response.getPolicies()).hasSize(1);
225 validateDecision(response, baseRequest, "value2");
227 // Ask for hello (should return nothing)
229 baseRequest.getResource().put("matchable", "hello");
233 response = makeDecision();
234 assertThat(response).isNotNull();
235 assertThat(response.getPolicies()).isEmpty();
238 private DecisionResponse makeDecision() {
239 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
240 LOGGER.info("Request Resources {}", baseRequest.getResource());
241 LOGGER.info("Decision {}", decision.getKey());
242 for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
243 LOGGER.info("Policy {}", entrySet.getKey());
245 return decision.getKey();
248 @SuppressWarnings("unchecked")
249 private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
250 for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
251 LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
252 assertThat(entrySet.getValue()).isInstanceOf(Map.class);
253 Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
254 assertThat(policyContents).containsKey("properties");
255 assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
256 Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
258 assertThat(policyProperties.get("nonmatchable").toString()).hasToString(value);