2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.xacml.pdp.application.naming;
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
29 import com.att.research.xacml.api.Response;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.util.Arrays;
36 import java.util.Collection;
37 import java.util.Iterator;
39 import java.util.Map.Entry;
40 import java.util.Properties;
41 import java.util.ServiceLoader;
42 import org.apache.commons.lang3.tuple.Pair;
43 import org.assertj.core.api.Condition;
44 import org.junit.BeforeClass;
45 import org.junit.ClassRule;
46 import org.junit.FixMethodOrder;
47 import org.junit.Test;
48 import org.junit.rules.TemporaryFolder;
49 import org.junit.runners.MethodSorters;
50 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
51 import org.onap.policy.common.utils.coder.CoderException;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.common.utils.resources.ResourceUtils;
54 import org.onap.policy.common.utils.resources.TextFileUtils;
55 import org.onap.policy.models.decisions.concepts.DecisionRequest;
56 import org.onap.policy.models.decisions.concepts.DecisionResponse;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
58 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
59 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
60 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
61 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
66 public class NamingPdpApplicationTest {
67 private static final Logger LOGGER = LoggerFactory.getLogger(NamingPdpApplicationTest.class);
68 private static Properties properties = new Properties();
69 private static File propertiesFile;
70 private static XacmlApplicationServiceProvider service;
71 private static StandardCoder gson = new StandardCoder();
72 private static DecisionRequest baseRequest;
73 private static RestServerParameters clientParams;
76 public static final TemporaryFolder policyFolder = new TemporaryFolder();
79 * Copies the xacml.properties and policies files into
80 * temporary folder and loads the service provider saving
81 * instance of provider off for other tests to use.
84 public static void setUp() throws Exception {
85 clientParams = mock(RestServerParameters.class);
86 when(clientParams.getHost()).thenReturn("localhost");
87 when(clientParams.getPort()).thenReturn(6969);
89 // Load Single Decision Request
91 baseRequest = gson.decode(
94 "src/test/resources/decision.naming.input.json"),
95 DecisionRequest.class);
97 // Setup our temporary folder
99 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
100 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
101 properties, myCreator);
103 // Copy the test policy types into data area
105 String policy = "onap.policies.Naming";
106 String policyType = ResourceUtils.getResourceAsString("policytypes/" + policy + ".yaml");
107 LOGGER.info("Copying {}", policyType);
108 Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
109 policyType.getBytes());
113 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
114 ServiceLoader.load(XacmlApplicationServiceProvider.class);
116 // Iterate through Xacml application services and find
117 // the optimization service. Save it for use throughout
118 // all the Junit tests.
120 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
121 Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
122 while (iterator.hasNext()) {
123 XacmlApplicationServiceProvider application = iterator.next();
125 // Is it our service?
127 if (application instanceof NamingPdpApplication) {
129 // Should be the first and only one
131 assertThat(service).isNull();
132 service = application;
134 strDump.append(application.applicationName());
135 strDump.append(" supports ");
136 strDump.append(application.supportedPolicyTypes());
137 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
139 LOGGER.debug("{}", strDump);
140 assertThat(service).isNotNull();
142 // Tell it to initialize based on the properties file
143 // we just built for it.
145 service.initialize(propertiesFile.toPath().getParent(), clientParams);
149 public void test01Basics() {
151 // Make sure there's an application name
153 assertThat(service.applicationName()).isNotEmpty();
157 assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
158 assertThat(service.actionDecisionsSupported()).contains("naming");
160 // Ensure it has the supported policy types and
161 // can support the correct policy types.
163 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
164 "onap.policies.Naming", "1.0.0"))).isTrue();
165 assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
166 "onap.foobar", "1.0.0"))).isFalse();
170 public void test02NoPolicies() throws CoderException {
172 // Ask for a decision when there are no policies loaded
174 LOGGER.info("Request {}", gson.encode(baseRequest));
175 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
176 LOGGER.info("Decision {}", decision.getKey());
178 assertThat(decision.getKey()).isNotNull();
179 assertThat(decision.getKey().getPolicies().size()).isEqualTo(0);
183 public void test03Naming() throws CoderException, FileNotFoundException, IOException,
184 XacmlApplicationException {
186 // Now load all the optimization policies
188 TestUtils.loadPolicies("policies/sdnc.policy.naming.input.tosca.yaml", service);
190 // Ask for a decision for available default policies
192 DecisionResponse response = makeDecision();
194 // There is no default policy
196 assertThat(response).isNotNull();
197 assertThat(response.getPolicies().size()).isEqualTo(0);
201 baseRequest.getResource().put("policy-type", Arrays.asList("onap.policies.Naming"));
203 // Ask for a decision for VNF default policies
205 response = makeDecision();
206 assertThat(response).isNotNull();
207 assertThat(response.getPolicies().size()).isEqualTo(1);
211 validateDecision(response, baseRequest);
214 private DecisionResponse makeDecision() {
215 Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
216 LOGGER.info("Request Resources {}", baseRequest.getResource());
217 LOGGER.info("Decision {}", decision.getKey());
218 for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
219 LOGGER.info("Policy {}", entrySet.getKey());
221 return decision.getKey();
224 @SuppressWarnings("unchecked")
225 private void validateDecision(DecisionResponse decision, DecisionRequest request) {
226 for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
227 LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
228 assertThat(entrySet.getValue()).isInstanceOf(Map.class);
229 Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
230 assertThat(policyContents.containsKey("properties")).isTrue();
231 assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
232 Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
234 validateMatchable((Collection<String>) request.getResource().get("nfRole"),
235 (Collection<String>) policyProperties.get("nfRole"));
237 validateMatchable((Collection<String>) request.getResource().get("naming-type"),
238 (Collection<String>) policyProperties.get("naming-type"));
240 validateMatchable((Collection<String>) request.getResource().get("property-name"),
241 (Collection<String>) policyProperties.get("property-name"));
245 private void validateMatchable(Collection<String> requestList, Collection<String> policyProperties) {
246 LOGGER.info("Validating matchable: {} with {}", policyProperties, requestList);
248 // Null or empty implies '*' - that is any value is acceptable
251 if (policyProperties == null || policyProperties.isEmpty()) {
254 Condition<String> condition = new Condition<>(
255 requestList::contains,
256 "Request list is contained");
257 assertThat(policyProperties).haveAtLeast(1, condition);