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