Adding optimization application finish guard
[policy/xacml-pdp.git] / applications / optimization / src / test / java / org / onap / policy / xacml / pdp / application / optimization / OptimizationPdpApplicationTest.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.optimization;
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.FileNotFoundException;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.TextFileUtils;
48 import org.onap.policy.models.decisions.concepts.DecisionRequest;
49 import org.onap.policy.models.decisions.concepts.DecisionResponse;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.yaml.snakeyaml.Yaml;
55
56 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
57 public class OptimizationPdpApplicationTest {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
60     private static Properties properties = new Properties();
61     private static File propertiesFile;
62     private static XacmlApplicationServiceProvider service;
63     private static StandardCoder gson = new StandardCoder();
64     private static DecisionRequest requestAffinity;
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         requestAffinity = gson.decode(
80                 TextFileUtils
81                     .getTextFileAsString(
82                             "../../main/src/test/resources/decisions/decision.optimization.affinity.input.json"),
83                     DecisionRequest.class);
84         //
85         // Setup our temporary folder
86         //
87         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
88         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
89                 properties, myCreator);
90         //
91         // Load service
92         //
93         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
94                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
95         //
96         // Iterate through Xacml application services and find
97         // the optimization service. Save it for use throughout
98         // all the Junit tests.
99         //
100         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
101         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
102         while (iterator.hasNext()) {
103             XacmlApplicationServiceProvider application = iterator.next();
104             //
105             // Is it our service?
106             //
107             if (application instanceof OptimizationPdpApplication) {
108                 //
109                 // Should be the first and only one
110                 //
111                 assertThat(service).isNull();
112                 service = application;
113             }
114             strDump.append(application.applicationName());
115             strDump.append(" supports ");
116             strDump.append(application.supportedPolicyTypes());
117             strDump.append(System.lineSeparator());
118         }
119         LOGGER.debug("{}", strDump);
120         //
121         // Tell it to initialize based on the properties file
122         // we just built for it.
123         //
124         service.initialize(propertiesFile.toPath().getParent());
125     }
126
127     @Test
128     public void test1Basics() {
129         //
130         // Make sure there's an application name
131         //
132         assertThat(service.applicationName()).isNotEmpty();
133         //
134         // Decisions
135         //
136         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
137         assertThat(service.actionDecisionsSupported()).contains("optimize");
138         //
139         // Ensure it has the supported policy types and
140         // can support the correct policy types.
141         //
142         assertThat(service.canSupportPolicyType("onap.policies.optimization.AffinityPolicy", "1.0.0")).isTrue();
143         assertThat(service.canSupportPolicyType("onap.foobar", "1.0.0")).isFalse();
144     }
145
146     @Test
147     public void test2NoPolicies() {
148         //
149         // Ask for a decision
150         //
151         DecisionResponse response = service.makeDecision(requestAffinity);
152         LOGGER.info("Decision {}", response);
153
154         assertThat(response).isNotNull();
155         assertThat(response.getPolicies().size()).isEqualTo(0);
156     }
157
158     @SuppressWarnings("unchecked")
159     @Test
160     public void test3AddOptimizationPolicies() throws CoderException, FileNotFoundException, IOException {
161         //
162         // Now load the optimization policies
163         //
164         try (InputStream is = new FileInputStream("src/test/resources/vCPE.policies.optimization.input.tosca.yaml")) {
165             //
166             // Have yaml parse it
167             //
168             Yaml yaml = new Yaml();
169             Map<String, Object> toscaObject = yaml.load(is);
170             List<Object> policies = (List<Object>) toscaObject.get("policies");
171             //
172             // Sanity check to ensure the policy type and version are supported
173             //
174             for (Object policyObject : policies) {
175                 //
176                 // Get the contents
177                 //
178                 Map<String, Object> policyContents = (Map<String, Object>) policyObject;
179                 for (Entry<String, Object> entrySet : policyContents.entrySet()) {
180                     LOGGER.info("Entry set {}", entrySet.getKey());
181                     Map<String, Object> policyDefinition = (Map<String, Object>) entrySet.getValue();
182                     //
183                     // Find the type and make sure the engine supports it
184                     //
185                     assertThat(policyDefinition.containsKey("type")).isTrue();
186                     assertThat(service.canSupportPolicyType(
187                             policyDefinition.get("type").toString(),
188                             policyDefinition.get("version").toString()))
189                         .isTrue();
190                 }
191             }
192             //
193             // Load the policies
194             //
195             service.loadPolicies(toscaObject);
196             //
197             // Ask for a decision
198             //
199             DecisionResponse response = service.makeDecision(requestAffinity);
200             LOGGER.info("Decision {}", response);
201
202             assertThat(response).isNotNull();
203             assertThat(response.getPolicies().size()).isEqualTo(1);
204             //
205             // Dump it out as Json
206             //
207             LOGGER.info(gson.encode(response));
208         }
209     }
210
211 }