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.onap.policy.guard.OperationsHistory;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public class CountRecentOperationsPipTest {
59 private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
61 private static final String ACTOR = "my-actor";
62 private static final String RECIPE = "my-recipe";
63 private static final String TARGET = "my-target";
64 private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
66 private static EntityManager em;
69 private PIPRequest pipRequest;
72 private PIPFinder pipFinder;
75 private PIPResponse resp1;
78 private PIPResponse resp2;
81 private PIPResponse resp3;
84 private Status okStatus;
86 private Properties properties;
87 private Queue<PIPResponse> responses;
88 private Queue<String> attributes;
90 private CountRecentOperationsPip pipEngine;
93 * Establishes a connection to the DB and keeps it open until all tests have
96 * @throws IOException if properties cannot be loaded
99 public static void setUpBeforeClass() throws IOException {
101 // Load our test properties to use
103 Properties props2 = new Properties();
104 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
108 // Connect to in-mem db
110 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
111 LOGGER.info("persistenceunit {}", persistenceUnit);
112 em = Persistence.createEntityManagerFactory(props2.getProperty(persistenceUnit), props2).createEntityManager();
116 LOGGER.info("Configured own entity manager", em.toString());
120 * Close the entity manager.
123 public static void cleanup() {
130 * Create an instance of our engine.
132 * @throws Exception if an error occurs
135 public void setUp() throws Exception {
136 MockitoAnnotations.initMocks(this);
138 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
140 pipEngine = new MyPip();
142 properties = new Properties();
143 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
147 when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1, resp2, resp3);
149 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
150 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, TARGET));
152 when(resp1.getStatus()).thenReturn(okStatus);
153 when(resp2.getStatus()).thenReturn(okStatus);
154 when(resp3.getStatus()).thenReturn(okStatus);
156 when(okStatus.isOk()).thenReturn(true);
160 public void testAttributesRequired() {
161 assertEquals(3, pipEngine.attributesRequired().size());
165 public void testConfigure_DbException() throws Exception {
166 properties.put("javax.persistence.jdbc.url", "invalid");
168 pipEngine.configure("issuer", properties)
169 ).doesNotThrowAnyException();
173 public void testGetAttributes_NullIssuer() throws PIPException {
174 when(pipRequest.getIssuer()).thenReturn(null);
175 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
179 public void testGetAttributes_WrongIssuer() throws PIPException {
180 when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
181 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
185 public void testGetAttributes_NullActor() throws PIPException {
186 attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
187 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
191 public void testGetAttributes_NullRecipe() throws PIPException {
192 attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
193 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
197 public void testGetAttributes_NullTarget() throws PIPException {
198 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
199 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
203 public void testShutdown() {
204 pipEngine.shutdown();
205 assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
206 .withMessageContaining("Engine is shutdown");
210 public void testGetCountFromDb() throws Exception {
212 // Configure it using properties
214 pipEngine.configure("issuer", properties);
215 LOGGER.info("PIP configured now creating our entity manager");
216 LOGGER.info("properties {}", properties);
220 OperationsHistory newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
224 assertEquals(0, getCount(newEntry));
228 em.getTransaction().begin();
229 em.persist(newEntry);
230 em.getTransaction().commit();
232 // Directly check ground truth
234 Query queryCount = em.createNativeQuery("select count(*) as numops from operationshistory").setParameter(1, 1);
235 LOGGER.info("{} entries", queryCount.getSingleResult());
237 // Should count 1 entry now
239 assertEquals(1, getCount(newEntry));
243 public void testStringToChronoUnit() throws PIPException {
244 // not configured yet
245 OperationsHistory newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
246 assertEquals(-1, getCount(newEntry));
249 pipEngine.configure("issuer", properties);
251 String[] units = {"second", "minute", "hour", "day", "week", "month", "year"};
253 for (String unit : units) {
254 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:" + unit);
257 * It would be better to use assertEquals below, but the test DB doesn't
258 * support week, month, or year.
261 // should run without throwing an exception
266 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:invalid");
267 assertEquals(-1, getCount(newEntry));
270 private long getCount(OperationsHistory newEntry) throws PIPException {
271 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
272 attributes = new LinkedList<>(
273 Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
275 PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
277 Attribute attr = result.getAttributes().iterator().next();
278 AttributeValue<?> value = attr.getValues().iterator().next();
280 return ((Number) value.getValue()).longValue();
283 private OperationsHistory createEntry(String cl, String target, String outcome) {
287 OperationsHistory newEntry = new OperationsHistory();
288 newEntry.setClosedLoopName(cl);
289 newEntry.setTarget(target);
290 newEntry.setOutcome(outcome);
291 newEntry.setActor("Controller");
292 newEntry.setOperation("operationA");
293 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
294 newEntry.setEndtime(Date.from(Instant.now()));
295 newEntry.setRequestId(UUID.randomUUID().toString());
299 private class MyPip extends CountRecentOperationsPip {
302 protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
303 return responses.remove();
307 protected String findFirstAttributeValue(PIPResponse pipResponse) {
308 return attributes.remove();