use shutdown to clear handle leak
[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-2020 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  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.pdp.xacml.application.common.operationshistory;
20
21 import static org.assertj.core.api.Assertions.assertThat;
22 import static org.assertj.core.api.Assertions.assertThatCode;
23 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotEquals;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.ArgumentMatchers.eq;
28 import static org.mockito.Mockito.when;
29
30 import com.att.research.xacml.api.Status;
31 import com.att.research.xacml.api.pip.PIPException;
32 import com.att.research.xacml.api.pip.PIPFinder;
33 import com.att.research.xacml.api.pip.PIPRequest;
34 import com.att.research.xacml.api.pip.PIPResponse;
35 import com.att.research.xacml.std.pip.StdPIPResponse;
36 import java.io.FileInputStream;
37 import java.lang.reflect.Method;
38 import java.sql.Date;
39 import java.time.Instant;
40 import java.util.Properties;
41 import java.util.UUID;
42 import javax.persistence.EntityManager;
43 import javax.persistence.Persistence;
44 import org.junit.AfterClass;
45 import org.junit.Before;
46 import org.junit.BeforeClass;
47 import org.junit.Test;
48 import org.mockito.Mock;
49 import org.mockito.MockitoAnnotations;
50 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class GetOperationOutcomePipTest {
55     private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
56     private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
57
58     private static EntityManager em;
59
60     private Properties properties;
61     private GetOperationOutcomePip pipEngine;
62
63     @Mock
64     private PIPRequest pipRequest;
65
66     @Mock
67     private PIPFinder pipFinder;
68
69     @Mock
70     private PIPResponse resp1;
71
72     @Mock
73     private Status okStatus;
74
75     /**
76      * Create an instance of our engine and also the persistence
77      * factory.
78      *
79      * @throws Exception connectivity issues
80      */
81     @BeforeClass
82     public static void setupDatabase() throws Exception {
83         LOGGER.info("Setting up PIP Testing");
84         //
85         // Load our test properties to use
86         //
87         Properties props = new Properties();
88         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
89             props.load(is);
90         }
91         //
92         // Connect to in-mem db
93         //
94         String persistenceUnit = GetOperationOutcomePip.ISSUER_NAME + ".persistenceunit";
95         LOGGER.info("persistenceunit {}", persistenceUnit);
96         em = Persistence.createEntityManagerFactory(props.getProperty(persistenceUnit), props)
97             .createEntityManager();
98         //
99         //
100         //
101         LOGGER.info("Configured own entity manager", em.toString());
102     }
103
104     /**
105      * Close the entity manager.
106      */
107     @AfterClass
108     public static void cleanup() {
109         if (em != null) {
110             em.close();
111         }
112     }
113
114     /**
115      * Create an instance of our engine.
116      *
117      * @throws Exception if an error occurs
118      */
119     @Before
120     public void setupEngine() throws Exception {
121         MockitoAnnotations.initMocks(this);
122
123         when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
124         //
125         // Create instance
126         //
127         pipEngine = new GetOperationOutcomePip();
128         //
129         // Load the properties
130         //
131         properties = new Properties();
132         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
133             properties.load(is);
134         }
135         //
136         // Configure it using properties
137         //
138         pipEngine.configure("issuer", properties);
139         LOGGER.info("PIP configured now creating our entity manager");
140         LOGGER.info("properties {}", properties);
141     }
142
143     @Test
144     public void testAttributesRequired() {
145         assertEquals(1, pipEngine.attributesRequired().size());
146     }
147
148     @Test
149     public void testConfigure_DbException() throws Exception {
150         properties.put("javax.persistence.jdbc.url", "invalid");
151         assertThatCode(() ->
152             pipEngine.configure("issuer", properties)
153         ).doesNotThrowAnyException();
154     }
155
156     @Test
157     public void testGetAttributes_NullIssuer() throws PIPException {
158         when(pipRequest.getIssuer()).thenReturn(null);
159         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
160     }
161
162     @Test
163     public void testGetAttributes_WrongIssuer() throws PIPException {
164         when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
165         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
166     }
167
168     @Test
169     public void testGetAttributes() throws Exception {
170         //
171         //
172         //
173         when(pipRequest.getIssuer()).thenReturn(ToscaDictionary.GUARD_ISSUER_PREFIX + "clname:clfoo");
174         when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1);
175         when(resp1.getStatus()).thenReturn(okStatus);
176         when(okStatus.isOk()).thenReturn(true);
177
178         assertNotEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
179
180         pipEngine.shutdown();
181
182         assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
183             .withMessageContaining("Engine is shutdown");
184     }
185
186     @Test
187     public void testGetOutcomeFromDb() throws Exception {
188         //
189         // Use reflection to run getCountFromDB
190         //
191         Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery",
192                                                                        String.class,
193                                                                        String.class);
194         method.setAccessible(true);
195         //
196         // Test pipEngine
197         //
198         String outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget1");
199         assertThat(outcome).isNull();
200         //
201         // Insert entry
202         //
203         insertEntry("testcl1", "testtarget1", "1");
204         //
205         // Test pipEngine
206         //
207         outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget1");
208         //
209         // outcome should be "1"
210         //
211         assertEquals("1", outcome);
212         //
213         // Insert more entries
214         //
215         insertEntry("testcl1", "testtarget1", "2");
216         insertEntry("testcl2", "testtarget2", "3");
217         insertEntry("testcl1", "testtarget2", "4");
218         //
219         // Test pipEngine
220         //
221         outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget1");
222         assertEquals("2", outcome);
223
224         outcome = (String) method.invoke(pipEngine, "testcl2", "testtarget2");
225         assertEquals("3", outcome);
226
227         outcome = (String) method.invoke(pipEngine, "testcl1", "testtarget2");
228         assertEquals("4", outcome);
229
230         //
231         // Shut it down
232         //
233         pipEngine.shutdown();
234
235         assertThat(method.invoke(pipEngine, "testcl1", "testtarget2")).isNull();
236     }
237
238     private void insertEntry(String cl, String target, String outcome) {
239         //
240         // Create entry
241         //
242         Dbao newEntry = new Dbao();
243         newEntry.setClosedLoopName(cl);
244         newEntry.setTarget(target);
245         newEntry.setOutcome(outcome);
246         newEntry.setActor("Controller");
247         newEntry.setOperation("operationA");
248         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
249         newEntry.setEndtime(Date.from(Instant.now()));
250         newEntry.setRequestId(UUID.randomUUID().toString());
251         //
252         // Add entry
253         //
254         em.getTransaction().begin();
255         em.persist(newEntry);
256         em.getTransaction().commit();
257     }
258 }