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