2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 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.junit.Assert.assertEquals;
22 import static org.mockito.Matchers.any;
23 import static org.mockito.Matchers.eq;
24 import static org.mockito.Mockito.when;
26 import com.att.research.xacml.api.Attribute;
27 import com.att.research.xacml.api.AttributeValue;
28 import com.att.research.xacml.api.Status;
29 import com.att.research.xacml.api.pip.PIPException;
30 import com.att.research.xacml.api.pip.PIPFinder;
31 import com.att.research.xacml.api.pip.PIPRequest;
32 import com.att.research.xacml.api.pip.PIPResponse;
33 import com.att.research.xacml.std.pip.StdPIPResponse;
34 import java.io.FileInputStream;
35 import java.io.IOException;
37 import java.time.Instant;
38 import java.util.Arrays;
39 import java.util.LinkedList;
40 import java.util.Properties;
41 import java.util.Queue;
42 import java.util.UUID;
43 import javax.persistence.EntityManager;
44 import javax.persistence.Persistence;
45 import javax.persistence.Query;
46 import org.junit.AfterClass;
47 import org.junit.Before;
48 import org.junit.BeforeClass;
49 import org.junit.Test;
50 import org.mockito.Mock;
51 import org.mockito.MockitoAnnotations;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 public class CountRecentOperationsPipTest {
56 private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);
58 private static final String ACTOR = "my-actor";
59 private static final String RECIPE = "my-recipe";
60 private static final String TARGET = "my-target";
61 private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
63 private static EntityManager em;
66 private PIPRequest pipRequest;
69 private PIPFinder pipFinder;
72 private PIPResponse resp1;
75 private PIPResponse resp2;
78 private PIPResponse resp3;
81 private Status okStatus;
83 private Properties properties;
84 private Queue<PIPResponse> responses;
85 private Queue<String> attributes;
87 private CountRecentOperationsPip pipEngine;
90 * Establishes a connection to the DB and keeps it open until all tests have
93 * @throws IOException if properties cannot be loaded
96 public static void setUpBeforeClass() throws IOException {
98 // Load our test properties to use
100 Properties props2 = new Properties();
101 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
105 // Connect to in-mem db
107 String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
108 LOGGER.info("persistenceunit {}", persistenceUnit);
109 em = Persistence.createEntityManagerFactory(props2.getProperty(persistenceUnit), props2).createEntityManager();
113 LOGGER.info("Configured own entity manager", em.toString());
117 * Create an instance of our engine.
119 * @throws Exception if an error occurs
122 public void setUp() throws Exception {
123 MockitoAnnotations.initMocks(this);
125 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
127 pipEngine = new MyPip();
129 properties = new Properties();
130 try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
134 when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1, resp2, resp3);
136 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
137 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, TARGET));
139 when(resp1.getStatus()).thenReturn(okStatus);
140 when(resp2.getStatus()).thenReturn(okStatus);
141 when(resp3.getStatus()).thenReturn(okStatus);
143 when(okStatus.isOk()).thenReturn(true);
146 private Dbao createEntry(String cl, String target, String outcome) {
150 Dbao newEntry = new Dbao();
151 newEntry.setClosedLoopName(cl);
152 newEntry.setTarget(target);
153 newEntry.setOutcome(outcome);
154 newEntry.setActor("Controller");
155 newEntry.setOperation("operationA");
156 newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
157 newEntry.setEndtime(Date.from(Instant.now()));
158 newEntry.setRequestId(UUID.randomUUID().toString());
163 public void testAttributesRequired() {
164 assertEquals(3, pipEngine.attributesRequired().size());
168 public void testConfigure_DbException() throws Exception {
169 properties.put("javax.persistence.jdbc.url", "invalid");
170 pipEngine.configure("issuer", properties);
174 public void testGetAttributes_NullIssuer() throws PIPException {
175 when(pipRequest.getIssuer()).thenReturn(null);
176 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
180 public void testGetAttributes_WrongIssuer() throws PIPException {
181 when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
182 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
186 public void testGetAttributes_NullActor() throws PIPException {
187 attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
188 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
192 public void testGetAttributes_NullRecipe() throws PIPException {
193 attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
194 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
198 public void testGetAttributes_NullTarget() throws PIPException {
199 attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
200 assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
204 public void testGetCountFromDb() throws Exception {
206 // Configure it using properties
208 pipEngine.configure("issuer", properties);
209 LOGGER.info("PIP configured now creating our entity manager");
210 LOGGER.info("properties {}", properties);
214 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
218 assertEquals(0, getCount(newEntry));
222 em.getTransaction().begin();
223 em.persist(newEntry);
224 em.getTransaction().commit();
226 // Directly check ground truth
228 Query queryCount = em.createNativeQuery("select count(*) as numops from operationshistory").setParameter(1, 1);
229 LOGGER.info("{} entries", queryCount.getSingleResult());
231 // Should count 1 entry now
233 assertEquals(1, getCount(newEntry));
236 private long getCount(Dbao newEntry) throws PIPException {
237 responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
238 attributes = new LinkedList<>(
239 Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));
241 PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);
243 Attribute attr = result.getAttributes().iterator().next();
244 AttributeValue<?> value = attr.getValues().iterator().next();
246 return ((Number) value.getValue()).longValue();
250 public void testStringToChronoUnit() throws PIPException {
251 // not configured yet
252 Dbao newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
253 assertEquals(-1, getCount(newEntry));
256 pipEngine.configure("issuer", properties);
258 String[] units = {"second", "minute", "hour", "day", "week", "month", "year"};
260 for (String unit : units) {
261 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:" + unit);
264 * It would be better to use assertEquals below, but the test DB doesn't
265 * support week, month, or year.
268 // should run without throwing an exception
273 when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:invalid");
274 assertEquals(-1, getCount(newEntry));
278 * Close the entity manager.
281 public static void cleanup() {
287 private class MyPip extends CountRecentOperationsPip {
290 protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
291 return responses.remove();
295 protected String findFirstAttributeValue(PIPResponse pipResponse) {
296 return attributes.remove();