Integrate using Policy Type to find Matchable
[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 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
28
29 import com.att.research.xacml.api.Response;
30 import java.io.File;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.nio.file.Files;
34 import java.nio.file.Paths;
35 import java.util.Iterator;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import org.apache.commons.lang3.tuple.Pair;
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.endpoints.parameters.RestServerParameters;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.common.utils.resources.TextFileUtils;
49 import org.onap.policy.models.decisions.concepts.DecisionRequest;
50 import org.onap.policy.models.decisions.concepts.DecisionResponse;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
52 import org.onap.policy.pdp.xacml.application.common.TestUtils;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
54 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
55 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
60 public class OptimizationPdpApplicationTest {
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(OptimizationPdpApplicationTest.class);
63     private static Properties properties = new Properties();
64     private static File propertiesFile;
65     private static XacmlApplicationServiceProvider service;
66     private static StandardCoder gson = new StandardCoder();
67     private static DecisionRequest requestAffinity;
68     private static RestServerParameters clientParams;
69     private static String[] listPolicyTypeFiles = { "onap.policies.Optimization",
70         "onap.policies.optimization.AffinityPolicy",
71         "onap.policies.optimization.DistancePolicy",
72         "onap.policies.optimization.SubscriberPolicy"};
73
74     @ClassRule
75     public static final TemporaryFolder policyFolder = new TemporaryFolder();
76
77     /**
78      * Copies the xacml.properties and policies files into
79      * temporary folder and loads the service provider saving
80      * instance of provider off for other tests to use.
81      */
82     @BeforeClass
83     public static void setUp() throws Exception {
84         clientParams = mock(RestServerParameters.class);
85         when(clientParams.getHost()).thenReturn("localhost");
86         when(clientParams.getPort()).thenReturn(6969);
87         //
88         // Load Single Decision Request
89         //
90         requestAffinity = gson.decode(
91                 TextFileUtils
92                     .getTextFileAsString(
93                             "../../main/src/test/resources/decisions/decision.optimization.affinity.input.json"),
94                     DecisionRequest.class);
95         //
96         // Setup our temporary folder
97         //
98         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
99         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
100                 properties, myCreator);
101         //
102         // Copy the test policy types into data area
103         //
104         for (String policy : listPolicyTypeFiles) {
105             Files.copy(Paths.get("src/test/resources", policy + "-1.0.0.json"),
106                     Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.json"));
107         }
108         //
109         // Load service
110         //
111         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
112                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
113         //
114         // Iterate through Xacml application services and find
115         // the optimization service. Save it for use throughout
116         // all the Junit tests.
117         //
118         StringBuilder strDump = new StringBuilder("Loaded applications:" + System.lineSeparator());
119         Iterator<XacmlApplicationServiceProvider> iterator = applicationLoader.iterator();
120         while (iterator.hasNext()) {
121             XacmlApplicationServiceProvider application = iterator.next();
122             //
123             // Is it our service?
124             //
125             if (application instanceof OptimizationPdpApplication) {
126                 //
127                 // Should be the first and only one
128                 //
129                 assertThat(service).isNull();
130                 service = application;
131             }
132             strDump.append(application.applicationName());
133             strDump.append(" supports ");
134             strDump.append(application.supportedPolicyTypes());
135             strDump.append(System.lineSeparator());
136         }
137         LOGGER.debug("{}", strDump);
138         //
139         // Tell it to initialize based on the properties file
140         // we just built for it.
141         //
142         service.initialize(propertiesFile.toPath().getParent(), clientParams);
143     }
144
145     @Test
146     public void test1Basics() {
147         //
148         // Make sure there's an application name
149         //
150         assertThat(service.applicationName()).isNotEmpty();
151         //
152         // Decisions
153         //
154         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
155         assertThat(service.actionDecisionsSupported()).contains("optimize");
156         //
157         // Ensure it has the supported policy types and
158         // can support the correct policy types.
159         //
160         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
161                 "onap.policies.optimization.AffinityPolicy", "1.0.0"))).isTrue();
162         assertThat(service.canSupportPolicyType(new ToscaPolicyTypeIdentifier(
163                 "onap.foobar", "1.0.0"))).isFalse();
164     }
165
166     @Test
167     public void test2NoPolicies() {
168         //
169         // Ask for a decision
170         //
171         Pair<DecisionResponse, Response> decision = service.makeDecision(requestAffinity);
172         LOGGER.info("Decision {}", decision.getKey());
173
174         assertThat(decision.getKey()).isNotNull();
175         assertThat(decision.getKey().getPolicies().size()).isEqualTo(0);
176     }
177
178     @Test
179     public void test3AddOptimizationPolicies() throws CoderException, FileNotFoundException, IOException,
180         XacmlApplicationException {
181         //
182         // Now load the optimization policies
183         //
184         TestUtils.loadPolicies("src/test/resources/vCPE.policies.optimization.input.tosca.yaml", service);
185         //
186         // Ask for a decision
187         //
188         Pair<DecisionResponse, Response> decision = service.makeDecision(requestAffinity);
189         LOGGER.info("Decision {}", decision.getKey());
190
191         assertThat(decision.getKey()).isNotNull();
192         assertThat(decision.getKey().getPolicies().size()).isEqualTo(4);
193         //
194         // Dump it out as Json
195         //
196         LOGGER.info(gson.encode(decision.getKey()));
197     }
198 }