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