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