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