Adding optimization application finish guard
[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 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 java.io.File;
28 import java.io.FileInputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Properties;
36 import java.util.ServiceLoader;
37
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.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.pdp.xacml.application.common.XacmlApplicationServiceProvider;
50 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.yaml.snakeyaml.Yaml;
54
55 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
56 public class MonitoringPdpApplicationTest {
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPdpApplicationTest.class);
59     private static Properties properties = new Properties();
60     private static File propertiesFile;
61     private static XacmlApplicationServiceProvider service;
62     private static DecisionRequest requestSinglePolicy;
63
64     private static StandardCoder gson = new StandardCoder();
65
66     @ClassRule
67     public static final TemporaryFolder policyFolder = new TemporaryFolder();
68
69     /**
70      * Copies the xacml.properties and policies files into
71      * temporary folder and loads the service provider saving
72      * instance of provider off for other tests to use.
73      */
74     @BeforeClass
75     public static void setup() throws Exception {
76         //
77         // Load Single Decision Request
78         //
79         requestSinglePolicy = gson.decode(
80                 TextFileUtils
81                     .getTextFileAsString("../../main/src/test/resources/decisions/decision.single.input.json"),
82                     DecisionRequest.class);
83         //
84         // Setup our temporary folder
85         //
86         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
87         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
88                 properties, myCreator);
89         //
90         // Load XacmlApplicationServiceProvider service
91         //
92         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
93                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
94         //
95         // Look for our class instance and save it
96         //
97         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
98         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
99         while (iterator.hasNext()) {
100             XacmlApplicationServiceProvider application = iterator.next();
101             //
102             // Is it our service?
103             //
104             if (application instanceof MonitoringPdpApplication) {
105                 //
106                 // Should be the first and only one
107                 //
108                 assertThat(service).isNull();
109                 service = application;
110             }
111             strDump.append(application.applicationName());
112             strDump.append(" supports ");
113             strDump.append(application.supportedPolicyTypes());
114             strDump.append(System.lineSeparator());
115         }
116         LOGGER.debug("{}", strDump);
117         //
118         // Tell it to initialize based on the properties file
119         // we just built for it.
120         //
121         service.initialize(propertiesFile.toPath().getParent());
122     }
123
124     @Test
125     public void test1Basics() {
126         //
127         // Make sure there's an application name
128         //
129         assertThat(service.applicationName()).isNotEmpty();
130         //
131         // Ensure it has the supported policy types and
132         // can support the correct policy types.
133         //
134         assertThat(service.canSupportPolicyType("onap.Monitoring", "1.0.0")).isTrue();
135         assertThat(service.canSupportPolicyType("onap.Monitoring", "1.5.0")).isTrue();
136         assertThat(service.canSupportPolicyType("onap.policies.monitoring.foobar", "1.0.1")).isTrue();
137         assertThat(service.canSupportPolicyType("onap.foobar", "1.0.0")).isFalse();
138         assertThat(service.supportedPolicyTypes()).contains("onap.Monitoring");
139         //
140         // Ensure it supports decisions
141         //
142         assertThat(service.actionDecisionsSupported()).contains("configure");
143     }
144
145     @Test
146     public void test2NoPolicies() {
147         //
148         // Ask for a decision
149         //
150         DecisionResponse response = service.makeDecision(requestSinglePolicy);
151         LOGGER.info("Decision {}", response);
152
153         assertThat(response).isNotNull();
154         assertThat(response.getPolicies().size()).isEqualTo(0);
155     }
156
157     @SuppressWarnings("unchecked")
158     @Test
159     public void test3AddvDnsPolicy() throws IOException, CoderException {
160         //
161         // Now load the vDNS Policy - make sure
162         // the pdp can support it and have it load
163         // into the PDP.
164         //
165         try (InputStream is = new FileInputStream("src/test/resources/vDNS.policy.input.yaml")) {
166             //
167             // Have yaml parse it
168             //
169             Yaml yaml = new Yaml();
170             Map<String, Object> toscaObject = yaml.load(is);
171             List<Object> policies = (List<Object>) toscaObject.get("policies");
172             //
173             // Sanity check to ensure the policy type and version are supported
174             //
175             for (Object policyObject : policies) {
176                 //
177                 // Get the contents
178                 //
179                 Map<String, Object> policyContents = (Map<String, Object>) policyObject;
180                 for (Entry<String, Object> entrySet : policyContents.entrySet()) {
181                     LOGGER.info("Entry set {}", entrySet.getKey());
182                     Map<String, Object> policyDefinition = (Map<String, Object>) entrySet.getValue();
183                     //
184                     // Find the type and make sure the engine supports it
185                     //
186                     assertThat(policyDefinition.containsKey("type")).isTrue();
187                     assertThat(service.canSupportPolicyType(
188                             policyDefinition.get("type").toString(),
189                             policyDefinition.get("version").toString()))
190                         .isTrue();
191                 }
192             }
193             //
194             // Load the policies
195             //
196             service.loadPolicies(toscaObject);
197             //
198             // Ask for a decision
199             //
200             DecisionResponse response = service.makeDecision(requestSinglePolicy);
201             LOGGER.info("Decision {}", response);
202
203             assertThat(response).isNotNull();
204             assertThat(response.getPolicies().size()).isEqualTo(1);
205             //
206             // Dump it out as Json
207             //
208             LOGGER.info(gson.encode(response));
209         }
210     }
211
212     @Test
213     public void test4BadPolicies() {
214         /*
215          *
216          * THESE TEST SHOULD BE MOVED INTO THE API PROJECT
217          *
218         //
219         // No need for service, just test some of the methods
220         // for bad policies
221         //
222         MonitoringPdpApplication onapPdpEngine = new MonitoringPdpApplication();
223
224         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
225             try (InputStream is =
226                     new FileInputStream("src/test/resources/test.monitoring.policy.missingmetadata.yaml")) {
227                 onapPdpEngine.convertPolicies(is);
228             }
229         }).withMessageContaining("missing metadata section");
230
231         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
232             try (InputStream is =
233                     new FileInputStream("src/test/resources/test.monitoring.policy.missingtype.yaml")) {
234                 onapPdpEngine.convertPolicies(is);
235             }
236         }).withMessageContaining("missing type value");
237
238         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
239             try (InputStream is =
240                     new FileInputStream("src/test/resources/test.monitoring.policy.missingversion.yaml")) {
241                 onapPdpEngine.convertPolicies(is);
242             }
243         }).withMessageContaining("missing version value");
244
245         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
246             try (InputStream is =
247                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.1.yaml")) {
248                 onapPdpEngine.convertPolicies(is);
249             }
250         }).withMessageContaining("missing metadata policy-version");
251
252         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> {
253             try (InputStream is =
254                     new FileInputStream("src/test/resources/test.monitoring.policy.badmetadata.2.yaml")) {
255                 onapPdpEngine.convertPolicies(is);
256             }
257         }).withMessageContaining("missing metadata policy-id");
258
259         */
260     }
261
262 }