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.junit.Assert.assertEquals;
23 import static org.mockito.ArgumentMatchers.any;
24 import static org.mockito.ArgumentMatchers.eq;
25 import static org.mockito.Mockito.when;
27 import com.att.research.xacml.api.Attribute;
28 import com.att.research.xacml.api.AttributeValue;
29 import com.att.research.xacml.api.Status;
30 import com.att.research.xacml.api.pip.PIPException;
31 import com.att.research.xacml.api.pip.PIPFinder;
32 import com.att.research.xacml.api.pip.PIPRequest;
33 import com.att.research.xacml.api.pip.PIPResponse;
34 import com.att.research.xacml.std.pip.StdPIPResponse;
35 import java.io.FileInputStream;
36 import java.io.IOException;
38 import java.time.Instant;
39 import java.util.Arrays;
40 import java.util.LinkedList;
41 import java.util.Properties;
42 import java.util.Queue;
43 import java.util.UUID;
44 import javax.persistence.EntityManager;
45 import javax.persistence.Persistence;
46 import javax.persistence.Query;
47 import org.junit.AfterClass;
48 import org.junit.Before;
49 import org.junit.BeforeClass;
50 import org.junit.Test;
51 import org.mockito.Mock;
52 import org.mockito.MockitoAnnotations;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public class CountRecentOperationsPipTest {
57 private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
59 private static final String ACTOR = "my-actor";
60 private static final String RECIPE = "my-recipe";
61 private static final String TARGET = "my-target";
62 private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
64 private static EntityManager em;
67 private PIPRequest pipRequest;
70 private PIPFinder pipFinder;
73 private PIPResponse resp1;
76 private PIPResponse resp2;
79 private PIPResponse resp3;
82 private Status okStatus;
84 private Properties properties;
85 private Queue<PIPResponse> responses;
86 private Queue<String> attributes;
88 private CountRecentOperationsPip pipEngine;
91 * Establishes a connection to the DB and keeps it open until all tests have
94 * @throws IOException if properties cannot be loaded
97 public static void setUpBeforeClass() throws IOException {
99 // Load our test properties to use
101 Properties props2 = new Properties();
102 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
106 // Connect to in-mem db
108 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
109 LOGGER.info("persistenceunit {}", persistenceUnit);
110 em = Persistence.createEntityManagerFactory(props2.getProperty(persistenceUnit), props2).createEntityManager();
114 LOGGER.info("Configured own entity manager", em.toString());
118 * Close the entity manager.
121 public static void cleanup() {
128 * Create an instance of our engine.
130 * @throws Exception if an error occurs
133 public void setUp() throws Exception {
134 MockitoAnnotations.initMocks(this);
136 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
138 pipEngine = new MyPip();
140 properties = new Properties();
141 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
145 when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1, resp2, resp3);
147 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
148 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, TARGET));
150 when(resp1.getStatus()).thenReturn(okStatus);
151 when(resp2.getStatus()).thenReturn(okStatus);
152 when(resp3.getStatus()).thenReturn(okStatus);
154 when(okStatus.isOk()).thenReturn(true);
158 public void testAttributesRequired() {
159 assertEquals(3, pipEngine.attributesRequired().size());
163 public void testConfigure_DbException() throws Exception {
164 properties.put("javax.persistence.jdbc.url", "invalid");
166 pipEngine.configure("issuer", properties)
167 ).doesNotThrowAnyException();
171 public void testGetAttributes_NullIssuer() throws PIPException {
172 when(pipRequest.getIssuer()).thenReturn(null);
173 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
177 public void testGetAttributes_WrongIssuer() throws PIPException {
178 when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
179 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
183 public void testGetAttributes_NullActor() throws PIPException {
184 attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
185 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
189 public void testGetAttributes_NullRecipe() throws PIPException {
190 attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
191 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
195 public void testGetAttributes_NullTarget() throws PIPException {
196 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
197 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
201 public void testGetCountFromDb() throws Exception {
203 // Configure it using properties
205 pipEngine.configure("issuer", properties);
206 LOGGER.info("PIP configured now creating our entity manager");
207 LOGGER.info("properties {}", properties);
211 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
215 assertEquals(0, getCount(newEntry));
219 em.getTransaction().begin();
220 em.persist(newEntry);
221 em.getTransaction().commit();
223 // Directly check ground truth
225 Query queryCount = em.createNativeQuery("select count(*) as numops from operationshistory").setParameter(1, 1);
226 LOGGER.info("{} entries", queryCount.getSingleResult());
228 // Should count 1 entry now
230 assertEquals(1, getCount(newEntry));
234 public void testStringToChronoUnit() throws PIPException {
235 // not configured yet
236 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
237 assertEquals(-1, getCount(newEntry));
240 pipEngine.configure("issuer", properties);
242 String[] units = {"second", "minute", "hour", "day", "week", "month", "year"};
244 for (String unit : units) {
245 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:" + unit);
248 * It would be better to use assertEquals below, but the test DB doesn't
249 * support week, month, or year.
252 // should run without throwing an exception
257 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:invalid");
258 assertEquals(-1, getCount(newEntry));
261 private long getCount(Dbao newEntry) throws PIPException {
262 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
263 attributes = new LinkedList<>(
264 Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
266 PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
268 Attribute attr = result.getAttributes().iterator().next();
269 AttributeValue<?> value = attr.getValues().iterator().next();
271 return ((Number) value.getValue()).longValue();
274 private Dbao createEntry(String cl, String target, String outcome) {
278 Dbao newEntry = new Dbao();
279 newEntry.setClosedLoopName(cl);
280 newEntry.setTarget(target);
281 newEntry.setOutcome(outcome);
282 newEntry.setActor("Controller");
283 newEntry.setOperation("operationA");
284 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
285 newEntry.setEndtime(Date.from(Instant.now()));
286 newEntry.setRequestId(UUID.randomUUID().toString());
290 private class MyPip extends CountRecentOperationsPip {
293 protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
294 return responses.remove();
298 protected String findFirstAttributeValue(PIPResponse pipResponse) {
299 return attributes.remove();