aboutsummaryrefslogtreecommitdiffstats
path: root/policy-management/src/test/java/org/onap/policy/drools/system/internal/FeatureLockImplTest.java
blob: 2ba7cde9a0d4feaee31cd40385112b402548dc71 (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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * 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.drools.system.internal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.policy.drools.core.DroolsRunnable;
import org.onap.policy.drools.core.PolicySession;
import org.onap.policy.drools.core.lock.LockCallback;
import org.onap.policy.drools.core.lock.LockState;
import org.onap.policy.drools.system.PolicyEngineConstants;
import org.springframework.test.util.ReflectionTestUtils;

@RunWith(MockitoJUnitRunner.class)
public class FeatureLockImplTest {
    private static final String POLICY_ENGINE_EXECUTOR_FIELD = "executorService";
    private static final String OWNER_KEY = "my key";
    private static final String RESOURCE = "my resource";
    private static final int HOLD_SEC = 100;
    private static final int HOLD_SEC2 = 120;

    private static ScheduledExecutorService saveExec;

    @Mock
    private ScheduledExecutorService exsvc;

    @Mock
    private LockCallback callback;

    /**
     * Saves static fields and configures the location of the property files.
     */
    @BeforeClass
    public static void setUpBeforeClass() {
        saveExec = (ScheduledExecutorService) ReflectionTestUtils.getField(PolicyEngineConstants.getManager(),
            POLICY_ENGINE_EXECUTOR_FIELD);
    }

    /**
     * Restores static fields.
     */
    @AfterClass
    public static void tearDownAfterClass() {
        ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, saveExec);
    }

    /**
     * Initializes the mocks and creates a feature that uses {@link #exsvc} to execute
     * tasks.
     */
    @Before
    public void setUp() {
        ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, exsvc);
    }

    @Test
    public void testNoArgs() {
        MyLock lock = new MyLock();
        assertNull(lock.getResourceId());
        assertNull(lock.getOwnerKey());
        assertNull(lock.getCallback());
        assertEquals(0, lock.getHoldSec());
    }

    @Test
    public void testFeatureLockImpl() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        assertTrue(lock.isWaiting());
        assertEquals(RESOURCE, lock.getResourceId());
        assertEquals(OWNER_KEY, lock.getOwnerKey());
        assertSame(callback, lock.getCallback());
        assertEquals(HOLD_SEC, lock.getHoldSec());
    }

    @Test
    public void testSerializable() throws Exception {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        lock = roundTrip(lock);

        assertTrue(lock.isWaiting());

        assertEquals(RESOURCE, lock.getResourceId());
        assertEquals(OWNER_KEY, lock.getOwnerKey());
        assertNull(lock.getCallback());
        assertEquals(HOLD_SEC, lock.getHoldSec());
    }

    @Test
    public void testGrant() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        lock.grant();

        assertTrue(lock.isActive());
        assertEquals(1, lock.nupdates);

        invokeCallback(1);
        verify(callback).lockAvailable(any());
        verify(callback, never()).lockUnavailable(any());
    }

    /**
     * Tests grant() when the lock is already unavailable.
     */
    @Test
    public void testGrantUnavailable() {
        MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        lock.setState(LockState.UNAVAILABLE);
        lock.grant();

        assertTrue(lock.isUnavailable());
        assertEquals(0, lock.nupdates);

        verify(exsvc, never()).execute(any());
    }

    @Test
    public void testDeny() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        lock.deny("my reason");

        assertTrue(lock.isUnavailable());

        invokeCallback(1);
        verify(callback, never()).lockAvailable(any());
        verify(callback).lockUnavailable(any());
    }

    /**
     * Tests doNotify() when a session exists.
     */
    @Test
    public void testDoNotifySession() {
        PolicySession session = mock(PolicySession.class);

        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback) {
            private static final long serialVersionUID = 1L;

            @Override
            protected PolicySession getSession() {
                return session;
            }
        };

        lock.grant();

        assertTrue(lock.isActive());
        assertEquals(1, lock.nupdates);

        verify(exsvc, never()).execute(any());

        ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class);
        verify(session).insertDrools(captor.capture());

        DroolsRunnable runner = (DroolsRunnable) captor.getValue();
        runner.run();

        verify(callback).lockAvailable(any());
        verify(callback, never()).lockUnavailable(any());
    }

    /**
     * Tests doNotify() when there is no session.
     */
    @Test
    public void testDoNotifyNoSession() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        lock.grant();

        assertTrue(lock.isActive());
        assertEquals(1, lock.nupdates);

        invokeCallback(1);
        verify(callback).lockAvailable(any());
        verify(callback, never()).lockUnavailable(any());
    }

    @Test
    public void testFreeAllowed() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        assertTrue(lock.freeAllowed());
    }

    /**
     * Tests freeAllowed() when the lock is unavailable.
     */
    @Test
    public void testFreeAllowedUnavailable() {
        MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback);
        assertFalse(lock.freeAllowed());
        assertTrue(lock.isUnavailable());
    }

    /**
     * Tests that free() works on a serialized lock with a new feature.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFreeAllowedSerialized() throws Exception {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        lock = roundTrip(lock);
        assertTrue(lock.freeAllowed());
    }

    /**
     * Tests free() on a serialized lock without a feature.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testFreeAllowedNoFeature() throws Exception {
        MyLock lock = new MyLockNoFeature(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        lock = roundTrip(lock);
        assertFalse(lock.freeAllowed());
        assertTrue(lock.isUnavailable());
    }

    @Test
    public void testExtendAllowed() {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        LockCallback scallback = mock(LockCallback.class);
        assertTrue(lock.extendAllowed(HOLD_SEC2, scallback));
        assertTrue(lock.isWaiting());
        assertEquals(HOLD_SEC2, lock.getHoldSec());
        assertSame(scallback, lock.getCallback());

        verify(exsvc, never()).execute(any());

        // invalid arguments

        // @formatter:off
        assertThatIllegalArgumentException().isThrownBy(
            () -> new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback)
                            .extendAllowed(-1, callback))
            .withMessageContaining("holdSec");
        // @formatter:on
    }

    /**
     * Tests extendAllowed() when the lock is unavailable.
     */
    @Test
    public void testExtendAllowedUnavailable() {
        MyLock lock = new MyLock(LockState.UNAVAILABLE, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        LockCallback scallback = mock(LockCallback.class);
        assertFalse(lock.extendAllowed(HOLD_SEC2, scallback));
        assertTrue(lock.isUnavailable());
        assertEquals(HOLD_SEC2, lock.getHoldSec());
        assertSame(scallback, lock.getCallback());

        invokeCallback(1);
        verify(scallback, never()).lockAvailable(lock);
        verify(scallback).lockUnavailable(lock);
    }

    /**
     * Tests that extendAllowed() works on a serialized lock with a new feature.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testExtendAllowedSerialized() throws Exception {
        MyLock lock = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        lock = roundTrip(lock);

        LockCallback scallback = mock(LockCallback.class);
        assertTrue(lock.extendAllowed(HOLD_SEC2, scallback));
        assertTrue(lock.isWaiting());
        assertEquals(HOLD_SEC2, lock.getHoldSec());
        assertSame(scallback, lock.getCallback());

        verify(exsvc, never()).execute(any());
    }

    /**
     * Tests extendAllowed() on a serialized lock without a feature.
     *
     * @throws Exception if an error occurs
     */
    @Test
    public void testExtendAllowedNoFeature() throws Exception {
        MyLock lock = new MyLockNoFeature(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        lock = roundTrip(lock);

        LockCallback scallback = mock(LockCallback.class);
        assertFalse(lock.extendAllowed(HOLD_SEC2, scallback));
        assertTrue(lock.isUnavailable());
        assertEquals(HOLD_SEC2, lock.getHoldSec());
        assertSame(scallback, lock.getCallback());

        invokeCallback(1);
        verify(scallback, never()).lockAvailable(lock);
        verify(scallback).lockUnavailable(lock);
    }

    @Test
    public void testGetSession() {
        MyLockStdSession lock = new MyLockStdSession(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback);

        // this should invoke the real policy session without throwing an exception
        assertThatCode(() -> lock.grant()).doesNotThrowAnyException();
    }

    @Test
    public void testToString() {
        String text = new MyLock(LockState.WAITING, RESOURCE, OWNER_KEY, HOLD_SEC, callback).toString();
        assertNotNull(text);
        assertThat(text).contains("LockImpl");
    }

    private MyLock roundTrip(MyLock lock) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(lock);
        }

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        try (ObjectInputStream ois = new ObjectInputStream(bais)) {
            return (MyLock) ois.readObject();
        }
    }

    /**
     * Invokes the last call-back in the work queue.
     *
     * @param nexpected number of call-backs expected in the work queue
     */
    private void invokeCallback(int nexpected) {
        ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
        verify(exsvc, times(nexpected)).execute(captor.capture());

        if (nexpected > 0) {
            captor.getAllValues().get(nexpected - 1).run();
        }
    }

    /**
     * Lock that inherits the normal getSession() method.
     */
    public static class MyLockStdSession extends FeatureLockImpl {
        private static final long serialVersionUID = 1L;
        protected int nupdates = 0;

        public MyLockStdSession() {
            super();
        }

        public MyLockStdSession(LockState state, String resourceId, String ownerKey, int holdSec,
            LockCallback callback) {
            super(state, resourceId, ownerKey, holdSec, callback);
        }

        @Override
        protected void updateGrant() {
            super.updateGrant();
            ++nupdates;
        }

        @Override
        public boolean free() {
            return false;
        }

        @Override
        public void extend(int holdSec, LockCallback callback) {
            // do nothing
        }

        @Override
        protected boolean addToFeature() {
            return true;
        }
    }

    public static class MyLock extends MyLockStdSession {
        private static final long serialVersionUID = 1L;

        public MyLock() {
            super();
        }

        public MyLock(LockState state, String resourceId, String ownerKey, int holdSec, LockCallback callback) {
            super(state, resourceId, ownerKey, holdSec, callback);
        }

        @Override
        protected PolicySession getSession() {
            return null;
        }
    }

    public static class MyLockNoFeature extends MyLock {
        private static final long serialVersionUID = 1L;

        public MyLockNoFeature() {
            super();
        }

        public MyLockNoFeature(LockState state, String resourceId, String ownerKey, int holdSec,
            LockCallback callback) {
            super(state, resourceId, ownerKey, holdSec, callback);
        }

        @Override
        protected boolean addToFeature() {
            return false;
        }
    }
}