Fix issues in xacml-pdp for new sonar rules
[policy/xacml-pdp.git] / applications / naming / src / test / java / org / onap / policy / xacml / pdp / application / naming / NamingPdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.xacml.pdp.application.naming;
24
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
28
29 import com.att.research.xacml.api.Response;
30 import java.io.File;
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;
38 import java.util.Map;
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;
64
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;
74
75     @ClassRule
76     public static final TemporaryFolder policyFolder = new TemporaryFolder();
77
78     /**
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.
82      */
83     @BeforeClass
84     public static void setUp() throws Exception {
85         clientParams = mock(RestServerParameters.class);
86         when(clientParams.getHost()).thenReturn("localhost");
87         when(clientParams.getPort()).thenReturn(6969);
88         //
89         // Load Single Decision Request
90         //
91         baseRequest = gson.decode(
92                 TextFileUtils
93                     .getTextFileAsString(
94                             "src/test/resources/decision.naming.input.json"),
95                     DecisionRequest.class);
96         //
97         // Setup our temporary folder
98         //
99         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
100         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
101                 properties, myCreator);
102         //
103         // Copy the test policy types into data area
104         //
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());
110         //
111         // Load service
112         //
113         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
114                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
115         //
116         // Iterate through Xacml application services and find
117         // the optimization service. Save it for use throughout
118         // all the Junit tests.
119         //
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();
124             //
125             // Is it our service?
126             //
127             if (application instanceof NamingPdpApplication) {
128                 //
129                 // Should be the first and only one
130                 //
131                 assertThat(service).isNull();
132                 service = application;
133             }
134             strDump.append(application.applicationName());
135             strDump.append(" supports ");
136             strDump.append(application.supportedPolicyTypes());
137             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
138         }
139         LOGGER.debug("{}", strDump);
140         assertThat(service).isNotNull();
141         //
142         // Tell it to initialize based on the properties file
143         // we just built for it.
144         //
145         service.initialize(propertiesFile.toPath().getParent(), clientParams);
146     }
147
148     @Test
149     public void test01Basics() {
150         //
151         // Make sure there's an application name
152         //
153         assertThat(service.applicationName()).isNotEmpty();
154         //
155         // Decisions
156         //
157         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
158         assertThat(service.actionDecisionsSupported()).contains("naming");
159         //
160         // Ensure it has the supported policy types and
161         // can support the correct policy types.
162         //
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();
167     }
168
169     @Test
170     public void test02NoPolicies() throws CoderException {
171         //
172         // Ask for a decision when there are no policies loaded
173         //
174         LOGGER.info("Request {}", gson.encode(baseRequest));
175         Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
176         LOGGER.info("Decision {}", decision.getKey());
177
178         assertThat(decision.getKey()).isNotNull();
179         assertThat(decision.getKey().getPolicies()).isEmpty();
180     }
181
182     @Test
183     public void test03Naming() throws CoderException, FileNotFoundException, IOException,
184         XacmlApplicationException {
185         //
186         // Now load all the optimization policies
187         //
188         TestUtils.loadPolicies("policies/sdnc.policy.naming.input.tosca.yaml", service);
189         //
190         // Ask for a decision for available default policies
191         //
192         DecisionResponse response = makeDecision();
193         //
194         // There is no default policy
195         //
196         assertThat(response).isNotNull();
197         assertThat(response.getPolicies()).isEmpty();
198         //
199         // Ask for VNF
200         //
201         baseRequest.getResource().put("policy-type", Arrays.asList("onap.policies.Naming"));
202         //
203         // Ask for a decision for VNF default policies
204         //
205         response = makeDecision();
206         assertThat(response).isNotNull();
207         assertThat(response.getPolicies()).hasSize(1);
208         //
209         // Validate it
210         //
211         validateDecision(response, baseRequest);
212     }
213
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());
220         }
221         return decision.getKey();
222     }
223
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");
231             assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
232             Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
233
234             validateMatchable((Collection<String>) request.getResource().get("nfRole"),
235                     (Collection<String>) policyProperties.get("nfRole"));
236
237             validateMatchable((Collection<String>) request.getResource().get("naming-type"),
238                     (Collection<String>) policyProperties.get("naming-type"));
239
240             validateMatchable((Collection<String>) request.getResource().get("property-name"),
241                     (Collection<String>) policyProperties.get("property-name"));
242         }
243     }
244
245     private void validateMatchable(Collection<String> requestList, Collection<String> policyProperties) {
246         LOGGER.info("Validating matchable: {} with {}", policyProperties, requestList);
247         //
248         // Null or empty implies '*' - that is any value is acceptable
249         // for this policy.
250         //
251         if (policyProperties == null || policyProperties.isEmpty()) {
252             return;
253         }
254         Condition<String> condition = new Condition<>(
255                 requestList::contains,
256                 "Request list is contained");
257         assertThat(policyProperties).haveAtLeast(1, condition);
258
259     }
260 }