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