*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.util.Collection;
-import java.util.Collections;
-import org.junit.Test;
+import java.util.List;
+import java.util.Set;
+import org.junit.jupiter.api.Test;
-public class ConstantArrayCollectionTest {
+class ConstantArrayCollectionTest {
private static final String[] ARRAY = new String[] { "a", "bb", "ccc" };
- private static final Collection<String> REF = ImmutableList.copyOf(ARRAY);
+ private static final Collection<String> REF = List.of(ARRAY);
private static Collection<String> create() {
return new ConstantArrayCollection<>(ARRAY.clone());
}
@Test
- public void testToString() {
+ void testToString() {
// Empty
- assertEquals(Collections.emptySet().toString(), new ConstantArrayCollection<>(new Object[0]).toString());
+ assertEquals(Set.of().toString(), new ConstantArrayCollection<>(new Object[0]).toString());
// Normal
assertEquals(REF.toString(), create().toString());
}
@Test
- public void testEquals() {
- final Collection<?> c = create();
+ void testEquals() {
+ final var c = create();
assertTrue(c.containsAll(REF));
assertTrue(REF.containsAll(c));
}
@Test
- public void testSimpleOperations() {
- final Collection<?> c = create();
+ void testSimpleOperations() {
+ final var c = create();
assertEquals(ARRAY.length, c.size());
assertFalse(c.isEmpty());
assertFalse(c.contains(""));
assertFalse(c.contains(1));
- assertTrue(c.containsAll(Collections.emptyList()));
- assertFalse(c.containsAll(Collections.singleton("")));
- assertFalse(c.containsAll(Collections.singleton(1)));
+ assertTrue(c.containsAll(List.of()));
+ assertFalse(c.containsAll(Set.of("")));
+ assertFalse(c.containsAll(Set.of(1)));
}
@Test
- public void testProtection() {
- final Collection<?> c = create();
+ void testProtection() {
+ final var c = create();
assertThrows(UnsupportedOperationException.class, () -> c.add(null));
assertThrows(UnsupportedOperationException.class, () -> c.remove(null));
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.CoreMatchers.startsWith;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for DurationStatsTracker.
*
* @author Thomas Pantelis
*/
-public class DurationStatisticsTrackerTest {
-
+class DurationStatisticsTrackerTest {
@Test
- public void test() {
-
- DurationStatisticsTracker tracker = DurationStatisticsTracker.createConcurrent();
+ void test() {
+ final var tracker = DurationStatisticsTracker.createConcurrent();
tracker.addDuration(10000);
- assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
- assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+ assertEquals(1, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(10000.0, tracker.getAverageDuration(), 0.1, "getAverageDuration");
+ assertEquals(10000, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(10000, tracker.getShortestDuration(), "getShortestDuration");
tracker.addDuration(30000);
- assertEquals("getTotalDurations", 2, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 20000.0, tracker.getAverageDuration(), 0.1);
- assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+ assertEquals(2, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(20000.0, tracker.getAverageDuration(), 0.1, "getAverageDuration");
+ assertEquals(30000, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(10000, tracker.getShortestDuration(), "getShortestDuration");
verifyDisplayableString("getDisplayableAverageDuration",
tracker.getDisplayableAverageDuration(), "20.0");
tracker.getDisplayableShortestDuration(), "10.0");
tracker.addDuration(10000);
- assertEquals("getTotalDurations", 3, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 16666.0, tracker.getAverageDuration(), 1.0);
- assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+ assertEquals(3, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(16666.0, tracker.getAverageDuration(), 1.0, "getAverageDuration");
+ assertEquals(30000, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(10000, tracker.getShortestDuration(), "getShortestDuration");
tracker.addDuration(5000);
- assertEquals("getTotalDurations", 4, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 13750.0, tracker.getAverageDuration(), 1.0);
- assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 5000, tracker.getShortestDuration());
+ assertEquals(4, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(13750.0, tracker.getAverageDuration(), 1.0, "getAverageDuration");
+ assertEquals(30000, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(5000, tracker.getShortestDuration(), "getShortestDuration");
tracker.reset();
- assertEquals("getTotalDurations", 0, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 0.0, tracker.getAverageDuration(), 0.1);
- assertEquals("getLongestDuration", 0, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 0, tracker.getShortestDuration());
+ assertEquals(0, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(0.0, tracker.getAverageDuration(), 0.1, "getAverageDuration");
+ assertEquals(0, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(0, tracker.getShortestDuration(), "getShortestDuration");
tracker.addDuration(10000);
- assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
- assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
- assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
- assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
+ assertEquals(1, tracker.getTotalDurations(), "getTotalDurations");
+ assertEquals(10000.0, tracker.getAverageDuration(), 0.1, "getAverageDuration");
+ assertEquals(10000, tracker.getLongestDuration(), "getLongestDuration");
+ assertEquals(10000, tracker.getShortestDuration(), "getShortestDuration");
}
private static void verifyDisplayableString(final String name, final String actual, final String expPrefix) {
- assertTrue(name + " starts with " + expPrefix + ". Actual: " + actual,
- actual.startsWith(expPrefix));
+ assertThat(actual, startsWith(expPrefix));
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.NoSuchElementException;
-import org.junit.Test;
-
-public class EmptyDequeTest {
+import org.junit.jupiter.api.Test;
+class EmptyDequeTest {
@Test
- public void testEmptyDeque() {
- final EmptyDeque<?> deque = EmptyDeque.instance();
+ void testEmptyDeque() {
+ final var deque = EmptyDeque.instance();
assertFalse(deque.offer(null));
assertFalse(deque.offerFirst(null));
assertFalse(deque.offerLast(null));
assertFalse(deque.descendingIterator().hasNext());
assertEquals(0L, deque.spliterator().estimateSize());
- final Object[] a = deque.toArray();
+ final var a = deque.toArray();
assertEquals(0, a.length);
assertSame(a, deque.toArray());
assertSame(a, deque.toArray(a));
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class HashCodeBuilderTest {
+class HashCodeBuilderTest {
@Test
- public void testAllMethodsOfHashCodeBuilder() {
- final HashCodeBuilder<String> builder = new HashCodeBuilder<>();
- assertEquals("Default hash code should be '1'.", 1, builder.build());
+ void testAllMethodsOfHashCodeBuilder() {
+ final var builder = new HashCodeBuilder<>();
+ assertEquals(1, builder.build(), "Default hash code should be '1'.");
- int nextHashCode = HashCodeBuilder.nextHashCode(1, "test");
- assertEquals("Next hash code should be '3556529'.", 3556529, nextHashCode);
+ final var nextHashCode = HashCodeBuilder.nextHashCode(1, "test");
+ assertEquals(3556529, nextHashCode, "Next hash code should be '3556529'.");
builder.addArgument("another test");
- assertEquals("Updated internal hash code should be '700442706'.", -700442706, builder.build());
+ assertEquals(-700442706, builder.build(), "Updated internal hash code should be '700442706'.");
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
-import java.util.Map;
import java.util.Set;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class ImmutableMapTemplateTest {
+class ImmutableMapTemplateTest {
private static final String FOO = "foo";
private static final String BAR = "bar";
private static final String BAZ = "baz";
private static final Set<String> TWO_KEYSET = ImmutableSet.of(FOO, BAR);
@Test
- public void testEmpty() {
+ void testEmpty() {
assertThrows(IllegalArgumentException.class, () -> ImmutableMapTemplate.ordered(ImmutableList.of()));
assertThrows(IllegalArgumentException.class, () -> ImmutableMapTemplate.unordered(ImmutableList.of()));
}
@Test
- public void testOneKeyTemplate() {
+ void testOneKeyTemplate() {
assertOne(ImmutableMapTemplate.ordered(ONE_KEYSET), SharedSingletonMap.Ordered.class);
assertOne(ImmutableMapTemplate.unordered(ONE_KEYSET), SharedSingletonMap.Unordered.class);
}
@Test
- public void testTwoKeyTemplate() {
+ void testTwoKeyTemplate() {
assertTwo(ImmutableMapTemplate.ordered(TWO_KEYSET), ImmutableOffsetMap.Ordered.class);
assertTwo(ImmutableMapTemplate.unordered(TWO_KEYSET), ImmutableOffsetMap.Unordered.class);
}
assertEquals(mapClass.getSimpleName() + "{keySet=[foo]}", template.toString());
// Successful instantiation
- Map<String, String> map = template.instantiateWithValues(BAR);
+ var map = template.instantiateWithValues(BAR);
assertTrue(mapClass.isInstance(map));
assertEquals(ImmutableMap.of(FOO, BAR), map);
assertEquals("{foo=bar}", map.toString());
assertEquals(mapClass.getSimpleName() + "{offsets={foo=0, bar=1}}", template.toString());
// Successful instantiation
- Map<String, String> map = template.instantiateWithValues(BAR, FOO);
+ var map = template.instantiateWithValues(BAR, FOO);
assertTrue(mapClass.isInstance(map));
assertEquals(ImmutableMap.of(FOO, BAR, BAR, FOO), map);
assertEquals("{foo=bar, bar=foo}", map.toString());
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
-import java.util.List;
-import org.junit.Test;
-
-public class LazyCollectionsTest {
+import org.junit.jupiter.api.Test;
+class LazyCollectionsTest {
@Test
- public void testLazyAddMethod() {
- final List<Integer> list = new ArrayList<>();
- List<Integer> anotherList = LazyCollections.lazyAdd(list, 5);
+ void testLazyAddMethod() {
+ final var list = new ArrayList<Integer>();
+ var anotherList = LazyCollections.lazyAdd(list, 5);
assertEquals(1, anotherList.size());
anotherList = LazyCollections.lazyAdd(anotherList, 4);
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.EventListener;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-
-public class ListenerRegistryTest {
- private ExtendedTestEventListener extendedTestEventListener;
- private ListenerRegistry<TestEventListener> registry;
-
- @Before
- public void init() {
- extendedTestEventListener = new ExtendedTestEventListener() {};
- registry = ListenerRegistry.create();
- }
+import org.junit.jupiter.api.Test;
+
+class ListenerRegistryTest {
+ private final ExtendedTestEventListener extendedTestEventListener = new ExtendedTestEventListener() {};
+ private final ListenerRegistry<TestEventListener> registry = ListenerRegistry.create();
@Test
- public void testCreateNewInstance() {
- assertNotNull("Intance of listener registry should not be null.", registry);
+ void testCreateNewInstance() {
+ assertNotNull(registry, "Intance of listener registry should not be null.");
}
@Test
- public void testGetListenersMethod() {
- assertEquals("Listener registry should not have any listeners.", 0, registry.streamListeners().count());
+ void testGetListenersMethod() {
+ assertEquals(0, registry.streamListeners().count(), "Listener registry should not have any listeners.");
}
@Test
- public void testRegisterMethod() {
- final ListenerRegistration<ExtendedTestEventListener> listenerRegistration = registry.register(
- extendedTestEventListener);
- assertEquals("Listeners should be the same.", extendedTestEventListener, listenerRegistration.getInstance());
+ void testRegisterMethod() {
+ final var listenerRegistration = registry.register(extendedTestEventListener);
+ assertEquals(extendedTestEventListener, listenerRegistration.getInstance(), "Listeners should be the same.");
}
interface TestEventListener extends EventListener {
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.HashMap;
-import java.util.Map;
import java.util.TreeMap;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
-public class MapAdaptorTest {
+class MapAdaptorTest {
private MapAdaptor adaptor;
- @Before
- public void setUp() {
+ @BeforeEach
+ void setUp() {
adaptor = MapAdaptor.getInstance(true, 10, 5);
}
@Test
- public void testTreeToEmpty() {
- final Map<String, String> input = new TreeMap<>();
+ void testTreeToEmpty() {
+ final var input = new TreeMap<>();
// Converts the input into a hashmap;
- final Map<?, ?> snap = adaptor.takeSnapshot(input);
+ final var snap = adaptor.takeSnapshot(input);
assertNotSame(input, snap);
- assertTrue(snap instanceof HashMap);
+ assertInstanceOf(HashMap.class, snap);
- final Map<?, ?> opt1 = adaptor.optimize(input);
+ final var opt1 = adaptor.optimize(input);
assertSame(ImmutableMap.of(), opt1);
- final Map<?, ?> opt2 = adaptor.optimize(snap);
+ final var opt2 = adaptor.optimize(snap);
assertSame(ImmutableMap.of(), opt2);
}
@Test
- public void testTreeToSingleton() {
- final Map<String, String> input = new TreeMap<>();
+ void testTreeToSingleton() {
+ final var input = new TreeMap<>();
input.put("a", "b");
- final Map<?, ?> snap = adaptor.takeSnapshot(input);
+ final var snap = adaptor.takeSnapshot(input);
assertNotSame(input, snap);
- assertTrue(snap instanceof HashMap);
+ assertInstanceOf(HashMap.class, snap);
assertEquals(input, snap);
- final Map<?, ?> opt1 = adaptor.optimize(input);
+ final var opt1 = adaptor.optimize(input);
assertNotSame(input, opt1);
assertEquals(input, opt1);
assertEquals(Collections.singletonMap(null, null).getClass(), opt1.getClass());
- final Map<?, ?> snap1 = adaptor.takeSnapshot(opt1);
- assertTrue(snap1 instanceof HashMap);
+ final var snap1 = adaptor.takeSnapshot(opt1);
+ assertInstanceOf(HashMap.class, snap1);
assertEquals(input, snap1);
- final Map<?, ?> opt2 = adaptor.optimize(snap);
+ final var opt2 = adaptor.optimize(snap);
assertNotSame(snap, opt2);
assertEquals(input, opt2);
assertEquals(Collections.singletonMap(null, null).getClass(), opt2.getClass());
- final Map<?, ?> snap2 = adaptor.takeSnapshot(opt2);
+ final var snap2 = adaptor.takeSnapshot(opt2);
assertNotSame(opt2, snap2);
- assertTrue(snap2 instanceof HashMap);
+ assertInstanceOf(HashMap.class, snap2);
assertEquals(input, snap2);
}
@Test
- public void testTreeToTrie() {
- final Map<String, String> input = new TreeMap<>();
- for (char c = 'a'; c <= 'z'; ++c) {
- final String s = String.valueOf(c);
+ void testTreeToTrie() {
+ final var input = new TreeMap<String, String>();
+ for (var c = 'a'; c <= 'z'; ++c) {
+ final var s = String.valueOf(c);
input.put(s, s);
}
- final Map<String, String> snap = adaptor.takeSnapshot(input);
- assertTrue(snap instanceof HashMap);
+ final var snap = adaptor.takeSnapshot(input);
+ assertInstanceOf(HashMap.class, snap);
assertEquals(input, snap);
- final Map<String, String> opt1 = adaptor.optimize(input);
+ final var opt1 = adaptor.optimize(input);
assertEquals(input, opt1);
assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
- final Map<String, String> snap2 = adaptor.takeSnapshot(opt1);
- assertTrue(snap2 instanceof ReadWriteTrieMap);
+ final var snap2 = adaptor.takeSnapshot(opt1);
+ assertInstanceOf(ReadWriteTrieMap.class, snap2);
assertEquals(opt1, snap2);
assertEquals(26, snap2.size());
// snap2 and snap3 are independent
- final Map<String, String> snap3 = adaptor.takeSnapshot(opt1);
+ final var snap3 = adaptor.takeSnapshot(opt1);
snap2.remove("a");
assertEquals(25, snap2.size());
}
@Test
- public void testTrieToHash() {
- final Map<String, String> input = new TreeMap<>();
+ void testTrieToHash() {
+ final var input = new TreeMap<String, String>();
for (char c = 'a'; c <= 'k'; ++c) {
final String s = String.valueOf(c);
input.put(s, s);
}
// Translated to read-only
- final Map<String, String> opt1 = adaptor.optimize(input);
+ final var opt1 = adaptor.optimize(input);
assertEquals(input, opt1);
assertEquals(ReadOnlyTrieMap.class, opt1.getClass());
assertEquals(11, opt1.size());
// 11 elements -- should retain TrieMap
- final Map<String, String> snap1 = adaptor.takeSnapshot(opt1);
+ final var snap1 = adaptor.takeSnapshot(opt1);
assertEquals(ReadWriteTrieMap.class, snap1.getClass());
assertEquals(11, snap1.size());
- for (char c = 'e'; c <= 'k'; ++c) {
- final String s = String.valueOf(c);
+ for (var c = 'e'; c <= 'k'; ++c) {
+ final var s = String.valueOf(c);
snap1.remove(s);
}
// 4 elements: should revert to HashMap
assertEquals(4, snap1.size());
- final Map<String, String> opt2 = adaptor.optimize(snap1);
+ final var opt2 = adaptor.optimize(snap1);
assertEquals(snap1, opt2);
assertEquals(HashMap.class, opt2.getClass());
assertEquals(4, opt2.size());
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.AbstractMap.SimpleEntry;
-import java.util.Collection;
-import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.NoSuchElementException;
-import java.util.Set;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class OffsetMapTest {
private final Map<String, String> twoEntryMap = ImmutableMap.of("k1", "v1", "k2", "v2");
return (ImmutableOffsetMap<String, String>) ImmutableOffsetMap.unorderedCopyOf(twoEntryMap);
}
- @Before
- public void setup() {
+ @BeforeEach
+ void setup() {
OffsetMapCache.invalidateCache();
}
}
@Test
- public void testCopyEmptyMap() {
- final Map<String, String> source = Collections.emptyMap();
- final Map<String, String> result = ImmutableOffsetMap.orderedCopyOf(source);
+ void testCopyEmptyMap() {
+ final var source = Map.of();
+ final var result = ImmutableOffsetMap.orderedCopyOf(source);
assertEquals(source, result);
- assertTrue(result instanceof ImmutableMap);
+ assertInstanceOf(ImmutableMap.class, result);
}
@Test
- public void testCopySingletonMap() {
- final Map<String, String> source = Collections.singletonMap("a", "b");
- final Map<String, String> result = ImmutableOffsetMap.orderedCopyOf(source);
+ void testCopySingletonMap() {
+ final var source = Map.of("a", "b");
+ final var result = ImmutableOffsetMap.orderedCopyOf(source);
assertEquals(source, result);
- assertTrue(result instanceof SharedSingletonMap);
+ assertInstanceOf(SharedSingletonMap.class, result);
}
@Test
- public void testCopyMap() {
- final ImmutableOffsetMap<String, String> map = createMap();
+ void testCopyMap() {
+ final var map = createMap();
// Equality in both directions
assertEquals(twoEntryMap, map);
// Should result in the same object
assertSame(map, ImmutableOffsetMap.orderedCopyOf(map));
- final Map<String, String> mutable = map.toModifiableMap();
- final Map<String, String> copy = ImmutableOffsetMap.orderedCopyOf(mutable);
+ final var mutable = map.toModifiableMap();
+ final var copy = ImmutableOffsetMap.orderedCopyOf(mutable);
assertEquals(mutable, copy);
assertEquals(map, copy);
}
@Test
- public void testImmutableSimpleEquals() {
- final Map<String, String> map = createMap();
+ void testImmutableSimpleEquals() {
+ final var map = createMap();
- assertTrue(map.equals(map));
- assertFalse(map.equals(null));
- assertFalse(map.equals("string"));
+ assertEquals(map, map);
+ assertNotEquals(null, map);
+ assertNotEquals("string", map);
}
@Test
- public void testImmutableGet() {
- final Map<String, String> map = createMap();
+ void testImmutableGet() {
+ final var map = createMap();
assertEquals("v1", map.get("k1"));
assertEquals("v2", map.get("k2"));
}
@Test
- public void testImmutableGuards() {
- final Map<String, String> map = createMap();
+ void testImmutableGuards() {
+ final var map = createMap();
- final Collection<String> values = map.values();
+ final var values = map.values();
assertThrows(UnsupportedOperationException.class, () -> values.add("v1"));
assertThrows(UnsupportedOperationException.class, () -> values.remove("v1"));
assertThrows(UnsupportedOperationException.class, () -> values.clear());
- final Iterator<String> vit = values.iterator();
+ final var vit = values.iterator();
vit.next();
assertThrows(UnsupportedOperationException.class, () -> vit.remove());
- final Set<String> keySet = map.keySet();
+ final var keySet = map.keySet();
assertThrows(UnsupportedOperationException.class, () -> keySet.add("k1"));
assertThrows(UnsupportedOperationException.class, () -> keySet.clear());
assertThrows(UnsupportedOperationException.class, () -> keySet.remove("k1"));
- final Iterator<String> kit = keySet.iterator();
+ final var kit = keySet.iterator();
kit.next();
assertThrows(UnsupportedOperationException.class, () -> kit.remove());
- final Set<Entry<String, String>> entrySet = map.entrySet();
+ final var entrySet = map.entrySet();
assertThrows(UnsupportedOperationException.class, () -> entrySet.clear());
assertThrows(UnsupportedOperationException.class, () -> entrySet.add(new SimpleEntry<>("k1", "v1")));
assertThrows(UnsupportedOperationException.class, () -> entrySet.remove(new SimpleEntry<>("k1", "v1")));
- final Iterator<Entry<String, String>> eit = entrySet.iterator();
+ final var eit = entrySet.iterator();
eit.next();
assertThrows(UnsupportedOperationException.class, () -> eit.remove());
}
@Test
- public void testMutableGet() {
- final Map<String, String> map = createMap().toModifiableMap();
+ void testMutableGet() {
+ final var map = createMap().toModifiableMap();
map.put("k3", "v3");
assertEquals("v1", map.get("k1"));
}
@Test
- public void testImmutableSize() {
- final Map<String, String> map = createMap();
+ void testImmutableSize() {
+ final var map = createMap();
assertEquals(2, map.size());
}
@Test
- public void testImmutableIsEmpty() {
- final Map<String, String> map = createMap();
+ void testImmutableIsEmpty() {
+ final var map = createMap();
assertFalse(map.isEmpty());
}
@Test
- public void testImmutableContains() {
- final Map<String, String> map = createMap();
+ void testImmutableContains() {
+ final var map = createMap();
assertTrue(map.containsKey("k1"));
assertTrue(map.containsKey("k2"));
assertFalse(map.containsKey("non-existent"));
}
@Test
- public void testImmutableEquals() {
- final Map<String, String> map = createMap();
+ void testImmutableEquals() {
+ final var map = createMap();
- assertFalse(map.equals(threeEntryMap));
- assertFalse(map.equals(ImmutableMap.of("k1", "v1", "k3", "v3")));
- assertFalse(map.equals(ImmutableMap.of("k1", "v1", "k2", "different-value")));
+ assertNotEquals(map, threeEntryMap);
+ assertNotEquals(map, ImmutableMap.of("k1", "v1", "k3", "v3"));
+ assertNotEquals(map, ImmutableMap.of("k1", "v1", "k2", "different-value"));
}
@Test
- public void testMutableContains() {
- final Map<String, String> map = createMap().toModifiableMap();
+ void testMutableContains() {
+ final var map = createMap().toModifiableMap();
map.put("k3", "v3");
assertTrue(map.containsKey("k1"));
assertTrue(map.containsKey("k2"));
}
@Test
- public void testtoModifiableMap() {
- final ImmutableOffsetMap<String, String> source = createMap();
- final Map<String, String> result = source.toModifiableMap();
+ void testtoModifiableMap() {
+ final var source = createMap();
+ final var result = source.toModifiableMap();
// The two maps should be equal, but isolated
- assertTrue(result instanceof MutableOffsetMap);
+ assertInstanceOf(MutableOffsetMap.class, result);
assertEquals(source, result);
assertEquals(result, source);
// Quick test for clearing MutableOffsetMap
result.clear();
assertEquals(0, result.size());
- assertEquals(Collections.emptyMap(), result);
+ assertEquals(Map.of(), result);
// The two maps should differ now
- assertFalse(source.equals(result));
- assertFalse(result.equals(source));
+ assertNotEquals(source, result);
+ assertNotEquals(result, source);
// The source map should still equal the template
assertEquals(twoEntryMap, source);
}
@Test
- public void testReusedFields() {
- final ImmutableOffsetMap<String, String> source = createMap();
- final MutableOffsetMap<String, String> mutable = source.toModifiableMap();
+ void testReusedFields() {
+ final var source = createMap();
+ final var mutable = source.toModifiableMap();
// Should not affect the result
mutable.remove("non-existent");
// Resulting map should be equal, but not the same object
- final ImmutableOffsetMap<String, String> result = (ImmutableOffsetMap<String, String>) mutable
+ final var result = (ImmutableOffsetMap<String, String>) mutable
.toUnmodifiableMap();
assertNotSame(source, result);
assertEquals(source, result);
}
@Test
- public void testReusedOffsets() {
- final ImmutableOffsetMap<String, String> source = createMap();
- final MutableOffsetMap<String, String> mutable = source.toModifiableMap();
+ void testReusedOffsets() {
+ final var source = createMap();
+ final var mutable = source.toModifiableMap();
mutable.remove("k1");
mutable.put("k1", "v1");
- final ImmutableOffsetMap<String, String> result = (ImmutableOffsetMap<String, String>) mutable
+ final var result = (ImmutableOffsetMap<String, String>) mutable
.toUnmodifiableMap();
- assertTrue(source.equals(result));
- assertTrue(result.equals(source));
+ assertEquals(source, result);
+ assertEquals(result, source);
// Iterator order must not be preserved
assertFalse(Iterators.elementsEqual(source.entrySet().iterator(), result.entrySet().iterator()));
}
@Test
- public void testReusedOffsetsUnordered() {
- final ImmutableOffsetMap<String, String> source = unorderedMap();
- final MutableOffsetMap<String, String> mutable = source.toModifiableMap();
+ void testReusedOffsetsUnordered() {
+ final var source = unorderedMap();
+ final var mutable = source.toModifiableMap();
mutable.remove("k1");
mutable.put("k1", "v1");
- final ImmutableOffsetMap<String, String> result = (ImmutableOffsetMap<String, String>) mutable
+ final var result = (ImmutableOffsetMap<String, String>) mutable
.toUnmodifiableMap();
assertEquals(source, result);
}
@Test
- public void testEmptyMutable() throws CloneNotSupportedException {
- final MutableOffsetMap<String, String> map = MutableOffsetMap.ordered();
+ void testEmptyMutable() throws CloneNotSupportedException {
+ final var map = MutableOffsetMap.ordered();
assertTrue(map.isEmpty());
- final Map<String, String> other = map.clone();
+ final var other = map.clone();
assertEquals(other, map);
assertNotSame(other, map);
}
@Test
- public void testMutableToEmpty() {
- final MutableOffsetMap<String, String> mutable = createMap().toModifiableMap();
+ void testMutableToEmpty() {
+ final var mutable = createMap().toModifiableMap();
mutable.remove("k1");
mutable.remove("k2");
}
@Test
- public void testMutableToSingleton() {
- final MutableOffsetMap<String, String> mutable = createMap().toModifiableMap();
+ void testMutableToSingleton() {
+ final var mutable = createMap().toModifiableMap();
mutable.remove("k1");
- final Map<String, String> result = mutable.toUnmodifiableMap();
+ final var result = mutable.toUnmodifiableMap();
// Should devolve to a singleton
- assertTrue(result instanceof SharedSingletonMap);
+ assertInstanceOf(SharedSingletonMap.class, result);
assertEquals(ImmutableMap.of("k2", "v2"), result);
}
@Test
- public void testMutableToNewSingleton() {
- final MutableOffsetMap<String, String> mutable = createMap().toModifiableMap();
+ void testMutableToNewSingleton() {
+ final var mutable = createMap().toModifiableMap();
mutable.remove("k1");
mutable.put("k3", "v3");
- final Map<String, String> result = mutable.toUnmodifiableMap();
+ final var result = mutable.toUnmodifiableMap();
- assertTrue(result instanceof ImmutableOffsetMap);
+ assertInstanceOf(ImmutableOffsetMap.class, result);
assertEquals(ImmutableMap.of("k2", "v2", "k3", "v3"), result);
}
@Test
- public void testMutableSize() {
- final MutableOffsetMap<String, String> mutable = createMap().toModifiableMap();
+ void testMutableSize() {
+ final var mutable = createMap().toModifiableMap();
assertEquals(2, mutable.size());
mutable.put("k3", "v3");
}
@Test
- public void testExpansionWithOrder() {
- final MutableOffsetMap<String, String> mutable = createMap().toModifiableMap();
+ void testExpansionWithOrder() {
+ final var mutable = createMap().toModifiableMap();
mutable.remove("k1");
mutable.put("k3", "v3");
assertEquals(ImmutableMap.of("k1", "v1", "k3", "v3"), mutable.newKeys());
- final Map<String, String> result = mutable.toUnmodifiableMap();
+ final var result = mutable.toUnmodifiableMap();
- assertTrue(result instanceof ImmutableOffsetMap);
+ assertInstanceOf(ImmutableOffsetMap.class, result);
assertEquals(threeEntryMap, result);
assertEquals(result, threeEntryMap);
assertFalse(Iterators.elementsEqual(threeEntryMap.entrySet().iterator(), result.entrySet().iterator()));
}
@Test
- public void testExpansionWithoutOrder() {
- final MutableOffsetMap<String, String> mutable = unorderedMap().toModifiableMap();
+ void testExpansionWithoutOrder() {
+ final var mutable = unorderedMap().toModifiableMap();
mutable.remove("k1");
mutable.put("k3", "v3");
assertEquals(ImmutableMap.of("k3", "v3"), mutable.newKeys());
- final Map<String, String> result = mutable.toUnmodifiableMap();
+ final var result = mutable.toUnmodifiableMap();
- assertTrue(result instanceof ImmutableOffsetMap);
+ assertInstanceOf(ImmutableOffsetMap.class, result);
assertEquals(threeEntryMap, result);
assertEquals(result, threeEntryMap);
assertTrue(Iterators.elementsEqual(threeEntryMap.entrySet().iterator(), result.entrySet().iterator()));
}
@Test
- public void testReplacedValue() {
- final ImmutableOffsetMap<String, String> source = createMap();
- final MutableOffsetMap<String, String> mutable = source.toModifiableMap();
+ void testReplacedValue() {
+ final var source = createMap();
+ final var mutable = source.toModifiableMap();
mutable.put("k1", "replaced");
- final ImmutableOffsetMap<String, String> result = (ImmutableOffsetMap<String, String>) mutable
+ final var result = (ImmutableOffsetMap<String, String>) mutable
.toUnmodifiableMap();
- final Map<String, String> reference = ImmutableMap.of("k1", "replaced", "k2", "v2");
+ final var reference = ImmutableMap.of("k1", "replaced", "k2", "v2");
assertEquals(reference, result);
assertEquals(result, reference);
}
@Test
- public void testCloneableFlipping() throws CloneNotSupportedException {
- final MutableOffsetMap<String, String> source = createMap().toModifiableMap();
+ void testCloneableFlipping() throws CloneNotSupportedException {
+ final var source = createMap().toModifiableMap();
// Must clone before mutation
assertTrue(source.needClone());
assertFalse(source.needClone());
// Create a clone of the map, which shares the array
- final MutableOffsetMap<String, String> result = source.clone();
+ final var result = source.clone();
assertFalse(source.needClone());
assertTrue(result.needClone());
assertSame(source.array(), result.array());
assertTrue(result.needClone());
// Forced copy, no cloning needed, but maps are equal
- final ImmutableOffsetMap<String, String> immutable = (ImmutableOffsetMap<String, String>) source
+ final var immutable = (ImmutableOffsetMap<String, String>) source
.toUnmodifiableMap();
assertFalse(source.needClone());
- assertTrue(source.equals(immutable));
- assertTrue(immutable.equals(source));
+ assertEquals(source, immutable);
+ assertEquals(immutable, source);
assertTrue(Iterables.elementsEqual(source.entrySet(), immutable.entrySet()));
}
@Test
- public void testCloneableFlippingUnordered() throws CloneNotSupportedException {
- final MutableOffsetMap<String, String> source = unorderedMap().toModifiableMap();
+ void testCloneableFlippingUnordered() throws CloneNotSupportedException {
+ final var source = unorderedMap().toModifiableMap();
// Must clone before mutation
assertTrue(source.needClone());
assertFalse(source.needClone());
// Create a clone of the map, which shares the array
- final MutableOffsetMap<String, String> result = source.clone();
+ final var result = source.clone();
assertFalse(source.needClone());
assertTrue(result.needClone());
assertSame(source.array(), result.array());
assertTrue(result.needClone());
// Creates a immutable view, which shares the array
- final ImmutableOffsetMap<String, String> immutable =
- (ImmutableOffsetMap<String, String>) source.toUnmodifiableMap();
+ final var immutable = (ImmutableOffsetMap<String, String>) source.toUnmodifiableMap();
assertTrue(source.needClone());
assertSame(source.array(), immutable.objects());
}
@Test
- public void testMutableEntrySet() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
+ void testMutableEntrySet() {
+ final var map = createMap().toModifiableMap();
assertTrue(map.entrySet().add(new SimpleEntry<>("k3", "v3")));
assertTrue(map.containsKey("k3"));
}
@Test
- public void testMutableSimpleEquals() {
- final ImmutableOffsetMap<String, String> source = createMap();
- final Map<String, String> map = source.toModifiableMap();
+ void testMutableSimpleEquals() {
+ final var source = createMap();
+ final var map = source.toModifiableMap();
- assertTrue(map.equals(map));
- assertFalse(map.equals(null));
- assertFalse(map.equals("string"));
- assertTrue(map.equals(source));
+ assertEquals(map, map);
+ assertNotEquals(null, map);
+ assertNotEquals("string", map);
+ assertEquals(map, source);
}
@Test
- public void testMutableSimpleHashCode() {
- final Map<String, String> map = createMap().toModifiableMap();
+ void testMutableSimpleHashCode() {
+ final var map = createMap().toModifiableMap();
assertEquals(twoEntryMap.hashCode(), map.hashCode());
}
@Test
- public void testMutableIteratorBasics() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ void testMutableIteratorBasics() {
+ final var map = createMap().toModifiableMap();
+ final var it = map.entrySet().iterator();
// Not advanced, remove should fail
assertThrows(IllegalStateException.class, () -> it.remove());
}
@Test
- public void testMutableIteratorWithRemove() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ void testMutableIteratorWithRemove() {
+ final var map = createMap().toModifiableMap();
+ final var it = map.entrySet().iterator();
// Advance one element
assertTrue(it.hasNext());
}
@Test
- public void testMutableIteratorOffsetReplaceWorks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ void testMutableIteratorOffsetReplaceWorks() {
+ final var map = createMap().toModifiableMap();
+ final var it = map.entrySet().iterator();
it.next();
map.put("k1", "new-v1");
}
@Test
- public void testMutableIteratorNewReplaceWorks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
+ void testMutableIteratorNewReplaceWorks() {
+ final var map = createMap().toModifiableMap();
map.put("k3", "v3");
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ final var it = map.entrySet().iterator();
it.next();
map.put("k3", "new-v3");
}
@Test
- public void testMutableIteratorOffsetAddBreaks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
+ void testMutableIteratorOffsetAddBreaks() {
+ final var map = createMap().toModifiableMap();
map.put("k3", "v3");
map.remove("k1");
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ final var it = map.entrySet().iterator();
it.next();
map.put("k1", "new-v1");
}
@Test
- public void testMutableIteratorNewAddBreaks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ void testMutableIteratorNewAddBreaks() {
+ final var map = createMap().toModifiableMap();
+ final var it = map.entrySet().iterator();
it.next();
map.put("k3", "v3");
}
@Test
- public void testMutableIteratorOffsetRemoveBreaks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ void testMutableIteratorOffsetRemoveBreaks() {
+ final var map = createMap().toModifiableMap();
+ final var it = map.entrySet().iterator();
it.next();
map.remove("k1");
}
@Test
- public void testMutableIteratorNewRemoveBreaks() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
+ void testMutableIteratorNewRemoveBreaks() {
+ final var map = createMap().toModifiableMap();
map.put("k3", "v3");
- final Iterator<Entry<String, String>> it = map.entrySet().iterator();
+ final var it = map.entrySet().iterator();
it.next();
map.remove("k3");
}
@Test
- public void testMutableCrossIteratorRemove() {
- final MutableOffsetMap<String, String> map = createMap().toModifiableMap();
- final Set<Entry<String, String>> es = map.entrySet();
- final Iterator<Entry<String, String>> it1 = es.iterator();
- final Iterator<Entry<String, String>> it2 = es.iterator();
+ void testMutableCrossIteratorRemove() {
+ final var map = createMap().toModifiableMap();
+ final var es = map.entrySet();
+ final var it1 = es.iterator();
+ final var it2 = es.iterator();
// Remove k1 via it1
it1.next();
}
@Test
- public void testImmutableSerialization() throws IOException, ClassNotFoundException {
- final Map<String, String> source = createMap();
+ void testImmutableSerialization() throws IOException, ClassNotFoundException {
+ final var source = createMap();
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ final var bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(source);
}
- final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ final var ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
@SuppressWarnings("unchecked")
- final Map<String, String> result = (Map<String, String>) ois.readObject();
+ final var result = (Map<String, String>) ois.readObject();
assertEquals(source, result);
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
-
-public class PropertyUtilsTest {
+import org.junit.jupiter.api.Test;
+class PropertyUtilsTest {
@Test
- public void testGetIntSystemProperty() {
- final int testValue = PropertyUtils.getIntSystemProperty("file.separator", 1);
- assertEquals("Property value should be '1'.", 1, testValue);
+ void testGetIntSystemProperty() {
+ final var testValue = PropertyUtils.getIntSystemProperty("file.separator", 1);
+ assertEquals(1, testValue, "Property value should be '1'.");
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
-import org.junit.Test;
-import tech.pantheon.triemap.MutableTrieMap;
+import org.junit.jupiter.api.Test;
import tech.pantheon.triemap.TrieMap;
-public class ReadWriteTrieMapTest {
+class ReadWriteTrieMapTest {
@Test
- public void testMethodsOfReadWriteTrieMap() {
- final MutableTrieMap<String, String> trieMap = TrieMap.create();
+ void testMethodsOfReadWriteTrieMap() {
+ final var trieMap = TrieMap.<String, String>create();
trieMap.put("0", "zero");
trieMap.put("1", "one");
- final ReadWriteTrieMap<String, String> readWriteTrieMap = new ReadWriteTrieMap<>(trieMap, 5);
+ final var readWriteTrieMap = new ReadWriteTrieMap<>(trieMap, 5);
- assertNotNull("Object readOnlyTrieMap shouldn't be 'null'.", readWriteTrieMap);
+ assertNotNull(readWriteTrieMap, "Object readOnlyTrieMap shouldn't be 'null'.");
- assertEquals("Size of readOnlyTrieMap should be '5'.", 5, readWriteTrieMap.size());
- assertFalse("Object readOnlyTrieMap shouldn't be empty.", readWriteTrieMap.isEmpty());
+ assertEquals(5, readWriteTrieMap.size(), "Size of readOnlyTrieMap should be '5'.");
+ assertFalse(readWriteTrieMap.isEmpty(), "Object readOnlyTrieMap shouldn't be empty.");
- assertTrue("Object readOnlyTrieMap should have key '0'.", readWriteTrieMap.containsKey("0"));
- assertTrue("Object readOnlyTrieMap should have value 'zero'.", readWriteTrieMap.containsValue("zero"));
- assertEquals("Object readOnlyTrieMap should have value 'zero'.", "zero", readWriteTrieMap.get("0"));
+ assertTrue(readWriteTrieMap.containsKey("0"), "Object readOnlyTrieMap should have key '0'.");
+ assertTrue(readWriteTrieMap.containsValue("zero"), "Object readOnlyTrieMap should have value 'zero'.");
+ assertEquals("zero", readWriteTrieMap.get("0"), "Object readOnlyTrieMap should have value 'zero'.");
- final Map<String, String> rwMap = readWriteTrieMap;
+ final var rwMap = readWriteTrieMap;
rwMap.put("2", "two");
rwMap.put("3", "three");
- assertEquals("Removed value from readOnlyTrieMap should be 'one'.", "one", rwMap.remove("1"));
+ assertEquals("one", rwMap.remove("1"), "Removed value from readOnlyTrieMap should be 'one'.");
- final Set<String> trieMapKeySet = readWriteTrieMap.keySet();
- assertEquals("Size of keySet should be '3'.", 3, trieMapKeySet.size());
+ final var trieMapKeySet = readWriteTrieMap.keySet();
+ assertEquals(3, trieMapKeySet.size(), "Size of keySet should be '3'.");
- final Collection<String> trieMapValues = readWriteTrieMap.values();
- assertEquals("Size of values should be '3'.", 3, trieMapValues.size());
+ final var trieMapValues = readWriteTrieMap.values();
+ assertEquals(3, trieMapValues.size(), "Size of values should be '3'.");
assertEquals(convertSetEntryToMap(readWriteTrieMap.entrySet()), trieMap);
trieMap.put("2", "two");
- final ReadWriteTrieMap<String, String> readWriteTrieMap2 = new ReadWriteTrieMap<>(trieMap, 4);
+ final var readWriteTrieMap2 = new ReadWriteTrieMap<>(trieMap, 4);
assertNotEquals(readWriteTrieMap, readWriteTrieMap2);
assertEquals(readWriteTrieMap.hashCode(), readWriteTrieMap2.hashCode());
- final Map<String, String> readOnlyTrieMap = readWriteTrieMap.toReadOnly();
+ final var readOnlyTrieMap = readWriteTrieMap.toReadOnly();
readWriteTrieMap.clear();
assertEquals(0, readWriteTrieMap.size());
assertEquals(6, readOnlyTrieMap.size());
}
private static Map<String, String> convertSetEntryToMap(final Set<Entry<String, String>> input) {
- Map<String, String> resultMap = new HashMap<>();
- for (Entry<String, String> entry : input) {
+ final var resultMap = new HashMap<String, String>();
+ for (var entry : input) {
resultMap.put(entry.getKey(), entry.getValue());
}
return resultMap;
*/
package org.opendaylight.yangtools.util;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableMap;
import java.util.Collections;
import java.util.Map;
-import java.util.Set;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class SharedSingletonMapTest {
+class SharedSingletonMapTest {
private static UnmodifiableMapPhase<String, String> create() {
return SharedSingletonMap.orderedOf("k1", "v1");
}
@Test
- public void testSimpleOperations() {
- final Map<String, String> m = create();
+ void testSimpleOperations() {
+ final var m = create();
assertFalse(m.isEmpty());
assertEquals(1, m.size());
assertNull(m.get(null));
assertNull(m.get("v1"));
- assertFalse(m.equals(null));
- assertTrue(m.equals(m));
- assertFalse(m.equals(""));
+ assertNotEquals(null, m);
+ assertEquals(m, m);
+ assertNotEquals("", m);
- final Map<String, String> same = Collections.singletonMap("k1", "v1");
+ final var same = Collections.singletonMap("k1", "v1");
assertEquals(same.toString(), m.toString());
- assertTrue(same.equals(m));
- assertTrue(m.equals(same));
+ assertEquals(same, m);
+ assertEquals(m, same);
assertEquals(same.entrySet(), m.entrySet());
assertEquals(same.values(), m.values());
assertEquals(same.hashCode(), m.hashCode());
assertEquals(same.hashCode(), m.hashCode());
- assertFalse(m.equals(Collections.singletonMap(null, null)));
- assertFalse(m.equals(Collections.singletonMap("k1", null)));
- assertFalse(m.equals(Collections.singletonMap(null, "v1")));
- assertFalse(m.equals(Collections.singletonMap("k1", "v2")));
- assertFalse(m.equals(ImmutableMap.of("k1", "v1", "k2", "v2")));
+ assertNotEquals(m, Collections.singletonMap(null, null));
+ assertNotEquals(m, Collections.singletonMap("k1", null));
+ assertNotEquals(m, Collections.singletonMap(null, "v1"));
+ assertNotEquals(m, Map.of("k1", "v2"));
+ assertNotEquals(m, ImmutableMap.of("k1", "v1", "k2", "v2"));
- final Set<String> set = m.keySet();
- assertThat(set, instanceOf(SingletonSet.class));
+ final var set = m.keySet();
+ assertInstanceOf(SingletonSet.class, set);
assertTrue(set.contains("k1"));
}
@Test
- public void testOrderedCopyOf() {
- final Map<String, String> t = Collections.singletonMap("k1", "v1");
- final Map<String, String> m = SharedSingletonMap.orderedCopyOf(t);
- assertTrue(t.equals(m));
- assertTrue(m.equals(t));
+ void testOrderedCopyOf() {
+ final var t = Map.of("k1", "v1");
+ final var m = SharedSingletonMap.orderedCopyOf(t);
+ assertEquals(t, m);
+ assertEquals(m, t);
}
@Test
- public void testUnorderedCopyOf() {
- final Map<String, String> t = Collections.singletonMap("k1", "v1");
- final Map<String, String> m = SharedSingletonMap.unorderedCopyOf(t);
- assertTrue(t.equals(m));
- assertTrue(m.equals(t));
+ void testUnorderedCopyOf() {
+ final var t = Map.of("k1", "v1");
+ final var m = SharedSingletonMap.unorderedCopyOf(t);
+ assertEquals(t, m);
+ assertEquals(m, t);
}
@Test
- public void testEmptyOrderedCopyOf() {
+ void testEmptyOrderedCopyOf() {
assertThrows(IllegalArgumentException.class, () -> SharedSingletonMap.orderedCopyOf(ImmutableMap.of()));
}
@Test
- public void testEmptyUnorderedCopyOf() {
+ void testEmptyUnorderedCopyOf() {
assertThrows(IllegalArgumentException.class, () -> SharedSingletonMap.unorderedCopyOf(ImmutableMap.of()));
}
@Test
- public void testClear() {
+ void testClear() {
assertThrows(UnsupportedOperationException.class, () -> create().clear());
}
@Test
- public void testPut() {
+ void testPut() {
assertThrows(UnsupportedOperationException.class, () -> create().put(null, null));
}
@Test
- public void testPutAll() {
+ void testPutAll() {
assertThrows(UnsupportedOperationException.class, () -> create().putAll(Collections.singletonMap("", "")));
}
@Test
- public void testRemove() {
+ void testRemove() {
assertThrows(UnsupportedOperationException.class, () -> create().remove(null));
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
-import java.util.Iterator;
-import org.junit.Test;
+import java.util.Set;
+import org.junit.jupiter.api.Test;
-public class SingletonSetTest {
+class SingletonSetTest {
private static final String ELEMENT = "element";
private static SingletonSet<?> nullSet() {
}
@Test
- public void testNullSingleton() {
- final SingletonSet<?> s = nullSet();
+ void testNullSingleton() {
+ final var s = nullSet();
assertFalse(s.isEmpty());
assertEquals(1, s.size());
assertTrue(s.contains(null));
assertNull(s.getElement());
assertEquals(0, s.hashCode());
- assertTrue(s.equals(Collections.singleton(null)));
- assertFalse(s.equals(Collections.singleton("")));
- assertFalse(s.equals(""));
- assertTrue(s.equals(s));
- assertFalse(s.equals(null));
+ assertEquals(s, Collections.singleton(null));
+ assertNotEquals(s, Collections.singleton(""));
+ assertNotEquals("", s);
+ assertEquals(s, s);
+ assertNotEquals(null, s);
assertEquals(Collections.singleton(null).toString(), s.toString());
}
@Test
- public void testRegularSingleton() {
- final SingletonSet<?> s = SingletonSet.of(ELEMENT);
+ void testRegularSingleton() {
+ final var s = SingletonSet.of(ELEMENT);
assertFalse(s.isEmpty());
assertEquals(1, s.size());
assertSame(ELEMENT, s.getElement());
assertEquals(ELEMENT.hashCode(), s.hashCode());
- assertTrue(s.equals(Collections.singleton(ELEMENT)));
- assertFalse(s.equals(Collections.singleton("")));
- assertFalse(s.equals(Collections.singleton(null)));
- assertFalse(s.equals(""));
- assertTrue(s.equals(s));
- assertFalse(s.equals(null));
+ assertEquals(s, Set.of(ELEMENT));
+ assertNotEquals(s, Set.of(""));
+ assertNotEquals(s, Collections.singleton(null));
+ assertNotEquals("", s);
+ assertEquals(s, s);
+ assertNotEquals(null, s);
assertEquals(Collections.singleton(ELEMENT).toString(), s.toString());
}
@Test
- public void testIterator() {
- final SingletonSet<?> s = SingletonSet.of(ELEMENT);
- final Iterator<?> it = s.iterator();
+ void testIterator() {
+ final var s = SingletonSet.of(ELEMENT);
+ final var it = s.iterator();
assertTrue(it.hasNext());
assertSame(ELEMENT, it.next());
}
@Test
- public void testRejectedAdd() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedAdd() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.add(null));
}
@Test
- public void testRejectedAddAll() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedAddAll() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.addAll(null));
}
@Test
- public void testRejectedClear() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedClear() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.clear());
}
@Test
- public void testRejectedRemove() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedRemove() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.remove(null));
}
@Test
- public void testRejectedRemoveAll() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedRemoveAll() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.removeAll(null));
}
@Test
- public void testRejectedRetainAll() {
- final SingletonSet<?> s = nullSet();
+ void testRejectedRetainAll() {
+ final var s = nullSet();
assertThrows(UnsupportedOperationException.class, () -> s.retainAll(null));
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class SynchronizedDurationStatsTrackerTest {
+class SynchronizedDurationStatsTrackerTest {
@Test
- public void testAllMethodsOfSynchronizedDurationStatsTracker() {
- final SynchronizedDurationStatsTracker statsTracker = new SynchronizedDurationStatsTracker();
+ void testAllMethodsOfSynchronizedDurationStatsTracker() {
+ final var statsTracker = new SynchronizedDurationStatsTracker();
statsTracker.addDuration(1000);
statsTracker.addDuration(2000);
statsTracker.addDuration(3000);
- assertEquals("Shortest recorded duration should be '1000'.", 1000, statsTracker.getShortest().duration());
- assertEquals("Average recorded duration should be '2000'.", 2000, statsTracker.getAverageDuration(), 0.0001);
- assertEquals("Longest recorded duration should be '3000'.", 3000, statsTracker.getLongest().duration());
- assertEquals("Total recorded duration count should be '3'.", 3, statsTracker.getTotalDurations());
+ assertEquals(1000, statsTracker.getShortest().duration(), "Shortest recorded duration should be '1000'.");
+ assertEquals(2000, statsTracker.getAverageDuration(), 0.0001, "Average recorded duration should be '2000'.");
+ assertEquals(3000, statsTracker.getLongest().duration(), "Longest recorded duration should be '3000'.");
+ assertEquals(3, statsTracker.getTotalDurations(), "Total recorded duration count should be '3'.");
statsTracker.reset();
- assertNull("Shortest recorded duration should be 'null'.", statsTracker.getShortest());
- assertEquals("Average recorded duration should be '0'.", 0, statsTracker.getAverageDuration(), 0.0001);
- assertNull("Longest recorded duration should be '0'.", statsTracker.getLongest());
- assertEquals("Total recorded duration should be '0'.", 0, statsTracker.getTotalDurations());
+ assertNull(statsTracker.getShortest(), "Shortest recorded duration should be 'null'.");
+ assertEquals(0, statsTracker.getAverageDuration(), 0.0001, "Average recorded duration should be '0'.");
+ assertNull(statsTracker.getLongest(), "Longest recorded duration should be '0'.");
+ assertEquals(0, statsTracker.getTotalDurations(), "Total recorded duration should be '0'.");
}
}
*/
package org.opendaylight.yangtools.util;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.opendaylight.yangtools.util.TopologicalSort.Node;
import org.opendaylight.yangtools.util.TopologicalSort.NodeImpl;
-public class TopologicalSortTest {
-
+class TopologicalSortTest {
@Test
- public void test() {
- Set<Node> nodes = new HashSet<>();
+ void test() {
+ final var nodes = new HashSet<Node>();
- NodeImpl node1 = new NodeImpl();
+ final var node1 = new NodeImpl();
nodes.add(node1);
- NodeImpl node2 = new NodeImpl();
+ final var node2 = new NodeImpl();
nodes.add(node2);
- NodeImpl node3 = new NodeImpl();
+ final var node3 = new NodeImpl();
nodes.add(node3);
node1.addEdge(node2);
}
@Test
- public void testValidSimple() throws Exception {
- Set<Node> nodes = new HashSet<>();
+ void testValidSimple() {
+ final var nodes = new HashSet<Node>();
- NodeImpl node1 = new NodeImpl();
+ final var node1 = new NodeImpl();
nodes.add(node1);
- NodeImpl node2 = new NodeImpl();
+ final var node2 = new NodeImpl();
nodes.add(node2);
- NodeImpl node3 = new NodeImpl();
+ final var node3 = new NodeImpl();
nodes.add(node3);
- Node node4 = new NodeImpl();
+ final var node4 = new NodeImpl();
nodes.add(node4);
node1.addEdge(node2);
node2.addEdge(node4);
node3.addEdge(node2);
- List<Node> sorted = TopologicalSort.sort(nodes);
+ final var sorted = TopologicalSort.sort(nodes);
assertEquals(node4, sorted.get(0));
assertEquals(node2, sorted.get(1));
*/
package org.opendaylight.yangtools.util;
-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 static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.UnmodifiableIterator;
import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-public class UnmodifiableCollectionTest {
+class UnmodifiableCollectionTest {
@Test
- public void testUnmodifiableCollection() {
- final List<Integer> immutableTestList = ImmutableList.<Integer>builder()
+ void testUnmodifiableCollection() {
+ final var immutableTestList = ImmutableList.<Integer>builder()
.add(1)
.add(2)
.add(3)
.add(4)
.add(5).build();
- final Collection<Integer> testUnmodifiableCollection = UnmodifiableCollection.create(immutableTestList);
+ final var testUnmodifiableCollection = UnmodifiableCollection.create(immutableTestList);
assertNotNull(testUnmodifiableCollection);
// Note: this cannot be ImmutableList, because UnmodifiableCollection does recognize it and returns it as is,
// without converting it to an UnmodifiableCollection -- which is not what we want.
- final List<Integer> testList = Arrays.asList(1, 2, 3, 4, 5);
- final Collection<Integer> testUnmodifiableCollection2 = UnmodifiableCollection.create(testList);
+ final var testList = Arrays.asList(1, 2, 3, 4, 5);
+ final var testUnmodifiableCollection2 = UnmodifiableCollection.create(testList);
- final Iterator<Integer> iterator = testUnmodifiableCollection2.iterator();
+ final var iterator = testUnmodifiableCollection2.iterator();
assertNotNull(iterator);
- assertTrue(iterator instanceof UnmodifiableIterator);
+ assertInstanceOf(UnmodifiableIterator.class, iterator);
assertEquals(5, testUnmodifiableCollection2.size());
assertTrue(testUnmodifiableCollection2.contains(1));
- final Object[] objectArray = testUnmodifiableCollection2.toArray();
+ final var objectArray = testUnmodifiableCollection2.toArray();
assertNotNull(objectArray);
assertEquals(5, objectArray.length);
- final Integer[] integerArray = testUnmodifiableCollection2.toArray(
+ final var integerArray = testUnmodifiableCollection2.toArray(
new Integer[testUnmodifiableCollection2.size()]);
assertNotNull(integerArray);
assertEquals(5, integerArray.length);
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.ArrayList;
-import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.opendaylight.yangtools.util.concurrent.CommonTestUtils.Invoker;
/**
*
* @author Thomas Pantelis
*/
-public class AsyncNotifyingListeningExecutorServiceTest {
+class AsyncNotifyingListeningExecutorServiceTest {
private ExecutorService listenerExecutor;
private AsyncNotifyingListeningExecutorService testExecutor;
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
if (listenerExecutor != null) {
listenerExecutor.shutdownNow();
}
}
@Test
- public void testListenerCallbackWithExecutor() throws InterruptedException {
+ void testListenerCallbackWithExecutor() throws InterruptedException {
- String listenerThreadPrefix = "ListenerThread";
+ final var listenerThreadPrefix = "ListenerThread";
listenerExecutor = Executors.newFixedThreadPool(3,
new ThreadFactoryBuilder().setNameFormat(listenerThreadPrefix + "-%d").build());
}
@Test
- public void testListenerCallbackWithNoExecutor() throws InterruptedException {
+ void testListenerCallbackWithNoExecutor() throws InterruptedException {
- String listenerThreadPrefix = "SingleThread";
+ final var listenerThreadPrefix = "SingleThread";
testExecutor = new AsyncNotifyingListeningExecutorService(
Executors.newSingleThreadExecutor(
new ThreadFactoryBuilder().setNameFormat(listenerThreadPrefix).build()),
static void testListenerCallback(final AsyncNotifyingListeningExecutorService executor,
final Invoker invoker, final String expListenerThreadPrefix) throws InterruptedException {
- AtomicReference<AssertionError> assertError = new AtomicReference<>();
- CountDownLatch futureNotifiedLatch = new CountDownLatch(1);
- CountDownLatch blockTaskLatch = new CountDownLatch(1);
+ final var assertError = new AtomicReference<AssertionError>();
+ var futureNotifiedLatch = new CountDownLatch(1);
+ final var blockTaskLatch = new CountDownLatch(1);
// The blockTaskLatch is used to block the task from completing until we've added
// our listener to the Future. Otherwise, if the task completes quickly and the Future is
// will immediately notify synchronously on this thread as Futures#addCallback defaults to
// a same thread executor. This would erroneously fail the test.
- ListenableFuture<?> future = invoker.invokeExecutor(executor, blockTaskLatch);
+ final var future = invoker.invokeExecutor(executor, blockTaskLatch);
addCallback(future, futureNotifiedLatch, expListenerThreadPrefix, assertError);
// Now that we've added our listener, signal the latch to let the task complete.
blockTaskLatch.countDown();
- assertTrue("ListenableFuture callback was not notified of onSuccess",
- futureNotifiedLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(futureNotifiedLatch.await(5, TimeUnit.SECONDS),
+ "ListenableFuture callback was not notified of onSuccess");
if (assertError.get() != null) {
throw assertError.get();
futureNotifiedLatch = new CountDownLatch(1);
addCallback(future, futureNotifiedLatch, Thread.currentThread().getName(), assertError);
- assertTrue("ListenableFuture callback was not notified of onSuccess",
- futureNotifiedLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(futureNotifiedLatch.await(5, TimeUnit.SECONDS),
+ "ListenableFuture callback was not notified of onSuccess");
if (assertError.get() != null) {
throw assertError.get();
@Override
public void onSuccess(final Object result) {
try {
- String theadName = Thread.currentThread().getName();
- assertTrue("ListenableFuture callback was not notified on the listener executor."
+ final var theadName = Thread.currentThread().getName();
+ assertTrue(theadName.startsWith(expListenerThreadPrefix),
+ "ListenableFuture callback was not notified on the listener executor."
+ " Expected thread name prefix \"" + expListenerThreadPrefix
- + "\". Actual thread name \"" + theadName + "\"",
- theadName.startsWith(expListenerThreadPrefix));
+ + "\". Actual thread name \"" + theadName + "\"");
} catch (AssertionError e) {
assertError.set(e);
} finally {
@Override
@SuppressWarnings("checkstyle:parameterName")
- public void onFailure(final Throwable t) {
+ public void onFailure(final Throwable cause) {
// Shouldn't happen
- fail("Unexpected failure " + t);
+ fail("Unexpected failure " + cause);
}
}, MoreExecutors.directExecutor());
}
@Test
- public void testDelegatedMethods() throws InterruptedException {
+ void testDelegatedMethods() throws InterruptedException {
- Runnable task = () -> { };
+ final var task = (Runnable) () -> { };
- List<Runnable> taskList = new ArrayList<>();
+ final var taskList = new ArrayList<Runnable>();
- ExecutorService mockDelegate = mock(ExecutorService.class);
+ final var mockDelegate = mock(ExecutorService.class);
doNothing().when(mockDelegate).execute(task);
doNothing().when(mockDelegate).shutdown();
doReturn(taskList).when(mockDelegate).shutdownNow();
doReturn(Boolean.TRUE).when(mockDelegate).isShutdown();
doReturn(Boolean.TRUE).when(mockDelegate).isTerminated();
- AsyncNotifyingListeningExecutorService executor = new AsyncNotifyingListeningExecutorService(
+ final var executor = new AsyncNotifyingListeningExecutorService(
mockDelegate, null);
executor.execute(task);
executor.shutdown();
- assertTrue("awaitTermination", executor.awaitTermination(3, TimeUnit.SECONDS));
- assertSame("shutdownNow", taskList, executor.shutdownNow());
- assertTrue("isShutdown", executor.isShutdown());
- assertTrue("isTerminated", executor.isTerminated());
+ assertTrue(executor.awaitTermination(3, TimeUnit.SECONDS), "awaitTermination");
+ assertSame(taskList, executor.shutdownNow(), "shutdownNow");
+ assertTrue(executor.isShutdown(), "isShutdown");
+ assertTrue(executor.isTerminated(), "isTerminated");
verify(mockDelegate).execute(task);
verify(mockDelegate).shutdown();
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.yangtools.util.concurrent;
import com.google.common.util.concurrent.ListenableFuture;
*
* @author Thomas Pantelis
*/
-public final class CommonTestUtils {
+final class CommonTestUtils {
private CommonTestUtils() {
throw new UnsupportedOperationException();
}
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.opendaylight.yangtools.util.ExecutorServiceUtil;
import org.opendaylight.yangtools.util.concurrent.ThreadPoolExecutorTest.Task;
*
* @author Thomas Pantelis
*/
-public class CountingRejectedExecutionHandlerTest {
+class CountingRejectedExecutionHandlerTest {
private ThreadPoolExecutor executor;
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
if (executor != null) {
executor.shutdownNow();
}
}
@Test
- public void testCallerRunsPolicyHandler() throws InterruptedException {
+ void testCallerRunsPolicyHandler() throws InterruptedException {
- CountDownLatch tasksRunLatch = new CountDownLatch(1);
- CountDownLatch blockLatch = new CountDownLatch(1);
+ final var tasksRunLatch = new CountDownLatch(1);
+ final var blockLatch = new CountDownLatch(1);
executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>()));
- CountingRejectedExecutionHandler countingHandler = CountingRejectedExecutionHandler.newCallerRunsPolicy();
+ final var countingHandler = CountingRejectedExecutionHandler.newCallerRunsPolicy();
executor.setRejectedExecutionHandler(countingHandler);
executor.execute(new Task(tasksRunLatch, blockLatch));
- int tasks = 5;
+ final var tasks = 5;
for (int i = 0; i < tasks - 1; i++) {
executor.execute(new Task(null, null, null, null, 0));
}
- assertEquals("getRejectedTaskCount", tasks - 1, countingHandler.getRejectedTaskCount());
+ assertEquals(tasks - 1, countingHandler.getRejectedTaskCount(), "getRejectedTaskCount");
blockLatch.countDown();
- assertTrue("Tasks complete", tasksRunLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(tasksRunLatch.await(5, TimeUnit.SECONDS), "Tasks complete");
}
@Test
- public void testAbortPolicyHandler() throws InterruptedException {
+ void testAbortPolicyHandler() throws InterruptedException {
- CountDownLatch tasksRunLatch = new CountDownLatch(1);
- CountDownLatch blockLatch = new CountDownLatch(1);
+ final var tasksRunLatch = new CountDownLatch(1);
+ final var blockLatch = new CountDownLatch(1);
executor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
ExecutorServiceUtil.offerFailingBlockingQueue(new LinkedBlockingQueue<>()));
- CountingRejectedExecutionHandler countingHandler = CountingRejectedExecutionHandler.newAbortPolicy();
+ final var countingHandler = CountingRejectedExecutionHandler.newAbortPolicy();
executor.setRejectedExecutionHandler(countingHandler);
executor.execute(new Task(tasksRunLatch, blockLatch));
- int tasks = 5;
+ final var tasks = 5;
for (int i = 0; i < tasks - 1; i++) {
assertThrows(RejectedExecutionException.class, () -> executor.execute(new Task(null, null, null, null, 0)));
}
- assertEquals("getRejectedTaskCount", tasks - 1, countingHandler.getRejectedTaskCount());
+ assertEquals(tasks - 1, countingHandler.getRejectedTaskCount(), "getRejectedTaskCount");
blockLatch.countDown();
- assertTrue("Tasks complete", tasksRunLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(tasksRunLatch.await(5, TimeUnit.SECONDS), "Tasks complete");
}
}
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.opendaylight.yangtools.util.concurrent.AsyncNotifyingListeningExecutorServiceTest.testListenerCallback;
import static org.opendaylight.yangtools.util.concurrent.CommonTestUtils.SUBMIT_CALLABLE;
import static org.opendaylight.yangtools.util.concurrent.CommonTestUtils.SUBMIT_RUNNABLE;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import java.io.Serial;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.opendaylight.yangtools.util.concurrent.CommonTestUtils.Invoker;
/**
*
* @author Thomas Pantelis
*/
-public class DeadlockDetectingListeningExecutorServiceTest {
+class DeadlockDetectingListeningExecutorServiceTest {
interface InitialInvoker {
void invokeExecutor(ListeningExecutorService executor, Runnable task);
static final InitialInvoker EXECUTE = Executor::execute;
public static class TestDeadlockException extends Exception {
- @Serial
+ @java.io.Serial
private static final long serialVersionUID = 1L;
}
DeadlockDetectingListeningExecutorService executor;
- @Before
- public void setup() {
- }
-
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
if (executor != null) {
executor.shutdownNow();
}
}
@Test
- public void testBlockingSubmitOffExecutor() throws Exception {
+ void testBlockingSubmitOffExecutor() throws Exception {
executor = newExecutor();
// Test submit with Callable.
- ListenableFuture<String> future = executor.submit(() -> "foo");
+ var future = executor.submit(() -> "foo");
- assertEquals("Future result", "foo", future.get(5, TimeUnit.SECONDS));
+ assertEquals("foo", future.get(5, TimeUnit.SECONDS), "Future result");
// Test submit with Runnable.
future = executor.submit(() -> { }, "foo");
- assertEquals("Future result", "foo", future.get(5, TimeUnit.SECONDS));
+ assertEquals("foo", future.get(5, TimeUnit.SECONDS), "Future result");
}
@Test
@SuppressWarnings("checkstyle:illegalThrows")
- public void testNonBlockingSubmitOnExecutorThread() throws Throwable {
+ void testNonBlockingSubmitOnExecutorThread() throws Throwable {
executor = newExecutor();
void testNonBlockingSubmitOnExecutorThread(final InitialInvoker initialInvoker, final Invoker invoker)
throws Throwable {
- final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
- final CountDownLatch futureCompletedLatch = new CountDownLatch(1);
+ final var caughtEx = new AtomicReference<Throwable>();
+ final var futureCompletedLatch = new CountDownLatch(1);
- Runnable task = () -> Futures.addCallback(invoker.invokeExecutor(executor, null), new FutureCallback<Object>() {
- @Override
- public void onSuccess(final Object result) {
- futureCompletedLatch.countDown();
- }
+ final var task = (Runnable) () -> Futures.addCallback(invoker.invokeExecutor(executor, null),
+ new FutureCallback<Object>() {
+ @Override
+ public void onSuccess(final Object result) {
+ futureCompletedLatch.countDown();
+ }
- @Override
- @SuppressWarnings("checkstyle:parameterName")
- public void onFailure(final Throwable t) {
- caughtEx.set(t);
- futureCompletedLatch.countDown();
- }
- }, MoreExecutors.directExecutor());
+ @Override
+ @SuppressWarnings("checkstyle:parameterName")
+ public void onFailure(final Throwable t) {
+ caughtEx.set(t);
+ futureCompletedLatch.countDown();
+ }
+ }, MoreExecutors.directExecutor());
initialInvoker.invokeExecutor(executor, task);
- assertTrue("Task did not complete - executor likely deadlocked",
- futureCompletedLatch.await(5, TimeUnit.SECONDS));
+ assertTrue(futureCompletedLatch.await(5, TimeUnit.SECONDS),
+ "Task did not complete - executor likely deadlocked");
if (caughtEx.get() != null) {
throw caughtEx.get();
}
@Test
- public void testBlockingSubmitOnExecutorThread() throws InterruptedException {
+ void testBlockingSubmitOnExecutorThread() throws InterruptedException {
executor = newExecutor();
void testBlockingSubmitOnExecutorThread(final InitialInvoker initialInvoker, final Invoker invoker)
throws InterruptedException {
- final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
- final CountDownLatch latch = new CountDownLatch(1);
+ final var caughtEx = new AtomicReference<Throwable>();
+ final var latch = new CountDownLatch(1);
- Runnable task = () -> {
+ final var task = (Runnable) () -> {
try {
invoker.invokeExecutor(executor, null).get();
initialInvoker.invokeExecutor(executor, task);
- assertTrue("Task did not complete - executor likely deadlocked", latch.await(5, TimeUnit.SECONDS));
- assertNotNull("Expected exception thrown", caughtEx.get());
- assertEquals("Caught exception type", TestDeadlockException.class, caughtEx.get().getClass());
+ assertTrue(latch.await(5, TimeUnit.SECONDS), "Task did not complete - executor likely deadlocked");
+ assertNotNull(caughtEx.get(), "Expected exception thrown");
+ assertEquals(TestDeadlockException.class, caughtEx.get().getClass(), "Caught exception type");
}
@Test
- public void testListenableFutureCallbackWithExecutor() throws InterruptedException {
+ void testListenableFutureCallbackWithExecutor() throws InterruptedException {
- String listenerThreadPrefix = "ListenerThread";
+ final var listenerThreadPrefix = "ListenerThread";
ExecutorService listenerExecutor = Executors.newFixedThreadPool(1,
new ThreadFactoryBuilder().setNameFormat(listenerThreadPrefix + "-%d").build());
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import com.google.common.base.Stopwatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager.BatchedInvoker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Thomas Pantelis
*/
-public class QueuedNotificationManagerTest {
+class QueuedNotificationManagerTest {
static class TestListener<N> {
}
void reset(final int newExpCount) {
- this.expCount = newExpCount;
+ expCount = newExpCount;
latch = new CountDownLatch(newExpCount);
actual.clear();
}
actual.addAll(data);
}
- RuntimeException localRuntimeEx = runtimeEx;
+ final var localRuntimeEx = runtimeEx;
if (localRuntimeEx != null) {
runtimeEx = null;
throw localRuntimeEx;
}
- Error localJvmError = jvmError;
+ final var localJvmError = jvmError;
if (localJvmError != null) {
jvmError = null;
throw localJvmError;
void verifyNotifications(final List<N> expected) {
verifyNotifications();
- assertEquals(name + ": Notifications", expected, actual);
+ assertEquals(expected, actual, name + ": Notifications");
}
// Implement bad hashCode/equals methods to verify it doesn't screw up the
@Override
public boolean equals(final Object obj) {
- TestListener<?> other = (TestListener<?>) obj;
+ final var other = (TestListener<?>) obj;
return other != null;
}
}
private static final Logger LOG = LoggerFactory.getLogger(QueuedNotificationManagerTest.class);
private ExecutorService queueExecutor;
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
if (queueExecutor != null) {
queueExecutor.shutdownNow();
}
}
- @Test(timeout = 10000)
- public void testNotificationsWithSingleListener() {
+ @Test
+ @Timeout(10000)
+ void testNotificationsWithSingleListener() {
queueExecutor = Executors.newFixedThreadPool(2);
- NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
- new TestNotifier<>(), 10, "TestMgr");
+ final NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(
+ queueExecutor, new TestNotifier<>(), 10, "TestMgr");
- int count = 100;
+ final var count = 100;
- TestListener<Integer> listener = new TestListener<>(count, 1);
+ final var listener = new TestListener<Integer>(count, 1);
listener.sleepTime = 20;
manager.submitNotifications(listener, Arrays.asList(1, 2));
listener.sleepTime = 0;
- List<Integer> expNotifications = new ArrayList<>(count);
+ final var expNotifications = new ArrayList<Integer>(count);
expNotifications.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
- int initialCount = 6;
+ final var initialCount = 6;
for (int i = 1; i <= count - initialCount; i++) {
- Integer val = Integer.valueOf(initialCount + i);
+ Integer val = initialCount + i;
expNotifications.add(val);
manager.submitNotification(listener, val);
}
}
@Test
- public void testNotificationsWithMultipleListeners() throws InterruptedException {
+ void testNotificationsWithMultipleListeners() throws InterruptedException {
- int count = 10;
+ final var count = 10;
queueExecutor = Executors.newFixedThreadPool(count);
- final ExecutorService stagingExecutor = Executors.newFixedThreadPool(count);
+ final var stagingExecutor = Executors.newFixedThreadPool(count);
final NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(
queueExecutor, new TestNotifier<>(), 5000, "TestMgr");
- final int nNotifications = 100000;
+ final var nNotifications = 100000;
LOG.info("Testing {} listeners with {} notifications each...", count, nNotifications);
- final Integer[] notifications = new Integer[nNotifications];
+ final var notifications = new Integer[nNotifications];
for (int i = 1; i <= nNotifications; i++) {
- notifications[i - 1] = Integer.valueOf(i);
+ notifications[i - 1] = i;
}
Stopwatch stopWatch = Stopwatch.createStarted();
- List<TestListener<Integer>> listeners = new ArrayList<>();
- List<Thread> threads = new ArrayList<>();
+ final var listeners = new ArrayList<TestListener<Integer>>();
+ final var threads = new ArrayList<Thread>();
for (int i = 1; i <= count; i++) {
- final TestListener<Integer> listener =
- i == 2 ? new TestListener2<>(nNotifications, i) :
- i == 3 ? new TestListener3<>(nNotifications, i) :
- new TestListener<>(nNotifications, i);
+ final var listener =
+ i == 2 ? new TestListener2<Integer>(nNotifications, i) :
+ i == 3 ? new TestListener3<Integer>(nNotifications, i) :
+ new TestListener<Integer>(nNotifications, i);
listeners.add(listener);
- final Thread t = new Thread(() -> {
+ final var t = new Thread(() -> {
for (int j = 1; j <= nNotifications; j++) {
final Integer n = notifications[j - 1];
stagingExecutor.execute(() -> manager.submitNotification(listener, n));
}
try {
- for (TestListener<Integer> listener: listeners) {
+ for (final var listener: listeners) {
listener.verifyNotifications();
LOG.info("{} succeeded", listener.name);
}
}
}
- @Test(timeout = 10000)
- public void testNotificationsWithListenerRuntimeEx() {
+ @Test
+ @Timeout(10000)
+ void testNotificationsWithListenerRuntimeEx() {
queueExecutor = Executors.newFixedThreadPool(1);
- NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
- new TestNotifier<>(), 10, "TestMgr");
+ final NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(
+ queueExecutor, new TestNotifier<>(), 10, "TestMgr");
- TestListener<Integer> listener = new TestListener<>(2, 1);
- final RuntimeException mockedRuntimeException = new RuntimeException("mock");
+ final var listener = new TestListener<Integer>(2, 1);
+ final var mockedRuntimeException = new RuntimeException("mock");
listener.runtimeEx = mockedRuntimeException;
manager.submitNotification(listener, 1);
manager.submitNotification(listener, 2);
listener.verifyNotifications();
- List<Runnable> tasks = queueExecutor.shutdownNow();
+ final var tasks = queueExecutor.shutdownNow();
assertTrue(tasks.isEmpty());
}
- @Test(timeout = 10000)
- public void testNotificationsWithListenerJVMError() {
+ @Test
+ @Timeout(10000)
+ void testNotificationsWithListenerJVMError() {
- final CountDownLatch errorCaughtLatch = new CountDownLatch(1);
+ final var errorCaughtLatch = new CountDownLatch(1);
queueExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>()) {
@Override
@SuppressWarnings("checkstyle:illegalCatch")
}
};
- NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(queueExecutor,
- new TestNotifier<>(), 10, "TestMgr");
+ final NotificationManager<TestListener<Integer>, Integer> manager = QueuedNotificationManager.create(
+ queueExecutor, new TestNotifier<>(), 10, "TestMgr");
- TestListener<Integer> listener = new TestListener<>(2, 1);
+ final var listener = new TestListener<Integer>(2, 1);
listener.jvmError = mock(Error.class);
manager.submitNotification(listener, 1);
- assertTrue("JVM Error caught", Uninterruptibles.awaitUninterruptibly(errorCaughtLatch, 5, TimeUnit.SECONDS));
+ assertTrue(Uninterruptibles.awaitUninterruptibly(errorCaughtLatch, 5, TimeUnit.SECONDS), "JVM Error caught");
manager.submitNotification(listener, 2);
listener.verifyNotifications();
- List<Runnable> tasks = queueExecutor.shutdownNow();
+ final var tasks = queueExecutor.shutdownNow();
assertTrue(tasks.isEmpty());
}
}
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
-import java.io.Serial;
import java.util.concurrent.ExecutionException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ReflectiveExceptionMapperTest {
- static final class NoArgumentCtorException extends Exception {
- @Serial
+ public static final class NoArgumentCtorException extends Exception {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
- NoArgumentCtorException() {
+ public NoArgumentCtorException() {
+ // Noop
}
}
- static final class PrivateCtorException extends Exception {
- @Serial
+ public static final class PrivateCtorException extends Exception {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private PrivateCtorException(final String message, final Throwable cause) {
}
}
- static final class FailingCtorException extends Exception {
- @Serial
+ public static final class FailingCtorException extends Exception {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
- FailingCtorException(final String message, final Throwable cause) {
+ public FailingCtorException(final String message, final Throwable cause) {
throw new IllegalArgumentException("just for test");
}
}
public static final class GoodException extends Exception {
- @Serial
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public GoodException(final String message, final Throwable cause) {
@Test
- public void testNoArgumentsContructor() {
+ void testNoArgumentsContructor() {
assertThrows(IllegalArgumentException.class,
() -> ReflectiveExceptionMapper.create("no arguments", NoArgumentCtorException.class));
}
@Test
- public void testPrivateContructor() {
+ void testPrivateContructor() {
assertThrows(IllegalArgumentException.class,
() -> ReflectiveExceptionMapper.create("private constructor", PrivateCtorException.class));
}
@Test
- public void testFailingContructor() {
+ void testFailingContructor() {
assertThrows(IllegalArgumentException.class,
() -> ReflectiveExceptionMapper.create("failing constructor", FailingCtorException.class));
}
@Test
- public void testInstantiation() {
- ReflectiveExceptionMapper<GoodException> mapper = ReflectiveExceptionMapper.create("instantiation",
- GoodException.class);
-
- final Throwable cause = new Throwable("some test message");
-
- GoodException ret = mapper.apply(new ExecutionException("test", cause));
+ void testInstantiation() {
+ final var mapper = ReflectiveExceptionMapper.create("instantiation", GoodException.class);
+ final var cause = new Throwable("some test message");
+ final var ret = mapper.apply(new ExecutionException("test", cause));
assertEquals("instantiation execution failed", ret.getMessage());
assertEquals(cause, ret.getCause());
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import com.google.common.base.Stopwatch;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Thomas Pantelis
*/
-public class ThreadPoolExecutorTest {
+class ThreadPoolExecutorTest {
private static final Logger LOG = LoggerFactory.getLogger(ThreadPoolExecutorTest.class);
private ExecutorService executor;
- @After
- public void tearDown() {
+ @AfterEach
+ void tearDown() {
if (executor != null) {
executor.shutdownNow();
}
}
@Test
- public void testFastThreadPoolExecution() throws InterruptedException {
+ void testFastThreadPoolExecution() throws InterruptedException {
testThreadPoolExecution(
SpecialExecutors.newBoundedFastThreadPool(50, 100000, "TestPool", getClass()), 100000, "TestPool", 0);
}
- @Test(expected = RejectedExecutionException.class)
- public void testFastThreadPoolRejectingTask() throws InterruptedException {
- executor = SpecialExecutors.newBoundedFastThreadPool(1, 1, "TestPool", getClass());
+ @Test
+ void testFastThreadPoolRejectingTask() throws InterruptedException {
+ assertThrows(RejectedExecutionException.class, () -> {
+ executor = SpecialExecutors.newBoundedFastThreadPool(1, 1, "TestPool", getClass());
- for (int i = 0; i < 5; i++) {
- executor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5, TimeUnit.SECONDS)));
- }
+ for (int i = 0; i < 5; i++) {
+ executor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5, TimeUnit.SECONDS)));
+ }
+ });
}
@Test
- public void testBlockingFastThreadPoolExecution() throws InterruptedException {
+ void testBlockingFastThreadPoolExecution() throws InterruptedException {
// With a queue capacity of 1, it should block at some point.
testThreadPoolExecution(
SpecialExecutors.newBlockingBoundedFastThreadPool(2, 1, "TestPool", getClass()), 1000, null, 10);
}
@Test
- public void testCachedThreadPoolExecution() throws InterruptedException {
+ void testCachedThreadPoolExecution() throws InterruptedException {
testThreadPoolExecution(SpecialExecutors.newBoundedCachedThreadPool(10, 100000, "TestPool", getClass()),
100000, "TestPool", 0);
}
- @Test(expected = RejectedExecutionException.class)
- public void testCachedThreadRejectingTask() throws InterruptedException {
- ExecutorService localExecutor = SpecialExecutors.newBoundedCachedThreadPool(1, 1, "TestPool", getClass());
+ @Test
+ void testCachedThreadRejectingTask() throws InterruptedException {
+ assertThrows(RejectedExecutionException.class, () -> {
+ ExecutorService localExecutor = SpecialExecutors.newBoundedCachedThreadPool(1, 1, "TestPool", getClass());
- for (int i = 0; i < 5; i++) {
- localExecutor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5, TimeUnit.SECONDS)));
- }
+ for (int i = 0; i < 5; i++) {
+ localExecutor.execute(new Task(null, null, null, null, TimeUnit.MICROSECONDS.convert(5,
+ TimeUnit.SECONDS)));
+ }
+ });
}
@Test
- public void testBlockingCachedThreadPoolExecution() throws InterruptedException {
+ void testBlockingCachedThreadPoolExecution() throws InterruptedException {
testThreadPoolExecution(
SpecialExecutors.newBlockingBoundedCachedThreadPool(2, 1, "TestPool", getClass()), 1000, null, 10);
}
LOG.debug("Testing {} with {} tasks.", executorToTest.getClass().getSimpleName(), numTasksToRun);
- final CountDownLatch tasksRunLatch = new CountDownLatch(numTasksToRun);
- final ConcurrentMap<Thread, AtomicLong> taskCountPerThread = new ConcurrentHashMap<>();
- final AtomicReference<AssertionError> threadError = new AtomicReference<>();
+ final var tasksRunLatch = new CountDownLatch(numTasksToRun);
+ final var taskCountPerThread = new ConcurrentHashMap<Thread, AtomicLong>();
+ final var threadError = new AtomicReference<AssertionError>();
- Stopwatch stopWatch = Stopwatch.createStarted();
+ final var stopWatch = Stopwatch.createStarted();
new Thread() {
@Override
}
}.start();
- boolean done = tasksRunLatch.await(15, TimeUnit.SECONDS);
+ final var done = tasksRunLatch.await(15, TimeUnit.SECONDS);
stopWatch.stop();
}
if (expThreadPrefix != null) {
- assertTrue("Thread name starts with " + expThreadPrefix,
- Thread.currentThread().getName().startsWith(expThreadPrefix));
+ assertTrue(Thread.currentThread().getName().startsWith(expThreadPrefix),
+ "Thread name starts with " + expThreadPrefix);
}
if (taskCountPerThread != null) {
*/
package org.opendaylight.yangtools.util.concurrent;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Unit tests for TrackingLinkedBlockingQueue.
*
* @author Thomas Pantelis
*/
-public class TrackingLinkedBlockingQueueTest {
+class TrackingLinkedBlockingQueueTest {
@Test
- public void testOffer() throws InterruptedException {
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(2);
+ void testOffer() throws InterruptedException {
+ final var queue = new TrackingLinkedBlockingQueue<>(2);
- assertTrue("offer", queue.offer("1"));
- assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
- assertEquals("size", 1, queue.size());
+ assertTrue(queue.offer("1"), "offer");
+ assertEquals(1, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(1, queue.size(), "size");
- assertTrue("offer", queue.offer("2", 1, TimeUnit.MILLISECONDS));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertTrue(queue.offer("2", 1, TimeUnit.MILLISECONDS), "offer");
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
- assertFalse("offer", queue.offer("3"));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertFalse(queue.offer("3"), "offer");
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
- assertFalse("offer", queue.offer("4", 1, TimeUnit.MILLISECONDS));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertFalse(queue.offer("4", 1, TimeUnit.MILLISECONDS), "offer");
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
}
@Test
- public void testPut() throws InterruptedException {
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>();
+ void testPut() throws InterruptedException {
+ final var queue = new TrackingLinkedBlockingQueue<>();
queue.put("1");
- assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
- assertEquals("size", 1, queue.size());
+ assertEquals(1, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(1, queue.size(), "size");
queue.put("2");
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
}
@Test
- public void testAdd() {
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(2);
+ void testAdd() {
+ final var queue = new TrackingLinkedBlockingQueue<>(2);
- assertTrue("add", queue.add("1"));
- assertEquals("getLargestQueueSize", 1, queue.getLargestQueueSize());
- assertEquals("size", 1, queue.size());
+ assertTrue(queue.add("1"), "add");
+ assertEquals(1, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(1, queue.size(), "size");
- assertTrue("add", queue.add("2"));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertTrue(queue.add("2"), "add");
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
assertThrows(IllegalStateException.class, () -> queue.add("3"));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
}
@Test
- public void testAddAll() {
- TrackingLinkedBlockingQueue<String> queue = new TrackingLinkedBlockingQueue<>(3);
+ void testAddAll() {
+ final var queue = new TrackingLinkedBlockingQueue<>(3);
queue.addAll(Arrays.asList("1", "2"));
- assertEquals("getLargestQueueSize", 2, queue.getLargestQueueSize());
- assertEquals("size", 2, queue.size());
+ assertEquals(2, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(2, queue.size(), "size");
assertThrows(IllegalStateException.class, () -> queue.addAll(Arrays.asList("3", "4")));
- assertEquals("getLargestQueueSize", 3, queue.getLargestQueueSize());
- assertEquals("size", 3, queue.size());
+ assertEquals(3, queue.getLargestQueueSize(), "getLargestQueueSize");
+ assertEquals(3, queue.size(), "size");
}
}