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