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
9 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
19 package org.onap.policy.pdp.xacml.application.common.operationshistory;
21 import static org.assertj.core.api.Assertions.assertThatCode;
22 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
23 import static org.junit.Assert.assertEquals;
24 import static org.mockito.ArgumentMatchers.any;
25 import static org.mockito.ArgumentMatchers.eq;
26 import static org.mockito.Mockito.when;
28 import com.att.research.xacml.api.Attribute;
29 import com.att.research.xacml.api.AttributeValue;
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.io.IOException;
39 import java.time.Instant;
40 import java.util.Arrays;
41 import java.util.LinkedList;
42 import java.util.Properties;
43 import java.util.Queue;
44 import java.util.UUID;
45 import javax.persistence.EntityManager;
46 import javax.persistence.Persistence;
47 import javax.persistence.Query;
48 import org.junit.AfterClass;
49 import org.junit.Before;
50 import org.junit.BeforeClass;
51 import org.junit.Test;
52 import org.mockito.Mock;
53 import org.mockito.MockitoAnnotations;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 public class CountRecentOperationsPipTest {
58 private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
60 private static final String ACTOR = "my-actor";
61 private static final String RECIPE = "my-recipe";
62 private static final String TARGET = "my-target";
63 private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
65 private static EntityManager em;
68 private PIPRequest pipRequest;
71 private PIPFinder pipFinder;
74 private PIPResponse resp1;
77 private PIPResponse resp2;
80 private PIPResponse resp3;
83 private Status okStatus;
85 private Properties properties;
86 private Queue<PIPResponse> responses;
87 private Queue<String> attributes;
89 private CountRecentOperationsPip pipEngine;
92 * Establishes a connection to the DB and keeps it open until all tests have
95 * @throws IOException if properties cannot be loaded
98 public static void setUpBeforeClass() throws IOException {
100 // Load our test properties to use
102 Properties props2 = new Properties();
103 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
107 // Connect to in-mem db
109 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
110 LOGGER.info("persistenceunit {}", persistenceUnit);
111 em = Persistence.createEntityManagerFactory(props2.getProperty(persistenceUnit), props2).createEntityManager();
115 LOGGER.info("Configured own entity manager", em.toString());
119 * Close the entity manager.
122 public static void cleanup() {
129 * Create an instance of our engine.
131 * @throws Exception if an error occurs
134 public void setUp() throws Exception {
135 MockitoAnnotations.initMocks(this);
137 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
139 pipEngine = new MyPip();
141 properties = new Properties();
142 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
146 when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1, resp2, resp3);
148 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
149 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, TARGET));
151 when(resp1.getStatus()).thenReturn(okStatus);
152 when(resp2.getStatus()).thenReturn(okStatus);
153 when(resp3.getStatus()).thenReturn(okStatus);
155 when(okStatus.isOk()).thenReturn(true);
159 public void testAttributesRequired() {
160 assertEquals(3, pipEngine.attributesRequired().size());
164 public void testConfigure_DbException() throws Exception {
165 properties.put("javax.persistence.jdbc.url", "invalid");
167 pipEngine.configure("issuer", properties)
168 ).doesNotThrowAnyException();
172 public void testGetAttributes_NullIssuer() throws PIPException {
173 when(pipRequest.getIssuer()).thenReturn(null);
174 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
178 public void testGetAttributes_WrongIssuer() throws PIPException {
179 when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
180 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
184 public void testGetAttributes_NullActor() throws PIPException {
185 attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
186 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
190 public void testGetAttributes_NullRecipe() throws PIPException {
191 attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
192 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
196 public void testGetAttributes_NullTarget() throws PIPException {
197 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
198 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
202 public void testShutdown() {
203 pipEngine.shutdown();
204 assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
205 .withMessageContaining("Engine is shutdown");
209 public void testGetCountFromDb() throws Exception {
211 // Configure it using properties
213 pipEngine.configure("issuer", properties);
214 LOGGER.info("PIP configured now creating our entity manager");
215 LOGGER.info("properties {}", properties);
219 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
223 assertEquals(0, getCount(newEntry));
227 em.getTransaction().begin();
228 em.persist(newEntry);
229 em.getTransaction().commit();
231 // Directly check ground truth
233 Query queryCount = em.createNativeQuery("select count(*) as numops from operationshistory").setParameter(1, 1);
234 LOGGER.info("{} entries", queryCount.getSingleResult());
236 // Should count 1 entry now
238 assertEquals(1, getCount(newEntry));
242 public void testStringToChronoUnit() throws PIPException {
243 // not configured yet
244 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
245 assertEquals(-1, getCount(newEntry));
248 pipEngine.configure("issuer", properties);
250 String[] units = {"second", "minute", "hour", "day", "week", "month", "year"};
252 for (String unit : units) {
253 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:" + unit);
256 * It would be better to use assertEquals below, but the test DB doesn't
257 * support week, month, or year.
260 // should run without throwing an exception
265 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:invalid");
266 assertEquals(-1, getCount(newEntry));
269 private long getCount(Dbao newEntry) throws PIPException {
270 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
271 attributes = new LinkedList<>(
272 Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
274 PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
276 Attribute attr = result.getAttributes().iterator().next();
277 AttributeValue<?> value = attr.getValues().iterator().next();
279 return ((Number) value.getValue()).longValue();
282 private Dbao createEntry(String cl, String target, String outcome) {
286 Dbao newEntry = new Dbao();
287 newEntry.setClosedLoopName(cl);
288 newEntry.setTarget(target);
289 newEntry.setOutcome(outcome);
290 newEntry.setActor("Controller");
291 newEntry.setOperation("operationA");
292 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
293 newEntry.setEndtime(Date.from(Instant.now()));
294 newEntry.setRequestId(UUID.randomUUID().toString());
298 private class MyPip extends CountRecentOperationsPip {
301 protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
302 return responses.remove();
306 protected String findFirstAttributeValue(PIPResponse pipResponse) {
307 return attributes.remove();