Upgrade Java 17 in xacml-pdp
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / operationshistory / GetOperationOutcomePipTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2023 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  */
19
20 package org.onap.policy.pdp.xacml.application.common.operationshistory;
21
22 import static org.assertj.core.api.Assertions.assertThat;
23 import static org.assertj.core.api.Assertions.assertThatCode;
24 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotEquals;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.when;
31
32 import com.att.research.xacml.api.Status;
33 import com.att.research.xacml.api.pip.PIPException;
34 import com.att.research.xacml.api.pip.PIPFinder;
35 import com.att.research.xacml.api.pip.PIPRequest;
36 import com.att.research.xacml.api.pip.PIPResponse;
37 import com.att.research.xacml.std.pip.StdPIPResponse;
38 import jakarta.persistence.EntityManager;
39 import jakarta.persistence.Persistence;
40 import java.io.FileInputStream;
41 import java.lang.reflect.Method;
42 import java.time.Instant;
43 import java.util.Date;
44 import java.util.Properties;
45 import java.util.UUID;
46 import org.junit.AfterClass;
47 import org.junit.Before;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.onap.policy.guard.OperationsHistory;
51 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 public class GetOperationOutcomePipTest {
56     private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
57     private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
58
59     private static EntityManager em;
60
61     private Properties properties;
62     private GetOperationOutcomePip pipEngine;
63
64     private final PIPRequest pipRequest = mock(PIPRequest.class);
65
66     private final PIPFinder pipFinder = mock(PIPFinder.class);
67
68     private final PIPResponse resp1 = mock(PIPResponse.class);
69
70     private final Status okStatus = mock(Status.class);
71
72     /**
73      * Create an instance of our engine and also the persistence
74      * factory.
75      *
76      * @throws Exception connectivity issues
77      */
78     @BeforeClass
79     public static void setupDatabase() throws Exception {
80         LOGGER.info("Setting up PIP Testing");
81         //
82         // Load our test properties to use
83         //
84         Properties props = new Properties();
85         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
86             props.load(is);
87         }
88         //
89         // Connect to in-mem db
90         //
91         String persistenceUnit = GetOperationOutcomePip.ISSUER_NAME + ".persistenceunit";
92         LOGGER.info("persistenceunit {}", persistenceUnit);
93         em = Persistence.createEntityManagerFactory(props.getProperty(persistenceUnit), props)
94             .createEntityManager();
95         //
96         //
97         //
98         LOGGER.info("Configured own entity manager", em.toString());
99     }
100
101     /**
102      * Close the entity manager.
103      */
104     @AfterClass
105     public static void cleanup() {
106         if (em != null) {
107             em.close();
108         }
109     }
110
111     /**
112      * Create an instance of our engine.
113      *
114      * @throws Exception if an error occurs
115      */
116     @Before
117     public void setupEngine() throws Exception {
118         when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
119         //
120         // Create instance
121         //
122         pipEngine = new GetOperationOutcomePip();
123         //
124         // Load the properties
125         //
126         properties = new Properties();
127         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
128             properties.load(is);
129         }
130         //
131         // Configure it using properties
132         //
133         pipEngine.configure("issuer", properties);
134         LOGGER.info("PIP configured now creating our entity manager");
135         LOGGER.info("properties {}", properties);
136     }
137
138     @Test
139     public void testAttributesRequired() {
140         assertEquals(1, pipEngine.attributesRequired().size());
141     }
142
143     @Test
144     public void testConfigure_DbException() throws Exception {
145         properties.put("jakarta.persistence.jdbc.url", "invalid");
146         assertThatCode(() ->
147             pipEngine.configure("issuer", properties)
148         ).doesNotThrowAnyException();
149     }
150
151     @Test
152     public void testGetAttributes_NullIssuer() throws PIPException {
153         when(pipRequest.getIssuer()).thenReturn(null);
154         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
155     }
156
157     @Test
158     public void testGetAttributes_WrongIssuer() throws PIPException {
159         when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
160         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
161     }
162
163     @Test
164     public void testGetAttributes() throws Exception {
165         //
166         //
167         //
168         when(pipRequest.getIssuer()).thenReturn(ToscaDictionary.GUARD_ISSUER_PREFIX + "clname:clfoo");
169         when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1);
170         when(resp1.getStatus()).thenReturn(okStatus);
171         when(okStatus.isOk()).thenReturn(true);
172
173         assertNotEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
174
175         pipEngine.shutdown();
176
177         assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
178             .withMessageContaining("Engine is shutdown");
179     }
180
181     @Test
182     public void testGetOutcomeFromDb() throws Exception {
183         //
184         // Use reflection to run getCountFromDB
185         //
186         Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery",
187                                                                        String.class);
188         method.setAccessible(true);
189         //
190         // Test pipEngine
191         //
192         String outcome = (String) method.invoke(pipEngine, "testcl1");
193         assertThat(outcome).isNull();
194         //
195         // Insert entry
196         //
197         insertEntry("testcl1", "testtarget1", "Started");
198         //
199         // Test pipEngine
200         //
201         outcome = (String) method.invoke(pipEngine, "testcl1");
202         //
203         // outcome should be "In_Progress"
204         //
205         assertEquals("In_Progress", outcome);
206         //
207         // Insert more entries
208         //
209         insertEntry("testcl2", "testtarget1", "Success");
210         insertEntry("testcl3", "testtarget2", "Failed");
211         //
212         // Test pipEngine
213         //
214         outcome = (String) method.invoke(pipEngine, "testcl2");
215         assertEquals("Complete", outcome);
216
217         outcome = (String) method.invoke(pipEngine, "testcl3");
218         assertEquals("Complete", outcome);
219
220         //
221         // Shut it down
222         //
223         pipEngine.shutdown();
224
225         assertThat(method.invoke(pipEngine, "testcl1")).isNull();
226     }
227
228     private void insertEntry(String cl, String target, String outcome) {
229         //
230         // Create entry
231         //
232         OperationsHistory newEntry = new OperationsHistory();
233         newEntry.setClosedLoopName(cl);
234         newEntry.setTarget(target);
235         newEntry.setOutcome(outcome);
236         newEntry.setActor("Controller");
237         newEntry.setOperation("operationA");
238         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
239         newEntry.setEndtime(Date.from(Instant.now()));
240         newEntry.setRequestId(UUID.randomUUID().toString());
241         //
242         // Add entry
243         //
244         em.getTransaction().begin();
245         em.persist(newEntry);
246         em.getTransaction().commit();
247     }
248 }