diff options
author | Jim Hahn <jrh3@att.com> | 2019-08-19 17:32:09 -0400 |
---|---|---|
committer | Jim Hahn <jrh3@att.com> | 2019-08-21 13:49:01 -0400 |
commit | cf0cd76d63f9eba680a6307dd4a708e7169cb403 (patch) | |
tree | 43e761425a3f3944ef52e07703ed5411388b07da /utils-test/src/test | |
parent | 98a4da643c738a4246cc4cc4aa9c9f21ae47cff8 (diff) |
Enhance TestTimeMulti
Enhance TestTimeMulti to support execution of tasks, whether
submitted via Timers or via Executors.
Change-Id: Ib5f216730b3b69028e9581052645370b827cd446
Issue-ID: POLICY-1968
Signed-off-by: Jim Hahn <jrh3@att.com>
Diffstat (limited to 'utils-test/src/test')
9 files changed, 1388 insertions, 69 deletions
diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java new file mode 100644 index 00000000..3e64edf3 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PeriodicItemTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +public class PeriodicItemTest { + private static final long DELAY_MS = 100L; + private static final long PERIOD_MS = 200L; + private static final Object ASSOCIATE = new Object(); + + private TestTime currentTime; + private int count; + private PeriodicItem item; + + /** + * Sets up objects, including {@link #item}. + */ + @Before + public void setUp() { + currentTime = new TestTime(); + count = 0; + item = new PeriodicItem(currentTime, ASSOCIATE, DELAY_MS, PERIOD_MS, () -> count++); + } + + @Test + public void testBumpNextTime() { + assertTrue(item.bumpNextTime()); + assertEquals(currentTime.getMillis() + PERIOD_MS, item.getNextMs()); + } + + @Test + public void testToString() { + assertNotNull(item.toString()); + } + + @Test + public void testPeriodicItem() { + assertSame(ASSOCIATE, item.getAssociate()); + assertNotNull(item.getAction()); + assertEquals(currentTime.getMillis() + DELAY_MS, item.getNextMs()); + + item.getAction().run(); + assertEquals(1, count); + + // invalid period + assertThatIllegalArgumentException() + .isThrownBy(() -> new PeriodicItem(currentTime, ASSOCIATE, DELAY_MS, 0, () -> count++)); + assertThatIllegalArgumentException() + .isThrownBy(() -> new PeriodicItem(currentTime, ASSOCIATE, DELAY_MS, -1, () -> count++)); + } + +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java new file mode 100644 index 00000000..70820c44 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledExecutorServiceTest.java @@ -0,0 +1,267 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Collections; +import java.util.concurrent.Callable; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; + +public class PseudoScheduledExecutorServiceTest { + private static final long DELAY_MS = 100L; + private static final long PERIOD_MS = 200L; + + private int ran; + private int called; + private TestTimeMulti currentTime; + private PseudoScheduledExecutorService svc; + + /** + * Sets up objects, including {@link #svc}. + */ + @Before + public void setUp() { + ran = 0; + called = 0; + currentTime = new TestTimeMulti(); + svc = new PseudoScheduledExecutorService(currentTime); + } + + @Test + public void testShutdown() { + // submit some tasks + svc.submit(new MyRun()); + svc.schedule(new MyRun(), 1L, TimeUnit.SECONDS); + + svc.shutdown(); + assertTrue(svc.isShutdown()); + + // task should have been removed + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testShutdownNow() { + // submit some tasks + svc.submit(new MyRun()); + svc.schedule(new MyRun(), 1L, TimeUnit.SECONDS); + + svc.shutdownNow(); + assertTrue(svc.isShutdown()); + + // task should have been removed + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testIsShutdown_testIsTerminated() { + assertFalse(svc.isShutdown()); + assertFalse(svc.isTerminated()); + + svc.shutdown(); + assertTrue(svc.isShutdown()); + assertTrue(svc.isTerminated()); + } + + @Test + public void testAwaitTermination() throws InterruptedException { + assertFalse(svc.awaitTermination(1L, TimeUnit.SECONDS)); + + svc.shutdown(); + assertTrue(svc.awaitTermination(1L, TimeUnit.SECONDS)); + } + + @Test + public void testSubmitCallableOfT() throws Exception { + Future<Integer> future = svc.submit(new MyCallable()); + currentTime.runOneTask(0); + + assertEquals(1, called); + assertEquals(1, future.get().intValue()); + + // nothing re-queued + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testSubmitRunnableT() throws Exception { + Future<Integer> future = svc.submit(new MyRun(), 2); + currentTime.runOneTask(0); + + assertEquals(1, ran); + assertEquals(2, future.get().intValue()); + + // nothing re-queued + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testSubmitRunnable() throws Exception { + assertNotNull(svc.submit(new MyRun())); + currentTime.runOneTask(0); + + assertEquals(1, ran); + + // nothing re-queued + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testInvokeAllCollectionOfQextendsCallableOfT() { + assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList())) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testInvokeAllCollectionOfQextendsCallableOfTLongTimeUnit() { + assertThatThrownBy(() -> svc.invokeAll(Collections.emptyList(), 1, TimeUnit.MILLISECONDS)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testInvokeAnyCollectionOfQextendsCallableOfT() { + assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList())) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testInvokeAnyCollectionOfQextendsCallableOfTLongTimeUnit() { + assertThatThrownBy(() -> svc.invokeAny(Collections.emptyList(), 1, TimeUnit.MILLISECONDS)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testExecute() throws InterruptedException { + svc.execute(new MyRun()); + currentTime.runOneTask(0); + + assertEquals(1, ran); + + // nothing re-queued + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testScheduleRunnableLongTimeUnit() throws InterruptedException { + assertNotNull(svc.schedule(new MyRun(), DELAY_MS, TimeUnit.MILLISECONDS)); + + assertEquals(DELAY_MS, oneTaskElapsedTime()); + assertEquals(1, ran); + + // verify nothing re-scheduled + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testScheduleCallableOfVLongTimeUnit() throws Exception { + ScheduledFuture<Integer> future = svc.schedule(new MyCallable(), DELAY_MS, TimeUnit.MILLISECONDS); + + assertEquals(DELAY_MS, oneTaskElapsedTime()); + assertEquals(1, called); + assertEquals(1, future.get().intValue()); + + // verify nothing re-scheduled + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testScheduleAtFixedRate() throws InterruptedException { + final ScheduledFuture<?> future = + svc.scheduleAtFixedRate(new MyRun(), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS); + + assertEquals(DELAY_MS, oneTaskElapsedTime()); + assertEquals(1, ran); + + assertEquals(PERIOD_MS, oneTaskElapsedTime()); + assertEquals(2, ran); + + assertEquals(PERIOD_MS, oneTaskElapsedTime()); + assertEquals(3, ran); + + future.cancel(false); + + // should not actually execute + assertEquals(0, oneTaskElapsedTime()); + assertEquals(3, ran); + + // verify nothing re-scheduled + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testScheduleWithFixedDelay() throws InterruptedException { + final ScheduledFuture<?> future = + svc.scheduleWithFixedDelay(new MyRun(), DELAY_MS, PERIOD_MS, TimeUnit.MILLISECONDS); + + assertEquals(DELAY_MS, oneTaskElapsedTime()); + assertEquals(1, ran); + + assertEquals(PERIOD_MS, oneTaskElapsedTime()); + assertEquals(2, ran); + + assertEquals(PERIOD_MS, oneTaskElapsedTime()); + assertEquals(3, ran); + + future.cancel(false); + + // should not actually execute + assertEquals(0, oneTaskElapsedTime()); + assertEquals(3, ran); + + // verify nothing re-scheduled + assertTrue(currentTime.isEmpty()); + } + + /** + * Runs a single task and returns its elapsed (pseudo) time. + * + * @return the elapsed time taken to run the task + * @throws InterruptedException if the thread is interrupted + */ + private long oneTaskElapsedTime() throws InterruptedException { + final long tbegin = currentTime.getMillis(); + currentTime.runOneTask(0); + return (currentTime.getMillis() - tbegin); + } + + private class MyRun implements Runnable { + @Override + public void run() { + ++ran; + } + } + + private class MyCallable implements Callable<Integer> { + @Override + public Integer call() { + return ++called; + } + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java new file mode 100644 index 00000000..e23bbd29 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoScheduledFutureTest.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +public class PseudoScheduledFutureTest { + private static final long DELAY_MS = 1000L; + + private int count; + + @Mock + private WorkItem work; + + private PseudoScheduledFuture<Integer> future; + + /** + * Sets up objects, including {@link #future}. + */ + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + + when(work.getDelay()).thenReturn(DELAY_MS); + + count = 0; + future = new PseudoScheduledFuture<>(() -> ++count, true); + future.setWorkItem(work); + } + + @Test + public void testRun() { + // verify with a periodic task - should execute twice + count = 0; + future.run(); + future.run(); + assertEquals(2, count); + + // verify with an aperiodic task - should only execute once + future = new PseudoScheduledFuture<>(() -> ++count, false); + count = 0; + future.run(); + future.run(); + assertEquals(1, count); + } + + @Test + public void testPseudoScheduledFutureRunnableTBoolean() throws Exception { + final Integer result = 100; + future = new PseudoScheduledFuture<>(() -> ++count, result, true); + assertTrue(future.isPeriodic()); + future.run(); + future.run(); + assertEquals(2, count); + + // verify with aperiodic constructor + future = new PseudoScheduledFuture<>(() -> ++count, result, false); + count = 0; + assertFalse(future.isPeriodic()); + future.run(); + future.run(); + assertEquals(1, count); + assertEquals(result, future.get()); + } + + @Test + public void testPseudoScheduledFutureCallableOfTBoolean() throws Exception { + assertTrue(future.isPeriodic()); + future.run(); + future.run(); + assertEquals(2, count); + + // verify with aperiodic constructor + future = new PseudoScheduledFuture<>(() -> ++count, false); + count = 0; + assertFalse(future.isPeriodic()); + future.run(); + assertEquals(1, future.get().intValue()); + future.run(); + assertEquals(1, count); + } + + @Test + public void testGetDelay() { + assertEquals(DELAY_MS, future.getDelay(TimeUnit.MILLISECONDS)); + assertEquals(TimeUnit.MILLISECONDS.toSeconds(DELAY_MS), future.getDelay(TimeUnit.SECONDS)); + } + + @Test + public void testCompareTo() { + Delayed delayed = mock(Delayed.class); + when(delayed.getDelay(TimeUnit.MILLISECONDS)).thenReturn(DELAY_MS + 1); + + assertTrue(future.compareTo(delayed) < 0); + } + + @Test + public void testIsPeriodic() { + assertTrue(future.isPeriodic()); + assertFalse(new PseudoScheduledFuture<>(() -> ++count, false).isPeriodic()); + } + + @Test + public void testGetWorkItem() { + assertSame(work, future.getWorkItem()); + } + + @Test + public void testSetWorkItem() { + work = mock(WorkItem.class); + future.setWorkItem(work); + assertSame(work, future.getWorkItem()); + } + +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java new file mode 100644 index 00000000..49710538 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/PseudoTimerTest.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import java.util.TimerTask; +import org.junit.Before; +import org.junit.Test; + +public class PseudoTimerTest { + private static final long DELAY_MS = 1000L; + private static final long PERIOD_MS = 2000L; + + private int count; + private TestTimeMulti currentTime; + private PseudoTimer timer; + + /** + * Sets up objects, including {@link #timer}. + */ + @Before + public void setUp() { + count = 0; + currentTime = new TestTimeMulti(); + timer = new PseudoTimer(currentTime); + } + + @Test + public void testCancel() { + // schedule two tasks + timer.scheduleAtFixedRate(new MyTask(), DELAY_MS, PERIOD_MS); + timer.schedule(new MyTask(), DELAY_MS); + + assertFalse(currentTime.isEmpty()); + + // cancel the timer + timer.cancel(); + + // invoke it again to ensure no exception + timer.cancel(); + } + + @Test + public void testPurge() { + assertEquals(0, timer.purge()); + assertEquals(0, timer.purge()); + } + + @Test + public void testScheduleTimerTaskLong() throws InterruptedException { + timer.schedule(new MyTask(), DELAY_MS); + assertFalse(currentTime.isEmpty()); + + // wait for the initial delay + currentTime.waitFor(DELAY_MS); + assertEquals(1, count); + + assertTrue(currentTime.isEmpty()); + } + + @Test + public void testScheduleTimerTaskDate() { + assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date())) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testScheduleTimerTaskLongLong() throws InterruptedException { + timer.schedule(new MyTask(), DELAY_MS, PERIOD_MS); + assertFalse(currentTime.isEmpty()); + + // wait for the initial delay plus a couple of additional periods + final long tbegin = System.currentTimeMillis(); + currentTime.waitFor(DELAY_MS + PERIOD_MS * 2); + assertTrue(count >= 3); + + assertFalse(currentTime.isEmpty()); + + // this thread should not have blocked while waiting + assertTrue(System.currentTimeMillis() < tbegin + 2000); + } + + @Test + public void testScheduleTimerTaskDateLong() { + assertThatThrownBy(() -> timer.schedule(new MyTask(), new Date(), 1L)) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + public void testScheduleAtFixedRateTimerTaskLongLong() throws InterruptedException { + timer.scheduleAtFixedRate(new MyTask(), DELAY_MS, PERIOD_MS); + assertFalse(currentTime.isEmpty()); + + // wait for the initial delay plus a couple of additional periods + final long tbegin = System.currentTimeMillis(); + currentTime.waitFor(DELAY_MS + PERIOD_MS * 2); + assertTrue(count >= 3); + + assertFalse(currentTime.isEmpty()); + + // this thread should not have blocked while waiting + assertTrue(System.currentTimeMillis() < tbegin + 2000); + } + + @Test + public void testScheduleAtFixedRateTimerTaskDateLong() { + assertThatThrownBy(() -> timer.scheduleAtFixedRate(new MyTask(), new Date(), 1L)) + .isInstanceOf(UnsupportedOperationException.class); + } + + private class MyTask extends TimerTask { + @Override + public void run() { + ++count; + } + + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java new file mode 100644 index 00000000..e7bbd018 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/RunnableItemTest.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.FutureTask; +import org.junit.Before; +import org.junit.Test; + +public class RunnableItemTest { + private static final long DELAY_MS = 100L; + private static final Object ASSOCIATE = new Object(); + + private TestTime currentTime; + private int count; + private RunnableItem item; + + /** + * Sets up objects, including {@link #item}. + */ + @Before + public void setUp() { + currentTime = new TestTime(); + count = 0; + item = new RunnableItem(currentTime, ASSOCIATE, DELAY_MS, () -> count++); + } + + @Test + public void testWasCancelled() { + assertFalse(item.wasCancelled()); + + FutureTask<Object> future = new FutureTask<>(() -> count++); + item = new RunnableItem(currentTime, ASSOCIATE, DELAY_MS, future); + assertFalse(item.wasCancelled()); + + future.cancel(true); + assertTrue(item.wasCancelled()); + } + + @Test + public void testIsAssociatedWith() { + assertFalse(item.isAssociatedWith(this)); + assertTrue(item.isAssociatedWith(ASSOCIATE)); + } + + @Test + public void testFire() { + item.fire(); + assertEquals(1, count); + + // verify that fire() works even if the action throws an exception + new RunnableItem(currentTime, ASSOCIATE, DELAY_MS, () -> { + throw new RuntimeException("expected exception"); + }).fire(); + } + + @Test + public void testRunnableItem_testGetAssociate_testGetAction() { + assertSame(ASSOCIATE, item.getAssociate()); + assertNotNull(item.getAction()); + assertEquals(currentTime.getMillis() + DELAY_MS, item.getNextMs()); + + item.getAction().run(); + assertEquals(1, count); + + // verify that work item is set when constructed with a future + PseudoScheduledFuture<Integer> schedFuture = new PseudoScheduledFuture<>(() -> count + 1, false); + item = new RunnableItem(currentTime, ASSOCIATE, DELAY_MS, schedFuture); + assertSame(item, schedFuture.getWorkItem()); + + // verify that work item is NOT set when constructed with a plain future + item = new RunnableItem(currentTime, ASSOCIATE, DELAY_MS, new FutureTask<>(() -> count + 1)); + } + + @Test + public void testToString() { + assertNotNull(item.toString()); + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java new file mode 100644 index 00000000..dbd54781 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/SleepItemTest.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; + +public class SleepItemTest { + private static final int SLEEP_MS = 250; + private static final long MAX_WAIT_MS = 5000L; + + private TestTime currentTime; + private Thread thread; + private CountDownLatch started; + private CountDownLatch finished; + private volatile InterruptedException threadEx; + private SleepItem item; + + /** + * Sets up objects, including {@link #item}. + */ + @Before + public void setUp() { + currentTime = new TestTime(); + started = new CountDownLatch(1); + finished = new CountDownLatch(1); + + thread = new Thread() { + @Override + public void run() { + try { + started.countDown(); + item.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + threadEx = e; + } + + finished.countDown(); + } + }; + thread.setDaemon(true); + + item = new SleepItem(currentTime, SLEEP_MS, thread); + } + + @Test + public void testInterrupt() throws InterruptedException { + startThread(); + + item.interrupt(); + + assertTrue(finished.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS)); + assertNotNull(threadEx); + } + + @Test + public void testFire_testAwait() throws InterruptedException { + startThread(); + + // verify that it hasn't finished yet + thread.join(250); + assertTrue(finished.getCount() > 0); + + // now fire it and verify that it finishes + item.fire(); + assertTrue(finished.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS)); + + assertNull(threadEx); + } + + @Test + public void testSleepItem() { + assertEquals(currentTime.getMillis() + SLEEP_MS, item.getNextMs()); + } + + @Test + public void testToString() { + assertNotNull(item.toString()); + } + + + private void startThread() throws InterruptedException { + thread.start(); + started.await(); + } +} diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java index f17235a2..8b6501a7 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java @@ -1,6 +1,6 @@ -/* +/*- * ============LICENSE_START======================================================= - * Common Utils-Test + * ONAP * ================================================================================ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -20,109 +20,478 @@ package org.onap.policy.common.utils.time; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +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.ArrayList; -import java.util.List; -import java.util.concurrent.Semaphore; +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; -/** - * Class to test TestTimeMulti. - */ 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 static final int NTHREADS = 10; - private static final int NTIMES = 100; - private static final long WAIT_SEC = 5L; - private static final long MIN_SLEEP_MS = 5L; + private TestTimeMulti multi; - private TestTimeMulti ttm; - private Semaphore done; + @Before + public void setUp() { + multi = new TestTimeMulti(); + } @Test - public void test() throws Exception { - ttm = new TestTimeMulti(NTHREADS); - done = new Semaphore(0); + public void testSleep() throws InterruptedException { + // negative sleep time + final long tbegin = multi.getMillis(); + MyThread thread = new MyThread(-5); + thread.start(); - final long tbeg = ttm.getMillis(); + // should complete without creating a work item + assertTrue(thread.await()); + assertNull(thread.ex); - // create threads - List<MyThread> threads = new ArrayList<>(NTHREADS); - for (int x = 0; x < NTHREADS; ++x) { - threads.add(new MyThread(x + MIN_SLEEP_MS)); - } + // 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); + } - // launch threads - for (MyThread thr : threads) { - thr.start(); + @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; } - // wait for each one to complete - for (MyThread thr : threads) { - assertTrue("complete " + thr.getSleepMs(), done.tryAcquire(WAIT_SEC, TimeUnit.SECONDS)); - ttm.threadCompleted(); + public MyWorkItem(boolean canceled) { + super(multi, DELAY_MS); + this.fired = new AtomicBoolean(); + this.canceled = canceled; } - // check results - for (MyThread thr : threads) { - assertEquals("time " + thr.getSleepMs(), thr.texpected, thr.tactual); + @Override + public void fire() { + fired.set(true); } - assertTrue(ttm.getMillis() >= tbeg + NTIMES * MIN_SLEEP_MS); + @Override + public boolean isAssociatedWith(Object associate) { + return (fired == associate); + } - // something in the queue, but no threads remain -> exception - assertThatIllegalStateException().isThrownBy(() -> ttm.threadCompleted()); + @Override + public boolean wasCancelled() { + return canceled; + } } private class MyThread extends Thread { - private final long sleepMs; - - private volatile long texpected; - private volatile long tactual; + private final CountDownLatch finished = new CountDownLatch(1); + private InterruptedException ex = null; public MyThread(long sleepMs) { this.sleepMs = sleepMs; - this.setDaemon(true); } - public long getSleepMs() { - return sleepMs; + public boolean await() throws InterruptedException { + return finished.await(MAX_WAIT_MS, TimeUnit.MILLISECONDS); } @Override public void run() { try { - for (int x = 0; x < NTIMES; ++x) { - // negative sleep should have no effect - texpected = ttm.getMillis(); - ttm.sleep(-1); - if ((tactual = ttm.getMillis()) != texpected) { - break; - } - - texpected = ttm.getMillis() + sleepMs; - ttm.sleep(sleepMs); - - if ((tactual = ttm.getMillis()) != texpected) { - break; - } - - if ((tactual = ttm.getDate().getTime()) != texpected) { - break; - } - } - - } catch (InterruptedException expected) { + multi.sleep(sleepMs); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); + ex = e; } - done.release(); + finished.countDown(); } } } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java index 3e7897e9..d2cf6783 100644 --- a/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * Common Utils-Test * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * 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. @@ -62,6 +62,11 @@ public class TestTimeTest { // ensure that no real time has elapsed assertTrue(System.currentTimeMillis() < treal + tsleep / 2); + + // negative sleep should not modify the time + tcur = tm.getMillis(); + tm.sleep(-1); + assertEquals(tcur, tm.getMillis()); } } diff --git a/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java new file mode 100644 index 00000000..4e6f92b5 --- /dev/null +++ b/utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 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.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import org.junit.Before; +import org.junit.Test; + +public class WorkItemTest { + private TestTime currentTime; + private WorkItem item; + + @Before + public void setUp() { + currentTime = new TestTime(); + item = new WorkItem(currentTime, 0); + } + + @Test + public void testWorkItem() { + assertThatIllegalArgumentException().isThrownBy(() -> new WorkItem(currentTime, -1)); + + // should not throw an exception + new WorkItem(currentTime, 1); + } + + @Test + public void testGetDelay() { + assertEquals(1, item.getDelay()); + } + + @Test + public void testWasCancelled() { + assertFalse(item.wasCancelled()); + } + + @Test + public void testBumpNextTime() { + assertFalse(item.bumpNextTime()); + } + + @Test + public void testBumpNextTimeLong() { + assertThatIllegalArgumentException().isThrownBy(() -> item.bumpNextTime(-1)); + + long cur = currentTime.getMillis(); + item.bumpNextTime(5); + assertEquals(cur + 5, item.getNextMs()); + + item.bumpNextTime(0); + + // should bump the time by at least 1 + assertEquals(cur + 1, item.getNextMs()); + } + + @Test + public void testInterrupt() { + item.interrupt(); + assertFalse(Thread.interrupted()); + } + + @Test + public void testIsAssociatedWith() { + assertFalse(item.isAssociatedWith(this)); + } + + @Test + public void testFire() { + // ensure no exception is thrown + item.fire(); + } + + @Test + public void testGetNextMs() { + assertEquals(currentTime.getMillis() + 1, item.getNextMs()); + assertEquals(currentTime.getMillis() + 10, new WorkItem(currentTime, 10).getNextMs()); + } + +} |