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;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.when;
30 import com.att.research.xacml.api.Response;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39 import java.util.ServiceLoader;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.junit.BeforeClass;
42 import org.junit.ClassRule;
43 import org.junit.FixMethodOrder;
44 import org.junit.Test;
45 import org.junit.rules.TemporaryFolder;
46 import org.junit.runners.MethodSorters;
47 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.common.utils.resources.ResourceUtils;
51 import org.onap.policy.common.utils.resources.TextFileUtils;
52 import org.onap.policy.models.decisions.concepts.DecisionRequest;
53 import org.onap.policy.models.decisions.concepts.DecisionResponse;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
56 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
57 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
58 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
63 public class MatchPdpApplicationTest {
64 private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
65 private static Properties properties = new Properties();
66 private static File propertiesFile;
67 private static XacmlApplicationServiceProvider service;
68 private static StandardCoder gson = new StandardCoder();
69 private static DecisionRequest baseRequest;
70 private static BusTopicParams clientParams;
73 public static final TemporaryFolder policyFolder = new TemporaryFolder();
76 * Copies the xacml.properties and policies files into
77 * temporary folder and loads the service provider saving
78 * instance of provider off for other tests to use.
81 public static void setUp() throws Exception {
82 clientParams = mock(BusTopicParams.class);
83 when(clientParams.getHostname()).thenReturn("localhost");
84 when(clientParams.getPort()).thenReturn(6969);
86 // Load Single Decision Request
88 baseRequest = gson.decode(
91 "src/test/resources/decision.match.input.json"),
92 DecisionRequest.class);
94 // Setup our temporary folder
96 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
97 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
98 properties, myCreator);
100 // Copy the test policy types into data area
102 String policy = "onap.policies.match.Test";
103 String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
104 LOGGER.info("Copying {}", policyType);
105 Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
106 policyType.getBytes());
110 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
111 ServiceLoader.load(XacmlApplicationServiceProvider.class);
113 // Iterate through Xacml application services and find
114 // the optimization service. Save it for use throughout
115 // all the Junit tests.
117 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
118 for (XacmlApplicationServiceProvider application : applicationLoader) {
120 // Is it our service?
122 if (application instanceof MatchPdpApplication) {
124 // Should be the first and only one
126 assertThat(service).isNull();
127 service = application;
129 strDump.append(application.applicationName());
130 strDump.append(" supports ");
131 strDump.append(application.supportedPolicyTypes());
132 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
134 LOGGER.debug("{}", strDump);
135 assertThat(service).isNotNull();
137 // Tell it to initialize based on the properties file
138 // we just built for it.
140 service.initialize(propertiesFile.toPath().getParent(), clientParams);
144 public void test01Basics() {
146 // Make sure there's an application name
148 assertThat(service.applicationName()).isNotEmpty();
152 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
153 assertThat(service.actionDecisionsSupported()).contains("match");
155 // Ensure it has the supported policy types and
156 // can support the correct policy types.
158 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
159 "onap.policies.match.Test", "1.0.0"))).isTrue();
160 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
161 "onap.foobar", "1.0.0"))).isFalse();
165 public void test02NoPolicies() throws CoderException {
167 // Ask for a decision when there are no policies loaded
169 LOGGER.info("Request {}", gson.encode(baseRequest));
170 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
171 LOGGER.info("Decision {}", decision.getKey());
173 assertThat(decision.getKey()).isNotNull();
174 assertThat(decision.getKey().getPolicies()).isEmpty();
178 public void test03Match() throws CoderException, FileNotFoundException, IOException,
179 XacmlApplicationException {
181 // Now load all the test match policies
183 TestUtils.loadPolicies("src/test/resources/test-match-policies.yaml", service);
185 // Ask for a decision
187 DecisionResponse response = makeDecision();
189 // There is no default policy
191 assertThat(response).isNotNull();
192 assertThat(response.getPolicies()).isEmpty();
194 // Match applications should not have this information returned
196 assertThat(response.getAdvice()).isNull();
197 assertThat(response.getObligations()).isNull();
198 assertThat(response.getAttributes()).isNull();
202 baseRequest.getResource().put("matchable", "foo");
206 response = makeDecision();
207 assertThat(response).isNotNull();
208 assertThat(response.getPolicies()).hasSize(1);
210 // Match applications should not have this information returned
212 assertThat(response.getAdvice()).isNull();
213 assertThat(response.getObligations()).isNull();
214 assertThat(response.getAttributes()).isNull();
218 validateDecision(response, baseRequest, "value1");
222 baseRequest.getResource().put("matchable", "bar");
226 response = makeDecision();
227 assertThat(response).isNotNull();
228 assertThat(response.getPolicies()).hasSize(1);
232 validateDecision(response, baseRequest, "value2");
234 // Ask for hello (should return nothing)
236 baseRequest.getResource().put("matchable", "hello");
240 response = makeDecision();
241 assertThat(response).isNotNull();
242 assertThat(response.getPolicies()).isEmpty();
245 private DecisionResponse makeDecision() {
246 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
247 LOGGER.info("Request Resources {}", baseRequest.getResource());
248 LOGGER.info("Decision {}", decision.getKey());
249 for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
250 LOGGER.info("Policy {}", entrySet.getKey());
252 return decision.getKey();
255 @SuppressWarnings("unchecked")
256 private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
257 for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
258 LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
259 assertThat(entrySet.getValue()).isInstanceOf(Map.class);
260 Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
261 assertThat(policyContents).containsKey("properties");
262 assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
263 Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
265 assertThat(policyProperties.get("nonmatchable").toString()).hasToString(value);