diff options
author | CNlucius <lukai1@huawei.com> | 2016-09-13 11:40:12 +0800 |
---|---|---|
committer | CNlucius <lukai1@huawei.com> | 2016-09-13 11:41:53 +0800 |
commit | b731e2f1dd0972409b136aebc7b463dd72c9cfad (patch) | |
tree | 5107d7d80c19ad8076c2c97c2b5ef8d1cf3ab903 /framework/src/onos/utils/misc/src/test/java/org/onlab/util | |
parent | ee93993458266114c29271a481ef9ce7ce621b2a (diff) |
ONOSFW-171
O/S-SFC-ONOS scenario documentation
Change-Id: I51ae1cf736ea24ab6680f8edca1b2bf5dd598365
Signed-off-by: CNlucius <lukai1@huawei.com>
Diffstat (limited to 'framework/src/onos/utils/misc/src/test/java/org/onlab/util')
18 files changed, 0 insertions, 2380 deletions
diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/AbstractAccumulatorTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/AbstractAccumulatorTest.java deleted file mode 100644 index 8a409c3d..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/AbstractAccumulatorTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; - -import java.util.List; -import java.util.stream.IntStream; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.onlab.junit.TestTools.assertAfter; - -/** - * Tests the operation of the accumulator. - */ -public class AbstractAccumulatorTest { - - - private final ManuallyAdvancingTimer timer = new ManuallyAdvancingTimer(true); - - private static final int LONG_REAL_TIME_DELAY = 30; - private static final int SHORT_REAL_TIME_DELAY = 5; - - - @Test - public void basics() throws Exception { - TestAccumulator accumulator = new TestAccumulator(); - assertEquals("incorrect timer", timer, accumulator.timer()); - assertEquals("incorrect max events", 5, accumulator.maxItems()); - assertEquals("incorrect max ms", 100, accumulator.maxBatchMillis()); - assertEquals("incorrect idle ms", 70, accumulator.maxIdleMillis()); - } - - @Test - public void eventTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.add(new TestItem("a")); - accumulator.add(new TestItem("b")); - accumulator.add(new TestItem("c")); - accumulator.add(new TestItem("d")); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("e")); - timer.advanceTimeMillis(20, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "abcde", accumulator.batch); - } - - @Test - public void timeTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.add(new TestItem("a")); - timer.advanceTimeMillis(30, SHORT_REAL_TIME_DELAY); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("b")); - timer.advanceTimeMillis(30, SHORT_REAL_TIME_DELAY); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("c")); - timer.advanceTimeMillis(30, SHORT_REAL_TIME_DELAY); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("d")); - timer.advanceTimeMillis(10, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "abcd", accumulator.batch); - } - - @Test - public void idleTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.add(new TestItem("a")); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("b")); - timer.advanceTimeMillis(70, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "ab", accumulator.batch); - } - - @Test - public void readyIdleTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.ready = false; - accumulator.add(new TestItem("a")); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("b")); - timer.advanceTimeMillis(80, SHORT_REAL_TIME_DELAY); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.ready = true; - timer.advanceTimeMillis(80, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "ab", accumulator.batch); - } - - @Test - public void readyLongTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.ready = false; - timer.advanceTimeMillis(120, SHORT_REAL_TIME_DELAY); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.add(new TestItem("a")); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.ready = true; - timer.advanceTimeMillis(120, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "a", accumulator.batch); - } - - @Test - public void readyMaxTrigger() { - TestAccumulator accumulator = new TestAccumulator(); - accumulator.ready = false; - accumulator.add(new TestItem("a")); - accumulator.add(new TestItem("b")); - accumulator.add(new TestItem("c")); - accumulator.add(new TestItem("d")); - accumulator.add(new TestItem("e")); - accumulator.add(new TestItem("f")); - assertTrue("should not have fired yet", accumulator.batch.isEmpty()); - accumulator.ready = true; - accumulator.add(new TestItem("g")); - timer.advanceTimeMillis(10, LONG_REAL_TIME_DELAY); - assertFalse("should have fired", accumulator.batch.isEmpty()); - assertEquals("incorrect batch", "abcdefg", accumulator.batch); - } - - @Test - public void stormTest() { - TestAccumulator accumulator = new TestAccumulator(); - IntStream.range(0, 1000).forEach(i -> accumulator.add(new TestItem("#" + i))); - timer.advanceTimeMillis(1); - assertAfter(100, () -> assertEquals("wrong item count", 1000, accumulator.itemCount)); - assertEquals("wrong batch count", 200, accumulator.batchCount); - } - - private class TestItem { - private final String s; - - public TestItem(String s) { - this.s = s; - } - } - - private class TestAccumulator extends AbstractAccumulator<TestItem> { - - String batch = ""; - boolean ready = true; - int batchCount = 0; - int itemCount = 0; - - protected TestAccumulator() { - super(timer, 5, 100, 70); - } - - @Override - public void processItems(List<TestItem> items) { - batchCount++; - itemCount += items.size(); - for (TestItem item : items) { - batch += item.s; - } - } - - @Override - public boolean isReady() { - return ready; - } - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BandwidthTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BandwidthTest.java deleted file mode 100644 index a3baf06c..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BandwidthTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import com.google.common.testing.EqualsTester; -import org.junit.Test; - -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; - -/** - * Unit tests for Bandwidth. - */ -public class BandwidthTest { - - private final Bandwidth small = Bandwidth.kbps(100.0); - private final Bandwidth large = Bandwidth.mbps(1.0); - - /** - * Tests equality of Bandwidth instances. - */ - @Test - public void testEquality() { - new EqualsTester() - .addEqualityGroup(Bandwidth.kbps(1000.0), Bandwidth.kbps(1000.0), Bandwidth.mbps(1.0)) - .addEqualityGroup(Bandwidth.gbps(1.0)) - .testEquals(); - } - - /** - * Tests add operation of two Bandwidths. - */ - @Test - public void testAdd() { - Bandwidth expected = Bandwidth.kbps(1100.0); - - assertThat(small.add(large), is(expected)); - } - - /** - * Tests subtract operation of two Bandwidths. - */ - @Test - public void testSubtract() { - Bandwidth expected = Bandwidth.kbps(900.0); - - assertThat(large.subtract(small), is(expected)); - } - - /** - * Tests if the first object is less than the second object. - */ - @Test - public void testLessThan() { - assertThat(small, is(lessThan(large))); - assertThat(small.isLessThan(large), is(true)); - } - - /** - * Tests if the first object is greater than the second object. - */ - @Test - public void testGreaterThan() { - assertThat(large, is(greaterThan(small))); - assertThat(large.isGreaterThan(small), is(true)); - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BlockingBooleanTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BlockingBooleanTest.java deleted file mode 100644 index 2d8b688e..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BlockingBooleanTest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.apache.commons.lang.mutable.MutableBoolean; -import org.junit.Ignore; -import org.junit.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.*; - -/** - * Tests of the BlockingBoolean utility. - */ -public class BlockingBooleanTest { - - private static final int TIMEOUT = 100; //ms - - @Test - public void basics() { - BlockingBoolean b = new BlockingBoolean(false); - assertEquals(false, b.get()); - b.set(true); - assertEquals(true, b.get()); - b.set(true); - assertEquals(true, b.get()); - b.set(false); - assertEquals(false, b.get()); - } - - private void waitChange(boolean value, int numThreads) { - BlockingBoolean b = new BlockingBoolean(!value); - - CountDownLatch latch = new CountDownLatch(numThreads); - ExecutorService exec = Executors.newFixedThreadPool(numThreads); - for (int i = 0; i < numThreads; i++) { - exec.submit(() -> { - try { - b.await(value); - latch.countDown(); - } catch (InterruptedException e) { - fail(); - } - }); - } - b.set(value); - try { - assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - exec.shutdown(); - } - - @Test - public void waitTrueChange() { - waitChange(true, 4); - } - - @Test - public void waitFalseChange() { - waitChange(false, 4); - } - - @Test - public void waitSame() { - BlockingBoolean b = new BlockingBoolean(true); - - CountDownLatch latch = new CountDownLatch(1); - ExecutorService exec = Executors.newSingleThreadExecutor(); - exec.submit(() -> { - try { - b.await(true); - latch.countDown(); - } catch (InterruptedException e) { - fail(); - } - }); - try { - assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - exec.shutdown(); - } - - @Test - public void someWait() { - BlockingBoolean b = new BlockingBoolean(false); - - int numThreads = 4; - CountDownLatch sameLatch = new CountDownLatch(numThreads / 2); - CountDownLatch waitLatch = new CountDownLatch(numThreads / 2); - - ExecutorService exec = Executors.newFixedThreadPool(numThreads); - for (int i = 0; i < numThreads; i++) { - final boolean value = (i % 2 == 1); - exec.submit(() -> { - try { - b.await(value); - if (value) { - waitLatch.countDown(); - } else { - sameLatch.countDown(); - } - } catch (InterruptedException e) { - fail(); - } - }); - } - try { - assertTrue(sameLatch.await(TIMEOUT, TimeUnit.MILLISECONDS)); - assertEquals(waitLatch.getCount(), numThreads / 2); - } catch (InterruptedException e) { - fail(); - } - b.set(true); - try { - assertTrue(waitLatch.await(TIMEOUT, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - exec.shutdown(); - } - - @Test - public void waitTimeout() { - BlockingBoolean b = new BlockingBoolean(true); - - CountDownLatch latch = new CountDownLatch(1); - ExecutorService exec = Executors.newSingleThreadExecutor(); - exec.submit(() -> { - try { - if (!b.await(false, 1, TimeUnit.NANOSECONDS)) { - latch.countDown(); - } else { - fail(); - } - } catch (InterruptedException e) { - fail(); - } - }); - try { - assertTrue(latch.await(TIMEOUT, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - exec.shutdown(); - - } - - @Test - @Ignore - public void samePerf() { - int iters = 10_000; - - BlockingBoolean b1 = new BlockingBoolean(false); - long t1 = System.nanoTime(); - for (int i = 0; i < iters; i++) { - b1.set(false); - } - long t2 = System.nanoTime(); - MutableBoolean b2 = new MutableBoolean(false); - for (int i = 0; i < iters; i++) { - b2.setValue(false); - } - long t3 = System.nanoTime(); - System.out.println((t2 - t1) + " " + (t3 - t2) + " " + ((t2 - t1) <= (t3 - t2))); - } - - @Test - @Ignore - public void changePerf() { - int iters = 10_000; - - BlockingBoolean b1 = new BlockingBoolean(false); - boolean v = true; - long t1 = System.nanoTime(); - for (int i = 0; i < iters; i++) { - b1.set(v); - v = !v; - } - long t2 = System.nanoTime(); - MutableBoolean b2 = new MutableBoolean(false); - for (int i = 0; i < iters; i++) { - b2.setValue(v); - v = !v; - } - long t3 = System.nanoTime(); - System.out.println((t2 - t1) + " " + (t3 - t2) + " " + ((t2 - t1) <= (t3 - t2))); - } - -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BoundedThreadPoolTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BoundedThreadPoolTest.java deleted file mode 100644 index c6132de1..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/BoundedThreadPoolTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import com.google.common.collect.Lists; -import org.junit.Test; - -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.junit.Assert.*; -import static org.onlab.util.BoundedThreadPool.*; -import static org.onlab.util.Tools.namedThreads; - -/** - * Test of BoundedThreadPool. - */ -public final class BoundedThreadPoolTest { - - @Test - public void simpleJob() { - final Thread myThread = Thread.currentThread(); - final AtomicBoolean sameThread = new AtomicBoolean(true); - final CountDownLatch latch = new CountDownLatch(1); - - BoundedThreadPool exec = newSingleThreadExecutor(namedThreads("test")); - exec.submit(() -> { - sameThread.set(myThread.equals(Thread.currentThread())); - latch.countDown(); - }); - - try { - assertTrue("Job not run", latch.await(100, TimeUnit.MILLISECONDS)); - assertFalse("Runnable used caller thread", sameThread.get()); - } catch (InterruptedException e) { - fail(); - } finally { - exec.shutdown(); - } - - // TODO perhaps move to tearDown - try { - assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - fail(); - } - } - - private List<CountDownLatch> fillExecutor(BoundedThreadPool exec) { - int numThreads = exec.getMaximumPoolSize(); - List<CountDownLatch> latches = Lists.newArrayList(); - final CountDownLatch started = new CountDownLatch(numThreads); - List<CountDownLatch> finished = Lists.newArrayList(); - - // seed the executor's threads - for (int i = 0; i < numThreads; i++) { - final CountDownLatch latch = new CountDownLatch(1); - final CountDownLatch fin = new CountDownLatch(1); - latches.add(latch); - finished.add(fin); - exec.submit(() -> { - try { - started.countDown(); - latch.await(); - fin.countDown(); - } catch (InterruptedException e) { - fail(); - } - }); - } - try { - assertTrue(started.await(100, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - // fill the queue - CountDownLatch startedBlocked = new CountDownLatch(1); - while (exec.getQueue().remainingCapacity() > 0) { - final CountDownLatch latch = new CountDownLatch(1); - latches.add(latch); - exec.submit(() -> { - try { - startedBlocked.countDown(); - latch.await(); - } catch (InterruptedException e) { - fail(); - } - }); - } - - latches.remove(0).countDown(); // release one of the executors - // ... we need to do this because load is recomputed when jobs are taken - // Note: For this to work, 1 / numThreads must be less than the load threshold (0.2) - - // verify that the old job has terminated - try { - assertTrue("Job didn't finish", - finished.remove(0).await(100, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - - // verify that a previously blocked thread has started - try { - assertTrue(startedBlocked.await(10, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(); - } - - - // add another job to fill the queue - final CountDownLatch latch = new CountDownLatch(1); - latches.add(latch); - exec.submit(() -> { - try { - latch.await(); - } catch (InterruptedException e) { - fail(); - } - }); - assertEquals(exec.getQueue().size(), maxQueueSize); - - return latches; - } - - @Test - public void releaseOneThread() { - maxQueueSize = 10; - BoundedThreadPool exec = newFixedThreadPool(4, namedThreads("test")); - List<CountDownLatch> latches = fillExecutor(exec); - - CountDownLatch myLatch = new CountDownLatch(1); - ExecutorService myExec = Executors.newSingleThreadExecutor(); - Future<Thread> expected = myExec.submit(Thread::currentThread); - - assertEquals(exec.getQueue().size(), maxQueueSize); - long start = System.nanoTime(); - Future<Thread> actual = myExec.submit(() -> { - return exec.submit(() -> { - myLatch.countDown(); - return Thread.currentThread(); - }).get(); - }); - - try { - assertFalse("Thread should still be blocked", - myLatch.await(10, TimeUnit.MILLISECONDS)); - - latches.remove(0).countDown(); // release the first thread - assertFalse("Thread should still be blocked", - myLatch.await(10, TimeUnit.MILLISECONDS)); - latches.remove(0).countDown(); // release the second thread - - assertTrue("Thread should be unblocked", - myLatch.await(10, TimeUnit.MILLISECONDS)); - long delta = System.nanoTime() - start; - double load = exec.getQueue().size() / (double) maxQueueSize; - assertTrue("Load is greater than threshold", load <= 0.8); - assertTrue("Load is less than threshold", load >= 0.6); - assertEquals("Work done on wrong thread", expected.get(), actual.get()); - assertTrue("Took more than one second", delta < Math.pow(10, 9)); - } catch (InterruptedException | ExecutionException e) { - fail(); - } finally { - latches.forEach(CountDownLatch::countDown); - exec.shutdown(); - } - - // TODO perhaps move to tearDown - try { - assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - fail(); - } - - } - - @Test - public void highLoadTimeout() { - maxQueueSize = 10; - BoundedThreadPool exec = newFixedThreadPool(2, namedThreads("test")); - List<CountDownLatch> latches = fillExecutor(exec); - - // true if the job is executed and it is done on the test thread - final AtomicBoolean sameThread = new AtomicBoolean(false); - final Thread myThread = Thread.currentThread(); - long start = System.nanoTime(); - exec.submit(() -> { - sameThread.set(myThread.equals(Thread.currentThread())); - }); - - long delta = System.nanoTime() - start; - assertEquals(maxQueueSize, exec.getQueue().size()); - assertTrue("Work done on wrong thread (or didn't happen)", sameThread.get()); - assertTrue("Took less than one second. Actual: " + delta / 1_000_000.0 + "ms", - delta > Math.pow(10, 9)); - assertTrue("Took more than two seconds", delta < 2 * Math.pow(10, 9)); - latches.forEach(CountDownLatch::countDown); - exec.shutdown(); - - // TODO perhaps move to tearDown - try { - assertTrue(exec.awaitTermination(1, TimeUnit.SECONDS)); - } catch (InterruptedException e) { - fail(); - } - } -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ByteArraySizeHashPrinterTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ByteArraySizeHashPrinterTest.java deleted file mode 100644 index e3a5e945..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ByteArraySizeHashPrinterTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import static org.junit.Assert.*; - -import java.util.Arrays; - -import org.junit.Test; - -/** - * Test cases for byte[] pretty printer. - */ -public class ByteArraySizeHashPrinterTest { - - /** - * Test method for {@link org.onlab.util.ByteArraySizeHashPrinter#toString()}. - */ - @Test - public void testToStringNull() { - final byte[] none = null; - - assertEquals("byte[]{null}", String.valueOf(ByteArraySizeHashPrinter.of(none))); - assertNull(ByteArraySizeHashPrinter.orNull(none)); - } - - /** - * Test method for {@link org.onlab.util.ByteArraySizeHashPrinter#toString()}. - */ - @Test - public void testToString() { - final byte[] some = new byte[] {2, 5, 0, 1 }; - final String expected = "byte[]{length=" + some.length + ", hash=" + Arrays.hashCode(some) + "}"; - - assertEquals(expected, String.valueOf(ByteArraySizeHashPrinter.of(some))); - assertNotNull(ByteArraySizeHashPrinter.orNull(some)); - } - -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/CounterTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/CounterTest.java deleted file mode 100644 index d30e1b59..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/CounterTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onlab.junit.TestTools.delay; - -/** - * Tests of the Counter utility. - */ -public class CounterTest { - - @Test - public void basics() { - Counter tt = new Counter(); - assertEquals("incorrect number of bytes", 0L, tt.total()); - assertEquals("incorrect throughput", 0.0, tt.throughput(), 0.0001); - tt.add(1234567890L); - assertEquals("incorrect number of bytes", 1234567890L, tt.total()); - assertTrue("incorrect throughput", 1234567890.0 < tt.throughput()); - delay(1500); - tt.add(1L); - assertEquals("incorrect number of bytes", 1234567891L, tt.total()); - assertTrue("incorrect throughput", 1234567891.0 > tt.throughput()); - tt.reset(); - assertEquals("incorrect number of bytes", 0L, tt.total()); - assertEquals("incorrect throughput", 0.0, tt.throughput(), 0.0001); - } - - @Test - public void freeze() { - Counter tt = new Counter(); - tt.add(123L); - assertEquals("incorrect number of bytes", 123L, tt.total()); - delay(1000); - tt.freeze(); - tt.add(123L); - assertEquals("incorrect number of bytes", 123L, tt.total()); - - double d = tt.duration(); - double t = tt.throughput(); - assertEquals("incorrect duration", d, tt.duration(), 0.0001); - assertEquals("incorrect throughput", t, tt.throughput(), 0.0001); - assertEquals("incorrect number of bytes", 123L, tt.total()); - } - - @Test - public void reset() { - Counter tt = new Counter(); - tt.add(123L); - assertEquals("incorrect number of bytes", 123L, tt.total()); - - double d = tt.duration(); - double t = tt.throughput(); - assertEquals("incorrect duration", d, tt.duration(), 0.0001); - assertEquals("incorrect throughput", t, tt.throughput(), 0.0001); - assertEquals("incorrect number of bytes", 123L, tt.total()); - - tt.reset(); - assertEquals("incorrect throughput", 0.0, tt.throughput(), 0.0001); - assertEquals("incorrect number of bytes", 0, tt.total()); - } - - @Test - public void syntheticTracker() { - Counter tt = new Counter(5000, 1000, 6000); - assertEquals("incorrect duration", 1, tt.duration(), 0.1); - assertEquals("incorrect throughput", 1000, tt.throughput(), 1.0); - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/DefaultHashMapTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/DefaultHashMapTest.java deleted file mode 100644 index db6b5fb7..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/DefaultHashMapTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Unit tests for {@link DefaultHashMap}. - */ -public class DefaultHashMapTest { - - private static final String ONE = "one"; - private static final String TWO = "two"; - private static final String THREE = "three"; - private static final String FOUR = "four"; - - private static final String ALPHA = "Alpha"; - private static final String BETA = "Beta"; - private static final String OMEGA = "Omega"; - - private DefaultHashMap<String, Integer> map; - private DefaultHashMap<String, String> chartis; - - private void loadMap() { - map.put(ONE, 1); - map.put(TWO, 2); - } - - private void fortioCharti() { - chartis.put(ONE, ALPHA); - chartis.put(TWO, BETA); - } - - @Test - public void nullDefaultIsAllowed() { - // but makes this class behave no different than HashMap - map = new DefaultHashMap<>(null); - loadMap(); - assertEquals("missing 1", 1, (int) map.get(ONE)); - assertEquals("missing 2", 2, (int) map.get(TWO)); - assertEquals("three?", null, map.get(THREE)); - assertEquals("four?", null, map.get(FOUR)); - } - - @Test - public void defaultToFive() { - map = new DefaultHashMap<>(5); - loadMap(); - assertEquals("missing 1", 1, (int) map.get(ONE)); - assertEquals("missing 2", 2, (int) map.get(TWO)); - assertEquals("three?", 5, (int) map.get(THREE)); - assertEquals("four?", 5, (int) map.get(FOUR)); - } - - @Test - public void defaultToOmega() { - chartis = new DefaultHashMap<>(OMEGA); - fortioCharti(); - assertEquals("missing 1", ALPHA, chartis.get(ONE)); - assertEquals("missing 2", BETA, chartis.get(TWO)); - assertEquals("three?", OMEGA, chartis.get(THREE)); - assertEquals("four?", OMEGA, chartis.get(FOUR)); - } - -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/FrequencyTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/FrequencyTest.java deleted file mode 100644 index 727c0f73..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/FrequencyTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import com.google.common.testing.EqualsTester; -import org.junit.Test; -import org.onlab.junit.ImmutableClassChecker; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.lessThan; - -public class FrequencyTest { - - private final Frequency frequency1 = Frequency.ofMHz(1000); - private final Frequency sameFrequency1 = Frequency.ofMHz(1000); - private final Frequency frequency2 = Frequency.ofGHz(1000); - private final Frequency sameFrequency2 = Frequency.ofGHz(1000); - private final Frequency moreSameFrequency2 = Frequency.ofTHz(1); - private final Frequency frequency3 = Frequency.ofTHz(193.1); - private final Frequency sameFrequency3 = Frequency.ofGHz(193100); - - /** - * Tests immutability of Frequency. - */ - @Test - public void testImmutability() { - ImmutableClassChecker.assertThatClassIsImmutable(Frequency.class); - } - - /** - * Tests equality of Frequency instances. - */ - @Test - public void testEquality() { - new EqualsTester() - .addEqualityGroup(frequency1, sameFrequency1) - .addEqualityGroup(frequency2, sameFrequency2, moreSameFrequency2) - .addEqualityGroup(frequency3, sameFrequency3) - .testEquals(); - } - - /** - * Tests the first object is less than the second object. - */ - @Test - public void testLessThan() { - assertThat(frequency1, is(lessThan(frequency2))); - assertThat(frequency1.isLessThan(frequency2), is(true)); - } - - @Test - public void testGreaterThan() { - assertThat(frequency2, is(greaterThan(frequency1))); - assertThat(frequency2.isGreaterThan(frequency1), is(true)); - } - - /** - * Tests add operation of two Frequencies. - */ - @Test - public void testAdd() { - Frequency low = Frequency.ofMHz(100); - Frequency high = Frequency.ofGHz(1); - Frequency expected = Frequency.ofMHz(1100); - - assertThat(low.add(high), is(expected)); - } - - /** - * Tests subtract operation of two Frequencies. - */ - @Test - public void testSubtract() { - Frequency high = Frequency.ofGHz(1); - Frequency low = Frequency.ofMHz(100); - Frequency expected = Frequency.ofMHz(900); - - assertThat(high.subtract(low), is(expected)); - } - - /** - * Tests multiply operation of Frequency. - */ - @Test - public void testMultiply() { - Frequency frequency = Frequency.ofMHz(1000); - long factor = 5; - Frequency expected = Frequency.ofGHz(5); - - assertThat(frequency.multiply(5), is(expected)); - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GeoLocationTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GeoLocationTest.java deleted file mode 100644 index a497bcc4..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GeoLocationTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** - * Test suite of the geo location. - */ -public class GeoLocationTest { - - @Test - public void basics() { - GeoLocation nLoc = new GeoLocation(40.7127, -74.0059); - GeoLocation wLoc = new GeoLocation(38.9047, -77.0164); - - assertEquals("incorrect latitude", 40.7127, nLoc.latitude(), 0.0001); - assertEquals("incorrect longitude", -74.00598, nLoc.longitude(), 0.0001); - assertEquals("incorrect distance", 326.74, nLoc.kilometersTo(wLoc), 0.01); - } - -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GroupedThreadFactoryTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GroupedThreadFactoryTest.java deleted file mode 100644 index 5be1cda4..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/GroupedThreadFactoryTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; -import org.onlab.junit.TestTools; - -import static org.junit.Assert.*; - -/** - * Tests of the group thread factory. - */ -public class GroupedThreadFactoryTest { - - @Test - public void basics() { - GroupedThreadFactory a = GroupedThreadFactory.groupedThreadFactory("foo"); - GroupedThreadFactory b = GroupedThreadFactory.groupedThreadFactory("foo"); - assertSame("factories should be same", a, b); - - assertTrue("wrong toString", a.toString().contains("foo")); - Thread t = a.newThread(() -> TestTools.print("yo")); - assertSame("wrong group", a.threadGroup(), t.getThreadGroup()); - } - - @Test - public void hierarchical() { - GroupedThreadFactory a = GroupedThreadFactory.groupedThreadFactory("foo/bar"); - GroupedThreadFactory b = GroupedThreadFactory.groupedThreadFactory("foo/goo"); - GroupedThreadFactory p = GroupedThreadFactory.groupedThreadFactory("foo"); - - assertSame("groups should be same", p.threadGroup(), a.threadGroup().getParent()); - assertSame("groups should be same", p.threadGroup(), b.threadGroup().getParent()); - - assertEquals("wrong name", "foo/bar", a.threadGroup().getName()); - assertEquals("wrong name", "foo/goo", b.threadGroup().getName()); - assertEquals("wrong name", "foo", p.threadGroup().getName()); - } - -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/HexStringTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/HexStringTest.java deleted file mode 100644 index f4aadd15..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/HexStringTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; - -import com.esotericsoftware.minlog.Log; - -import junit.framework.TestCase; - -import static org.junit.Assert.fail; - -/** - * Test of the Hexstring. - * - */ - -public class HexStringTest { - - @Test - public void testMarshalling() throws Exception { - String dpidStr = "00:00:00:23:20:2d:16:71"; - long dpid = HexString.toLong(dpidStr); - String testStr = HexString.toHexString(dpid); - TestCase.assertEquals(dpidStr, testStr); - } - - @Test - public void testToLong() { - String dpidStr = "3e:1f:01:fc:72:8c:63:31"; - long valid = 0x3e1f01fc728c6331L; - long testLong = HexString.toLong(dpidStr); - TestCase.assertEquals(valid, testLong); - } - - @Test - public void testToLongMsb() { - String dpidStr = "ca:7c:5e:d1:64:7a:95:9b"; - long valid = -3856102927509056101L; - long testLong = HexString.toLong(dpidStr); - TestCase.assertEquals(valid, testLong); - } - - @Test - public void testToLongError() { - String dpidStr = "09:08:07:06:05:04:03:02:01"; - try { - HexString.toLong(dpidStr); - fail("HexString.toLong() should have thrown a NumberFormatException"); - } catch (NumberFormatException expected) { - Log.info("HexString.toLong() have thrown a NumberFormatException"); - } - } - - @Test - public void testToStringBytes() { - byte[] dpid = {0, 0, 0, 0, 0, 0, 0, -1 }; - String valid = "00:00:00:00:00:00:00:ff"; - String testString = HexString.toHexString(dpid); - TestCase.assertEquals(valid, testString); - } - - @Test - public void testFromHexStringError() { - String invalidStr = "00:00:00:00:00:00:ffff"; - try { - HexString.fromHexString(invalidStr); - fail("HexString.fromHexString() should have thrown a NumberFormatException"); - } catch (NumberFormatException expected) { - Log.info("HexString.toLong() have thrown a NumberFormatException"); - } - } -} - diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimer.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimer.java deleted file mode 100644 index 8fb008e8..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimer.java +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import com.google.common.collect.Lists; -import org.onlab.junit.TestUtils; -import org.slf4j.Logger; - -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.TimerTask; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.onlab.junit.TestTools.delay; -import static org.slf4j.LoggerFactory.getLogger; - - -/** - * Provides manually scheduled timer utility. All schedulable methods are subject to overflow (you can set a period of - * max long). Additionally if a skip skips a period of time greater than one period for a periodic task that task will - * only be executed once for that skip and scheduled it's period after the last execution. - */ -public class ManuallyAdvancingTimer extends java.util.Timer { - - /* States whether or not the static values from timer task have been set ensures population will only occur once.*/ - private boolean staticsPopulated = false; - - /* Virgin value from timer task */ - private int virginState; - - /* Scheduled value from timer task */ - private int scheduledState; - - /* Executed value from timer task */ - private int executedState; - - /* Cancelled value from timer task */ - private int cancelledState; - - private final Logger logger = getLogger(getClass()); - - /* Service for executing timer tasks */ - private final ExecutorService executorService = Executors.newSingleThreadExecutor(); - - /* Internal time representation independent of system time, manually advanced */ - private final TimerKeeper timerKeeper = new TimerKeeper(); - - /* Data structure for tracking tasks */ - private final TaskQueue queue = new TaskQueue(); - - /* Whether execution should execute on the executor thread or the calling thread. */ - private final boolean runLocally; - - public ManuallyAdvancingTimer(boolean runLocally) { - this.runLocally = runLocally; - } - - - @Override - public void schedule(TimerTask task, long delay) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, delay > 0 ? timerKeeper.currentTimeInMillis() + delay : - timerKeeper.currentTimeInMillis() - delay, 0)) { - logger.error("Failed to submit task"); - } - } - - @Override - public void schedule(TimerTask task, Date time) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, time.getTime(), 0)) { - logger.error("Failed to submit task"); - } - } - - @Override - public void schedule(TimerTask task, long delay, long period) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, delay > 0 ? timerKeeper.currentTimeInMillis() + delay : - timerKeeper.currentTimeInMillis() - delay, period)) { - logger.error("Failed to submit task"); - } - } - - @Override - public void schedule(TimerTask task, Date firstTime, long period) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, firstTime.getTime(), period)) { - logger.error("Failed to submit task"); - } - } - - /*################################################WARNING################################################*/ - /* Schedule at fixed rate methods do not work exactly as in the java timer. They are clones of the periodic - *scheduling methods. */ - @Override - public void scheduleAtFixedRate(TimerTask task, long delay, long period) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, delay > 0 ? timerKeeper.currentTimeInMillis() + delay : - timerKeeper.currentTimeInMillis() - delay, period)) { - logger.error("Failed to submit task"); - } - } - - @Override - public void scheduleAtFixedRate(TimerTask task, Date firstTime, long period) { - if (!staticsPopulated) { - populateStatics(task); - } - if (!submitTask(task, firstTime.getTime(), period)) { - logger.error("Failed to submit task"); - } - } - - @Override - public void cancel() { - executorService.shutdown(); - queue.clear(); - } - - @Override - public int purge() { - return queue.removeCancelled(); - } - - /** - * Returns the virtual current time in millis. - * - * @return long representing simulated current time. - */ - public long currentTimeInMillis() { - return timerKeeper.currentTimeInMillis(); - } - - /** - * Returns the new simulated current time in millis after advancing the absolute value of millis to advance. - * Triggers event execution of all events scheduled for execution at times up to and including the returned time. - * Passing in the number zero has no effect. - * - * @param millisToAdvance the number of millis to advance. - * @return a long representing the current simulated time in millis - */ - public long advanceTimeMillis(long millisToAdvance) { - return timerKeeper.advanceTimeMillis(millisToAdvance); - } - - /** - * Advances the virtual time a certain number of millis triggers execution delays a certain amount to - * allow time for execution. If runLocally is true then all real time delays are ignored. - * - * @param virtualTimeAdvance the time to be advances in millis of simulated time. - * @param realTimeDelay the time to delay in real time to allow for processing. - */ - public void advanceTimeMillis(long virtualTimeAdvance, int realTimeDelay) { - timerKeeper.advanceTimeMillis(virtualTimeAdvance); - if (!runLocally) { - delay(realTimeDelay); - } - } - - /** - * Sets up the task and submits it to the queue. - * - * @param task the task to be added to the queue - * @param runtime the first runtime of the task - * @param period the period between runs thereafter - * @return returns true if the task was successfully submitted, false otherwise - */ - private boolean submitTask(TimerTask task, long runtime, long period) { - checkNotNull(task); - try { - TestUtils.setField(task, "state", scheduledState); - TestUtils.setField(task, "nextExecutionTime", runtime); - TestUtils.setField(task, "period", period); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - return false; - } - queue.insertOrdered(task); - return true; - } - - /** - * Executes the given task (only if it is in the scheduled state) and proceeds to reschedule it or mark it as - * executed. Does not remove from the queue (this must be done outside). - * - * @param task the timer task to be executed - */ - private boolean executeTask(TimerTask task) { - checkNotNull(task); - int currentState; - try { - currentState = TestUtils.getField(task, "state"); - } catch (TestUtils.TestUtilsException e) { - logger.error("Could not get state of task."); - e.printStackTrace(); - return false; - } - //If cancelled or already executed stop here. - if (currentState == executedState || currentState == cancelledState) { - return false; - } else if (currentState == virginState) { - logger.error("Task was set for execution without being scheduled."); - return false; - } else if (currentState == scheduledState) { - long period; - - try { - period = TestUtils.getField(task, "period"); - } catch (TestUtils.TestUtilsException e) { - logger.error("Could not read period of task."); - e.printStackTrace(); - return false; - } - //Period of zero means one time execution. - if (period == 0) { - try { - TestUtils.setField(task, "state", executedState); - } catch (TestUtils.TestUtilsException e) { - logger.error("Could not set executed state."); - e.printStackTrace(); - return false; - } - if (runLocally) { - task.run(); - } else { - executorService.execute(task); - } - return true; - } else { - //Calculate next execution time, using absolute value of period - long nextTime = (period > 0) ? (timerKeeper.currentTimeInMillis() + period) : - (timerKeeper.currentTimeInMillis() - period); - try { - TestUtils.setField(task, "nextExecutionTime", nextTime); - } catch (TestUtils.TestUtilsException e) { - logger.error("Could not set next execution time."); - e.printStackTrace(); - return false; - } - //Schedule next execution - queue.insertOrdered(task); - if (runLocally) { - task.run(); - } else { - executorService.execute(task); - } - return true; - } - } - logger.error("State property of {} is in an illegal state and did not execute.", task); - return false; - } - - /** - * Executes all tasks in the queue scheduled for execution up to and including the current time. - * - * @return the total number of tasks run, -1 if failure - */ - private int executeEventsUpToPresent() { - int totalRun = 0; - if (queue.isEmpty()) { - return -1; - } - TimerTask currTask = queue.peek(); - long currExecTime; - try { - currExecTime = TestUtils.getField(currTask, "nextExecutionTime"); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - throw new RuntimeException("Could not get nextExecutionTime"); - } - while (currExecTime <= timerKeeper.currentTimeInMillis()) { - if (executeTask(queue.pop())) { - totalRun++; - } - if (queue.isEmpty()) { - break; - } - currTask = queue.peek(); - try { - currExecTime = TestUtils.getField(currTask, "nextExecutionTime"); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - throw new RuntimeException("Could not get nextExecutionTime"); - } - } - return totalRun; - } - - /** - * Populates the static fields from timer task. Should only be called once. - */ - private void populateStatics(TimerTask task) { - try { - virginState = TestUtils.getField(task, "VIRGIN"); - scheduledState = TestUtils.getField(task, "SCHEDULED"); - executedState = TestUtils.getField(task, "EXECUTED"); - cancelledState = TestUtils.getField(task, "CANCELLED"); - staticsPopulated = true; - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - } - } - - /** - * A class used to maintain the virtual time. - */ - private class TimerKeeper { - - private long currentTime = 0; - - /** - * Returns the virtual current time in millis. - * - * @return long representing simulated current time. - */ - long currentTimeInMillis() { - return currentTime; - } - - /** - * Returns the new simulated current time in millis after advancing the absolute value of millis to advance. - * Triggers event execution of all events scheduled for execution at times up to and including the returned - * time. Passing in the number zero has no effect. - * - * @param millisToAdvance the number of millis to advance. - * @return a long representing the current simulated time in millis - */ - long advanceTimeMillis(long millisToAdvance) { - currentTime = (millisToAdvance >= 0) ? (currentTime + millisToAdvance) : (currentTime - millisToAdvance); - if (millisToAdvance != 0) { - executeEventsUpToPresent(); - } - return currentTime; - } - } - - /** - * A queue backed by a linked list. Keeps elements sorted in ascending order of execution time. All calls are safe - * even on empty queue's. - */ - private class TaskQueue { - private final LinkedList<TimerTask> taskList = Lists.newLinkedList(); - - /** - * Adds the task to the queue in ascending order of scheduled execution. If execution time has already passed - * execute immediately. - * - * @param task the task to be added to the queue - */ - void insertOrdered(TimerTask task) { - //Using O(N) insertion because random access is expensive in linked lists worst case is 2N links followed - // for binary insertion vs N for simple insertion. - checkNotNull(task); - if (!staticsPopulated) { - populateStatics(task); - } - long insertTime; - try { - insertTime = TestUtils.getField(task, "nextExecutionTime"); - TestUtils.setField(task, "state", scheduledState); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - return; - } - //If the task was scheduled in the past or for the current time run it immediately and do not add to the - // queue, subsequent executions will be scheduled as normal - if (insertTime <= timerKeeper.currentTimeInMillis()) { - executeTask(task); - return; - } - - Iterator<TimerTask> iter = taskList.iterator(); - int positionCounter = 0; - long nextTaskTime; - TimerTask currentTask; - while (iter.hasNext()) { - currentTask = iter.next(); - try { - nextTaskTime = TestUtils.getField(currentTask, "nextExecutionTime"); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - return; - } - if (insertTime < nextTaskTime) { - taskList.add(positionCounter, task); - return; - } - positionCounter++; - } - taskList.addLast(task); - } - - /** - * Returns the first item in the queue (next scheduled for execution) without removing it, returns null if the - * queue is empty. - * - * @return the next TimerTask to run or null if the queue is empty - */ - TimerTask peek() { - if (taskList.isEmpty()) { - return null; - } - return taskList.getFirst(); - } - - /** - * Returns and removes the first item in the queue or null if it is empty. - * - * @return the first element of the queue or null if the queue is empty - */ - TimerTask pop() { - if (taskList.isEmpty()) { - return null; - } - return taskList.pop(); - } - - /** - * Performs a sort on the set of timer tasks, earliest task is first. Does nothing if queue is empty. - */ - void sort() { - if (taskList.isEmpty()) { - return; - } - taskList.sort((o1, o2) -> { - checkNotNull(o1); - checkNotNull(o2); - long executionTimeOne; - long executionTimeTwo; - try { - executionTimeOne = TestUtils.getField(o1, "nextExecutionTime"); - executionTimeTwo = TestUtils.getField(o2, "nextExecutionTime"); - } catch (TestUtils.TestUtilsException e) { - e.printStackTrace(); - throw new RuntimeException("Could not get next execution time."); - } - if (executionTimeOne == executionTimeTwo) { - return 0; - } else if (executionTimeOne < executionTimeTwo) { - return -1; - } else { - return 1; - } - }); - } - - /** - * Returns whether the queue is currently empty. - * - * @return true if the queue is empty, false otherwise - */ - boolean isEmpty() { - return taskList.isEmpty(); - } - - /** - * Clears the underlying list of the queue. - */ - void clear() { - taskList.clear(); - } - - /** - * Removes all cancelled tasks from the queue. Has no effect on behavior. - * - * @return returns the total number of items removed, -1 if list is empty or failure occurs. - */ - int removeCancelled() { - if (taskList.isEmpty()) { - return -1; - } - int removedCount = 0; - Iterator<TimerTask> taskIterator = taskList.iterator(); - TimerTask currTask; - int currState; - while (taskIterator.hasNext()) { - currTask = taskIterator.next(); - try { - currState = TestUtils.getField(currTask, "state"); - } catch (TestUtils.TestUtilsException e) { - logger.error("Could not get task state."); - e.printStackTrace(); - return -1; - } - if (currState == cancelledState) { - removedCount++; - taskIterator.remove(); - } - } - return removedCount; - } - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimerTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimerTest.java deleted file mode 100644 index 36b50e67..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ManuallyAdvancingTimerTest.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import com.google.common.collect.Lists; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Date; -import java.util.TimerTask; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.onlab.junit.TestTools.delay; - -/** - * Testing class for manually advancing timer. - */ -public class ManuallyAdvancingTimerTest { - - private ManuallyAdvancingTimer timer; - - /* Generates unique id's for TestTasks */ - private AtomicInteger idGenerator; - - /* Tracks TestTasks in order of creation, tasks are automatically added at creation. */ - private ArrayList<TestTask> taskList; - - /* Total number of tasks run */ - private AtomicInteger tasksRunCount; - - // FIXME if this class fails first try increasing the real time delay to account for heavy system load. - private static final int REAL_TIME_DELAY = 10; - - /** - * Sets up the testing environment. - */ - @Before - public void setup() { - timer = new ManuallyAdvancingTimer(true); - idGenerator = new AtomicInteger(1); - tasksRunCount = new AtomicInteger(0); - taskList = Lists.newArrayList(); - } - - /** - * Tests the one time schedule with delay. - * - * @throws Exception throws an exception if the test fails - */ - @Test - public void testScheduleByDelay() throws Exception { - /* Test scheduling in the future as normal. */ - timer.schedule(new TestTask(), 10); - timer.advanceTimeMillis(5); - assertFalse(taskList.get(0).hasRun()); - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertTrue(taskList.get(0).hasRun()); - - /* Test scheduling with negative numbers */ - timer.schedule(new TestTask(), -10); - timer.advanceTimeMillis(5); - assertFalse(taskList.get(1).hasRun()); - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertTrue(taskList.get(1).hasRun()); - - /* Reset list, counter and timer for next test */ - taskList.clear(); - idGenerator.set(1); - tasksRunCount.set(0); - - for (int i = 0; i < 50; i++) { - timer.schedule(new TestTask(), i); - } - /* Test that a task scheduled for present is run and not placed in the queue */ - assertEquals("Only the first task should have run.", 1, tasksRunCount.get()); - - for (int i = 2; i <= 50; i++) { - timer.advanceTimeMillis(1, REAL_TIME_DELAY); - assertEquals("One task should be executed per loop", i, tasksRunCount.get()); - } - /* Below tests ordered insertion, this will only be done once, it is the same for all schedule methods. */ - - tasksRunCount.set(0); - - for (int i = 0; i < 10; i++) { - timer.schedule(new TestTask(), 500); - } - - assertEquals("No new tasks should have been run since run count reset.", 0, tasksRunCount.get()); - timer.schedule(new TestTask(), 10); - assertEquals("No new tasks should have been run since run count reset.", 0, tasksRunCount.get()); - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertEquals("One new tasks should have been run since run count reset.", 1, tasksRunCount.get()); - timer.advanceTimeMillis(510, REAL_TIME_DELAY); - assertEquals("Eleven new tasks should have been run since run count reset.", 11, tasksRunCount.get()); - } - - /** - * Tests scheduling for a particular date or time which may be in the past. - * - * @throws Exception throws an exception if the test fails - */ - @Test - public void testScheduleByDate() throws Exception { - /* Tests basic scheduling for future times. */ - timer.schedule(new TestTask(), new Date(10)); - timer.advanceTimeMillis(5); - assertFalse(taskList.get(0).hasRun()); - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertTrue(taskList.get(0).hasRun()); - - /* Test scheduling with past times numbers */ - timer.schedule(new TestTask(), new Date(0)); - delay(REAL_TIME_DELAY); - assertTrue(taskList.get(1).hasRun()); - - /* Tests cancellation on non-periodic events */ - TestTask task = new TestTask(); - timer.schedule(task, new Date(timer.currentTimeInMillis() + 10)); - task.cancel(); - timer.advanceTimeMillis(12, REAL_TIME_DELAY); - assertFalse(task.hasRun()); - - } - - /** - * Test scheduling beginning after a delay and recurring periodically. - * - * @throws Exception throws an exception if the test fails - */ - @Test - public void testScheduleByDelayPeriodic() throws Exception { - /* Test straightforward periodic execution */ - timer.schedule(new TestTask(), 0, 10); - delay(REAL_TIME_DELAY); - assertEquals("Task should have run once when added.", 1, taskList.get(0).timesRun()); - - /* Tests whether things that are not added to the queue are scheduled for future executions (ones which execute - immediately on add). */ - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertEquals("Task should have run once when added.", 2, taskList.get(0).timesRun()); - - /* Tests whether cancellation works on periodic events. */ - taskList.get(0).cancel(); - - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertEquals("The task should not have run another time.", 2, taskList.get(0).timesRun()); - - TestTask task = new TestTask(); - timer.schedule(task, 0, 10); - timer.advanceTimeMillis(100, REAL_TIME_DELAY); - assertEquals("Should have run immeditaley and subsequently once during the larger skip", task.timesRun(), 2); - - } - - /** - * Test scheduling beginning at a specified date and recurring periodically. - * - * @throws Exception throws an exception if the test fails - */ - @Test - public void testScheduleByDatePeriodic() throws Exception { - /* Test straightforward periodic execution */ - timer.schedule(new TestTask(), new Date(timer.currentTimeInMillis()), 10); - delay(REAL_TIME_DELAY); - assertEquals("Task should have run once when added.", 1, taskList.get(0).timesRun()); - - /* Tests whether things that are not added to the queue are scheduled for future executions (ones which execute - immediately on add). */ - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertEquals("Task should have run once when added.", 2, taskList.get(0).timesRun()); - - /* Tests whether cancellation works on periodic events. */ - taskList.get(0).cancel(); - - timer.advanceTimeMillis(10, REAL_TIME_DELAY); - assertEquals("The task should not have run another time.", 2, taskList.get(0).timesRun()); - - TestTask task = new TestTask(); - timer.schedule(task, new Date(timer.currentTimeInMillis()), 10); - timer.advanceTimeMillis(100, REAL_TIME_DELAY); - assertEquals("Should have run immediately and subsequently once during the larger skip", task.timesRun(), 2); - } - - /* Schedule at fixed rate runs exactly like the two scheduling methods just tested so tests are not included */ - - /** - * Timer task with added functions to make it better for testing. - */ - private class TestTask extends TimerTask { - - /* Remains true once the task has been run at least once */ - private boolean hasRun; - - /* Unique id per event. */ - private int id; - - /* Specifies the number of times an event has run */ - private int timesRun; - - /** - * Constructor initializes id, timesRun, and id fields. - */ - public TestTask() { - id = idGenerator.getAndIncrement(); - timesRun = 0; - hasRun = false; - taskList.add(this); - } - - @Override - public void run() { - this.hasRun = true; - tasksRunCount.incrementAndGet(); - timesRun++; - } - - /** - * Returns whether this event has run. - * - * @return true if the event has run, false otherwise. - */ - public boolean hasRun() { - return hasRun; - } - - /** - * Returns the number of times this task has run. - * - * @return an int representing the number of times this task has been run - */ - public int timesRun() { - return timesRun; - } - - /** - * Returns the unique identifier of this task. - * - * @return a unique integer identifier - */ - public int getId() { - return id; - } - } -}
\ No newline at end of file diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/PositionalParameterStringFormatterTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/PositionalParameterStringFormatterTest.java deleted file mode 100644 index 9758511f..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/PositionalParameterStringFormatterTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ - -package org.onlab.util; - -import static org.junit.Assert.*; -import static org.onlab.util.PositionalParameterStringFormatter.format; - -import org.junit.Test; - -public class PositionalParameterStringFormatterTest { - - @Test - public void testFormat0() { - String fmt = "Some string 1 2 3"; - assertEquals("Some string 1 2 3", format(fmt)); - } - - @Test - public void testFormat1() { - String fmt = "Some string {} 2 3"; - assertEquals("Some string 1 2 3", format(fmt, 1)); - } - - @Test - public void testFormat2() { - String fmt = "Some string {} 2 {}"; - assertEquals("Some string 1 2 3", format(fmt, 1, "3")); - } - - @Test - public void testFormatNull() { - String fmt = "Some string {} 2 {}"; - assertEquals("Some string 1 2 null", format(fmt, 1, null)); - } - - @Test - public void testFormatExtraBracket() { - String fmt = "Some string {} 2 {}"; - assertEquals("Some string 1 2 {}", format(fmt, 1)); - } - - @Test - public void testFormatMissingBracket() { - String fmt = "Some string 1 2 3"; - assertEquals("Some string 1 2 3", format(fmt, 7)); - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/RetryingFunctionTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/RetryingFunctionTest.java deleted file mode 100644 index 4b08d2fc..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/RetryingFunctionTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -/** - * Unit tests for RetryingFunction. - * - */ -public class RetryingFunctionTest { - - private int round; - - @Before - public void setUp() { - round = 1; - } - - @After - public void tearDown() { - round = 0; - } - - @Test(expected = RetryableException.class) - public void testNoRetries() { - new RetryingFunction<>(this::succeedAfterOneFailure, RetryableException.class, 0, 10).apply(null); - } - - @Test - public void testSuccessAfterOneRetry() { - new RetryingFunction<>(this::succeedAfterOneFailure, RetryableException.class, 1, 10).apply(null); - } - - @Test(expected = RetryableException.class) - public void testFailureAfterOneRetry() { - new RetryingFunction<>(this::succeedAfterTwoFailures, RetryableException.class, 1, 10).apply(null); - } - - @Test - public void testFailureAfterTwoRetries() { - new RetryingFunction<>(this::succeedAfterTwoFailures, RetryableException.class, 2, 10).apply(null); - } - - @Test(expected = NonRetryableException.class) - public void testFailureWithNonRetryableFailure() { - new RetryingFunction<>(this::failCompletely, RetryableException.class, 2, 10).apply(null); - } - - private String succeedAfterOneFailure(String input) { - if (round++ <= 1) { - throw new RetryableException(); - } else { - return "pass"; - } - } - - private String succeedAfterTwoFailures(String input) { - if (round++ <= 2) { - throw new RetryableException(); - } else { - return "pass"; - } - } - - private String failCompletely(String input) { - if (round++ <= 1) { - throw new NonRetryableException(); - } else { - return "pass"; - } - } - - private class RetryableException extends RuntimeException { - } - - private class NonRetryableException extends RuntimeException { - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SharedExecutorsTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SharedExecutorsTest.java deleted file mode 100644 index 1730ca1f..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SharedExecutorsTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; - -import java.util.concurrent.ExecutorService; - -import static org.junit.Assert.*; - -/** - * Tests of the SharedExecutors Test. - */ -public class SharedExecutorsTest { - - @Test - public void singleThread() { - ExecutorService a = SharedExecutors.getSingleThreadExecutor(); - assertNotNull("ExecutorService must not be null", a); - ExecutorService b = SharedExecutors.getSingleThreadExecutor(); - assertSame("factories should be same", a, b); - - } - - @Test - public void poolThread() { - ExecutorService a = SharedExecutors.getPoolThreadExecutor(); - assertNotNull("ExecutorService must not be null", a); - ExecutorService b = SharedExecutors.getPoolThreadExecutor(); - assertSame("factories should be same", a, b); - - } - - @Test - public void timer() { - java.util.Timer a = SharedExecutors.getTimer(); - assertNotNull("Timer must not be null", a); - java.util.Timer b = SharedExecutors.getTimer(); - assertSame("factories should be same", a, b); - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SlidingWindowCounterTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SlidingWindowCounterTest.java deleted file mode 100644 index c15cc8a6..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/SlidingWindowCounterTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import static junit.framework.TestCase.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Unit tests for the sliding window counter. - */ - -@Ignore("Disable these for now because of intermittent load related failures on Jenkins runs.") -public class SlidingWindowCounterTest { - - private SlidingWindowCounter counter; - - @Before - public void setUp() { - counter = new SlidingWindowCounter(2); - } - - @After - public void tearDown() { - counter.destroy(); - } - - @Test - public void testIncrementCount() { - assertEquals(0, counter.get(1)); - assertEquals(0, counter.get(2)); - counter.incrementCount(); - assertEquals(1, counter.get(1)); - assertEquals(1, counter.get(2)); - counter.incrementCount(2); - assertEquals(3, counter.get(2)); - } - - @Test - public void testSlide() { - counter.incrementCount(); - counter.advanceHead(); - assertEquals(0, counter.get(1)); - assertEquals(1, counter.get(2)); - counter.incrementCount(2); - assertEquals(2, counter.get(1)); - assertEquals(3, counter.get(2)); - } - - @Test - public void testWrap() { - counter.incrementCount(); - counter.advanceHead(); - counter.incrementCount(2); - counter.advanceHead(); - assertEquals(0, counter.get(1)); - assertEquals(2, counter.get(2)); - counter.advanceHead(); - assertEquals(0, counter.get(1)); - assertEquals(0, counter.get(2)); - - } - - @Test - public void testCornerCases() { - try { - counter.get(3); - fail("Exception should have been thrown"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - try { - new SlidingWindowCounter(0); - fail("Exception should have been thrown"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - - try { - new SlidingWindowCounter(-1); - fail("Exception should have been thrown"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - } -} diff --git a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ToolsTest.java b/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ToolsTest.java deleted file mode 100644 index 56f0f957..00000000 --- a/framework/src/onos/utils/misc/src/test/java/org/onlab/util/ToolsTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * 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. - */ -package org.onlab.util; - -import org.junit.Test; -import org.onlab.junit.TestTools; - -import java.util.concurrent.ThreadFactory; - -import static org.junit.Assert.*; -import static org.onlab.junit.TestTools.assertAfter; - -/** - * Test of the miscellaneous tools. - */ -public class ToolsTest { - - @Test - public void fromHex() throws Exception { - assertEquals(15, Tools.fromHex("0f")); - assertEquals(16, Tools.fromHex("10")); - assertEquals(65535, Tools.fromHex("ffff")); - assertEquals(4096, Tools.fromHex("1000")); - assertEquals(0xffffffffffffffffL, Tools.fromHex("ffffffffffffffff")); - } - - @Test - public void toHex() throws Exception { - assertEquals("0f", Tools.toHex(15, 2)); - assertEquals("ffff", Tools.toHex(65535, 4)); - assertEquals("1000", Tools.toHex(4096, 4)); - assertEquals("000000000000000f", Tools.toHex(15)); - assertEquals("ffffffffffffffff", Tools.toHex(0xffffffffffffffffL)); - - } - - @Test - public void namedThreads() { - ThreadFactory f = Tools.namedThreads("foo-%d"); - Thread t = f.newThread(() -> TestTools.print("yo")); - assertTrue("wrong pattern", t.getName().startsWith("foo-")); - } - - @Test - public void groupedThreads() { - ThreadFactory f = Tools.groupedThreads("foo/bar-me", "foo-%d"); - Thread t = f.newThread(() -> TestTools.print("yo")); - assertTrue("wrong pattern", t.getName().startsWith("foo-bar-me-foo-")); - assertTrue("wrong group", t.getThreadGroup().getName().equals("foo/bar-me")); - } - - @Test - public void exceptionHandler() throws InterruptedException { - ThreadFactory f = Tools.namedThreads("foo"); - Thread t = f.newThread(() -> { - throw new IllegalStateException("BOOM!"); - }); - assertNotNull("thread should have exception handler", t.getUncaughtExceptionHandler()); - t.start(); - assertAfter(100, () -> assertEquals("incorrect thread state", Thread.State.TERMINATED, t.getState())); - } - -} |