2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-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.naming;
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;
36 import java.util.Arrays;
37 import java.util.Collection;
38 import java.util.Iterator;
40 import java.util.Map.Entry;
41 import java.util.Properties;
42 import java.util.ServiceLoader;
43 import org.apache.commons.lang3.tuple.Pair;
44 import org.assertj.core.api.Condition;
45 import org.junit.BeforeClass;
46 import org.junit.ClassRule;
47 import org.junit.FixMethodOrder;
48 import org.junit.Test;
49 import org.junit.rules.TemporaryFolder;
50 import org.junit.runners.MethodSorters;
51 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.common.utils.resources.ResourceUtils;
55 import org.onap.policy.common.utils.resources.TextFileUtils;
56 import org.onap.policy.models.decisions.concepts.DecisionRequest;
57 import org.onap.policy.models.decisions.concepts.DecisionResponse;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
60 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
61 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
62 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
67 public class NamingPdpApplicationTest {
68 private static final Logger LOGGER = LoggerFactory.getLogger(NamingPdpApplicationTest.class);
69 private static Properties properties = new Properties();
70 private static File propertiesFile;
71 private static XacmlApplicationServiceProvider service;
72 private static StandardCoder gson = new StandardCoder();
73 private static DecisionRequest baseRequest;
74 private static BusTopicParams clientParams;
77 public static final TemporaryFolder policyFolder = new TemporaryFolder();
80 * Copies the xacml.properties and policies files into
81 * temporary folder and loads the service provider saving
82 * instance of provider off for other tests to use.
85 public static void setUp() throws Exception {
86 clientParams = mock(BusTopicParams.class);
87 when(clientParams.getHostname()).thenReturn("localhost");
88 when(clientParams.getPort()).thenReturn(6969);
90 // Load Single Decision Request
92 baseRequest = gson.decode(
95 "src/test/resources/decision.naming.input.json"),
96 DecisionRequest.class);
98 // Setup our temporary folder
100 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
101 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
102 properties, myCreator);
104 // Copy the test policy types into data area
106 String policy = "onap.policies.Naming";
107 String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
108 LOGGER.info("Copying {}", policyType);
109 Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
110 policyType.getBytes());
114 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
115 ServiceLoader.load(XacmlApplicationServiceProvider.class);
117 // Iterate through Xacml application services and find
118 // the optimization service. Save it for use throughout
119 // all the Junit tests.
121 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
122 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
123 while (iterator.hasNext()) {
124 XacmlApplicationServiceProvider application = iterator.next();
126 // Is it our service?
128 if (application instanceof NamingPdpApplication) {
130 // Should be the first and only one
132 assertThat(service).isNull();
133 service = application;
135 strDump.append(application.applicationName());
136 strDump.append(" supports ");
137 strDump.append(application.supportedPolicyTypes());
138 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
140 LOGGER.debug("{}", strDump);
141 assertThat(service).isNotNull();
143 // Tell it to initialize based on the properties file
144 // we just built for it.
146 service.initialize(propertiesFile.toPath().getParent(), clientParams);
150 public void test01Basics() {
152 // Make sure there's an application name
154 assertThat(service.applicationName()).isNotEmpty();
158 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
159 assertThat(service.actionDecisionsSupported()).contains("naming");
161 // Ensure it has the supported policy types and
162 // can support the correct policy types.
164 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
165 "onap.policies.Naming", "1.0.0"))).isTrue();
166 assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
167 "onap.foobar", "1.0.0"))).isFalse();
171 public void test02NoPolicies() throws CoderException {
173 // Ask for a decision when there are no policies loaded
175 LOGGER.info("Request {}", gson.encode(baseRequest));
176 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
177 LOGGER.info("Decision {}", decision.getKey());
179 assertThat(decision.getKey()).isNotNull();
180 assertThat(decision.getKey().getPolicies()).isEmpty();
184 public void test03Naming() throws CoderException, FileNotFoundException, IOException,
185 XacmlApplicationException {
187 // Now load all the optimization policies
189 TestUtils.loadPolicies("policies/sdnc.policy.naming.input.tosca.yaml", service);
191 // Ask for a decision for available default policies
193 DecisionResponse response = makeDecision();
195 // There is no default policy
197 assertThat(response).isNotNull();
198 assertThat(response.getPolicies()).isEmpty();
202 baseRequest.getResource().put("policy-type", Arrays.asList("onap.policies.Naming"));
204 // Ask for a decision for VNF default policies
206 response = makeDecision();
207 assertThat(response).isNotNull();
208 assertThat(response.getPolicies()).hasSize(1);
212 validateDecision(response, baseRequest);
215 private DecisionResponse makeDecision() {
216 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
217 LOGGER.info("Request Resources {}", baseRequest.getResource());
218 LOGGER.info("Decision {}", decision.getKey());
219 for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
220 LOGGER.info("Policy {}", entrySet.getKey());
222 return decision.getKey();
225 @SuppressWarnings("unchecked")
226 private void validateDecision(DecisionResponse decision, DecisionRequest request) {
227 for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
228 LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
229 assertThat(entrySet.getValue()).isInstanceOf(Map.class);
230 Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
231 assertThat(policyContents).containsKey("properties");
232 assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
233 Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
235 validateMatchable((Collection<String>) request.getResource().get("nfRole"),
236 (Collection<String>) policyProperties.get("nfRole"));
238 validateMatchable((Collection<String>) request.getResource().get("naming-type"),
239 (Collection<String>) policyProperties.get("naming-type"));
241 validateMatchable((Collection<String>) request.getResource().get("property-name"),
242 (Collection<String>) policyProperties.get("property-name"));
246 private void validateMatchable(Collection<String> requestList, Collection<String> policyProperties) {
247 LOGGER.info("Validating matchable: {} with {}", policyProperties, requestList);
249 // Null or empty implies '*' - that is any value is acceptable
252 if (policyProperties == null || policyProperties.isEmpty()) {
255 Condition<String> condition = new Condition<>(
256 requestList::contains,
257 "Request list is contained");
258 assertThat(policyProperties).haveAtLeast(1, condition);