Support of onap.policies.monitoring.tcagen2 2.0.0
[policy/xacml-pdp.git] / main / src / test / java / org / onap / policy / pdpx / main / rest / XacmlPdpApplicationManagerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020-2022 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.utils.coder.CoderException;
39 import org.onap.policy.common.utils.coder.StandardYamlCoder;
40 import org.onap.policy.common.utils.resources.ResourceUtils;
41 import org.onap.policy.models.decisions.concepts.DecisionRequest;
42 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
43 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
44 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
45 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
46 import org.onap.policy.pdpx.main.parameters.CommonTestData;
47 import org.onap.policy.pdpx.main.parameters.XacmlApplicationParameters;
48 import org.onap.policy.xacml.pdp.application.nativ.NativePdpApplication;
49 import org.onap.policy.xacml.pdp.application.optimization.OptimizationPdpApplication;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class XacmlPdpApplicationManagerTest {
54     private static final Logger LOGGER = LoggerFactory.getLogger(XacmlPdpApplicationManagerTest.class);
55     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
56     private static Path appsDirectory;
57     private static ToscaServiceTemplate completedJtst;
58     private static final CommonTestData testData = new CommonTestData();
59
60     @ClassRule
61     public static final TemporaryFolder appsFolder = new TemporaryFolder();
62
63     /**
64      * setupTestEnvironment.
65      *
66      * @throws Exception Exception if anything is missing
67      */
68     @BeforeClass
69     public static void setupTestEnvironment() throws Exception {
70         //
71         // Load an example policy
72         //
73         String policyYaml = ResourceUtils
74                 .getResourceAsString("../applications/monitoring/src/test/resources/vDNS.policy.input.yaml");
75         //
76         // Serialize it into a class
77         //
78         ToscaServiceTemplate serviceTemplate;
79         try {
80             serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
81         } catch (CoderException e) {
82             throw new XacmlApplicationException("Failed to decode policy from resource file", e);
83         }
84         //
85         // Make sure all the fields are setup properly
86         //
87         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
88         jtst.fromAuthorative(serviceTemplate);
89         completedJtst = jtst.toAuthorative();
90         //
91         // We need at least 1 policies
92         //
93         assertThat(completedJtst).isNotNull();
94         assertThat(completedJtst.getToscaTopologyTemplate().getPolicies()).isNotEmpty();
95         //
96         // Copy test directory over of the application directories
97         //
98         Path src = Paths.get("src/test/resources/apps");
99         File apps = appsFolder.newFolder("apps");
100         Files.walk(src).forEach(source -> copy(source, apps.toPath().resolve(src.relativize(source))));
101         appsDirectory = apps.toPath();
102     }
103
104     @Test
105     public void testXacmlPdpApplicationManagerBadPath() throws Exception {
106         //
107         // Make up a non existent directory to initialize from
108         //
109         Path nonExistentPath = Paths.get(appsFolder.getRoot().getAbsolutePath(), "nonexistent");
110         final XacmlApplicationParameters xacmlApplicationParameters =
111                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
112                         nonExistentPath.toString()), XacmlApplicationParameters.class);
113         //
114         // Create our app manager
115         //
116         XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, null);
117         //
118         // Still creates the manager, but the apps were not able to initialize
119         //
120         assertThat(manager).isNotNull();
121         assertThat(manager.findNativeApplication()).isNull();
122         //
123         // Now create the directory
124         //
125         Files.createDirectory(nonExistentPath);
126         manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, null);
127         //
128         // Now it should have initialized the apps
129         //
130         assertThat(manager).isNotNull();
131         assertThat(manager.findNativeApplication()).isNull();
132     }
133
134     @Test
135     public void testXacmlPdpApplicationManagerSimple() {
136         final String[] exclusions = {"org.onap.policy.xacml.pdp.application.guard.GuardPdpApplication",
137             "org.onap.policy.xacml.pdp.application.match.MatchPdpApplication" };
138         final XacmlApplicationParameters xacmlApplicationParameters =
139                 testData.toObject(testData.getXacmlapplicationParametersMap(false,
140                         appsDirectory.toString(), exclusions), XacmlApplicationParameters.class);
141         XacmlPdpApplicationManager manager = new XacmlPdpApplicationManager(xacmlApplicationParameters, null);
142         //
143         // Test the basics from the startup
144         //
145         assertThat(manager).isNotNull();
146         assertThat(manager.getPolicyCount()).isZero();
147         assertThat(manager.getPolicyTypeCount()).isEqualTo(18);
148         assertThat(manager.getToscaPolicies()).isEmpty();
149         assertThat(manager.getToscaPolicyIdentifiers()).isEmpty();
150         assertThat(manager.getToscaPolicyTypeIdents()).hasSize(18);
151
152         assertThat(manager.findNativeApplication()).isInstanceOf(NativePdpApplication.class);
153
154         DecisionRequest request = new DecisionRequest();
155         request.setAction("optimize");
156         assertThat(manager.findApplication(request)).isInstanceOf(OptimizationPdpApplication.class);
157         request.setAction("guard");
158         assertThat(manager.findApplication(request)).isInstanceOf(TestGuardOverrideApplication.class);
159         //
160         // Test Exclusion
161         //
162         request.setAction("match");
163         assertThat(manager.findApplication(request)).isNull();
164         //
165         // Try to unload a policy that isn't loaded
166         //
167         ToscaPolicy policy = null;
168         for (Map<String, ToscaPolicy> map : completedJtst.getToscaTopologyTemplate().getPolicies()) {
169             policy = map.get("onap.scaleout.tca");
170         }
171         assertThat(policy).isNotNull();
172         //
173         // Without this being set, it throws NonNull Exception
174         //
175         policy.setTypeVersion("1.0.0");
176         //
177         // Try loading and unloading
178         //
179         final ToscaPolicy policyFinal = policy;
180         assertThatCode(() -> {
181             manager.removeUndeployedPolicy(policyFinal);
182             assertThat(manager.getPolicyCount()).isZero();
183             manager.loadDeployedPolicy(policyFinal);
184             assertThat(manager.getPolicyCount()).isEqualTo(1);
185             manager.removeUndeployedPolicy(policyFinal);
186             assertThat(manager.getPolicyCount()).isZero();
187         }).doesNotThrowAnyException();
188         //
189         // try loading something unsupported
190         //
191         assertThatExceptionOfType(XacmlApplicationException.class).isThrownBy(() -> {
192             ToscaPolicy unsupportedPolicy = new ToscaPolicy();
193             unsupportedPolicy.setType("I.am.not.supported");
194             unsupportedPolicy.setTypeVersion("5.5.5");
195             manager.loadDeployedPolicy(unsupportedPolicy);
196         });
197     }
198
199     private static void copy(Path source, Path dest) {
200         try {
201             Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
202         } catch (IOException e) {
203             LOGGER.error("Failed to copy {} to {}", source, dest);
204         }
205     }
206
207 }