aboutsummaryrefslogtreecommitdiffstats
path: root/applications/common/src/test/java/org/onap/policy/pdp/xacml/application/common/operationshistory/CountRecentOperationsPipTest.java
blob: e564cd9636356f4546b020bc76708f864d5a714c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*-
 * ============LICENSE_START=======================================================
 * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2023 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.pdp.xacml.application.common.operationshistory;

import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import com.att.research.xacml.api.Attribute;
import com.att.research.xacml.api.AttributeValue;
import com.att.research.xacml.api.Status;
import com.att.research.xacml.api.pip.PIPException;
import com.att.research.xacml.api.pip.PIPFinder;
import com.att.research.xacml.api.pip.PIPRequest;
import com.att.research.xacml.api.pip.PIPResponse;
import com.att.research.xacml.std.pip.StdPIPResponse;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Date;
import java.time.Instant;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Queue;
import java.util.UUID;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.policy.guard.OperationsHistory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RunWith(MockitoJUnitRunner.class)
public class CountRecentOperationsPipTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(CountRecentOperationsPipTest.class);

    private static final String ACTOR = "my-actor";
    private static final String RECIPE = "my-recipe";
    private static final String TARGET = "my-target";
    private static final String TEST_PROPERTIES = "src/test/resources/test.properties";

    private static EntityManager em;

    @Mock
    private PIPRequest pipRequest;

    @Mock
    private PIPFinder pipFinder;

    @Mock
    private PIPResponse resp1;

    @Mock
    private PIPResponse resp2;

    @Mock
    private PIPResponse resp3;

    @Mock
    private Status okStatus;

    private Properties properties;
    private Queue<PIPResponse> responses;
    private Queue<String> attributes;

    private CountRecentOperationsPip pipEngine;

    /**
     * Establishes a connection to the DB and keeps it open until all tests have
     * completed.
     *
     * @throws IOException if properties cannot be loaded
     */
    @BeforeClass
    public static void setUpBeforeClass() throws IOException {
        //
        // Load our test properties to use
        //
        Properties props2 = new Properties();
        try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
            props2.load(is);
        }
        //
        // Connect to in-mem db
        //
        String persistenceUnit = CountRecentOperationsPip.ISSUER_NAME + ".persistenceunit";
        LOGGER.info("persistenceunit {}", persistenceUnit);
        em = Persistence.createEntityManagerFactory(props2.getProperty(persistenceUnit), props2).createEntityManager();
        //
        //
        //
        LOGGER.info("Configured own entity manager", em.toString());
    }

    /**
     * Close the entity manager.
     */
    @AfterClass
    public static void cleanup() {
        if (em != null) {
            em.close();
        }
    }

    /**
     * Create an instance of our engine.
     *
     * @throws Exception if an error occurs
     */
    @Before
    public void setUp() throws Exception {
        when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:hour");

        pipEngine = new MyPip();

        properties = new Properties();
        try (FileInputStream is = new FileInputStream(TEST_PROPERTIES)) {
            properties.load(is);
        }

        responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
        attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, TARGET));
    }

    @Test
    public void testAttributesRequired() {
        assertEquals(3, pipEngine.attributesRequired().size());
    }

    @Test
    public void testConfigure_DbException() throws Exception {
        properties.put("jakarta.persistence.jdbc.url", "invalid");
        assertThatCode(() ->
            pipEngine.configure("issuer", properties)
        ).doesNotThrowAnyException();
    }

    @Test
    public void testGetAttributes_NullIssuer() throws PIPException {
        when(pipRequest.getIssuer()).thenReturn(null);
        assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
    }

    @Test
    public void testGetAttributes_WrongIssuer() throws PIPException {
        when(pipRequest.getIssuer()).thenReturn("wrong-issuer");
        assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
    }

    @Test
    public void testGetAttributes_NullActor() throws PIPException {
        attributes = new LinkedList<>(Arrays.asList(null, RECIPE, TARGET));
        assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
    }

    @Test
    public void testGetAttributes_NullRecipe() throws PIPException {
        attributes = new LinkedList<>(Arrays.asList(ACTOR, null, TARGET));
        assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
    }

    @Test
    public void testGetAttributes_NullTarget() throws PIPException {
        attributes = new LinkedList<>(Arrays.asList(ACTOR, RECIPE, null));
        assertEquals(StdPIPResponse.PIP_RESPONSE_EMPTY, pipEngine.getAttributes(pipRequest, pipFinder));
    }

    @Test
    public void testShutdown() {
        pipEngine.shutdown();
        assertThatExceptionOfType(PIPException.class).isThrownBy(() -> pipEngine.getAttributes(pipRequest, pipFinder))
            .withMessageContaining("Engine is shutdown");
    }

    @Test
    public void testGetCountFromDb() throws Exception {
        //
        // Configure it using properties
        //
        pipEngine.configure("issuer", properties);
        LOGGER.info("PIP configured now creating our entity manager");
        LOGGER.info("properties {}", properties);
        //
        // create entry
        //
        OperationsHistory newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
        //
        // No entries yet
        //
        assertEquals(0, getCount(newEntry));
        //
        // Add entry
        //
        em.getTransaction().begin();
        em.persist(newEntry);
        em.getTransaction().commit();
        //
        // Directly check ground truth
        //
        Query queryCount = em.createNativeQuery("select count(*) as numops from operationshistory");
        LOGGER.info("{} entries", queryCount.getSingleResult());
        //
        // Should count 1 entry now
        //
        assertEquals(1, getCount(newEntry));
    }

    @Test
    public void testStringToChronoUnit() throws PIPException {
        // not configured yet
        OperationsHistory newEntry = createEntry("cl-foobar-1", "vnf-1", "SUCCESS");
        assertEquals(-1, getCount(newEntry));

        // now configure it
        pipEngine.configure("issuer", properties);

        String[] units = {"second", "minute", "hour", "day", "week", "month", "year"};

        for (String unit : units) {
            when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:" + unit);

            /*
             * It would be better to use assertEquals below, but the test DB doesn't
             * support week, month, or year.
             */

            // should run without throwing an exception
            getCount(newEntry);
        }

        // invalid time unit
        when(pipRequest.getIssuer()).thenReturn("urn:org:onap:xacml:guard:tw:1:invalid");
        assertEquals(-1, getCount(newEntry));
    }

    private long getCount(OperationsHistory newEntry) throws PIPException {
        responses = new LinkedList<>(Arrays.asList(resp1, resp2, resp3));
        attributes = new LinkedList<>(
                        Arrays.asList(newEntry.getActor(), newEntry.getOperation(), newEntry.getTarget()));

        PIPResponse result = pipEngine.getAttributes(pipRequest, pipFinder);

        Attribute attr = result.getAttributes().iterator().next();
        AttributeValue<?> value = attr.getValues().iterator().next();

        return ((Number) value.getValue()).longValue();
    }

    private OperationsHistory createEntry(String cl, String target, String outcome) {
        //
        // Create entry
        //
        OperationsHistory newEntry = new OperationsHistory();
        newEntry.setClosedLoopName(cl);
        newEntry.setTarget(target);
        newEntry.setOutcome(outcome);
        newEntry.setActor("Controller");
        newEntry.setOperation("operationA");
        newEntry.setStarttime(Date.from(Instant.now().minusMillis(20000)));
        newEntry.setEndtime(Date.from(Instant.now()));
        newEntry.setRequestId(UUID.randomUUID().toString());
        return newEntry;
    }

    private class MyPip extends CountRecentOperationsPip {

        @Override
        protected PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) {
            return responses.remove();
        }

        @Override
        protected String findFirstAttributeValue(PIPResponse pipResponse) {
            return attributes.remove();
        }
    }
}