5ab8507224e40e5ef6d5322a57b39cd1e2bbaf1b
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2018-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
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
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=========================================================
17  */
18
19 package org.onap.policy.database.operationshistory;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertNull;
23 import static org.mockito.ArgumentMatchers.anyString;
24 import static org.mockito.Mockito.mock;
25 import static org.mockito.Mockito.when;
26
27 import com.att.research.xacml.api.Attribute;
28 import com.att.research.xacml.api.AttributeValue;
29 import com.att.research.xacml.api.XACML3;
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.sql.Date;
37 import java.time.Instant;
38 import java.util.Collection;
39 import java.util.Properties;
40 import java.util.UUID;
41 import javax.persistence.EntityManager;
42 import javax.persistence.EntityManagerFactory;
43 import javax.persistence.NoResultException;
44 import javax.persistence.Persistence;
45 import org.junit.AfterClass;
46 import org.junit.Before;
47 import org.junit.BeforeClass;
48 import org.junit.Test;
49 import org.onap.policy.database.ToscaDictionary;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class GetOperationOutcomePipTest {
54     private static final String ID = "issuer";
55     private static final String TEST_CL1 = "testcl1";
56     private static final String TEST_TARGET1 = "testtarget1";
57     private static final String TEST_TARGET2 = "testtarget2";
58     private static final String ACTOR = "Controller";
59     private static final String RECIPE = "operationA";
60     private static final String EXPECTED_EXCEPTION = "expected exception";
61     private static final String ISSUER_PREFIX = ToscaDictionary.GUARD_ISSUER_PREFIX + "-my-issuer:clname:";
62     private static final String ISSUER = ISSUER_PREFIX + TEST_CL1;
63     private static final Logger LOGGER = LoggerFactory.getLogger(GetOperationOutcomePipTest.class);
64
65     private static MyPip pipEngine;
66     private static Properties properties;
67
68     private static EntityManagerFactory emf;
69     private static EntityManager em;
70
71     private PIPRequest req;
72
73     /**
74      * Create an instance of our engine and also the persistence
75      * factory.
76      *
77      * @throws Exception connectivity issues
78      */
79     @BeforeClass
80     public static void setUpBeforeClass() throws Exception {
81         LOGGER.info("Setting up PIP Testing");
82         //
83         // Create instance
84         //
85         pipEngine = new MyPip(TEST_TARGET1);
86         //
87         // Load our test properties to use
88         //
89         properties = new Properties();
90         try (FileInputStream is = new FileInputStream("src/test/resources/test.properties")) {
91             properties.load(is);
92         }
93         //
94         // Configure it using properties
95         //
96         pipEngine.configure(ID, properties);
97         LOGGER.info("PIP configured now creating our entity manager");
98         LOGGER.info("properties {}", properties);
99         //
100         // Connect to in-mem db
101         //
102         String persistenceUnit = GetOperationOutcomePip.ISSUER_NAME + ".persistenceunit";
103         LOGGER.info("persistenceunit {}", persistenceUnit);
104         emf = Persistence.createEntityManagerFactory(properties.getProperty(persistenceUnit), properties);
105         em = emf.createEntityManager();
106         //
107         //
108         //
109         LOGGER.info("Configured own entity manager", em.toString());
110     }
111
112     @Before
113     public void setUp() {
114         req = mock(PIPRequest.class);
115         when(req.getIssuer()).thenReturn(ISSUER);
116     }
117
118     private void insertEntry(String cl, String target, String outcome) {
119         //
120         // Create entry
121         //
122         Dbao newEntry = new Dbao();
123         newEntry.setClosedLoopName(cl);
124         newEntry.setTarget(target);
125         newEntry.setOutcome(outcome);
126         newEntry.setActor(ACTOR);
127         newEntry.setOperation(RECIPE);
128         newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
129         newEntry.setEndtime(Date.from(Instant.now()));
130         newEntry.setRequestId(UUID.randomUUID().toString());
131         //
132         // Add entry
133         //
134         em.getTransaction().begin();
135         em.persist(newEntry);
136         em.getTransaction().commit();
137     }
138
139
140     @Test
141     public void testAttributesRequired() {
142         assertEquals(1, pipEngine.attributesRequired().size());
143     }
144
145     @Test
146     public void testGetAttributes_InvalidRequestInfo() throws PIPException {
147         // invalid request - null issuer
148         when(req.getIssuer()).thenReturn(null);
149         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(req, null));
150
151         /*
152          * Make a valid issuer in the request, for subsequent tests.
153          */
154         when(req.getIssuer()).thenReturn(ISSUER);
155
156         // null target
157         MyPip pip = new MyPip(null);
158         pip.configure(ID, properties);
159         assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pip.getAttributes(req, null));
160     }
161
162     @Test
163     public void testDoDatabaseQuery() throws Exception {
164         //
165         // Insert entry
166         //
167         insertEntry(TEST_CL1, TEST_TARGET1, "1");
168         //
169         // outcome should be "1"
170         //
171         assertEquals("1", getOutcome(pipEngine.getAttributes(req, null)));
172         //
173         // Insert more entries
174         //
175         insertEntry(TEST_CL1, TEST_TARGET1, "2");
176         insertEntry("testcl2", TEST_TARGET2, "3");
177         insertEntry(TEST_CL1, TEST_TARGET2, "4");
178         //
179         // Test pipEngine
180         //
181         assertEquals("2", getOutcome(TEST_CL1, TEST_TARGET1));
182
183         assertEquals("3", getOutcome("testcl2", TEST_TARGET2));
184
185         assertEquals("4", getOutcome(TEST_CL1, TEST_TARGET2));
186     }
187
188     @Test
189     public void testDoDatabaseQuery_NoResult() throws Exception {
190         MyPip pip = new MyPip(TEST_TARGET1) {
191             @Override
192             public void configure(String id, Properties properties) throws PIPException {
193                 em = mock(EntityManager.class);
194                 when(em.createQuery(anyString())).thenThrow(new NoResultException());
195             }
196         };
197         pip.configure(ID, properties);
198
199         assertNull(getOutcome(pip.getAttributes(req, null)));
200     }
201
202     @Test
203     public void testDoDatabaseQuery_EmException() throws Exception {
204         MyPip pip = new MyPip(TEST_TARGET1) {
205             @Override
206             public void configure(String id, Properties properties) throws PIPException {
207                 em = mock(EntityManager.class);
208                 when(em.createQuery(anyString())).thenThrow(new RuntimeException(EXPECTED_EXCEPTION));
209             }
210         };
211         pip.configure(ID, properties);
212
213         assertEquals(null, getOutcome(pip.getAttributes(req, null)));
214     }
215
216     private String getOutcome(String clname, String target) throws PIPException {
217         req = mock(PIPRequest.class);
218         when(req.getIssuer()).thenReturn(ISSUER_PREFIX + clname);
219
220         MyPip pip = new MyPip(target);
221         pip.configure(ID, properties);
222
223         return getOutcome(pip.getAttributes(req, null));
224     }
225
226     private String getOutcome(PIPResponse resp) {
227         Collection<Attribute> attrs = resp.getAttributes();
228         assertEquals(1, attrs.size());
229
230         Attribute attr = attrs.iterator().next();
231         assertEquals(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, attr.getCategory());
232         assertEquals(ToscaDictionary.ID_RESOURCE_GUARD_OPERATIONOUTCOME, attr.getAttributeId());
233
234         Collection<AttributeValue<?>> values = attr.getValues();
235         assertEquals(1, values.size());
236
237         AttributeValue<?> value = values.iterator().next();
238         return (String) value.getValue();
239     }
240
241     /**
242      * Close the entity manager.
243      */
244     @AfterClass
245     public static void cleanup() {
246         if (emf != null) {
247             emf.close();
248         }
249     }
250
251     private static class MyPip extends GetOperationOutcomePip {
252         private String target;
253
254         public MyPip(String target) {
255             this.target = target;
256         }
257
258         @Override
259         protected String getActor(PIPFinder pipFinder) {
260             return ACTOR;
261         }
262
263         @Override
264         protected String getRecipe(PIPFinder pipFinder) {
265             return RECIPE;
266         }
267
268         @Override
269         protected String getTarget(PIPFinder pipFinder) {
270             return target;
271         }
272     }
273 }