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