Change RestServerParameters to BusTopicParams
[policy/xacml-pdp.git] / applications / match / src / test / java / org / onap / policy / xacml / pdp / application / match / MatchPdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.xacml.pdp.application.match;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.when;
29
30 import com.att.research.xacml.api.Response;
31 import java.io.File;
32 import java.io.FileNotFoundException;
33 import java.io.IOException;
34 import java.nio.file.Files;
35 import java.nio.file.Paths;
36 import java.util.Map;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39 import java.util.ServiceLoader;
40 import org.apache.commons.lang3.tuple.Pair;
41 import org.junit.BeforeClass;
42 import org.junit.ClassRule;
43 import org.junit.FixMethodOrder;
44 import org.junit.Test;
45 import org.junit.rules.TemporaryFolder;
46 import org.junit.runners.MethodSorters;
47 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
48 import org.onap.policy.common.utils.coder.CoderException;
49 import org.onap.policy.common.utils.coder.StandardCoder;
50 import org.onap.policy.common.utils.resources.ResourceUtils;
51 import org.onap.policy.common.utils.resources.TextFileUtils;
52 import org.onap.policy.models.decisions.concepts.DecisionRequest;
53 import org.onap.policy.models.decisions.concepts.DecisionResponse;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
56 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
57 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
58 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
63 public class MatchPdpApplicationTest {
64     private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
65     private static Properties properties = new Properties();
66     private static File propertiesFile;
67     private static XacmlApplicationServiceProvider service;
68     private static StandardCoder gson = new StandardCoder();
69     private static DecisionRequest baseRequest;
70     private static BusTopicParams clientParams;
71
72     @ClassRule
73     public static final TemporaryFolder policyFolder = new TemporaryFolder();
74
75     /**
76      * Copies the xacml.properties and policies files into
77      * temporary folder and loads the service provider saving
78      * instance of provider off for other tests to use.
79      */
80     @BeforeClass
81     public static void setUp() throws Exception {
82         clientParams = mock(BusTopicParams.class);
83         when(clientParams.getHostname()).thenReturn("localhost");
84         when(clientParams.getPort()).thenReturn(6969);
85         //
86         // Load Single Decision Request
87         //
88         baseRequest = gson.decode(
89                 TextFileUtils
90                     .getTextFileAsString(
91                             "src/test/resources/decision.match.input.json"),
92                     DecisionRequest.class);
93         //
94         // Setup our temporary folder
95         //
96         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
97         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
98                 properties, myCreator);
99         //
100         // Copy the test policy types into data area
101         //
102         String policy = "onap.policies.match.Test";
103         String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
104         LOGGER.info("Copying {}", policyType);
105         Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
106                 policyType.getBytes());
107         //
108         // Load service
109         //
110         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
111                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
112         //
113         // Iterate through Xacml application services and find
114         // the optimization service. Save it for use throughout
115         // all the Junit tests.
116         //
117         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
118         for (XacmlApplicationServiceProvider application : applicationLoader) {
119             //
120             // Is it our service?
121             //
122             if (application instanceof MatchPdpApplication) {
123                 //
124                 // Should be the first and only one
125                 //
126                 assertThat(service).isNull();
127                 service = application;
128             }
129             strDump.append(application.applicationName());
130             strDump.append(" supports ");
131             strDump.append(application.supportedPolicyTypes());
132             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
133         }
134         LOGGER.debug("{}", strDump);
135         assertThat(service).isNotNull();
136         //
137         // Tell it to initialize based on the properties file
138         // we just built for it.
139         //
140         service.initialize(propertiesFile.toPath().getParent(), clientParams);
141     }
142
143     @Test
144     public void test01Basics() {
145         //
146         // Make sure there's an application name
147         //
148         assertThat(service.applicationName()).isNotEmpty();
149         //
150         // Decisions
151         //
152         assertThat(service.actionDecisionsSupported().size()).isEqualTo(1);
153         assertThat(service.actionDecisionsSupported()).contains("match");
154         //
155         // Ensure it has the supported policy types and
156         // can support the correct policy types.
157         //
158         assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
159                 "onap.policies.match.Test", "1.0.0"))).isTrue();
160         assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
161                 "onap.foobar", "1.0.0"))).isFalse();
162     }
163
164     @Test
165     public void test02NoPolicies() throws CoderException {
166         //
167         // Ask for a decision when there are no policies loaded
168         //
169         LOGGER.info("Request {}", gson.encode(baseRequest));
170         Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
171         LOGGER.info("Decision {}", decision.getKey());
172
173         assertThat(decision.getKey()).isNotNull();
174         assertThat(decision.getKey().getPolicies()).isEmpty();
175     }
176
177     @Test
178     public void test03Match() throws CoderException, FileNotFoundException, IOException,
179         XacmlApplicationException {
180         //
181         // Now load all the test match policies
182         //
183         TestUtils.loadPolicies("src/test/resources/test-match-policies.yaml", service);
184         //
185         // Ask for a decision
186         //
187         DecisionResponse response = makeDecision();
188         //
189         // There is no default policy
190         //
191         assertThat(response).isNotNull();
192         assertThat(response.getPolicies()).isEmpty();
193         //
194         // Ask for foo
195         //
196         baseRequest.getResource().put("matchable", "foo");
197         //
198         // Get the decision
199         //
200         response = makeDecision();
201         assertThat(response).isNotNull();
202         assertThat(response.getPolicies()).hasSize(1);
203         //
204         // Validate it
205         //
206         validateDecision(response, baseRequest, "value1");
207         //
208         // Ask for bar
209         //
210         baseRequest.getResource().put("matchable", "bar");
211         //
212         // Get the decision
213         //
214         response = makeDecision();
215         assertThat(response).isNotNull();
216         assertThat(response.getPolicies()).hasSize(1);
217         //
218         // Validate it
219         //
220         validateDecision(response, baseRequest, "value2");
221         //
222         // Ask for hello (should return nothing)
223         //
224         baseRequest.getResource().put("matchable", "hello");
225         //
226         // Get the decision
227         //
228         response = makeDecision();
229         assertThat(response).isNotNull();
230         assertThat(response.getPolicies()).isEmpty();
231     }
232
233     private DecisionResponse makeDecision() {
234         Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
235         LOGGER.info("Request Resources {}", baseRequest.getResource());
236         LOGGER.info("Decision {}", decision.getKey());
237         for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
238             LOGGER.info("Policy {}", entrySet.getKey());
239         }
240         return decision.getKey();
241     }
242
243     @SuppressWarnings("unchecked")
244     private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
245         for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
246             LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
247             assertThat(entrySet.getValue()).isInstanceOf(Map.class);
248             Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
249             assertThat(policyContents).containsKey("properties");
250             assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
251             Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
252
253             assertThat(policyProperties.get("nonmatchable").toString()).hasToString(value);
254         }
255     }
256 }