2  * ============LICENSE_START=======================================================
 
   3  * Copyright (C) 2019-2021 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.assertThat;
 
  22 import static org.assertj.core.api.Assertions.assertThatCode;
 
  23 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
 
  24 import static org.junit.Assert.assertEquals;
 
  25 import static org.junit.Assert.assertNotEquals;
 
  26 import static org.mockito.ArgumentMatchers.any;
 
  27 import static org.mockito.ArgumentMatchers.eq;
 
  28 import static org.mockito.Mockito.when;
 
  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.lang.reflect.Method;
 
  38 import java.time.Instant;
 
  39 import java.util.Date;
 
  40 import java.util.Properties;
 
  41 import java.util.UUID;
 
  42 import javax.persistence.EntityManager;
 
  43 import javax.persistence.Persistence;
 
  44 import org.junit.AfterClass;
 
  45 import org.junit.Before;
 
  46 import org.junit.BeforeClass;
 
  47 import org.junit.Test;
 
  48 import org.junit.runner.RunWith;
 
  49 import org.mockito.Mock;
 
  50 import org.mockito.junit.MockitoJUnitRunner;
 
  51 import org.onap.policy.guard.OperationsHistory;
 
  52 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
 
  53 import org.slf4j.Logger;
 
  54 import org.slf4j.LoggerFactory;
 
  56 @RunWith(MockitoJUnitRunner.class)
 
  57 public class GetOperationOutcomePipTest {
 
  58     private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
 
  59     private static final String TEST_PROPERTIES = "src/test/resources/test.properties";
 
  61     private static EntityManager em;
 
  63     private Properties properties;
 
  64     private GetOperationOutcomePip pipEngine;
 
  67     private PIPRequest pipRequest;
 
  70     private PIPFinder pipFinder;
 
  73     private PIPResponse resp1;
 
  76     private Status okStatus;
 
  79      * Create an instance of our engine and also the persistence
 
  82      * @throws Exception connectivity issues
 
  85     public static void setupDatabase() throws Exception {
 
  86         LOGGER.info("Setting up PIP Testing");
 
  88         // Load our test properties to use
 
  90         Properties props = new Properties();
 
  91         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
 
  95         // Connect to in-mem db
 
  97         String persistenceUnit = GetOperationOutcomePip.ISSUER_NAME + ".persistenceunit";
 
  98         LOGGER.info("persistenceunit {}", persistenceUnit);
 
  99         em = Persistence.createEntityManagerFactory(props.getProperty(persistenceUnit), props)
 
 100             .createEntityManager();
 
 104         LOGGER.info("Configured own entity manager", em.toString());
 
 108      * Close the entity manager.
 
 111     public static void cleanup() {
 
 118      * Create an instance of our engine.
 
 120      * @throws Exception if an error occurs
 
 123     public void setupEngine() throws Exception {
 
 124         when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");
 
 128         pipEngine = new GetOperationOutcomePip();
 
 130         // Load the properties
 
 132         properties = new Properties();
 
 133         try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
 
 137         // Configure it using properties
 
 139         pipEngine.configure("issuer", properties);
 
 140         LOGGER.info("PIP configured now creating our entity manager");
 
 141         LOGGER.info("properties {}", properties);
 
 145     public void testAttributesRequired() {
 
 146         assertEquals(1, pipEngine.attributesRequired().size());
 
 150     public void testConfigure_DbException() throws Exception {
 
 151         properties.put("javax.persistence.jdbc.url", "invalid");
 
 153             pipEngine.configure("issuer", properties)
 
 154         ).doesNotThrowAnyException();
 
 158     public void testGetAttributes_NullIssuer() throws PIPException {
 
 159         when(pipRequest.getIssuer()).thenReturn(null);
 
 160         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
 
 164     public void testGetAttributes_WrongIssuer() throws PIPException {
 
 165         when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
 
 166         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
 
 170     public void testGetAttributes() throws Exception {
 
 174         when(pipRequest.getIssuer()).thenReturn(ToscaDictionary.GUARD_ISSUER_PREFIX + "clname:clfoo");
 
 175         when(pipFinder.getMatchingAttributes(any(), eq(pipEngine))).thenReturn(resp1);
 
 176         when(resp1.getStatus()).thenReturn(okStatus);
 
 177         when(okStatus.isOk()).thenReturn(true);
 
 179         assertNotEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
 
 181         pipEngine.shutdown();
 
 183         assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
 
 184             .withMessageContaining("Engine is shutdown");
 
 188     public void testGetOutcomeFromDb() throws Exception {
 
 190         // Use reflection to run getCountFromDB
 
 192         Method method = GetOperationOutcomePip.class.getDeclaredMethod("doDatabaseQuery",
 
 194         method.setAccessible(true);
 
 198         String outcome = (String) method.invoke(pipEngine, "testcl1");
 
 199         assertThat(outcome).isNull();
 
 203         insertEntry("testcl1", "testtarget1", "Started");
 
 207         outcome = (String) method.invoke(pipEngine, "testcl1");
 
 209         // outcome should be "In_Progress"
 
 211         assertEquals("In_Progress", outcome);
 
 213         // Insert more entries
 
 215         insertEntry("testcl2", "testtarget1", "Success");
 
 216         insertEntry("testcl3", "testtarget2", "Failed");
 
 220         outcome = (String) method.invoke(pipEngine, "testcl2");
 
 221         assertEquals("Complete", outcome);
 
 223         outcome = (String) method.invoke(pipEngine, "testcl3");
 
 224         assertEquals("Complete", outcome);
 
 229         pipEngine.shutdown();
 
 231         assertThat(method.invoke(pipEngine, "testcl1")).isNull();
 
 234     private void insertEntry(String cl, String target, String outcome) {
 
 238         OperationsHistory newEntry = new OperationsHistory();
 
 239         newEntry.setClosedLoopName(cl);
 
 240         newEntry.setTarget(target);
 
 241         newEntry.setOutcome(outcome);
 
 242         newEntry.setActor("Controller");
 
 243         newEntry.setOperation("operationA");
 
 244         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
 
 245         newEntry.setEndtime(Date.from(Instant.now()));
 
 246         newEntry.setRequestId(UUID.randomUUID().toString());
 
 250         em.getTransaction().begin();
 
 251         em.persist(newEntry);
 
 252         em.getTransaction().commit();