Include returned attributes in Decision
[policy/xacml-pdp.git] / applications / monitoring / src / test / java / org / onap / policy / xacml / pdp / application / monitoring / MonitoringPdpApplicationTest.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.monitoring;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27
28 import com.att.research.xacml.api.Response;
29 import java.io.File;
30 import java.io.IOException;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.junit.BeforeClass;
39 import org.junit.ClassRule;
40 import org.junit.FixMethodOrder;
41 import org.junit.Test;
42 import org.junit.rules.TemporaryFolder;
43 import org.junit.runners.MethodSorters;
44 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.TextFileUtils;
48 import org.onap.policy.models.decisions.concepts.DecisionRequest;
49 import org.onap.policy.models.decisions.concepts.DecisionResponse;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
54 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
55 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
60 public class MonitoringPdpApplicationTest {
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
63     private static Properties properties = new Properties();
64     private static File propertiesFile;
65     private static XacmlApplicationServiceProvider service;
66     private static DecisionRequest requestSinglePolicy;
67     private static DecisionRequest requestPolicyType;
68
69     private static StandardCoder gson = new StandardCoder();
70     private static BusTopicParams clientParams = new BusTopicParams();
71
72     @ClassRule
73     public static final TemporaryFolder policyFolder = new TemporaryFolder();
74
75     /**
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.
79      */
80     @BeforeClass
81     public static void setup() throws Exception {
82         //
83         // Load Single Decision Request
84         //
85         requestSinglePolicy = gson.decode(
86                 TextFileUtils
87                     .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
88                     DecisionRequest.class);
89         // Load Single Decision Request
90         //
91         requestPolicyType = gson.decode(
92                 TextFileUtils
93                 .getTextFileAsString("../../main/src/test/resources/decisions/decision.policytype.input.json"),
94                 DecisionRequest.class);
95         //
96         // Setup our temporary folder
97         //
98         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
99         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
100                 properties, myCreator);
101         //
102         // Load XacmlApplicationServiceProvider service
103         //
104         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
105                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
106         //
107         // Look for our class instance and save it
108         //
109         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
110         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
111         while (iterator.hasNext()) {
112             XacmlApplicationServiceProvider application = iterator.next();
113             //
114             // Is it our service?
115             //
116             if (application instanceof MonitoringPdpApplication) {
117                 //
118                 // Should be the first and only one
119                 //
120                 assertThat(service).isNull();
121                 service = application;
122             }
123             strDump.append(application.applicationName());
124             strDump.append(" supports ");
125             strDump.append(application.supportedPolicyTypes());
126             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
127         }
128         LOGGER.debug("{}", strDump);
129         //
130         // Tell it to initialize based on the properties file
131         // we just built for it.
132         //
133         service.initialize(propertiesFile.toPath().getParent(), clientParams);
134     }
135
136     @Test
137     public void test1Basics() {
138         //
139         // Make sure there's an application name
140         //
141         assertThat(service.applicationName()).isNotEmpty();
142         //
143         // Ensure it has the supported policy types and
144         // can support the correct policy types.
145         //
146         assertThat(service.canSupportPolicyType(
147                 new ToscaConceptIdentifier("onap.policies.monitoring.tcagen2", "1.0.0"))).isTrue();
148         assertThat(service.canSupportPolicyType(
149                 new ToscaConceptIdentifier(
150                 "onap.policies.monitoring.foobar", "1.0.1"))).isTrue();
151         assertThat(service.canSupportPolicyType(
152                 new ToscaConceptIdentifier("onap.foobar", "1.0.0"))).isFalse();
153         //
154         // Ensure it supports decisions
155         //
156         assertThat(service.actionDecisionsSupported()).contains("configure");
157     }
158
159     @Test
160     public void test2NoPolicies() {
161         //
162         // Ask for a decision
163         //
164         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
165         LOGGER.info("Decision {}", decision);
166
167         assertThat(decision.getKey()).isNotNull();
168         assertThat(decision.getKey().getPolicies()).isEmpty();
169         //
170         // Test the branch for query params, and we have no policy anyway
171         //
172         Map<String, String[]> requestQueryParams = new HashMap<>();
173         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
174         LOGGER.info("Decision {}", decision);
175
176         assertThat(decision.getKey()).isNotNull();
177         assertThat(decision.getKey().getPolicies()).isEmpty();
178         //
179         // Test the branch for query params, and we have no policy anyway
180         //
181         requestQueryParams.put("abbrev", new String[] {"false"});
182         decision = service.makeDecision(requestSinglePolicy, requestQueryParams);
183         LOGGER.info("Decision {}", decision);
184
185         assertThat(decision.getKey()).isNotNull();
186         assertThat(decision.getKey().getPolicies()).isEmpty();
187         //
188         // Monitoring applications should not have this information returned
189         //
190         assertThat(decision.getKey().getAdvice()).isNull();
191         assertThat(decision.getKey().getObligations()).isNull();
192         assertThat(decision.getKey().getAttributes()).isNull();
193     }
194
195     @SuppressWarnings("unchecked")
196     @Test
197     public void test3AddvDnsPolicy() throws IOException, CoderException, XacmlApplicationException {
198         //
199         // Now load the vDNS Policy - make sure
200         // the pdp can support it and have it load
201         // into the PDP.
202         //
203         //
204         // Now load the monitoring policies
205         //
206         final List<ToscaPolicy> loadedPolicies = TestUtils.loadPolicies("src/test/resources/vDNS.policy.input.yaml",
207                 service);
208         //
209         // Ask for a decision
210         //
211         Pair<DecisionResponse, Response> decision = service.makeDecision(requestSinglePolicy, null);
212         LOGGER.info("Decision {}", decision);
213         //
214         // Should have one policy returned
215         //
216         assertThat(decision.getKey()).isNotNull();
217         assertThat(decision.getKey().getPolicies()).hasSize(1);
218         //
219         // Monitoring applications should not have this information returned
220         //
221         assertThat(decision.getKey().getAdvice()).isNull();
222         assertThat(decision.getKey().getObligations()).isNull();
223         assertThat(decision.getKey().getAttributes()).isNull();
224         //
225         // Dump it out as Json
226         //
227         LOGGER.info(gson.encode(decision.getKey()));
228         //
229         // Ask for a decision based on policy-type
230         //
231         decision = service.makeDecision(requestPolicyType, null);
232         LOGGER.info("Decision {}", decision);
233         //
234         // Should have one policy returned
235         //
236         assertThat(decision.getKey()).isNotNull();
237         assertThat(decision.getKey().getPolicies()).hasSize(1);
238         //
239         // Monitoring applications should not have this information returned
240         //
241         assertThat(decision.getKey().getAdvice()).isNull();
242         assertThat(decision.getKey().getObligations()).isNull();
243         assertThat(decision.getKey().getAttributes()).isNull();
244         //
245         // Validate the full policy is returned
246         //
247         Map<String, Object> jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
248         assertThat(jsonPolicy).isNotNull();
249         assertThat(jsonPolicy.get("properties")).isNotNull();
250         //
251         // Dump it out as Json
252         //
253         LOGGER.info(gson.encode(decision.getKey()));
254         //
255         // Ask for abbreviated results
256         //
257         Map<String, String[]> requestQueryParams = new HashMap<>();
258         requestQueryParams.put("abbrev", new String[] {"true"});
259         decision = service.makeDecision(requestPolicyType, requestQueryParams);
260         LOGGER.info("Decision {}", decision);
261         //
262         // Should have one policy returned
263         //
264         assertThat(decision.getKey()).isNotNull();
265         assertThat(decision.getKey().getPolicies()).hasSize(1);
266         //
267         // Monitoring applications should not have this information returned
268         //
269         assertThat(decision.getKey().getAdvice()).isNull();
270         assertThat(decision.getKey().getObligations()).isNull();
271         assertThat(decision.getKey().getAttributes()).isNull();
272         //
273         // Validate an abbreviated policy is returned
274         //
275         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
276         assertThat(jsonPolicy).isNotNull().doesNotContainKey("properties");
277         //
278         // Don't Ask for abbreviated results
279         //
280         requestQueryParams = new HashMap<>();
281         requestQueryParams.put("abbrev", new String[] {"false"});
282         decision = service.makeDecision(requestPolicyType, requestQueryParams);
283         LOGGER.info("Decision {}", decision);
284         //
285         // Should have one policy returned
286         //
287         assertThat(decision.getKey()).isNotNull();
288         assertThat(decision.getKey().getPolicies()).hasSize(1);
289         //
290         // Monitoring applications should not have this information returned
291         //
292         assertThat(decision.getKey().getAdvice()).isNull();
293         assertThat(decision.getKey().getObligations()).isNull();
294         assertThat(decision.getKey().getAttributes()).isNull();
295         //
296         // And should have full policy returned
297         //
298         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
299         assertThat(jsonPolicy).isNotNull();
300         assertThat(jsonPolicy.get("properties")).isNotNull();
301         //
302         // Throw an unknown exception
303         //
304         requestQueryParams = new HashMap<>();
305         requestQueryParams.put("unknown", new String[] {"true"});
306         decision = service.makeDecision(requestPolicyType, requestQueryParams);
307         LOGGER.info("Decision {}", decision);
308
309         assertThat(decision.getKey()).isNotNull();
310         assertThat(decision.getKey().getPolicies()).hasSize(1);
311         jsonPolicy = (Map<String, Object>) decision.getKey().getPolicies().get("onap.scaleout.tca");
312         assertThat(jsonPolicy).isNotNull();
313         assertThat(jsonPolicy.get("properties")).isNotNull();
314         //
315         // Dump it out as Json
316         //
317         LOGGER.info(gson.encode(decision.getKey()));
318         //
319         // Now unload it
320         //
321         LOGGER.info("Now testing unloading of policy");
322         for (ToscaPolicy policy : loadedPolicies) {
323             assertThat(service.unloadPolicy(policy)).isTrue();
324         }
325         //
326         // Ask for a decision
327         //
328         decision = service.makeDecision(requestSinglePolicy, null);
329         LOGGER.info("Decision {}", decision.getKey());
330
331         assertThat(decision.getKey()).isNotNull();
332         assertThat(decision.getKey().getPolicies()).isEmpty();
333     }
334
335 }