4619b2aeda039623e5b841dcf122d867d3e2297c
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / XacmlPdpApplicationManagerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pdpx.main.rest;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.assertj.core.api.Assertions.assertThatCode;
25 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.nio.file.StandardCopyOption;
33 import java.util.Map;
34 import org.junit.BeforeClass;
35 import org.junit.ClassRule;
36 import org.junit.Test;
37 import org.junit.rules.TemporaryFolder;
38 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardYamlCoder;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42 import org.onap.policy.models.decisions.concepts.DecisionRequest;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
44 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
45 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
46 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
47 import org.onap.policy.pdpx.main.parameters.CommonTestData;
48 import org.onap.policy.pdpx.main.parameters.XacmlApplicationParameters;
49 import org.onap.policy.xacml.pdp.application.guard.GuardPdpApplication;
50 import org.onap.policy.xacml.pdp.application.nativ.NativePdpApplication;
51 import org.onap.policy.xacml.pdp.application.optimization.OptimizationPdpApplication;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 public class XacmlPdpApplicationManagerTest {
56     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManagerTest.class);
57     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
58     private static final BusTopicParams params = new BusTopicParams();
59     private static Path appsDirectory;
60     private static ToscaServiceTemplate completedJtst;
61     private static CommonTestData testData = new CommonTestData();
62
63     @ClassRule
64     public static final TemporaryFolder appsFolder = new TemporaryFolder();
65
66     /**
67      * setupTestEnvironment.
68      *
69      * @throws Exception Exception if anything is missing
70      */
71     @BeforeClass
72     public static void setupTestEnvironment() throws Exception {
73         //
74         // No need to do more than this
75         //
76         params.setClientName("policyApiParameters");
77         //
78         // Load an example policy
79         //
80         String policyYaml = ResourceUtils
81                 .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml");
82         //
83         // Serialize it into a class
84         //
85         ToscaServiceTemplate serviceTemplate;
86         try {
87             serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
88         } catch (CoderException e) {
89             throw new XacmlApplicationException("Failed to decode policy from resource file", e);
90         }
91         //
92         // Make sure all the fields are setup properly
93         //
94         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
95         jtst.fromAuthorative(serviceTemplate);
96         completedJtst = jtst.toAuthorative();
97         //
98         // We need at least 1 policies
99         //
100         assertThat(completedJtst).isNotNull();
101         assertThat(completedJtst.getToscaTopologyTemplate().getPolicies().size()).isPositive();
102         //
103         // Copy test directory over of the application directories
104         //
105         Path src = Paths.get("src/test/resources/apps");
106         File apps = appsFolder.newFolder("apps");
107         Files.walk(src).forEach(source -> {
108             copy(source, apps.toPath().resolve(src.relativize(source)));
109         });
110         appsDirectory = apps.toPath();
111     }
112
113     @Test
114     public void testXacmlPdpApplicationManagerBadPath() throws Exception {
115         //
116         // Make up a non existent directory to initialize from
117         //
118         Path nonExistentPath = Paths.get(appsFolder.getRoot().getAbsolutePath(), "nonexistent");
119         final XacmlApplicationParameters xacmlApplicationParameters =
120                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
121                         nonExistentPath.toString()), XacmlApplicationParameters.class);
122         //
123         // Create our app manager
124         //
125         XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, params);
126         //
127         // Still creates the manager, but the apps were not able to initialize
128         //
129         assertThat(manager).isNotNull();
130         assertThat(manager.findNativeApplication()).isNull();
131         //
132         // Now create the directory
133         //
134         Files.createDirectory(nonExistentPath);
135         manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, params);
136         //
137         // Now it should have initialized the apps
138         //
139         assertThat(manager).isNotNull();
140         assertThat(manager.findNativeApplication()).isNull();
141     }
142
143     @Test
144     public void testXacmlPdpApplicationManagerSimple() {
145         final XacmlApplicationParameters xacmlApplicationParameters =
146                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
147                         appsDirectory.toString()), XacmlApplicationParameters.class);
148         XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, params);
149         //
150         // Test the basics from the startup
151         //
152         assertThat(manager).isNotNull();
153         assertThat(manager.getPolicyCount()).isZero();
154         assertThat(manager.getPolicyTypeCount()).isEqualTo(18);
155         assertThat(manager.getToscaPolicies()).isEmpty();
156         assertThat(manager.getToscaPolicyIdentifiers()).isEmpty();
157         assertThat(manager.getToscaPolicyTypeIdents()).hasSize(18);
158
159         assertThat(manager.findNativeApplication()).isInstanceOf(NativePdpApplication.class);
160
161         DecisionRequest request = new DecisionRequest();
162         request.setAction("optimize");
163         assertThat(manager.findApplication(request)).isInstanceOf(OptimizationPdpApplication.class);
164         request.setAction("guard");
165         assertThat(manager.findApplication(request)).isInstanceOf(GuardPdpApplication.class);
166         //
167         // Try to unload a policy that isn't loaded
168         //
169         ToscaPolicy policy = null;
170         for (Map<String, ToscaPolicy> map : completedJtst.getToscaTopologyTemplate().getPolicies()) {
171             policy = map.get("onap.scaleout.tca");
172         }
173         assertThat(policy).isNotNull();
174         //
175         // Without this being set, it throws NonNull Exception
176         //
177         policy.setTypeVersion("1.0.0");
178         //
179         // Try loading and unloading
180         //
181         final ToscaPolicy policyFinal = policy;
182         assertThatCode(() -> {
183             manager.removeUndeployedPolicy(policyFinal);
184             assertThat(manager.getPolicyCount()).isZero();
185             manager.loadDeployedPolicy(policyFinal);
186             assertThat(manager.getPolicyCount()).isEqualTo(1);
187             manager.removeUndeployedPolicy(policyFinal);
188             assertThat(manager.getPolicyCount()).isZero();
189         }).doesNotThrowAnyException();
190         //
191         // try loading something unsupported
192         //
193         assertThatExceptionOfType(XacmlApplicationException.class).isThrownBy(() -> {
194             ToscaPolicy unsupportedPolicy = new ToscaPolicy();
195             unsupportedPolicy.setType("I.am.not.supported");
196             unsupportedPolicy.setTypeVersion("5.5.5");
197             manager.loadDeployedPolicy(unsupportedPolicy);
198         });
199     }
200
201     private static void copy(Path source, Path dest) {
202         try {
203             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
204         } catch (IOException e) {
205             LOGGER.error("Failed to copy {} to {}", source, dest);
206         }
207     }
208
209 }