aboutsummaryrefslogtreecommitdiffstats
path: root/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java
blob: 8b6501a7e36f058ddcd70200b0cba7955f5596cf (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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.common.utils.time;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.awaitility.Awaitility.await;
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.assertTrue;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.Before;
import org.junit.Test;

public class TestTimeMultiTest {
    private static final long SHORT_WAIT_MS = 100L;
    private static final long DELAY_MS = 500L;
    private static final long MAX_WAIT_MS = 5000L;

    private TestTimeMulti multi;

    @Before
    public void setUp() {
        multi = new TestTimeMulti();
    }

    @Test
    public void testSleep() throws InterruptedException {
        // negative sleep time
        final long tbegin = multi.getMillis();
        MyThread thread = new MyThread(-5);
        thread.start();

        // should complete without creating a work item
        assertTrue(thread.await());
        assertNull(thread.ex);

        // time should not have changed
        assertEquals(tbegin, multi.getMillis());


        // positive sleep time
        thread = new MyThread(DELAY_MS);
        thread.start();

        // must execute the SleepItem
        multi.runOneTask(MAX_WAIT_MS);

        assertTrue(multi.isEmpty());
        assertTrue(thread.await());
        assertNull(thread.ex);

        // time SHOULD HAVE changed
        assertEquals(tbegin + DELAY_MS, multi.getMillis());
    }

    @Test
    public void testTestTimeMulti() {
        assertTrue(multi.getMaxWaitMs() > 0);
    }

    @Test
    public void testTestTimeMultiLong() {
        assertEquals(200, new TestTimeMulti(200).getMaxWaitMs());
    }

    @Test
    public void testIsEmpty_testQueueLength() throws InterruptedException {
        assertTrue(multi.isEmpty());

        // queue up two items
        multi.enqueue(new WorkItem(multi, DELAY_MS));
        assertFalse(multi.isEmpty());
        assertEquals(1, multi.queueLength());

        multi.enqueue(new WorkItem(multi, DELAY_MS));
        assertEquals(2, multi.queueLength());

        // run one - should not be empty yet
        multi.runOneTask(0);
        assertFalse(multi.isEmpty());
        assertEquals(1, multi.queueLength());

        // run the other - should be empty now
        multi.runOneTask(0);
        assertTrue(multi.isEmpty());
        assertEquals(0, multi.queueLength());
    }

    @Test
    public void testDestroy() throws InterruptedException {
        // this won't interrupt
        multi.enqueue(new WorkItem(multi, DELAY_MS));

        // these will interrupt
        AtomicBoolean interrupted1 = new AtomicBoolean(false);
        multi.enqueue(new WorkItem(multi, DELAY_MS) {
            @Override
            public void interrupt() {
                interrupted1.set(true);
            }
        });

        AtomicBoolean interrupted2 = new AtomicBoolean(false);
        multi.enqueue(new WorkItem(multi, DELAY_MS) {
            @Override
            public void interrupt() {
                interrupted2.set(true);
            }
        });

        multi.destroy();
        assertTrue(multi.isEmpty());

        assertTrue(interrupted1.get());
        assertTrue(interrupted2.get());
    }

    @Test
    public void testRunOneTask() throws InterruptedException {
        // nothing in the queue yet
        assertFalse(multi.runOneTask(0));

        // put something in the queue
        multi.enqueue(new WorkItem(multi, DELAY_MS));

        final long tbegin = multi.getMillis();
        assertTrue(multi.runOneTask(MAX_WAIT_MS));

        assertEquals(tbegin + DELAY_MS, multi.getMillis());

        // nothing in the queue now
        assertFalse(multi.runOneTask(0));

        // time doesn't change
        assertEquals(tbegin + DELAY_MS, multi.getMillis());
    }

    @Test
    public void testWaitFor() throws InterruptedException {
        // queue up a couple of items
        multi.enqueue(new WorkItem(multi, DELAY_MS));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 3));

        final long realBegin = System.currentTimeMillis();
        final long tbegin = multi.getMillis();
        multi.waitFor(DELAY_MS * 2 - 1);
        assertEquals(tbegin + DELAY_MS * 2, multi.getMillis());

        // minimal real time should have elapsed
        assertTrue(System.currentTimeMillis() < realBegin + TestTimeMulti.DEFAULT_MAX_WAIT_MS);
    }

    @Test
    public void testWaitFor_EmptyQueue() throws InterruptedException {
        multi = new TestTimeMulti(SHORT_WAIT_MS);

        final long realBegin = System.currentTimeMillis();
        final long tbegin = multi.getMillis();

        multi.waitFor(2);

        assertEquals(tbegin + 2, multi.getMillis());
        assertTrue(System.currentTimeMillis() >= realBegin + SHORT_WAIT_MS);
    }

    @Test
    public void testWaitUntilCallable() throws InterruptedException {
        multi.enqueue(new WorkItem(multi, DELAY_MS));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 3));

        final long tbegin = multi.getMillis();
        AtomicInteger count = new AtomicInteger(0);
        multi.waitUntil(() -> count.incrementAndGet() == 3);

        assertEquals(tbegin + DELAY_MS * 2, multi.getMillis());

        // should still be one item left in the queue
        assertEquals(1, multi.queueLength());
        assertEquals(3, count.get());
    }

    @Test
    public void testWaitUntilCallable_InterruptEx() throws InterruptedException {
        multi = new TestTimeMulti();

        Callable<Boolean> callable = () -> {
            throw new InterruptedException("expected exception");
        };

        LinkedBlockingQueue<Error> errors = new LinkedBlockingQueue<>();

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    multi.waitUntil(callable);
                } catch (Error ex) {
                    errors.add(ex);
                }
            }
        };

        thread.start();

        Error ex = errors.poll(MAX_WAIT_MS, TimeUnit.MILLISECONDS);
        assertNotNull(ex);
        assertEquals("interrupted while waiting for condition: expected exception", ex.getMessage());
    }

    @Test
    public void testWaitUntilCallable_ConditionThrowsEx() throws InterruptedException {
        multi = new TestTimeMulti();

        Callable<Boolean> callable = () -> {
            throw new IllegalStateException("expected exception");
        };

        final long realBegin = System.currentTimeMillis();
        assertThatThrownBy(() -> multi.waitUntil(callable))
                        .hasMessage("condition evaluator threw an exception: expected exception");

        assertTrue(System.currentTimeMillis() < realBegin + TestTimeMulti.DEFAULT_MAX_WAIT_MS);
    }

    @Test
    public void testWaitUntilCallable_NeverSatisfied() throws InterruptedException {
        multi = new TestTimeMulti(SHORT_WAIT_MS);

        final long realBegin = System.currentTimeMillis();
        assertThatThrownBy(() -> multi.waitUntil(() -> false))
                        .hasMessage(TestTimeMulti.NEVER_SATISFIED);
        assertTrue(System.currentTimeMillis() >= realBegin + SHORT_WAIT_MS);
    }

    @Test
    public void testWaitUntilLongTimeUnitCallable() throws InterruptedException {
        multi.enqueue(new WorkItem(multi, DELAY_MS));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 3));

        final long tbegin = multi.getMillis();
        AtomicInteger count = new AtomicInteger(0);
        multi.waitUntil(DELAY_MS * 4, TimeUnit.MILLISECONDS, () -> count.incrementAndGet() == 3);

        assertEquals(tbegin + DELAY_MS * 2, multi.getMillis());

        // should still be one item left in the queue
        assertEquals(1, multi.queueLength());
        assertEquals(3, count.get());
    }

    @Test
    public void testWaitUntilLongTimeUnitCallable_PseudoTimeExpires() throws InterruptedException {
        multi.enqueue(new WorkItem(multi, DELAY_MS));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
        multi.enqueue(new WorkItem(multi, DELAY_MS * 3));

        final long tbegin = multi.getMillis();
        assertThatThrownBy(() -> multi.waitUntil(DELAY_MS * 2 - 1, TimeUnit.MILLISECONDS, () -> false))
                        .hasMessage(TestTimeMulti.NEVER_SATISFIED);
        assertEquals(tbegin + DELAY_MS * 2, multi.getMillis());
    }

    @Test
    public void testRunItem() throws InterruptedException {
        AtomicBoolean fired = new AtomicBoolean(false);
        multi.enqueue(new MyWorkItem(fired));

        assertTrue(multi.runOneTask(1));

        // should no longer be in the queue
        assertTrue(multi.isEmpty());

        // should have been fired
        assertTrue(fired.get());
    }

    @Test
    public void testRunItem_Rescheduled() throws InterruptedException {
        AtomicBoolean fired = new AtomicBoolean(false);

        multi.enqueue(new MyWorkItem(fired) {
            @Override
            public boolean bumpNextTime() {
                bumpNextTime(DELAY_MS);
                return true;
            }
        });

        assertTrue(multi.runOneTask(1));

        // should still be in the queue
        assertEquals(1, multi.queueLength());

        // should have been fired
        assertTrue(fired.get());
    }

    @Test
    public void testRunItem_Canceled() throws InterruptedException {
        AtomicBoolean fired = new AtomicBoolean(false);

        multi.enqueue(new MyWorkItem(fired) {
            @Override
            public boolean wasCancelled() {
                return true;
            }

            @Override
            public boolean bumpNextTime() {
                return true;
            }
        });

        final long tbegin = multi.getMillis();
        assertTrue(multi.runOneTask(1));

        // time should be unchanged
        assertEquals(tbegin, multi.getMillis());

        assertTrue(multi.isEmpty());

        // should not have been fired
        assertFalse(fired.get());
    }

    @Test
    public void testEnqueue() throws InterruptedException {
        CountDownLatch started = new CountDownLatch(1);
        CountDownLatch finished = new CountDownLatch(1);
        AtomicReference<InterruptedException> ex = new AtomicReference<>();

        Thread thread = new Thread() {
            @Override
            public void run() {
                started.countDown();

                try {
                    multi.runOneTask(DELAY_MS * 3);
                } catch (InterruptedException e) {
                    ex.set(e);
                }

                finished.countDown();
            }
        };

        thread.start();

        // wait for thread to start
        started.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS);

        // wait for it to block on the lock
        await().atMost(MAX_WAIT_MS, TimeUnit.MILLISECONDS).until(() -> thread.getState() == Thread.State.TIMED_WAITING);

        // add an item to the queue - should trigger the thread to continue
        multi.enqueue(new WorkItem(multi, DELAY_MS));

        assertTrue(finished.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS));
        assertNull(ex.get());
    }

    @Test
    public void testCancelItems() throws InterruptedException {
        AtomicBoolean fired1 = new AtomicBoolean();
        multi.enqueue(new MyWorkItem(fired1));

        AtomicBoolean fired2 = new AtomicBoolean();
        multi.enqueue(new MyWorkItem(fired2));
        multi.enqueue(new MyWorkItem(fired2));

        AtomicBoolean fired3 = new AtomicBoolean();
        multi.enqueue(new MyWorkItem(fired3));

        // cancel some
        multi.cancelItems(fired2);

        // should have only canceled two of them
        assertEquals(2, multi.queueLength());

        // fire both
        multi.runOneTask(0);
        multi.runOneTask(0);

        // these should have fired
        assertTrue(fired1.get());
        assertTrue(fired3.get());

        // these should NOT have fired
        assertFalse(fired2.get());
    }

    @Test
    public void testPurgeItems() throws InterruptedException {
        AtomicBoolean fired = new AtomicBoolean();

        // queue up two that are canceled, one that is not
        multi.enqueue(new MyWorkItem(true));
        multi.enqueue(new MyWorkItem(fired));
        multi.enqueue(new MyWorkItem(true));

        multi.purgeItems();

        assertEquals(1, multi.queueLength());

        multi.runOneTask(0);
        assertTrue(fired.get());
    }

    private class MyWorkItem extends WorkItem {
        private final AtomicBoolean fired;
        private final boolean canceled;

        public MyWorkItem(AtomicBoolean fired) {
            super(multi, DELAY_MS);
            this.fired = fired;
            this.canceled = false;
        }

        public MyWorkItem(boolean canceled) {
            super(multi, DELAY_MS);
            this.fired = new AtomicBoolean();
            this.canceled = canceled;
        }

        @Override
        public void fire() {
            fired.set(true);
        }

        @Override
        public boolean isAssociatedWith(Object associate) {
            return (fired == associate);
        }

        @Override
        public boolean wasCancelled() {
            return canceled;
        }
    }

    private class MyThread extends Thread {
        private final long sleepMs;
        private final CountDownLatch finished = new CountDownLatch(1);
        private InterruptedException ex = null;

        public MyThread(long sleepMs) {
            this.sleepMs = sleepMs;
            this.setDaemon(true);
        }

        public boolean await() throws InterruptedException {
            return finished.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS);
        }

        @Override
        public void run() {
            try {
                multi.sleep(sleepMs);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                ex = e;
            }

            finished.countDown();
        }
    }
}