diff options
author | CNlucius <lukai1@huawei.com> | 2016-09-13 11:40:12 +0800 |
---|---|---|
committer | CNlucius <lukai1@huawei.com> | 2016-09-13 11:41:53 +0800 |
commit | b731e2f1dd0972409b136aebc7b463dd72c9cfad (patch) | |
tree | 5107d7d80c19ad8076c2c97c2b5ef8d1cf3ab903 /framework/src/onos/core/store/dist/src/test/java | |
parent | ee93993458266114c29271a481ef9ce7ce621b2a (diff) |
ONOSFW-171
O/S-SFC-ONOS scenario documentation
Change-Id: I51ae1cf736ea24ab6680f8edca1b2bf5dd598365
Signed-off-by: CNlucius <lukai1@huawei.com>
Diffstat (limited to 'framework/src/onos/core/store/dist/src/test/java')
23 files changed, 0 insertions, 5179 deletions
diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/StaticClusterService.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/StaticClusterService.java deleted file mode 100644 index faaf2978..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/StaticClusterService.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.cluster; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import org.onosproject.cluster.ClusterServiceAdapter; -import org.onosproject.cluster.ControllerNode; -import org.onosproject.cluster.ControllerNode.State; -import org.onosproject.cluster.NodeId; - -import com.google.common.collect.Sets; - -public abstract class StaticClusterService extends ClusterServiceAdapter { - - protected final Map<NodeId, ControllerNode> nodes = new HashMap<>(); - protected final Map<NodeId, ControllerNode.State> nodeStates = new HashMap<>(); - protected ControllerNode localNode; - - @Override - public ControllerNode getLocalNode() { - return localNode; - } - - @Override - public Set<ControllerNode> getNodes() { - return Sets.newHashSet(nodes.values()); - } - - @Override - public ControllerNode getNode(NodeId nodeId) { - return nodes.get(nodeId); - } - - @Override - public State getState(NodeId nodeId) { - return nodeStates.get(nodeId); - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/messaging/impl/ClusterCommunicationManagerTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/messaging/impl/ClusterCommunicationManagerTest.java deleted file mode 100644 index daeaa12c..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/cluster/messaging/impl/ClusterCommunicationManagerTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.cluster.messaging.impl; - -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onosproject.cluster.DefaultControllerNode; -import org.onosproject.cluster.NodeId; -import org.onosproject.store.cluster.impl.ClusterNodesDelegate; -import org.onlab.packet.IpAddress; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -/** - * Tests of the cluster communication manager. - */ -public class ClusterCommunicationManagerTest { - - private static final NodeId N1 = new NodeId("n1"); - private static final NodeId N2 = new NodeId("n2"); - - private static final int P1 = 9881; - private static final int P2 = 9882; - - private static final IpAddress IP = IpAddress.valueOf("127.0.0.1"); - - private ClusterCommunicationManager ccm1; - private ClusterCommunicationManager ccm2; - - private TestDelegate cnd1 = new TestDelegate(); - private TestDelegate cnd2 = new TestDelegate(); - - private DefaultControllerNode node1 = new DefaultControllerNode(N1, IP, P1); - private DefaultControllerNode node2 = new DefaultControllerNode(N2, IP, P2); - - @Before - public void setUp() throws Exception { - - NettyMessagingManager messagingService = new NettyMessagingManager(); - messagingService.activate(); - - ccm1 = new ClusterCommunicationManager(); - ccm1.activate(); - - ccm2 = new ClusterCommunicationManager(); - ccm2.activate(); - -// ccm1.initialize(node1, cnd1); -// ccm2.initialize(node2, cnd2); - } - - @After - public void tearDown() { - ccm1.deactivate(); - ccm2.deactivate(); - } - - @Ignore("FIXME: failing randomly?") - @Test - public void connect() throws Exception { - cnd1.latch = new CountDownLatch(1); - cnd2.latch = new CountDownLatch(1); - -// ccm1.addNode(node2); - validateDelegateEvent(cnd1, Op.DETECTED, node2.id()); - validateDelegateEvent(cnd2, Op.DETECTED, node1.id()); - } - - @Test - @Ignore - public void disconnect() throws Exception { - cnd1.latch = new CountDownLatch(1); - cnd2.latch = new CountDownLatch(1); - -// ccm1.addNode(node2); - validateDelegateEvent(cnd1, Op.DETECTED, node2.id()); - validateDelegateEvent(cnd2, Op.DETECTED, node1.id()); - - cnd1.latch = new CountDownLatch(1); - cnd2.latch = new CountDownLatch(1); - ccm1.deactivate(); -// -// validateDelegateEvent(cnd2, Op.VANISHED, node1.id()); - } - - private void validateDelegateEvent(TestDelegate delegate, Op op, NodeId nodeId) - throws InterruptedException { - assertTrue("did not connect in time", delegate.latch.await(2500, TimeUnit.MILLISECONDS)); - assertEquals("incorrect event", op, delegate.op); - assertEquals("incorrect event node", nodeId, delegate.nodeId); - } - - enum Op { DETECTED, VANISHED, REMOVED } - - private class TestDelegate implements ClusterNodesDelegate { - - Op op; - CountDownLatch latch; - NodeId nodeId; - - @Override - public DefaultControllerNode nodeDetected(NodeId nodeId, IpAddress ip, int tcpPort) { - latch(nodeId, Op.DETECTED); - return new DefaultControllerNode(nodeId, ip, tcpPort); - } - - @Override - public void nodeVanished(NodeId nodeId) { - latch(nodeId, Op.VANISHED); - } - - @Override - public void nodeRemoved(NodeId nodeId) { - latch(nodeId, Op.REMOVED); - } - - private void latch(NodeId nodeId, Op op) { - this.op = op; - this.nodeId = nodeId; - latch.countDown(); - } - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/config/impl/DistributedNetworkConfigStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/config/impl/DistributedNetworkConfigStoreTest.java deleted file mode 100644 index 06fe7b37..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/config/impl/DistributedNetworkConfigStoreTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.config.impl; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onosproject.net.config.Config; -import org.onosproject.net.config.ConfigFactory; -import org.onosproject.net.config.SubjectFactory; -import org.onosproject.store.service.TestStorageService; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; - -public class DistributedNetworkConfigStoreTest { - private DistributedNetworkConfigStore configStore; - - /** - * Sets up the config store and the storage service test harness. - */ - @Before - public void setUp() { - configStore = new DistributedNetworkConfigStore(); - configStore.storageService = new TestStorageService(); - configStore.setDelegate(event -> { }); - configStore.activate(); - } - - /** - * Tears down the config store. - */ - @After - public void tearDown() { - configStore.deactivate(); - } - - /** - * Config class for testing. - */ - public class BasicConfig extends Config<String> { } - - /** - * Config factory class for testing. - */ - public class MockConfigFactory extends ConfigFactory<String, BasicConfig> { - protected MockConfigFactory(SubjectFactory<String> subjectFactory, - Class<BasicConfig> configClass, String configKey) { - super(subjectFactory, configClass, configKey); - } - @Override - public BasicConfig createConfig() { - return new BasicConfig(); - } - } - - /** - * Tests creation, query and removal of a config. - */ - @Test - public void testCreateConfig() { - configStore.addConfigFactory(new MockConfigFactory(null, BasicConfig.class, "config1")); - - configStore.createConfig("config1", BasicConfig.class); - assertThat(configStore.getConfigClasses("config1"), hasSize(1)); - assertThat(configStore.getSubjects(String.class, BasicConfig.class), hasSize(1)); - assertThat(configStore.getSubjects(String.class), hasSize(1)); - - BasicConfig queried = configStore.getConfig("config1", BasicConfig.class); - assertThat(queried, notNullValue()); - - configStore.clearConfig("config1", BasicConfig.class); - assertThat(configStore.getConfigClasses("config1"), hasSize(0)); - assertThat(configStore.getSubjects(String.class, BasicConfig.class), hasSize(0)); - assertThat(configStore.getSubjects(String.class), hasSize(0)); - - BasicConfig queriedAfterClear = configStore.getConfig("config1", BasicConfig.class); - assertThat(queriedAfterClear, nullValue()); - } - - /** - * Tests creation, query and removal of a factory. - */ - @Test - public void testCreateFactory() { - MockConfigFactory mockFactory = new MockConfigFactory(null, BasicConfig.class, "config1"); - - assertThat(configStore.getConfigFactory(BasicConfig.class), nullValue()); - - configStore.addConfigFactory(mockFactory); - assertThat(configStore.getConfigFactory(BasicConfig.class), is(mockFactory)); - - configStore.removeConfigFactory(mockFactory); - assertThat(configStore.getConfigFactory(BasicConfig.class), nullValue()); - } - - /** - * Tests applying a config. - */ - @Test - public void testApplyConfig() { - configStore.addConfigFactory(new MockConfigFactory(null, BasicConfig.class, "config1")); - - configStore.applyConfig("config1", BasicConfig.class, new ObjectMapper().createObjectNode()); - assertThat(configStore.getConfigClasses("config1"), hasSize(1)); - assertThat(configStore.getSubjects(String.class, BasicConfig.class), hasSize(1)); - assertThat(configStore.getSubjects(String.class), hasSize(1)); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/DefaultAsyncConsistentMapTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/DefaultAsyncConsistentMapTest.java deleted file mode 100644 index 3f6402c5..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/DefaultAsyncConsistentMapTest.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.consistent.impl; - -import static java.util.Collections.unmodifiableCollection; -import static java.util.Collections.unmodifiableSet; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Consumer; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onosproject.core.ApplicationId; -import org.onosproject.core.DefaultApplicationId; -import org.onosproject.store.service.Serializer; -import org.onosproject.store.service.Transaction; -import org.onosproject.store.service.Versioned; - -import com.google.common.base.MoreObjects; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import net.kuujo.copycat.Task; -import net.kuujo.copycat.cluster.Cluster; -import net.kuujo.copycat.resource.ResourceState; - -/** - * - */ -public class DefaultAsyncConsistentMapTest { - - private static final ApplicationId APP_ID = new DefaultApplicationId(42, "what"); - - private static final TestData KEY1A = new TestData("One", "a"); - private static final TestData KEY1B = new TestData("One", "b"); - - private static final TestData VALUE2A = new TestData("Two", "a"); - private static final TestData VALUE2B = new TestData("Two", "b"); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testKeySet() throws Exception { - DefaultAsyncConsistentMap<TestData, TestData> map; - String name = "map_name"; - Database database = new TestDatabase(); - Serializer serializer = Serializer.forTypes(TestData.class); - - map = new DefaultAsyncConsistentMap<>(name, APP_ID, database, serializer, - false, false, false); - map.put(KEY1A, VALUE2A); - map.put(KEY1B, VALUE2A); - - Set<TestData> set = map.keySet().get(); - assertEquals("Should contain 2 keys", - 2, set.size()); - assertThat(set.contains(KEY1A), is(true)); - assertThat(set.contains(KEY1B), is(true)); - assertThat(set.contains(new TestData("One", "a")), is(true)); - } - - @Test - public void testEntrySet() throws Exception { - DefaultAsyncConsistentMap<TestData, TestData> map; - String name = "map_name"; - Database database = new TestDatabase(); - Serializer serializer = Serializer.forTypes(TestData.class); - - map = new DefaultAsyncConsistentMap<>(name, APP_ID, database, serializer, - false, false, false); - map.put(KEY1A, VALUE2A); - map.put(KEY1B, VALUE2A); - - assertEquals("Should contain 2 entry", - 2, - map.entrySet().get().size()); - } - - /** - * Object to be used as a test data. - * - * {@link Object#equals(Object)} use only part of it's fields. - * - * As a result there can be 2 instances which the - * serialized bytes are not-equal but - * {@link Object#equals(Object)}-wise they are equal. - */ - public static class TestData { - - private final String theKey; - - @SuppressWarnings("unused") - private final String notUsedForEquals; - - public TestData(String theKey, String notUsedForEquals) { - this.theKey = theKey; - this.notUsedForEquals = notUsedForEquals; - } - - @Override - public int hashCode() { - return Objects.hashCode(theKey); - } - - @Override - public boolean equals(Object obj) { - if (obj instanceof TestData) { - TestData that = (TestData) obj; - return Objects.equals(this.theKey, that.theKey); - } - return false; - } - - @Override - public String toString() { - return MoreObjects.toStringHelper(this) - .add("theKey", theKey) - .add("notUsedForEquals", notUsedForEquals) - .toString(); - } - } - - /** - * {@link Database} implementation for testing. - * - * There is only 1 backing Map, {@code mapName} will be ignored. - */ - public class TestDatabase implements Database { - - Map<String, Versioned<byte[]>> map = new ConcurrentHashMap<>(); - - @Override - public CompletableFuture<Set<String>> maps() { - return CompletableFuture.completedFuture(ImmutableSet.of()); - } - - @Override - public CompletableFuture<Map<String, Long>> counters() { - return CompletableFuture.completedFuture(ImmutableMap.of()); - } - - @Override - public CompletableFuture<Integer> mapSize(String mapName) { - return CompletableFuture.completedFuture(map.size()); - } - - @Override - public CompletableFuture<Boolean> mapIsEmpty(String mapName) { - return CompletableFuture.completedFuture(map.isEmpty()); - } - - @Override - public CompletableFuture<Boolean> mapContainsKey(String mapName, - String key) { - return CompletableFuture.completedFuture(map.containsKey(key)); - } - - @Override - public CompletableFuture<Boolean> mapContainsValue(String mapName, - byte[] value) { - return CompletableFuture.completedFuture(map.containsValue(value)); - } - - @Override - public CompletableFuture<Versioned<byte[]>> mapGet(String mapName, - String key) { - return CompletableFuture.completedFuture(map.get(key)); - } - - @Override - public synchronized CompletableFuture<Result<UpdateResult<String, byte[]>>> mapUpdate(String mapName, - String key, - Match<byte[]> valueMatch, - Match<Long> versionMatch, - byte[] value) { - - boolean updated = false; - final Versioned<byte[]> oldValue; - final Versioned<byte[]> newValue; - - Versioned<byte[]> old = map.getOrDefault(key, new Versioned<byte[]>(null, 0)); - if (valueMatch.matches(old.value()) && versionMatch.matches(old.version())) { - updated = true; - oldValue = old; - newValue = new Versioned<>(value, old.version() + 1); - map.put(key, newValue); - } else { - updated = false; - oldValue = old; - newValue = old; - } - return CompletableFuture.completedFuture( - Result.ok(new UpdateResult<String, byte[]>(updated, - mapName, key, oldValue, newValue))); - } - - @Override - public CompletableFuture<Result<Void>> mapClear(String mapName) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Set<String>> mapKeySet(String mapName) { - return CompletableFuture.completedFuture(unmodifiableSet(map.keySet())); - } - - @Override - public CompletableFuture<Collection<Versioned<byte[]>>> mapValues(String mapName) { - return CompletableFuture.completedFuture(unmodifiableCollection(map.values())); - } - - @Override - public CompletableFuture<Set<Entry<String, Versioned<byte[]>>>> mapEntrySet(String mapName) { - return CompletableFuture.completedFuture(unmodifiableSet(map.entrySet())); - } - - @Override - public CompletableFuture<Long> counterAddAndGet(String counterName, - long delta) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Long> counterGetAndAdd(String counterName, - long delta) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Void> counterSet(String counterName, - long value) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Boolean> counterCompareAndSet(String counterName, - long expectedValue, - long update) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Long> counterGet(String counterName) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Long> queueSize(String queueName) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Void> queuePush(String queueName, - byte[] entry) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<byte[]> queuePop(String queueName) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<byte[]> queuePeek(String queueName) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<CommitResponse> prepareAndCommit(Transaction transaction) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Boolean> prepare(Transaction transaction) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<CommitResponse> commit(Transaction transaction) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Boolean> rollback(Transaction transaction) { - throw new UnsupportedOperationException(); - } - - @Override - public String name() { - return "name"; - } - - @Override - public ResourceState state() { - return ResourceState.HEALTHY; - } - - @Override - public Cluster cluster() { - throw new UnsupportedOperationException(); - } - - @Override - public Database addStartupTask(Task<CompletableFuture<Void>> task) { - throw new UnsupportedOperationException(); - } - - @Override - public Database addShutdownTask(Task<CompletableFuture<Void>> task) { - throw new UnsupportedOperationException(); - } - - @Override - public CompletableFuture<Database> open() { - return CompletableFuture.completedFuture(this); - } - - @Override - public boolean isOpen() { - return true; - } - - @Override - public CompletableFuture<Void> close() { - return CompletableFuture.completedFuture(null); - } - - @Override - public boolean isClosed() { - return false; - } - - @Override - public void registerConsumer(Consumer<StateMachineUpdate> consumer) { - } - - @Override - public void unregisterConsumer(Consumer<StateMachineUpdate> consumer) { - } - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/MatchTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/MatchTest.java deleted file mode 100644 index 952393aa..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/MatchTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.consistent.impl; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertTrue; - -import org.junit.Test; - -import com.google.common.base.Objects; - -/** - * Unit tests for Match. - */ -public class MatchTest { - - @Test - public void testMatches() { - Match<String> m1 = Match.any(); - assertTrue(m1.matches(null)); - assertTrue(m1.matches("foo")); - assertTrue(m1.matches("bar")); - - Match<String> m2 = Match.ifNull(); - assertTrue(m2.matches(null)); - assertFalse(m2.matches("foo")); - - Match<String> m3 = Match.ifValue("foo"); - assertFalse(m3.matches(null)); - assertFalse(m3.matches("bar")); - assertTrue(m3.matches("foo")); - } - - @Test - public void testEquals() { - Match<String> m1 = Match.any(); - Match<String> m2 = Match.any(); - Match<String> m3 = Match.ifNull(); - Match<String> m4 = Match.ifValue("bar"); - assertEquals(m1, m2); - assertFalse(Objects.equal(m1, m3)); - assertFalse(Objects.equal(m3, m4)); - } - - @Test - public void testMap() { - Match<String> m1 = Match.ifNull(); - assertEquals(m1.map(s -> "bar"), Match.ifNull()); - Match<String> m2 = Match.ifValue("foo"); - Match<String> m3 = m2.map(s -> "bar"); - assertTrue(m3.matches("bar")); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/ResultTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/ResultTest.java deleted file mode 100644 index 2d329d14..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/ResultTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.consistent.impl; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertFalse; -import static junit.framework.TestCase.assertNull; -import static junit.framework.TestCase.assertTrue; - -import org.junit.Test; - -/** - * Unit tests for Result. - */ -public class ResultTest { - - @Test - public void testLocked() { - Result<String> r = Result.locked(); - assertFalse(r.success()); - assertNull(r.value()); - assertEquals(Result.Status.LOCKED, r.status()); - } - - @Test - public void testOk() { - Result<String> r = Result.ok("foo"); - assertTrue(r.success()); - assertEquals("foo", r.value()); - assertEquals(Result.Status.OK, r.status()); - } - - @Test - public void testEquality() { - Result<String> r1 = Result.ok("foo"); - Result<String> r2 = Result.locked(); - Result<String> r3 = Result.ok("bar"); - Result<String> r4 = Result.ok("foo"); - assertTrue(r1.equals(r4)); - assertFalse(r1.equals(r2)); - assertFalse(r1.equals(r3)); - assertFalse(r2.equals(r3)); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/UpdateResultTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/UpdateResultTest.java deleted file mode 100644 index ab53710b..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/consistent/impl/UpdateResultTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.consistent.impl; - -import static junit.framework.TestCase.assertEquals; -import static junit.framework.TestCase.assertNull; -import static junit.framework.TestCase.assertTrue; - -import org.junit.Test; -import org.onosproject.store.service.MapEvent; -import org.onosproject.store.service.Versioned; - -/** - * Unit tests for UpdateResult. - */ -public class UpdateResultTest { - - @Test - public void testGetters() { - Versioned<String> oldValue = new Versioned<>("a", 1); - Versioned<String> newValue = new Versioned<>("b", 2); - UpdateResult<String, String> ur = - new UpdateResult<>(true, "foo", "k", oldValue, newValue); - - assertTrue(ur.updated()); - assertEquals("foo", ur.mapName()); - assertEquals("k", ur.key()); - assertEquals(oldValue, ur.oldValue()); - assertEquals(newValue, ur.newValue()); - } - - @Test - public void testToMapEvent() { - Versioned<String> oldValue = new Versioned<>("a", 1); - Versioned<String> newValue = new Versioned<>("b", 2); - UpdateResult<String, String> ur1 = - new UpdateResult<>(true, "foo", "k", oldValue, newValue); - MapEvent<String, String> event1 = ur1.toMapEvent(); - assertEquals(MapEvent.Type.UPDATE, event1.type()); - assertEquals("k", event1.key()); - assertEquals(newValue, event1.value()); - - UpdateResult<String, String> ur2 = - new UpdateResult<>(true, "foo", "k", null, newValue); - MapEvent<String, String> event2 = ur2.toMapEvent(); - assertEquals(MapEvent.Type.INSERT, event2.type()); - assertEquals("k", event2.key()); - assertEquals(newValue, event2.value()); - - UpdateResult<String, String> ur3 = - new UpdateResult<>(true, "foo", "k", oldValue, null); - MapEvent<String, String> event3 = ur3.toMapEvent(); - assertEquals(MapEvent.Type.REMOVE, event3.type()); - assertEquals("k", event3.key()); - assertEquals(oldValue, event3.value()); - - UpdateResult<String, String> ur4 = - new UpdateResult<>(false, "foo", "k", oldValue, oldValue); - assertNull(ur4.toMapEvent()); - } - - @Test - public void testMap() { - Versioned<String> oldValue = new Versioned<>("a", 1); - Versioned<String> newValue = new Versioned<>("b", 2); - UpdateResult<String, String> ur1 = - new UpdateResult<>(true, "foo", "k", oldValue, newValue); - UpdateResult<Integer, Integer> ur2 = ur1.map(s -> s.length(), s -> s.length()); - - assertEquals(ur2.updated(), ur1.updated()); - assertEquals(ur1.mapName(), ur2.mapName()); - assertEquals(new Integer(1), ur2.key()); - assertEquals(oldValue.map(s -> s.length()), ur2.oldValue()); - assertEquals(newValue.map(s -> s.length()), ur2.newValue()); - - UpdateResult<String, String> ur3 = - new UpdateResult<>(true, "foo", "k", null, newValue); - UpdateResult<Integer, Integer> ur4 = ur3.map(s -> s.length(), s -> s.length()); - - assertEquals(ur3.updated(), ur4.updated()); - assertEquals(ur3.mapName(), ur4.mapName()); - assertEquals(new Integer(1), ur4.key()); - assertNull(ur4.oldValue()); - assertEquals(newValue.map(s -> s.length()), ur4.newValue()); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/DeviceFragmentIdTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/DeviceFragmentIdTest.java deleted file mode 100644 index 191b3bea..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/DeviceFragmentIdTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.device.impl; - -import static org.onosproject.net.DeviceId.deviceId; - -import org.junit.Test; -import org.onosproject.net.DeviceId; -import org.onosproject.net.provider.ProviderId; - -import com.google.common.testing.EqualsTester; - -public class DeviceFragmentIdTest { - - private static final ProviderId PID = new ProviderId("of", "foo"); - private static final ProviderId PIDA = new ProviderId("of", "bar", true); - private static final DeviceId DID1 = deviceId("of:foo"); - private static final DeviceId DID2 = deviceId("of:bar"); - - @Test - public final void testEquals() { - - new EqualsTester() - .addEqualityGroup(new DeviceFragmentId(DID1, PID), - new DeviceFragmentId(DID1, PID)) - .addEqualityGroup(new DeviceFragmentId(DID2, PID), - new DeviceFragmentId(DID2, PID)) - .addEqualityGroup(new DeviceFragmentId(DID1, PIDA), - new DeviceFragmentId(DID1, PIDA)) - .addEqualityGroup(new DeviceFragmentId(DID2, PIDA), - new DeviceFragmentId(DID2, PIDA)) - .testEquals(); - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/GossipDeviceStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/GossipDeviceStoreTest.java deleted file mode 100644 index 5cbf360a..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/GossipDeviceStoreTest.java +++ /dev/null @@ -1,908 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.device.impl; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; - -import org.easymock.Capture; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onlab.packet.ChassisId; -import org.onlab.packet.IpAddress; -import org.onosproject.cluster.ClusterService; -import org.onosproject.cluster.ControllerNode; -import org.onosproject.cluster.DefaultControllerNode; -import org.onosproject.cluster.NodeId; -import org.onosproject.mastership.MastershipServiceAdapter; -import org.onosproject.net.Annotations; -import org.onosproject.net.DefaultAnnotations; -import org.onosproject.net.Device; -import org.onosproject.net.DeviceId; -import org.onosproject.net.MastershipRole; -import org.onosproject.net.Port; -import org.onosproject.net.PortNumber; -import org.onosproject.net.SparseAnnotations; -import org.onosproject.net.device.DefaultDeviceDescription; -import org.onosproject.net.device.DefaultPortDescription; -import org.onosproject.net.device.DeviceClockService; -import org.onosproject.net.device.DeviceClockServiceAdapter; -import org.onosproject.net.device.DeviceDescription; -import org.onosproject.net.device.DeviceEvent; -import org.onosproject.net.device.DeviceStore; -import org.onosproject.net.device.DeviceStoreDelegate; -import org.onosproject.net.device.PortDescription; -import org.onosproject.net.provider.ProviderId; -import org.onosproject.store.Timestamp; -import org.onosproject.store.cluster.StaticClusterService; -import org.onosproject.store.cluster.messaging.ClusterCommunicationService; -import org.onosproject.store.cluster.messaging.ClusterMessage; -import org.onosproject.store.cluster.messaging.ClusterMessageHandler; -import org.onosproject.store.cluster.messaging.MessageSubject; -import org.onosproject.store.consistent.impl.DatabaseManager; -import org.onosproject.store.impl.MastershipBasedTimestamp; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Function; - -import static java.util.Arrays.asList; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; -import static org.onosproject.cluster.ControllerNode.State.ACTIVE; -import static org.onosproject.net.DefaultAnnotations.union; -import static org.onosproject.net.Device.Type.SWITCH; -import static org.onosproject.net.DeviceId.deviceId; -import static org.onosproject.net.device.DeviceEvent.Type.*; - - -// TODO add tests for remote replication -/** - * Test of the gossip based distributed DeviceStore implementation. - */ -public class GossipDeviceStoreTest { - - private static final ProviderId PID = new ProviderId("of", "foo"); - private static final ProviderId PIDA = new ProviderId("of", "bar", true); - private static final DeviceId DID1 = deviceId("of:foo"); - private static final DeviceId DID2 = deviceId("of:bar"); - private static final String MFR = "whitebox"; - private static final String HW = "1.1.x"; - private static final String SW1 = "3.8.1"; - private static final String SW2 = "3.9.5"; - private static final String SN = "43311-12345"; - private static final ChassisId CID = new ChassisId(); - - private static final PortNumber P1 = PortNumber.portNumber(1); - private static final PortNumber P2 = PortNumber.portNumber(2); - private static final PortNumber P3 = PortNumber.portNumber(3); - - private static final SparseAnnotations A1 = DefaultAnnotations.builder() - .set("A1", "a1") - .set("B1", "b1") - .build(); - private static final SparseAnnotations A1_2 = DefaultAnnotations.builder() - .remove("A1") - .set("B3", "b3") - .build(); - private static final SparseAnnotations A2 = DefaultAnnotations.builder() - .set("A2", "a2") - .set("B2", "b2") - .build(); - private static final SparseAnnotations A2_2 = DefaultAnnotations.builder() - .remove("A2") - .set("B4", "b4") - .build(); - - // local node - private static final NodeId NID1 = new NodeId("local"); - private static final ControllerNode ONOS1 = - new DefaultControllerNode(NID1, IpAddress.valueOf("127.0.0.1")); - - // remote node - private static final NodeId NID2 = new NodeId("remote"); - private static final ControllerNode ONOS2 = - new DefaultControllerNode(NID2, IpAddress.valueOf("127.0.0.2")); - private static final List<SparseAnnotations> NO_ANNOTATION = Collections.<SparseAnnotations>emptyList(); - - - private TestGossipDeviceStore testGossipDeviceStore; - private GossipDeviceStore gossipDeviceStore; - private DeviceStore deviceStore; - - private DeviceClockService deviceClockService = new TestDeviceClockService(); - private ClusterCommunicationService clusterCommunicator; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - - @Before - public void setUp() throws Exception { - clusterCommunicator = createNiceMock(ClusterCommunicationService.class); - clusterCommunicator.addSubscriber(anyObject(MessageSubject.class), - anyObject(ClusterMessageHandler.class), anyObject(ExecutorService.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - ClusterService clusterService = new TestClusterService(); - - testGossipDeviceStore = new TestGossipDeviceStore(deviceClockService, clusterService, clusterCommunicator); - testGossipDeviceStore.mastershipService = new TestMastershipService(); - - TestDatabaseManager testDatabaseManager = new TestDatabaseManager(); - testDatabaseManager.init(clusterService, clusterCommunicator); - testGossipDeviceStore.storageService = testDatabaseManager; - testGossipDeviceStore.deviceClockService = deviceClockService; - - gossipDeviceStore = testGossipDeviceStore; - gossipDeviceStore.activate(); - deviceStore = gossipDeviceStore; - verify(clusterCommunicator); - reset(clusterCommunicator); - } - - @After - public void tearDown() throws Exception { - gossipDeviceStore.deactivate(); - } - - private void putDevice(DeviceId deviceId, String swVersion, - SparseAnnotations... annotations) { - DeviceDescription description = - new DefaultDeviceDescription(deviceId.uri(), SWITCH, MFR, - HW, swVersion, SN, CID, annotations); - reset(clusterCommunicator); - clusterCommunicator.<InternalDeviceEvent>broadcast( - anyObject(InternalDeviceEvent.class), anyObject(MessageSubject.class), anyObject(Function.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - deviceStore.createOrUpdateDevice(PID, deviceId, description); - verify(clusterCommunicator); - } - - private void putDeviceAncillary(DeviceId deviceId, String swVersion, - SparseAnnotations... annotations) { - DeviceDescription description = - new DefaultDeviceDescription(deviceId.uri(), SWITCH, MFR, - HW, swVersion, SN, CID, annotations); - deviceStore.createOrUpdateDevice(PIDA, deviceId, description); - } - - private static void assertDevice(DeviceId id, String swVersion, Device device) { - assertNotNull(device); - assertEquals(id, device.id()); - assertEquals(MFR, device.manufacturer()); - assertEquals(HW, device.hwVersion()); - assertEquals(swVersion, device.swVersion()); - assertEquals(SN, device.serialNumber()); - } - - /** - * Verifies that Annotations created by merging {@code annotations} is - * equal to actual Annotations. - * - * @param actual Annotations to check - * @param annotations - */ - private static void assertAnnotationsEquals(Annotations actual, SparseAnnotations... annotations) { - SparseAnnotations expected = DefaultAnnotations.builder().build(); - for (SparseAnnotations a : annotations) { - expected = DefaultAnnotations.union(expected, a); - } - assertEquals(expected.keys(), actual.keys()); - for (String key : expected.keys()) { - assertEquals(expected.value(key), actual.value(key)); - } - } - - private static void assertDeviceDescriptionEquals(DeviceDescription expected, - DeviceDescription actual) { - if (expected == actual) { - return; - } - assertEquals(expected.deviceUri(), actual.deviceUri()); - assertEquals(expected.hwVersion(), actual.hwVersion()); - assertEquals(expected.manufacturer(), actual.manufacturer()); - assertEquals(expected.serialNumber(), actual.serialNumber()); - assertEquals(expected.swVersion(), actual.swVersion()); - - assertAnnotationsEquals(actual.annotations(), expected.annotations()); - } - - private static void assertDeviceDescriptionEquals(DeviceDescription expected, - List<SparseAnnotations> expectedAnnotations, - DeviceDescription actual) { - if (expected == actual) { - return; - } - assertEquals(expected.deviceUri(), actual.deviceUri()); - assertEquals(expected.hwVersion(), actual.hwVersion()); - assertEquals(expected.manufacturer(), actual.manufacturer()); - assertEquals(expected.serialNumber(), actual.serialNumber()); - assertEquals(expected.swVersion(), actual.swVersion()); - - assertAnnotationsEquals(actual.annotations(), - expectedAnnotations.toArray(new SparseAnnotations[0])); - } - - @Test - public final void testGetDeviceCount() { - assertEquals("initialy empty", 0, deviceStore.getDeviceCount()); - - putDevice(DID1, SW1); - putDevice(DID2, SW2); - putDevice(DID1, SW1); - - assertEquals("expect 2 uniq devices", 2, deviceStore.getDeviceCount()); - } - - @Test - public final void testGetDevices() { - assertEquals("initialy empty", 0, Iterables.size(deviceStore.getDevices())); - - putDevice(DID1, SW1); - putDevice(DID2, SW2); - putDevice(DID1, SW1); - - assertEquals("expect 2 uniq devices", - 2, Iterables.size(deviceStore.getDevices())); - - Map<DeviceId, Device> devices = new HashMap<>(); - for (Device device : deviceStore.getDevices()) { - devices.put(device.id(), device); - } - - assertDevice(DID1, SW1, devices.get(DID1)); - assertDevice(DID2, SW2, devices.get(DID2)); - - // add case for new node? - } - - @Test - public final void testGetDevice() { - - putDevice(DID1, SW1); - - assertDevice(DID1, SW1, deviceStore.getDevice(DID1)); - assertNull("DID2 shouldn't be there", deviceStore.getDevice(DID2)); - } - - private void assertInternalDeviceEvent(NodeId sender, - DeviceId deviceId, - ProviderId providerId, - DeviceDescription expectedDesc, - Capture<InternalDeviceEvent> actualEvent, - Capture<MessageSubject> actualSubject, - Capture<Function<InternalDeviceEvent, byte[]>> actualEncoder) { - assertTrue(actualEvent.hasCaptured()); - assertTrue(actualSubject.hasCaptured()); - assertTrue(actualEncoder.hasCaptured()); - - assertEquals(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, - actualSubject.getValue()); - assertEquals(deviceId, actualEvent.getValue().deviceId()); - assertEquals(providerId, actualEvent.getValue().providerId()); - assertDeviceDescriptionEquals(expectedDesc, actualEvent.getValue().deviceDescription().value()); - } - - private void assertInternalDeviceEvent(NodeId sender, - DeviceId deviceId, - ProviderId providerId, - DeviceDescription expectedDesc, - List<SparseAnnotations> expectedAnnotations, - Capture<InternalDeviceEvent> actualEvent, - Capture<MessageSubject> actualSubject, - Capture<Function<InternalDeviceEvent, byte[]>> actualEncoder) { - assertTrue(actualEvent.hasCaptured()); - assertTrue(actualSubject.hasCaptured()); - assertTrue(actualEncoder.hasCaptured()); - - assertEquals(GossipDeviceStoreMessageSubjects.DEVICE_UPDATE, - actualSubject.getValue()); - assertEquals(deviceId, actualEvent.getValue().deviceId()); - assertEquals(providerId, actualEvent.getValue().providerId()); - assertDeviceDescriptionEquals( - expectedDesc, - expectedAnnotations, - actualEvent.getValue().deviceDescription().value()); - } - - @Test - public final void testCreateOrUpdateDevice() throws IOException { - DeviceDescription description = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW1, SN, CID); - Capture<InternalDeviceEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - DeviceEvent event = deviceStore.createOrUpdateDevice(PID, DID1, description); - assertEquals(DEVICE_ADDED, event.type()); - assertDevice(DID1, SW1, event.subject()); - verify(clusterCommunicator); - assertInternalDeviceEvent(NID1, DID1, PID, description, message, subject, encoder); - - - DeviceDescription description2 = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW2, SN, CID); - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - DeviceEvent event2 = deviceStore.createOrUpdateDevice(PID, DID1, description2); - assertEquals(DEVICE_UPDATED, event2.type()); - assertDevice(DID1, SW2, event2.subject()); - - verify(clusterCommunicator); - assertInternalDeviceEvent(NID1, DID1, PID, description2, message, subject, encoder); - reset(clusterCommunicator); - - assertNull("No change expected", deviceStore.createOrUpdateDevice(PID, DID1, description2)); - } - - @Test - public final void testCreateOrUpdateDeviceAncillary() throws IOException { - // add - DeviceDescription description = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW1, SN, CID, A2); - Capture<ClusterMessage> bcast = new Capture<>(); - - Capture<InternalDeviceEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - DeviceEvent event = deviceStore.createOrUpdateDevice(PIDA, DID1, description); - assertEquals(DEVICE_ADDED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertEquals(PIDA, event.subject().providerId()); - assertAnnotationsEquals(event.subject().annotations(), A2); - assertFalse("Ancillary will not bring device up", deviceStore.isAvailable(DID1)); - verify(clusterCommunicator); - assertInternalDeviceEvent(NID1, DID1, PIDA, description, message, subject, encoder); - - // update from primary - DeviceDescription description2 = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW2, SN, CID, A1); - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - - DeviceEvent event2 = deviceStore.createOrUpdateDevice(PID, DID1, description2); - assertEquals(DEVICE_UPDATED, event2.type()); - assertDevice(DID1, SW2, event2.subject()); - assertEquals(PID, event2.subject().providerId()); - assertAnnotationsEquals(event2.subject().annotations(), A1, A2); - assertTrue(deviceStore.isAvailable(DID1)); - verify(clusterCommunicator); - assertInternalDeviceEvent(NID1, DID1, PID, description2, message, subject, encoder); - - // no-op update from primary - resetCommunicatorExpectingNoBroadcast(message, subject, encoder); - assertNull("No change expected", deviceStore.createOrUpdateDevice(PID, DID1, description2)); - - verify(clusterCommunicator); - assertFalse("no broadcast expected", bcast.hasCaptured()); - - // For now, Ancillary is ignored once primary appears - resetCommunicatorExpectingNoBroadcast(message, subject, encoder); - - assertNull("No change expected", deviceStore.createOrUpdateDevice(PIDA, DID1, description)); - - verify(clusterCommunicator); - assertFalse("no broadcast expected", bcast.hasCaptured()); - - // But, Ancillary annotations will be in effect - DeviceDescription description3 = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW1, SN, CID, A2_2); - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - - DeviceEvent event3 = deviceStore.createOrUpdateDevice(PIDA, DID1, description3); - assertEquals(DEVICE_UPDATED, event3.type()); - // basic information will be the one from Primary - assertDevice(DID1, SW2, event3.subject()); - assertEquals(PID, event3.subject().providerId()); - // but annotation from Ancillary will be merged - assertAnnotationsEquals(event3.subject().annotations(), A1, A2, A2_2); - assertTrue(deviceStore.isAvailable(DID1)); - verify(clusterCommunicator); - // note: only annotation from PIDA is sent over the wire - assertInternalDeviceEvent(NID1, DID1, PIDA, description3, - asList(union(A2, A2_2)), message, subject, encoder); - - } - - - @Test - public final void testMarkOffline() { - - putDevice(DID1, SW1); - assertTrue(deviceStore.isAvailable(DID1)); - - Capture<InternalDeviceEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - DeviceEvent event = deviceStore.markOffline(DID1); - assertEquals(DEVICE_AVAILABILITY_CHANGED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertFalse(deviceStore.isAvailable(DID1)); - verify(clusterCommunicator); - // TODO: verify broadcast message - assertTrue(message.hasCaptured()); - - - resetCommunicatorExpectingNoBroadcast(message, subject, encoder); - DeviceEvent event2 = deviceStore.markOffline(DID1); - assertNull("No change, no event", event2); - verify(clusterCommunicator); - assertFalse(message.hasCaptured()); - } - - @Test - public final void testUpdatePorts() { - putDevice(DID1, SW1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true), - new DefaultPortDescription(P2, true) - ); - Capture<InternalDeviceEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - List<DeviceEvent> events = deviceStore.updatePorts(PID, DID1, pds); - verify(clusterCommunicator); - // TODO: verify broadcast message - assertTrue(message.hasCaptured()); - - Set<PortNumber> expectedPorts = Sets.newHashSet(P1, P2); - for (DeviceEvent event : events) { - assertEquals(PORT_ADDED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertTrue("PortNumber is one of expected", - expectedPorts.remove(event.port().number())); - assertTrue("Port is enabled", event.port().isEnabled()); - } - assertTrue("Event for all expectedport appeared", expectedPorts.isEmpty()); - - - List<PortDescription> pds2 = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, false), - new DefaultPortDescription(P2, true), - new DefaultPortDescription(P3, true) - ); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - events = deviceStore.updatePorts(PID, DID1, pds2); - verify(clusterCommunicator); - // TODO: verify broadcast message - assertTrue(message.hasCaptured()); - - assertFalse("event should be triggered", events.isEmpty()); - for (DeviceEvent event : events) { - PortNumber num = event.port().number(); - if (P1.equals(num)) { - assertEquals(PORT_UPDATED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertFalse("Port is disabled", event.port().isEnabled()); - } else if (P2.equals(num)) { - fail("P2 event not expected."); - } else if (P3.equals(num)) { - assertEquals(PORT_ADDED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertTrue("Port is enabled", event.port().isEnabled()); - } else { - fail("Unknown port number encountered: " + num); - } - } - - List<PortDescription> pds3 = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, false), - new DefaultPortDescription(P2, true) - ); - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - events = deviceStore.updatePorts(PID, DID1, pds3); - verify(clusterCommunicator); - // TODO: verify broadcast message - assertTrue(message.hasCaptured()); - - assertFalse("event should be triggered", events.isEmpty()); - for (DeviceEvent event : events) { - PortNumber num = event.port().number(); - if (P1.equals(num)) { - fail("P1 event not expected."); - } else if (P2.equals(num)) { - fail("P2 event not expected."); - } else if (P3.equals(num)) { - assertEquals(PORT_REMOVED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertTrue("Port was enabled", event.port().isEnabled()); - } else { - fail("Unknown port number encountered: " + num); - } - } - } - - @Test - public final void testUpdatePortStatus() { - putDevice(DID1, SW1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true) - ); - deviceStore.updatePorts(PID, DID1, pds); - - Capture<InternalPortStatusEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalPortStatusEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - final DefaultPortDescription desc = new DefaultPortDescription(P1, false); - DeviceEvent event = deviceStore.updatePortStatus(PID, DID1, desc); - assertEquals(PORT_UPDATED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertEquals(P1, event.port().number()); - assertFalse("Port is disabled", event.port().isEnabled()); - verify(clusterCommunicator); - assertInternalPortStatusEvent(NID1, DID1, PID, desc, NO_ANNOTATION, message, subject, encoder); - assertTrue(message.hasCaptured()); - } - - @Test - public final void testUpdatePortStatusAncillary() throws IOException { - putDeviceAncillary(DID1, SW1); - putDevice(DID1, SW1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true, A1) - ); - deviceStore.updatePorts(PID, DID1, pds); - - Capture<InternalPortStatusEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalPortStatusEvent, byte[]>> encoder = new Capture<>(); - - // update port from primary - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - - final DefaultPortDescription desc1 = new DefaultPortDescription(P1, false, A1_2); - DeviceEvent event = deviceStore.updatePortStatus(PID, DID1, desc1); - assertEquals(PORT_UPDATED, event.type()); - assertDevice(DID1, SW1, event.subject()); - assertEquals(P1, event.port().number()); - assertAnnotationsEquals(event.port().annotations(), A1, A1_2); - assertFalse("Port is disabled", event.port().isEnabled()); - verify(clusterCommunicator); - assertInternalPortStatusEvent(NID1, DID1, PID, desc1, asList(A1, A1_2), message, subject, encoder); - assertTrue(message.hasCaptured()); - - // update port from ancillary with no attributes - resetCommunicatorExpectingNoBroadcast(message, subject, encoder); - final DefaultPortDescription desc2 = new DefaultPortDescription(P1, true); - DeviceEvent event2 = deviceStore.updatePortStatus(PIDA, DID1, desc2); - assertNull("Ancillary is ignored if primary exists", event2); - verify(clusterCommunicator); - assertFalse(message.hasCaptured()); - - // but, Ancillary annotation update will be notified - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - final DefaultPortDescription desc3 = new DefaultPortDescription(P1, true, A2); - DeviceEvent event3 = deviceStore.updatePortStatus(PIDA, DID1, desc3); - assertEquals(PORT_UPDATED, event3.type()); - assertDevice(DID1, SW1, event3.subject()); - assertEquals(P1, event3.port().number()); - assertAnnotationsEquals(event3.port().annotations(), A1, A1_2, A2); - assertFalse("Port is disabled", event3.port().isEnabled()); - verify(clusterCommunicator); - assertInternalPortStatusEvent(NID1, DID1, PIDA, desc3, asList(A2), message, subject, encoder); - assertTrue(message.hasCaptured()); - - // port only reported from Ancillary will be notified as down - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - final DefaultPortDescription desc4 = new DefaultPortDescription(P2, true); - DeviceEvent event4 = deviceStore.updatePortStatus(PIDA, DID1, desc4); - assertEquals(PORT_ADDED, event4.type()); - assertDevice(DID1, SW1, event4.subject()); - assertEquals(P2, event4.port().number()); - assertAnnotationsEquals(event4.port().annotations()); - assertFalse("Port is disabled if not given from primary provider", - event4.port().isEnabled()); - verify(clusterCommunicator); - // TODO: verify broadcast message content - assertInternalPortStatusEvent(NID1, DID1, PIDA, desc4, NO_ANNOTATION, message, subject, encoder); - assertTrue(message.hasCaptured()); - } - - private void assertInternalPortStatusEvent(NodeId sender, - DeviceId did, - ProviderId pid, - DefaultPortDescription expectedDesc, - List<SparseAnnotations> expectedAnnotations, - Capture<InternalPortStatusEvent> actualEvent, - Capture<MessageSubject> actualSubject, - Capture<Function<InternalPortStatusEvent, byte[]>> actualEncoder) { - - assertTrue(actualEvent.hasCaptured()); - assertTrue(actualSubject.hasCaptured()); - assertTrue(actualEncoder.hasCaptured()); - - assertEquals(GossipDeviceStoreMessageSubjects.PORT_STATUS_UPDATE, - actualSubject.getValue()); - assertEquals(did, actualEvent.getValue().deviceId()); - assertEquals(pid, actualEvent.getValue().providerId()); - assertPortDescriptionEquals(expectedDesc, expectedAnnotations, - actualEvent.getValue().portDescription().value()); - } - - private void assertPortDescriptionEquals( - PortDescription expectedDesc, - List<SparseAnnotations> expectedAnnotations, - PortDescription actual) { - - assertEquals(expectedDesc.portNumber(), actual.portNumber()); - assertEquals(expectedDesc.isEnabled(), actual.isEnabled()); - - assertAnnotationsEquals(actual.annotations(), - expectedAnnotations.toArray(new SparseAnnotations[0])); - } - - private <T> void resetCommunicatorExpectingNoBroadcast( - Capture<T> message, - Capture<MessageSubject> subject, - Capture<Function<T, byte[]>> encoder) { - message.reset(); - subject.reset(); - encoder.reset(); - reset(clusterCommunicator); - replay(clusterCommunicator); - } - - private <T> void resetCommunicatorExpectingSingleBroadcast( - Capture<T> message, - Capture<MessageSubject> subject, - Capture<Function<T, byte[]>> encoder) { - - message.reset(); - subject.reset(); - encoder.reset(); - reset(clusterCommunicator); - clusterCommunicator.broadcast( - capture(message), - capture(subject), - capture(encoder)); - expectLastCall().once(); - replay(clusterCommunicator); - } - - @Test - public final void testGetPorts() { - putDevice(DID1, SW1); - putDevice(DID2, SW1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true), - new DefaultPortDescription(P2, true) - ); - deviceStore.updatePorts(PID, DID1, pds); - - Set<PortNumber> expectedPorts = Sets.newHashSet(P1, P2); - List<Port> ports = deviceStore.getPorts(DID1); - for (Port port : ports) { - assertTrue("Port is enabled", port.isEnabled()); - assertTrue("PortNumber is one of expected", - expectedPorts.remove(port.number())); - } - assertTrue("Event for all expectedport appeared", expectedPorts.isEmpty()); - - - assertTrue("DID2 has no ports", deviceStore.getPorts(DID2).isEmpty()); - } - - @Test - public final void testGetPort() { - putDevice(DID1, SW1); - putDevice(DID2, SW1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true), - new DefaultPortDescription(P2, false) - ); - deviceStore.updatePorts(PID, DID1, pds); - - Port port1 = deviceStore.getPort(DID1, P1); - assertEquals(P1, port1.number()); - assertTrue("Port is enabled", port1.isEnabled()); - - Port port2 = deviceStore.getPort(DID1, P2); - assertEquals(P2, port2.number()); - assertFalse("Port is disabled", port2.isEnabled()); - - Port port3 = deviceStore.getPort(DID1, P3); - assertNull("P3 not expected", port3); - } - - @Test - public final void testRemoveDevice() { - putDevice(DID1, SW1, A1); - List<PortDescription> pds = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true, A2) - ); - deviceStore.updatePorts(PID, DID1, pds); - putDevice(DID2, SW1); - - assertEquals(2, deviceStore.getDeviceCount()); - assertEquals(1, deviceStore.getPorts(DID1).size()); - assertAnnotationsEquals(deviceStore.getDevice(DID1).annotations(), A1); - assertAnnotationsEquals(deviceStore.getPort(DID1, P1).annotations(), A2); - - Capture<InternalDeviceEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalDeviceEvent, byte[]>> encoder = new Capture<>(); - - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - - DeviceEvent event = deviceStore.removeDevice(DID1); - assertEquals(DEVICE_REMOVED, event.type()); - assertDevice(DID1, SW1, event.subject()); - - assertEquals(1, deviceStore.getDeviceCount()); - assertEquals(0, deviceStore.getPorts(DID1).size()); - verify(clusterCommunicator); - // TODO: verify broadcast message - assertTrue(message.hasCaptured()); - - // putBack Device, Port w/o annotation - putDevice(DID1, SW1); - List<PortDescription> pds2 = Arrays.<PortDescription>asList( - new DefaultPortDescription(P1, true) - ); - deviceStore.updatePorts(PID, DID1, pds2); - - // annotations should not survive - assertEquals(2, deviceStore.getDeviceCount()); - assertEquals(1, deviceStore.getPorts(DID1).size()); - assertAnnotationsEquals(deviceStore.getDevice(DID1).annotations()); - assertAnnotationsEquals(deviceStore.getPort(DID1, P1).annotations()); - } - - // If Delegates should be called only on remote events, - // then Simple* should never call them, thus not test required. - // TODO add test for Port events when we have them - @Ignore("Ignore until Delegate spec. is clear.") - @Test - public final void testEvents() throws InterruptedException { - final CountDownLatch addLatch = new CountDownLatch(1); - DeviceStoreDelegate checkAdd = event -> { - assertEquals(DEVICE_ADDED, event.type()); - assertDevice(DID1, SW1, event.subject()); - addLatch.countDown(); - }; - final CountDownLatch updateLatch = new CountDownLatch(1); - DeviceStoreDelegate checkUpdate = event -> { - assertEquals(DEVICE_UPDATED, event.type()); - assertDevice(DID1, SW2, event.subject()); - updateLatch.countDown(); - }; - final CountDownLatch removeLatch = new CountDownLatch(1); - DeviceStoreDelegate checkRemove = event -> { - assertEquals(DEVICE_REMOVED, event.type()); - assertDevice(DID1, SW2, event.subject()); - removeLatch.countDown(); - }; - - DeviceDescription description = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW1, SN, CID); - deviceStore.setDelegate(checkAdd); - deviceStore.createOrUpdateDevice(PID, DID1, description); - assertTrue("Add event fired", addLatch.await(1, TimeUnit.SECONDS)); - - - DeviceDescription description2 = - new DefaultDeviceDescription(DID1.uri(), SWITCH, MFR, - HW, SW2, SN, CID); - deviceStore.unsetDelegate(checkAdd); - deviceStore.setDelegate(checkUpdate); - deviceStore.createOrUpdateDevice(PID, DID1, description2); - assertTrue("Update event fired", updateLatch.await(1, TimeUnit.SECONDS)); - - deviceStore.unsetDelegate(checkUpdate); - deviceStore.setDelegate(checkRemove); - deviceStore.removeDevice(DID1); - assertTrue("Remove event fired", removeLatch.await(1, TimeUnit.SECONDS)); - } - - private final class TestMastershipService extends MastershipServiceAdapter { - @Override - public NodeId getMasterFor(DeviceId deviceId) { - return NID1; - } - @Override - public CompletableFuture<MastershipRole> requestRoleFor(DeviceId deviceId) { - return CompletableFuture.completedFuture(null); - } - } - - private static final class TestGossipDeviceStore extends GossipDeviceStore { - - public TestGossipDeviceStore( - DeviceClockService deviceClockService, - ClusterService clusterService, - ClusterCommunicationService clusterCommunicator) { - this.deviceClockService = deviceClockService; - this.clusterService = clusterService; - this.clusterCommunicator = clusterCommunicator; - } - } - - private static final class TestClusterService extends StaticClusterService { - - public TestClusterService() { - localNode = ONOS1; - nodes.put(NID1, ONOS1); - nodeStates.put(NID1, ACTIVE); - - nodes.put(NID2, ONOS2); - nodeStates.put(NID2, ACTIVE); - } - } - - private final class TestDeviceClockService extends DeviceClockServiceAdapter { - - private final AtomicLong ticker = new AtomicLong(); - - @Override - public Timestamp getTimestamp(DeviceId deviceId) { - if (DID1.equals(deviceId)) { - return new MastershipBasedTimestamp(1, ticker.getAndIncrement()); - } else if (DID2.equals(deviceId)) { - return new MastershipBasedTimestamp(2, ticker.getAndIncrement()); - } else { - throw new IllegalStateException(); - } - } - - @Override - public boolean isTimestampAvailable(DeviceId deviceId) { - return DID1.equals(deviceId) || DID2.equals(deviceId); - } - } - - private class TestDatabaseManager extends DatabaseManager { - void init(ClusterService clusterService, - ClusterCommunicationService clusterCommunicator) { - this.clusterService = clusterService; - this.clusterCommunicator = clusterCommunicator; - } - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/PortFragmentIdTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/PortFragmentIdTest.java deleted file mode 100644 index 5b862520..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/device/impl/PortFragmentIdTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.device.impl; - -import static org.onosproject.net.DeviceId.deviceId; - -import org.junit.Test; -import org.onosproject.net.DeviceId; -import org.onosproject.net.PortNumber; -import org.onosproject.net.provider.ProviderId; - -import com.google.common.testing.EqualsTester; - -public class PortFragmentIdTest { - - private static final ProviderId PID = new ProviderId("of", "foo"); - private static final ProviderId PIDA = new ProviderId("of", "bar", true); - - private static final DeviceId DID1 = deviceId("of:foo"); - private static final DeviceId DID2 = deviceId("of:bar"); - - private static final PortNumber PN1 = PortNumber.portNumber(1); - private static final PortNumber PN2 = PortNumber.portNumber(2); - - @Test - public final void testEquals() { - new EqualsTester() - .addEqualityGroup(new PortFragmentId(DID1, PID, PN1), - new PortFragmentId(DID1, PID, PN1)) - .addEqualityGroup(new PortFragmentId(DID2, PID, PN1), - new PortFragmentId(DID2, PID, PN1)) - .addEqualityGroup(new PortFragmentId(DID1, PIDA, PN1), - new PortFragmentId(DID1, PIDA, PN1)) - .addEqualityGroup(new PortFragmentId(DID2, PIDA, PN1), - new PortFragmentId(DID2, PIDA, PN1)) - - .addEqualityGroup(new PortFragmentId(DID1, PID, PN2), - new PortFragmentId(DID1, PID, PN2)) - .addEqualityGroup(new PortFragmentId(DID2, PID, PN2), - new PortFragmentId(DID2, PID, PN2)) - .addEqualityGroup(new PortFragmentId(DID1, PIDA, PN2), - new PortFragmentId(DID1, PIDA, PN2)) - .addEqualityGroup(new PortFragmentId(DID2, PIDA, PN2), - new PortFragmentId(DID2, PIDA, PN2)) - .testEquals(); - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/EventuallyConsistentMapImplTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/EventuallyConsistentMapImplTest.java deleted file mode 100644 index b74aa370..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/EventuallyConsistentMapImplTest.java +++ /dev/null @@ -1,914 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.ecmap; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.Function; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.packet.IpAddress; -import org.onlab.util.KryoNamespace; -import org.onosproject.cluster.ClusterService; -import org.onosproject.cluster.ControllerNode; -import org.onosproject.cluster.DefaultControllerNode; -import org.onosproject.cluster.NodeId; -import org.onosproject.event.AbstractEvent; -import org.onosproject.persistence.PersistenceService; -import org.onosproject.store.Timestamp; -import org.onosproject.store.cluster.messaging.ClusterCommunicationService; -import org.onosproject.store.cluster.messaging.ClusterCommunicationServiceAdapter; -import org.onosproject.store.cluster.messaging.MessageSubject; -import org.onosproject.store.impl.LogicalTimestamp; -import org.onosproject.store.persistence.TestPersistenceService; -import org.onosproject.store.serializers.KryoNamespaces; -import org.onosproject.store.serializers.KryoSerializer; -import org.onosproject.store.service.EventuallyConsistentMap; -import org.onosproject.store.service.EventuallyConsistentMapEvent; -import org.onosproject.store.service.EventuallyConsistentMapListener; -import org.onosproject.store.service.WallClockTimestamp; - -import com.google.common.collect.ComparisonChain; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.util.concurrent.MoreExecutors; - -import static com.google.common.base.Preconditions.checkArgument; -import static junit.framework.TestCase.assertFalse; -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -/** - * Unit tests for EventuallyConsistentMapImpl. - */ -public class EventuallyConsistentMapImplTest { - - private EventuallyConsistentMap<String, String> ecMap; - - private PersistenceService persistenceService; - private ClusterService clusterService; - private ClusterCommunicationService clusterCommunicator; - private SequentialClockService<String, String> clockService; - - private static final String MAP_NAME = "test"; - private static final MessageSubject UPDATE_MESSAGE_SUBJECT - = new MessageSubject("ecm-" + MAP_NAME + "-update"); - private static final MessageSubject ANTI_ENTROPY_MESSAGE_SUBJECT - = new MessageSubject("ecm-" + MAP_NAME + "-anti-entropy"); - - private static final String KEY1 = "one"; - private static final String KEY2 = "two"; - private static final String VALUE1 = "oneValue"; - private static final String VALUE2 = "twoValue"; - - private final ControllerNode self = - new DefaultControllerNode(new NodeId("local"), IpAddress.valueOf(1)); - - private Consumer<Collection<UpdateEntry<String, String>>> updateHandler; - private Consumer<AntiEntropyAdvertisement<String>> antiEntropyHandler; - - /* - * Serialization is a bit tricky here. We need to serialize in the tests - * to set the expectations, which will use this serializer here, but the - * EventuallyConsistentMap will use its own internal serializer. This means - * this serializer must be set up exactly the same as map's internal - * serializer. - */ - private static final KryoSerializer SERIALIZER = new KryoSerializer() { - @Override - protected void setupKryoPool() { - serializerPool = KryoNamespace.newBuilder() - // Classes we give to the map - .register(KryoNamespaces.API) - .register(TestTimestamp.class) - // Below is the classes that the map internally registers - .register(LogicalTimestamp.class) - .register(WallClockTimestamp.class) - .register(ArrayList.class) - .register(AntiEntropyAdvertisement.class) - .register(HashMap.class) - .register(Optional.class) - .build(); - } - }; - - @Before - public void setUp() throws Exception { - clusterService = createMock(ClusterService.class); - expect(clusterService.getLocalNode()).andReturn(self).anyTimes(); - expect(clusterService.getNodes()).andReturn(ImmutableSet.of(self)).anyTimes(); - replay(clusterService); - - clusterCommunicator = createMock(ClusterCommunicationService.class); - - persistenceService = new TestPersistenceService(); - // Add expectation for adding cluster message subscribers which - // delegate to our ClusterCommunicationService implementation. This - // allows us to get a reference to the map's internal cluster message - // handlers so we can induce events coming in from a peer. - clusterCommunicator.<String>addSubscriber(anyObject(MessageSubject.class), - anyObject(Function.class), anyObject(Consumer.class), anyObject(Executor.class)); - expectLastCall().andDelegateTo(new TestClusterCommunicationService()).times(2); - - replay(clusterCommunicator); - - clockService = new SequentialClockService<>(); - - KryoNamespace.Builder serializer = KryoNamespace.newBuilder() - .register(KryoNamespaces.API) - .register(TestTimestamp.class); - - ecMap = new EventuallyConsistentMapBuilderImpl<String, String>( - clusterService, clusterCommunicator, persistenceService) - .withName(MAP_NAME) - .withSerializer(serializer) - .withTimestampProvider((k, v) -> clockService.getTimestamp(k, v)) - .withCommunicationExecutor(MoreExecutors.newDirectExecutorService()) - .withPersistence() - .build(); - - // Reset ready for tests to add their own expectations - reset(clusterCommunicator); - } - - @After - public void tearDown() { - reset(clusterCommunicator); - ecMap.destroy(); - } - - @SuppressWarnings("unchecked") - private EventuallyConsistentMapListener<String, String> getListener() { - return createMock(EventuallyConsistentMapListener.class); - } - - @Test - public void testSize() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertEquals(0, ecMap.size()); - ecMap.put(KEY1, VALUE1); - assertEquals(1, ecMap.size()); - ecMap.put(KEY1, VALUE2); - assertEquals(1, ecMap.size()); - ecMap.put(KEY2, VALUE2); - assertEquals(2, ecMap.size()); - for (int i = 0; i < 10; i++) { - ecMap.put("" + i, "" + i); - } - assertEquals(12, ecMap.size()); - ecMap.remove(KEY1); - assertEquals(11, ecMap.size()); - ecMap.remove(KEY1); - assertEquals(11, ecMap.size()); - } - - @Test - public void testIsEmpty() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertTrue(ecMap.isEmpty()); - ecMap.put(KEY1, VALUE1); - assertFalse(ecMap.isEmpty()); - ecMap.remove(KEY1); - assertTrue(ecMap.isEmpty()); - } - - @Test - public void testContainsKey() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertFalse(ecMap.containsKey(KEY1)); - ecMap.put(KEY1, VALUE1); - assertTrue(ecMap.containsKey(KEY1)); - assertFalse(ecMap.containsKey(KEY2)); - ecMap.remove(KEY1); - assertFalse(ecMap.containsKey(KEY1)); - } - - @Test - public void testContainsValue() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertFalse(ecMap.containsValue(VALUE1)); - ecMap.put(KEY1, VALUE1); - assertTrue(ecMap.containsValue(VALUE1)); - assertFalse(ecMap.containsValue(VALUE2)); - ecMap.put(KEY1, VALUE2); - assertFalse(ecMap.containsValue(VALUE1)); - assertTrue(ecMap.containsValue(VALUE2)); - ecMap.remove(KEY1); - assertFalse(ecMap.containsValue(VALUE2)); - } - - @Test - public void testGet() throws Exception { - expectPeerMessage(clusterCommunicator); - - CountDownLatch latch; - - // Local put - assertNull(ecMap.get(KEY1)); - ecMap.put(KEY1, VALUE1); - assertEquals(VALUE1, ecMap.get(KEY1)); - - // Remote put - List<UpdateEntry<String, String>> message - = ImmutableList.of(generatePutMessage(KEY2, VALUE2, clockService.getTimestamp(KEY2, VALUE2))); - - // Create a latch so we know when the put operation has finished - latch = new CountDownLatch(1); - ecMap.addListener(new TestListener(latch)); - - assertNull(ecMap.get(KEY2)); - updateHandler.accept(message); - assertTrue("External listener never got notified of internal event", - latch.await(100, TimeUnit.MILLISECONDS)); - assertEquals(VALUE2, ecMap.get(KEY2)); - - // Local remove - ecMap.remove(KEY2); - assertNull(ecMap.get(KEY2)); - - // Remote remove - message = ImmutableList.of(generateRemoveMessage(KEY1, clockService.getTimestamp(KEY1, VALUE1))); - - // Create a latch so we know when the remove operation has finished - latch = new CountDownLatch(1); - ecMap.addListener(new TestListener(latch)); - - updateHandler.accept(message); - assertTrue("External listener never got notified of internal event", - latch.await(100, TimeUnit.MILLISECONDS)); - assertNull(ecMap.get(KEY1)); - } - - @Test - public void testPut() throws Exception { - // Set up expectations of external events to be sent to listeners during - // the test. These don't use timestamps so we can set them all up at once. - EventuallyConsistentMapListener<String, String> listener - = getListener(); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE2)); - replay(listener); - - ecMap.addListener(listener); - - // Set up expected internal message to be broadcast to peers on first put - expectSpecificMulticastMessage(generatePutMessage(KEY1, VALUE1, clockService - .peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - // Put first value - assertNull(ecMap.get(KEY1)); - ecMap.put(KEY1, VALUE1); - assertEquals(VALUE1, ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Set up expected internal message to be broadcast to peers on second put - expectSpecificMulticastMessage(generatePutMessage( - KEY1, VALUE2, clockService.peekAtNextTimestamp()), UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - // Update same key to a new value - ecMap.put(KEY1, VALUE2); - assertEquals(VALUE2, ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Do a put with a older timestamp than the value already there. - // The map data should not be changed and no notifications should be sent. - reset(clusterCommunicator); - replay(clusterCommunicator); - - clockService.turnBackTime(); - ecMap.put(KEY1, VALUE1); - // Value should not have changed. - assertEquals(VALUE2, ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Check that our listener received the correct events during the test - verify(listener); - } - - @Test - public void testRemove() throws Exception { - // Set up expectations of external events to be sent to listeners during - // the test. These don't use timestamps so we can set them all up at once. - EventuallyConsistentMapListener<String, String> listener - = getListener(); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2)); - replay(listener); - - ecMap.addListener(listener); - - // Put in an initial value - expectPeerMessage(clusterCommunicator); - ecMap.put(KEY1, VALUE1); - assertEquals(VALUE1, ecMap.get(KEY1)); - - // Remove the value and check the correct internal cluster messages - // are sent - expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()), - UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - ecMap.remove(KEY1); - assertNull(ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Remove the same value again. Even though the value is no longer in - // the map, we expect that the tombstone is updated and another remove - // event is sent to the cluster and external listeners. - expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()), - UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - ecMap.remove(KEY1); - assertNull(ecMap.get(KEY1)); - - verify(clusterCommunicator); - - - // Put in a new value for us to try and remove - expectPeerMessage(clusterCommunicator); - - ecMap.put(KEY2, VALUE2); - - clockService.turnBackTime(); - - // Remove should have no effect, since it has an older timestamp than - // the put. Expect no notifications to be sent out - reset(clusterCommunicator); - replay(clusterCommunicator); - - ecMap.remove(KEY2); - - verify(clusterCommunicator); - - // Check that our listener received the correct events during the test - verify(listener); - } - - @Test - public void testCompute() throws Exception { - // Set up expectations of external events to be sent to listeners during - // the test. These don't use timestamps so we can set them all up at once. - EventuallyConsistentMapListener<String, String> listener - = getListener(); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2)); - replay(listener); - - ecMap.addListener(listener); - - // Put in an initial value - expectPeerMessage(clusterCommunicator); - ecMap.compute(KEY1, (k, v) -> VALUE1); - assertEquals(VALUE1, ecMap.get(KEY1)); - - // Remove the value and check the correct internal cluster messages - // are sent - expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()), - UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - ecMap.compute(KEY1, (k, v) -> null); - assertNull(ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Remove the same value again. Even though the value is no longer in - // the map, we expect that the tombstone is updated and another remove - // event is sent to the cluster and external listeners. - expectSpecificMulticastMessage(generateRemoveMessage(KEY1, clockService.peekAtNextTimestamp()), - UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - ecMap.compute(KEY1, (k, v) -> null); - assertNull(ecMap.get(KEY1)); - - verify(clusterCommunicator); - - // Put in a new value for us to try and remove - expectPeerMessage(clusterCommunicator); - - ecMap.compute(KEY2, (k, v) -> VALUE2); - - clockService.turnBackTime(); - - // Remove should have no effect, since it has an older timestamp than - // the put. Expect no notifications to be sent out - reset(clusterCommunicator); - replay(clusterCommunicator); - - ecMap.compute(KEY2, (k, v) -> null); - - verify(clusterCommunicator); - - // Check that our listener received the correct events during the test - verify(listener); - } - - @Test - public void testPutAll() throws Exception { - // putAll() with an empty map is a no-op - no messages will be sent - reset(clusterCommunicator); - replay(clusterCommunicator); - - ecMap.putAll(new HashMap<>()); - - verify(clusterCommunicator); - - // Set up the listener with our expected events - EventuallyConsistentMapListener<String, String> listener - = getListener(); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.PUT, KEY2, VALUE2)); - replay(listener); - - ecMap.addListener(listener); - - // Expect a multi-update inter-instance message - expectSpecificBroadcastMessage(generatePutMessage(KEY1, VALUE1, KEY2, VALUE2), UPDATE_MESSAGE_SUBJECT, - clusterCommunicator); - - Map<String, String> putAllValues = new HashMap<>(); - putAllValues.put(KEY1, VALUE1); - putAllValues.put(KEY2, VALUE2); - - // Put the values in the map - ecMap.putAll(putAllValues); - - // Check the correct messages and events were sent - verify(clusterCommunicator); - verify(listener); - } - - @Test - public void testClear() throws Exception { - EventuallyConsistentMapListener<String, String> listener - = getListener(); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY1, VALUE1)); - listener.event(new EventuallyConsistentMapEvent<>( - MAP_NAME, EventuallyConsistentMapEvent.Type.REMOVE, KEY2, VALUE2)); - replay(listener); - - // clear() on an empty map is a no-op - no messages will be sent - reset(clusterCommunicator); - replay(clusterCommunicator); - - assertTrue(ecMap.isEmpty()); - ecMap.clear(); - verify(clusterCommunicator); - - // Put some items in the map - expectPeerMessage(clusterCommunicator); - ecMap.put(KEY1, VALUE1); - ecMap.put(KEY2, VALUE2); - - ecMap.addListener(listener); - expectSpecificBroadcastMessage(generateRemoveMessage(KEY1, KEY2), UPDATE_MESSAGE_SUBJECT, clusterCommunicator); - - ecMap.clear(); - - verify(clusterCommunicator); - verify(listener); - } - - @Test - public void testKeySet() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertTrue(ecMap.keySet().isEmpty()); - - // Generate some keys - Set<String> keys = new HashSet<>(); - for (int i = 1; i <= 10; i++) { - keys.add("" + i); - } - - // Put each key in the map - keys.forEach(k -> ecMap.put(k, "value" + k)); - - // Check keySet() returns the correct value - assertEquals(keys, ecMap.keySet()); - - // Update the value for one of the keys - ecMap.put(keys.iterator().next(), "new-value"); - - // Check the key set is still the same - assertEquals(keys, ecMap.keySet()); - - // Remove a key - String removeKey = keys.iterator().next(); - keys.remove(removeKey); - ecMap.remove(removeKey); - - // Check the key set is still correct - assertEquals(keys, ecMap.keySet()); - } - - @Test - public void testValues() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertTrue(ecMap.values().isEmpty()); - - // Generate some values - Map<String, String> expectedValues = new HashMap<>(); - for (int i = 1; i <= 10; i++) { - expectedValues.put("" + i, "value" + i); - } - - // Add them into the map - expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue())); - - // Check the values collection is correct - assertEquals(expectedValues.values().size(), ecMap.values().size()); - expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v))); - - // Update the value for one of the keys - Map.Entry<String, String> first = expectedValues.entrySet().iterator().next(); - expectedValues.put(first.getKey(), "new-value"); - ecMap.put(first.getKey(), "new-value"); - - // Check the values collection is still correct - assertEquals(expectedValues.values().size(), ecMap.values().size()); - expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v))); - - // Remove a key - String removeKey = expectedValues.keySet().iterator().next(); - expectedValues.remove(removeKey); - ecMap.remove(removeKey); - - // Check the values collection is still correct - assertEquals(expectedValues.values().size(), ecMap.values().size()); - expectedValues.values().forEach(v -> assertTrue(ecMap.values().contains(v))); - } - - @Test - public void testEntrySet() throws Exception { - expectPeerMessage(clusterCommunicator); - - assertTrue(ecMap.entrySet().isEmpty()); - - // Generate some values - Map<String, String> expectedValues = new HashMap<>(); - for (int i = 1; i <= 10; i++) { - expectedValues.put("" + i, "value" + i); - } - - // Add them into the map - expectedValues.entrySet().forEach(e -> ecMap.put(e.getKey(), e.getValue())); - - // Check the entry set is correct - assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet())); - - // Update the value for one of the keys - Map.Entry<String, String> first = expectedValues.entrySet().iterator().next(); - expectedValues.put(first.getKey(), "new-value"); - ecMap.put(first.getKey(), "new-value"); - - // Check the entry set is still correct - assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet())); - - // Remove a key - String removeKey = expectedValues.keySet().iterator().next(); - expectedValues.remove(removeKey); - ecMap.remove(removeKey); - - // Check the entry set is still correct - assertTrue(entrySetsAreEqual(expectedValues, ecMap.entrySet())); - } - - private static boolean entrySetsAreEqual(Map<String, String> expectedMap, Set<Map.Entry<String, String>> actual) { - if (expectedMap.entrySet().size() != actual.size()) { - return false; - } - - for (Map.Entry<String, String> e : actual) { - if (!expectedMap.containsKey(e.getKey())) { - return false; - } - if (!Objects.equals(expectedMap.get(e.getKey()), e.getValue())) { - return false; - } - } - return true; - } - - @Test - public void testDestroy() throws Exception { - clusterCommunicator.removeSubscriber(UPDATE_MESSAGE_SUBJECT); - clusterCommunicator.removeSubscriber(ANTI_ENTROPY_MESSAGE_SUBJECT); - - replay(clusterCommunicator); - - ecMap.destroy(); - - verify(clusterCommunicator); - - try { - ecMap.get(KEY1); - fail("get after destroy should throw exception"); - } catch (IllegalStateException e) { - assertTrue(true); - } - - try { - ecMap.put(KEY1, VALUE1); - fail("put after destroy should throw exception"); - } catch (IllegalStateException e) { - assertTrue(true); - } - } - - private UpdateEntry<String, String> generatePutMessage(String key, String value, Timestamp timestamp) { - return new UpdateEntry<>(key, new MapValue<>(value, timestamp)); - } - - private List<UpdateEntry<String, String>> generatePutMessage( - String key1, String value1, String key2, String value2) { - List<UpdateEntry<String, String>> list = new ArrayList<>(); - - Timestamp timestamp1 = clockService.peek(1); - Timestamp timestamp2 = clockService.peek(2); - - list.add(generatePutMessage(key1, value1, timestamp1)); - list.add(generatePutMessage(key2, value2, timestamp2)); - - return list; - } - - private UpdateEntry<String, String> generateRemoveMessage(String key, Timestamp timestamp) { - return new UpdateEntry<>(key, new MapValue<>(null, timestamp)); - } - - private List<UpdateEntry<String, String>> generateRemoveMessage(String key1, String key2) { - List<UpdateEntry<String, String>> list = new ArrayList<>(); - - Timestamp timestamp1 = clockService.peek(1); - Timestamp timestamp2 = clockService.peek(2); - - list.add(generateRemoveMessage(key1, timestamp1)); - list.add(generateRemoveMessage(key2, timestamp2)); - - return list; - } - - /** - * Sets up a mock ClusterCommunicationService to expect a specific cluster - * message to be broadcast to the cluster. - * - * @param message message we expect to be sent - * @param clusterCommunicator a mock ClusterCommunicationService to set up - */ - //FIXME rename - private static <T> void expectSpecificBroadcastMessage( - T message, - MessageSubject subject, - ClusterCommunicationService clusterCommunicator) { - reset(clusterCommunicator); - clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - } - - /** - * Sets up a mock ClusterCommunicationService to expect a specific cluster - * message to be multicast to the cluster. - * - * @param message message we expect to be sent - * @param subject subject we expect to be sent to - * @param clusterCommunicator a mock ClusterCommunicationService to set up - */ - //FIXME rename - private static <T> void expectSpecificMulticastMessage(T message, MessageSubject subject, - ClusterCommunicationService clusterCommunicator) { - reset(clusterCommunicator); - clusterCommunicator.<T>multicast(eq(message), eq(subject), anyObject(Function.class), anyObject(Set.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - } - - - /** - * Sets up a mock ClusterCommunicationService to expect a multicast cluster message - * that is sent to it. This is useful for unit tests where we aren't - * interested in testing the messaging component. - * - * @param clusterCommunicator a mock ClusterCommunicationService to set up - */ - //FIXME rename - private <T> void expectPeerMessage(ClusterCommunicationService clusterCommunicator) { - reset(clusterCommunicator); -// expect(clusterCommunicator.multicast(anyObject(ClusterMessage.class), -// anyObject(Iterable.class))) - expect(clusterCommunicator.<T>unicast( - anyObject(), - anyObject(MessageSubject.class), - anyObject(Function.class), - anyObject(NodeId.class))) - .andReturn(CompletableFuture.completedFuture(null)) - .anyTimes(); - replay(clusterCommunicator); - } - - /** - * Sets up a mock ClusterCommunicationService to expect a broadcast cluster message - * that is sent to it. This is useful for unit tests where we aren't - * interested in testing the messaging component. - * - * @param clusterCommunicator a mock ClusterCommunicationService to set up - */ - private void expectBroadcastMessage(ClusterCommunicationService clusterCommunicator) { - reset(clusterCommunicator); - clusterCommunicator.<AbstractEvent>multicast( - anyObject(AbstractEvent.class), - anyObject(MessageSubject.class), - anyObject(Function.class), - anyObject(Set.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - } - - /** - * ClusterCommunicationService implementation that the map's addSubscriber - * call will delegate to. This means we can get a reference to the - * internal cluster message handler used by the map, so that we can simulate - * events coming in from other instances. - */ - private final class TestClusterCommunicationService - extends ClusterCommunicationServiceAdapter { - - @Override - public <M> void addSubscriber(MessageSubject subject, - Function<byte[], M> decoder, Consumer<M> handler, - Executor executor) { - if (subject.equals(UPDATE_MESSAGE_SUBJECT)) { - updateHandler = (Consumer<Collection<UpdateEntry<String, String>>>) handler; - } else if (subject.equals(ANTI_ENTROPY_MESSAGE_SUBJECT)) { - antiEntropyHandler = (Consumer<AntiEntropyAdvertisement<String>>) handler; - } else { - throw new RuntimeException("Unexpected message subject " + subject.toString()); - } - } - } - - /** - * ClockService implementation that gives out timestamps based on a - * sequential counter. This clock service enables more control over the - * timestamps that are given out, including being able to "turn back time" - * to give out timestamps from the past. - * - * @param <T> Type that the clock service will give out timestamps for - * @param <U> Second type that the clock service will give out values for - */ - private class SequentialClockService<T, U> { - - private static final long INITIAL_VALUE = 1; - private final AtomicLong counter = new AtomicLong(INITIAL_VALUE); - - public Timestamp getTimestamp(T object, U object2) { - return new TestTimestamp(counter.getAndIncrement()); - } - - /** - * Returns what the next timestamp will be without consuming the - * timestamp. This allows test code to set expectations correctly while - * still allowing the CUT to get the same timestamp. - * - * @return timestamp equal to the timestamp that will be returned by the - * next call to {@link #getTimestamp(T, U)}. - */ - public Timestamp peekAtNextTimestamp() { - return peek(1); - } - - /** - * Returns the ith timestamp to be given out in the future without - * consuming the timestamp. For example, i=1 returns the next timestamp, - * i=2 returns the timestamp after that, and so on. - * - * @param i number of the timestamp to peek at - * @return the ith timestamp that will be given out - */ - public Timestamp peek(int i) { - checkArgument(i > 0, "i must be a positive integer"); - - return new TestTimestamp(counter.get() + i - 1); - } - - /** - * Turns the clock back two ticks, so the next call to getTimestamp will - * return an older timestamp than the previous call to getTimestamp. - */ - public void turnBackTime() { - // Not atomic, but should be OK for these tests. - counter.decrementAndGet(); - counter.decrementAndGet(); - } - - } - - /** - * Timestamp implementation where the value of the timestamp can be - * specified explicitly at creation time. - */ - private class TestTimestamp implements Timestamp { - - private final long timestamp; - - /** - * Creates a new timestamp that has the specified value. - * - * @param timestamp value of the timestamp - */ - public TestTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - @Override - public int compareTo(Timestamp o) { - checkArgument(o instanceof TestTimestamp); - TestTimestamp otherTimestamp = (TestTimestamp) o; - return ComparisonChain.start() - .compare(this.timestamp, otherTimestamp.timestamp) - .result(); - } - } - - /** - * EventuallyConsistentMapListener implementation which triggers a latch - * when it receives an event. - */ - private class TestListener implements EventuallyConsistentMapListener<String, String> { - private CountDownLatch latch; - - /** - * Creates a new listener that will trigger the specified latch when it - * receives and event. - * - * @param latch the latch to trigger on events - */ - public TestListener(CountDownLatch latch) { - this.latch = latch; - } - - @Override - public void event(EventuallyConsistentMapEvent<String, String> event) { - latch.countDown(); - } - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/MapValueTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/MapValueTest.java deleted file mode 100644 index d6dca9b8..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/ecmap/MapValueTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.ecmap; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onosproject.store.Timestamp; -import org.onosproject.store.ecmap.MapValue.Digest; -import org.onosproject.store.impl.LogicalTimestamp; - -/** - * Unit tests for MapValue. - */ -public class MapValueTest { - - @Test - public void testConstruction() { - Timestamp ts = new LogicalTimestamp(10); - MapValue<String> mv = new MapValue<>("foo", ts); - assertEquals("foo", mv.get()); - assertEquals(ts, mv.timestamp()); - assertTrue(mv.isAlive()); - } - - @Test - public void testDigest() { - Timestamp ts = new LogicalTimestamp(10); - MapValue<String> mv = new MapValue<>("foo", ts); - Digest actual = mv.digest(); - Digest expected = new MapValue.Digest(ts, false); - assertEquals(actual, expected); - } - - @Test - public void testComparison() { - Timestamp ts1 = new LogicalTimestamp(9); - Timestamp ts2 = new LogicalTimestamp(10); - Timestamp ts3 = new LogicalTimestamp(11); - MapValue<String> mv1 = new MapValue<>("foo", ts1); - MapValue<String> mv2 = new MapValue<>("foo", ts2); - MapValue<String> mv3 = new MapValue<>("foo", ts3); - assertTrue(mv2.isNewerThan(mv1)); - assertFalse(mv1.isNewerThan(mv3)); - - assertTrue(mv3.isNewerThan(ts2)); - assertFalse(mv1.isNewerThan(ts2)); - - assertTrue(mv1.compareTo(mv2) < 0); - assertTrue(mv1.compareTo(mv1) == 0); - assertTrue(mv3.compareTo(mv2) > 0); - } - - @Test - public void testTombstone() { - Timestamp ts1 = new LogicalTimestamp(9); - MapValue<String> mv = MapValue.tombstone(ts1); - assertTrue(mv.isTombstone()); - assertFalse(mv.isAlive()); - assertNull(mv.get()); - assertEquals(ts1, mv.timestamp()); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flow/impl/ReplicaInfoManagerTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flow/impl/ReplicaInfoManagerTest.java deleted file mode 100644 index 76ff8045..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flow/impl/ReplicaInfoManagerTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.flow.impl; - -import com.google.common.base.Optional; -import com.google.common.collect.Maps; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onosproject.cluster.NodeId; -import org.onosproject.cluster.RoleInfo; -import org.onosproject.common.event.impl.TestEventDispatcher; -import org.onosproject.event.ListenerRegistry; -import org.onosproject.mastership.MastershipEvent; -import org.onosproject.mastership.MastershipEvent.Type; -import org.onosproject.mastership.MastershipListener; -import org.onosproject.mastership.MastershipService; -import org.onosproject.mastership.MastershipServiceAdapter; -import org.onosproject.net.DeviceId; -import org.onosproject.store.flow.ReplicaInfo; -import org.onosproject.store.flow.ReplicaInfoEvent; -import org.onosproject.store.flow.ReplicaInfoEventListener; -import org.onosproject.store.flow.ReplicaInfoService; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class ReplicaInfoManagerTest { - - - private static final DeviceId DID1 = DeviceId.deviceId("of:1"); - private static final DeviceId DID2 = DeviceId.deviceId("of:2"); - private static final NodeId NID1 = new NodeId("foo"); - - private ReplicaInfoManager mgr; - private ReplicaInfoService service; - - private ListenerRegistry<MastershipEvent, MastershipListener> - mastershipListenerRegistry; - private TestEventDispatcher eventDispatcher; - - - @Before - public void setUp() throws Exception { - mastershipListenerRegistry = new ListenerRegistry<>(); - - mgr = new ReplicaInfoManager(); - service = mgr; - - eventDispatcher = new TestEventDispatcher(); - mgr.eventDispatcher = eventDispatcher; - mgr.mastershipService = new TestMastershipService(); - - // register dummy mastership event source - mgr.eventDispatcher.addSink(MastershipEvent.class, mastershipListenerRegistry); - - mgr.activate(); - } - - @After - public void tearDown() throws Exception { - mgr.deactivate(); - } - - @Test - public void testGetReplicaInfoFor() { - ReplicaInfo info1 = service.getReplicaInfoFor(DID1); - assertEquals(Optional.of(NID1), info1.master()); - // backups are always empty for now - assertEquals(Collections.emptyList(), info1.backups()); - - ReplicaInfo info2 = service.getReplicaInfoFor(DID2); - assertEquals("There's no master", Optional.absent(), info2.master()); - // backups are always empty for now - assertEquals(Collections.emptyList(), info2.backups()); - } - - @Test - public void testReplicaInfoEvent() throws InterruptedException { - final CountDownLatch latch = new CountDownLatch(1); - service.addListener(new MasterNodeCheck(latch, DID1, NID1)); - - // fake MastershipEvent - eventDispatcher.post(new MastershipEvent(Type.MASTER_CHANGED, DID1, - new RoleInfo(NID1, new LinkedList<>()))); - - assertTrue(latch.await(1, TimeUnit.SECONDS)); - } - - - private final class MasterNodeCheck implements ReplicaInfoEventListener { - private final CountDownLatch latch; - private Optional<NodeId> expectedMaster; - private DeviceId expectedDevice; - - - MasterNodeCheck(CountDownLatch latch, DeviceId did, - NodeId nid) { - this.latch = latch; - this.expectedMaster = Optional.fromNullable(nid); - this.expectedDevice = did; - } - - @Override - public void event(ReplicaInfoEvent event) { - assertEquals(expectedDevice, event.subject()); - assertEquals(expectedMaster, event.replicaInfo().master()); - // backups are always empty for now - assertEquals(Collections.emptyList(), event.replicaInfo().backups()); - latch.countDown(); - } - } - - - private final class TestMastershipService - extends MastershipServiceAdapter - implements MastershipService { - - private Map<DeviceId, NodeId> masters; - - TestMastershipService() { - masters = Maps.newHashMap(); - masters.put(DID1, NID1); - // DID2 has no master - } - - @Override - public NodeId getMasterFor(DeviceId deviceId) { - return masters.get(deviceId); - } - - @Override - public RoleInfo getNodesFor(DeviceId deviceId) { - return new RoleInfo(masters.get(deviceId), Collections.emptyList()); - } - - @Override - public void addListener(MastershipListener listener) { - mastershipListenerRegistry.addListener(listener); - } - - @Override - public void removeListener(MastershipListener listener) { - mastershipListenerRegistry.removeListener(listener); - } - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flowobjective/impl/DistributedFlowObjectiveStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flowobjective/impl/DistributedFlowObjectiveStoreTest.java deleted file mode 100644 index efa226c1..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/flowobjective/impl/DistributedFlowObjectiveStoreTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.flowobjective.impl; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onosproject.net.behaviour.DefaultNextGroup; -import org.onosproject.net.behaviour.NextGroup; -import org.onosproject.net.flowobjective.FlowObjectiveStore; -import org.onosproject.store.service.TestStorageService; - -import com.google.common.base.Charsets; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; - -/** - * Unit tests for distributed flow objective store. - */ -public class DistributedFlowObjectiveStoreTest { - DistributedFlowObjectiveStore storeImpl; - FlowObjectiveStore store; - - @Before - public void setUp() { - storeImpl = new DistributedFlowObjectiveStore(); - storeImpl.storageService = new TestStorageService(); - storeImpl.activate(); - store = storeImpl; - } - - @After - public void tearDown() { - storeImpl.deactivate(); - } - - @Test - public void testFlowObjectiveStore() { - NextGroup group2 = new DefaultNextGroup("2".getBytes(Charsets.US_ASCII)); - int group1Id = store.allocateNextId(); - int group2Id = store.allocateNextId(); - - NextGroup group1add = store.getNextGroup(group1Id); - assertThat(group1add, nullValue()); - - store.putNextGroup(group2Id, group2); - NextGroup group2Query = store.getNextGroup(group2Id); - assertThat(group2Query.data(), is(group2.data())); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/group/impl/DistributedGroupStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/group/impl/DistributedGroupStoreTest.java deleted file mode 100644 index 560fdb3a..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/group/impl/DistributedGroupStoreTest.java +++ /dev/null @@ -1,420 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.group.impl; - -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.junit.TestUtils; -import org.onosproject.core.DefaultGroupId; -import org.onosproject.core.GroupId; -import org.onosproject.mastership.MastershipServiceAdapter; -import org.onosproject.net.DeviceId; -import org.onosproject.net.MastershipRole; -import org.onosproject.net.PortNumber; -import org.onosproject.net.flow.DefaultTrafficTreatment; -import org.onosproject.net.flow.TrafficTreatment; -import org.onosproject.net.group.DefaultGroup; -import org.onosproject.net.group.DefaultGroupBucket; -import org.onosproject.net.group.DefaultGroupDescription; -import org.onosproject.net.group.DefaultGroupKey; -import org.onosproject.net.group.Group; -import org.onosproject.net.group.GroupBucket; -import org.onosproject.net.group.GroupBuckets; -import org.onosproject.net.group.GroupDescription; -import org.onosproject.net.group.GroupEvent; -import org.onosproject.net.group.GroupKey; -import org.onosproject.net.group.GroupOperation; -import org.onosproject.net.group.GroupStore; -import org.onosproject.net.group.GroupStoreDelegate; -import org.onosproject.store.cluster.messaging.ClusterCommunicationServiceAdapter; -import org.onosproject.store.service.EventuallyConsistentMap; -import org.onosproject.store.service.TestStorageService; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import com.google.common.testing.EqualsTester; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.onosproject.net.NetTestTools.APP_ID; -import static org.onosproject.net.NetTestTools.did; - -/** - * Distributed group store test. - */ -public class DistributedGroupStoreTest { - - DeviceId deviceId1 = did("dev1"); - DeviceId deviceId2 = did("dev2"); - GroupId groupId1 = new DefaultGroupId(1); - GroupId groupId2 = new DefaultGroupId(2); - GroupKey groupKey1 = new DefaultGroupKey("abc".getBytes()); - GroupKey groupKey2 = new DefaultGroupKey("def".getBytes()); - - TrafficTreatment treatment = - DefaultTrafficTreatment.emptyTreatment(); - GroupBucket selectGroupBucket = - DefaultGroupBucket.createSelectGroupBucket(treatment); - GroupBucket failoverGroupBucket = - DefaultGroupBucket.createFailoverGroupBucket(treatment, - PortNumber.IN_PORT, groupId1); - - GroupBuckets buckets = new GroupBuckets(ImmutableList.of(selectGroupBucket)); - GroupDescription groupDescription1 = new DefaultGroupDescription( - deviceId1, - GroupDescription.Type.INDIRECT, - buckets, - groupKey1, - groupId1.id(), - APP_ID); - GroupDescription groupDescription2 = new DefaultGroupDescription( - deviceId2, - GroupDescription.Type.INDIRECT, - buckets, - groupKey2, - groupId2.id(), - APP_ID); - - DistributedGroupStore groupStoreImpl; - GroupStore groupStore; - EventuallyConsistentMap auditPendingReqQueue; - - static class MasterOfAll extends MastershipServiceAdapter { - @Override - public MastershipRole getLocalRole(DeviceId deviceId) { - return MastershipRole.MASTER; - } - } - - @Before - public void setUp() throws Exception { - groupStoreImpl = new DistributedGroupStore(); - groupStoreImpl.storageService = new TestStorageService(); - groupStoreImpl.clusterCommunicator = new ClusterCommunicationServiceAdapter(); - groupStoreImpl.mastershipService = new MasterOfAll(); - groupStoreImpl.activate(); - groupStore = groupStoreImpl; - auditPendingReqQueue = - TestUtils.getField(groupStoreImpl, "auditPendingReqQueue"); - } - - @After - public void tearDown() throws Exception { - groupStoreImpl.deactivate(); - } - - /** - * Tests the initial state of the store. - */ - @Test - public void testEmptyStore() { - assertThat(groupStore.getGroupCount(deviceId1), is(0)); - assertThat(groupStore.getGroup(deviceId1, groupId1), nullValue()); - assertThat(groupStore.getGroup(deviceId1, groupKey1), nullValue()); - } - - /** - * Tests adding a pending group. - */ - @Test - public void testAddPendingGroup() throws Exception { - // Make sure the pending list starts out empty - assertThat(auditPendingReqQueue.size(), is(0)); - - // Add a new pending group. Make sure that the store remains empty - groupStore.storeGroupDescription(groupDescription1); - assertThat(groupStore.getGroupCount(deviceId1), is(0)); - assertThat(groupStore.getGroup(deviceId1, groupId1), nullValue()); - assertThat(groupStore.getGroup(deviceId1, groupKey1), nullValue()); - - // Make sure the group is pending - assertThat(auditPendingReqQueue.size(), is(1)); - - groupStore.deviceInitialAuditCompleted(deviceId1, true); - - // Make sure the group isn't pending anymore - assertThat(auditPendingReqQueue.size(), is(0)); - } - - - /** - * Tests adding and removing a group. - */ - @Test - public void testAddRemoveGroup() throws Exception { - groupStore.deviceInitialAuditCompleted(deviceId1, true); - assertThat(groupStore.deviceInitialAuditStatus(deviceId1), is(true)); - - // Make sure the pending list starts out empty - assertThat(auditPendingReqQueue.size(), is(0)); - - groupStore.storeGroupDescription(groupDescription1); - assertThat(groupStore.getGroupCount(deviceId1), is(1)); - assertThat(groupStore.getGroup(deviceId1, groupId1), notNullValue()); - assertThat(groupStore.getGroup(deviceId1, groupKey1), notNullValue()); - - // Make sure that nothing is pending - assertThat(auditPendingReqQueue.size(), is(0)); - - Group groupById = groupStore.getGroup(deviceId1, groupId1); - Group groupByKey = groupStore.getGroup(deviceId1, groupKey1); - assertThat(groupById, notNullValue()); - assertThat(groupByKey, notNullValue()); - assertThat(groupById, is(groupByKey)); - assertThat(groupById.deviceId(), is(did("dev1"))); - - groupStore.removeGroupEntry(groupById); - - assertThat(groupStore.getGroupCount(deviceId1), is(0)); - assertThat(groupStore.getGroup(deviceId1, groupId1), nullValue()); - assertThat(groupStore.getGroup(deviceId1, groupKey1), nullValue()); - - // Make sure that nothing is pending - assertThat(auditPendingReqQueue.size(), is(0)); - } - - /** - * Tests adding and removing a group. - */ - @Test - public void testRemoveGroupDescription() throws Exception { - groupStore.deviceInitialAuditCompleted(deviceId1, true); - - groupStore.storeGroupDescription(groupDescription1); - - groupStore.deleteGroupDescription(deviceId1, groupKey1); - - // Group should still be there, marked for removal - assertThat(groupStore.getGroupCount(deviceId1), is(1)); - Group queriedGroup = groupStore.getGroup(deviceId1, groupId1); - assertThat(queriedGroup.state(), is(Group.GroupState.PENDING_DELETE)); - - } - - /** - * Tests pushing group metrics. - */ - @Test - public void testPushGroupMetrics() { - groupStore.deviceInitialAuditCompleted(deviceId1, true); - groupStore.deviceInitialAuditCompleted(deviceId2, true); - - GroupDescription groupDescription3 = new DefaultGroupDescription( - deviceId1, - GroupDescription.Type.SELECT, - buckets, - new DefaultGroupKey("aaa".getBytes()), - null, - APP_ID); - - groupStore.storeGroupDescription(groupDescription1); - groupStore.storeGroupDescription(groupDescription2); - groupStore.storeGroupDescription(groupDescription3); - Group group1 = groupStore.getGroup(deviceId1, groupId1); - - assertThat(group1, instanceOf(DefaultGroup.class)); - DefaultGroup defaultGroup1 = (DefaultGroup) group1; - defaultGroup1.setPackets(55L); - defaultGroup1.setBytes(66L); - groupStore.pushGroupMetrics(deviceId1, ImmutableList.of(group1)); - - // Make sure the group was updated. - - Group requeryGroup1 = groupStore.getGroup(deviceId1, groupId1); - assertThat(requeryGroup1.packets(), is(55L)); - assertThat(requeryGroup1.bytes(), is(66L)); - - } - - class TestDelegate implements GroupStoreDelegate { - private List<GroupEvent> eventsSeen = new LinkedList<>(); - @Override - public void notify(GroupEvent event) { - eventsSeen.add(event); - } - - public List<GroupEvent> eventsSeen() { - return eventsSeen; - } - - public void resetEvents() { - eventsSeen.clear(); - } - } - - /** - * Tests group operation failed interface. - */ - @Test - public void testGroupOperationFailed() { - TestDelegate delegate = new TestDelegate(); - groupStore.setDelegate(delegate); - groupStore.deviceInitialAuditCompleted(deviceId1, true); - groupStore.deviceInitialAuditCompleted(deviceId2, true); - - groupStore.storeGroupDescription(groupDescription1); - groupStore.storeGroupDescription(groupDescription2); - - List<GroupEvent> eventsAfterAdds = delegate.eventsSeen(); - assertThat(eventsAfterAdds, hasSize(2)); - eventsAfterAdds.stream().forEach(event -> assertThat(event.type(), is(GroupEvent.Type.GROUP_ADD_REQUESTED))); - delegate.resetEvents(); - - GroupOperation opAdd = - GroupOperation.createAddGroupOperation(groupId1, - GroupDescription.Type.INDIRECT, - buckets); - groupStore.groupOperationFailed(deviceId1, opAdd); - - List<GroupEvent> eventsAfterAddFailed = delegate.eventsSeen(); - assertThat(eventsAfterAddFailed, hasSize(2)); - assertThat(eventsAfterAddFailed.get(0).type(), - is(GroupEvent.Type.GROUP_ADD_FAILED)); - assertThat(eventsAfterAddFailed.get(1).type(), - is(GroupEvent.Type.GROUP_REMOVED)); - delegate.resetEvents(); - - GroupOperation opModify = - GroupOperation.createModifyGroupOperation(groupId2, - GroupDescription.Type.INDIRECT, - buckets); - groupStore.groupOperationFailed(deviceId2, opModify); - List<GroupEvent> eventsAfterModifyFailed = delegate.eventsSeen(); - assertThat(eventsAfterModifyFailed, hasSize(1)); - assertThat(eventsAfterModifyFailed.get(0).type(), - is(GroupEvent.Type.GROUP_UPDATE_FAILED)); - delegate.resetEvents(); - - GroupOperation opDelete = - GroupOperation.createDeleteGroupOperation(groupId2, - GroupDescription.Type.INDIRECT); - groupStore.groupOperationFailed(deviceId2, opDelete); - List<GroupEvent> eventsAfterDeleteFailed = delegate.eventsSeen(); - assertThat(eventsAfterDeleteFailed, hasSize(1)); - assertThat(eventsAfterDeleteFailed.get(0).type(), - is(GroupEvent.Type.GROUP_REMOVE_FAILED)); - delegate.resetEvents(); - } - - /** - * Tests extraneous group operations. - */ - @Test - public void testExtraneousOperations() { - ArrayList<Group> extraneous; - groupStore.deviceInitialAuditCompleted(deviceId1, true); - - groupStore.storeGroupDescription(groupDescription1); - Group group1 = groupStore.getGroup(deviceId1, groupId1); - - extraneous = Lists.newArrayList(groupStore.getExtraneousGroups(deviceId1)); - assertThat(extraneous, hasSize(0)); - - groupStore.addOrUpdateExtraneousGroupEntry(group1); - extraneous = Lists.newArrayList(groupStore.getExtraneousGroups(deviceId1)); - assertThat(extraneous, hasSize(1)); - - groupStore.removeExtraneousGroupEntry(group1); - extraneous = Lists.newArrayList(groupStore.getExtraneousGroups(deviceId1)); - assertThat(extraneous, hasSize(0)); - } - - /** - * Tests updating of group descriptions. - */ - @Test - public void testUpdateGroupDescription() { - - GroupBuckets buckets = - new GroupBuckets(ImmutableList.of(failoverGroupBucket)); - - groupStore.deviceInitialAuditCompleted(deviceId1, true); - groupStore.storeGroupDescription(groupDescription1); - - GroupKey newKey = new DefaultGroupKey("123".getBytes()); - groupStore.updateGroupDescription(deviceId1, - groupKey1, - GroupStore.UpdateType.ADD, - buckets, - newKey); - Group group1 = groupStore.getGroup(deviceId1, groupId1); - assertThat(group1.appCookie(), is(newKey)); - assertThat(group1.buckets().buckets(), hasSize(2)); - } - - @Test - public void testEqualsGroupStoreIdMapKey() { - DistributedGroupStore.GroupStoreIdMapKey key1 = - new DistributedGroupStore.GroupStoreIdMapKey(deviceId1, groupId1); - DistributedGroupStore.GroupStoreIdMapKey sameAsKey1 = - new DistributedGroupStore.GroupStoreIdMapKey(deviceId1, groupId1); - DistributedGroupStore.GroupStoreIdMapKey key2 = - new DistributedGroupStore.GroupStoreIdMapKey(deviceId2, groupId1); - DistributedGroupStore.GroupStoreIdMapKey key3 = - new DistributedGroupStore.GroupStoreIdMapKey(deviceId1, groupId2); - - new EqualsTester() - .addEqualityGroup(key1, sameAsKey1) - .addEqualityGroup(key2) - .addEqualityGroup(key3) - .testEquals(); - } - - @Test - public void testEqualsGroupStoreKeyMapKey() { - DistributedGroupStore.GroupStoreKeyMapKey key1 = - new DistributedGroupStore.GroupStoreKeyMapKey(deviceId1, groupKey1); - DistributedGroupStore.GroupStoreKeyMapKey sameAsKey1 = - new DistributedGroupStore.GroupStoreKeyMapKey(deviceId1, groupKey1); - DistributedGroupStore.GroupStoreKeyMapKey key2 = - new DistributedGroupStore.GroupStoreKeyMapKey(deviceId2, groupKey1); - DistributedGroupStore.GroupStoreKeyMapKey key3 = - new DistributedGroupStore.GroupStoreKeyMapKey(deviceId1, groupKey2); - - new EqualsTester() - .addEqualityGroup(key1, sameAsKey1) - .addEqualityGroup(key2) - .addEqualityGroup(key3) - .testEquals(); - } - - @Test - public void testEqualsGroupStoreMapKey() { - DistributedGroupStore.GroupStoreMapKey key1 = - new DistributedGroupStore.GroupStoreMapKey(deviceId1); - DistributedGroupStore.GroupStoreMapKey sameAsKey1 = - new DistributedGroupStore.GroupStoreMapKey(deviceId1); - DistributedGroupStore.GroupStoreMapKey key2 = - new DistributedGroupStore.GroupStoreMapKey(deviceId2); - DistributedGroupStore.GroupStoreMapKey key3 = - new DistributedGroupStore.GroupStoreMapKey(did("dev3")); - - new EqualsTester() - .addEqualityGroup(key1, sameAsKey1) - .addEqualityGroup(key2) - .addEqualityGroup(key3) - .testEquals(); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/host/impl/DistributedHostStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/host/impl/DistributedHostStoreTest.java deleted file mode 100644 index 0732126d..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/host/impl/DistributedHostStoreTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.host.impl; - -import junit.framework.TestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onlab.packet.IpAddress; -import org.onlab.packet.MacAddress; -import org.onosproject.net.Host; -import org.onosproject.net.HostId; -import org.onosproject.net.HostLocation; -import org.onosproject.net.host.DefaultHostDescription; -import org.onosproject.net.host.HostDescription; -import org.onosproject.net.provider.ProviderId; -import org.onosproject.store.service.TestStorageService; - -import java.util.HashSet; -import java.util.Set; - -/** - * Tests for the ECHostStore. - */ -public class DistributedHostStoreTest extends TestCase { - - private DistributedHostStore ecXHostStore; - - private static final HostId HOSTID = HostId.hostId(MacAddress.valueOf("1a:1a:1a:1a:1a:1a")); - - private static final IpAddress IP1 = IpAddress.valueOf("10.2.0.2"); - private static final IpAddress IP2 = IpAddress.valueOf("10.2.0.3"); - - private static final ProviderId PID = new ProviderId("of", "foo"); - - @Before - public void setUp() { - ecXHostStore = new DistributedHostStore(); - - ecXHostStore.storageService = new TestStorageService(); - ecXHostStore.activate(); - } - - @After - public void tearDown() { - ecXHostStore.deactivate(); - } - - /** - * Tests the removeIp method call. - */ - @Test - public void testRemoveIp() { - Set<IpAddress> ips = new HashSet<>(); - ips.add(IP1); - ips.add(IP2); - - HostDescription description = new DefaultHostDescription(HOSTID.mac(), - HOSTID.vlanId(), - HostLocation.NONE, - ips); - ecXHostStore.createOrUpdateHost(PID, HOSTID, description, false); - ecXHostStore.removeIp(HOSTID, IP1); - Host host = ecXHostStore.getHost(HOSTID); - - assertFalse(host.ipAddresses().contains(IP1)); - assertTrue(host.ipAddresses().contains(IP2)); - } - -}
\ No newline at end of file diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/MastershipBasedTimestampTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/MastershipBasedTimestampTest.java deleted file mode 100644 index eb9d324e..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/MastershipBasedTimestampTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.impl; - -import static org.junit.Assert.*; - -import java.nio.ByteBuffer; - -import org.junit.Test; -import org.onosproject.store.Timestamp; -import org.onosproject.store.serializers.custom.MastershipBasedTimestampSerializer; -import org.onlab.util.KryoNamespace; - -import com.google.common.testing.EqualsTester; - -/** - * Test of {@link MastershipBasedTimestamp}. - */ -public class MastershipBasedTimestampTest { - - private static final Timestamp TS_1_1 = new MastershipBasedTimestamp(1, 1); - private static final Timestamp TS_1_2 = new MastershipBasedTimestamp(1, 2); - private static final Timestamp TS_2_1 = new MastershipBasedTimestamp(2, 1); - private static final Timestamp TS_2_2 = new MastershipBasedTimestamp(2, 2); - - @Test - public final void testBasic() { - final int termNumber = 5; - final int sequenceNumber = 6; - MastershipBasedTimestamp ts = new MastershipBasedTimestamp(termNumber, - sequenceNumber); - - assertEquals(termNumber, ts.termNumber()); - assertEquals(sequenceNumber, ts.sequenceNumber()); - } - - @Test - public final void testCompareTo() { - assertTrue(TS_1_1.compareTo(TS_1_1) == 0); - assertTrue(TS_1_1.compareTo(new MastershipBasedTimestamp(1, 1)) == 0); - - assertTrue(TS_1_1.compareTo(TS_1_2) < 0); - assertTrue(TS_1_2.compareTo(TS_1_1) > 0); - - assertTrue(TS_1_2.compareTo(TS_2_1) < 0); - assertTrue(TS_1_2.compareTo(TS_2_2) < 0); - assertTrue(TS_2_1.compareTo(TS_1_1) > 0); - assertTrue(TS_2_2.compareTo(TS_1_1) > 0); - } - - @Test - public final void testEqualsObject() { - new EqualsTester() - .addEqualityGroup(new MastershipBasedTimestamp(1, 1), - new MastershipBasedTimestamp(1, 1), TS_1_1) - .addEqualityGroup(new MastershipBasedTimestamp(1, 2), - new MastershipBasedTimestamp(1, 2), TS_1_2) - .addEqualityGroup(new MastershipBasedTimestamp(2, 1), - new MastershipBasedTimestamp(2, 1), TS_2_1) - .addEqualityGroup(new MastershipBasedTimestamp(2, 2), - new MastershipBasedTimestamp(2, 2), TS_2_2) - .testEquals(); - } - - @Test - public final void testKryoSerializable() { - final ByteBuffer buffer = ByteBuffer.allocate(1 * 1024 * 1024); - final KryoNamespace kryos = KryoNamespace.newBuilder() - .register(MastershipBasedTimestamp.class) - .build(); - - kryos.serialize(TS_2_1, buffer); - buffer.flip(); - Timestamp copy = kryos.deserialize(buffer); - - new EqualsTester() - .addEqualityGroup(TS_2_1, copy) - .testEquals(); - } - - @Test - public final void testKryoSerializableWithHandcraftedSerializer() { - final ByteBuffer buffer = ByteBuffer.allocate(1 * 1024 * 1024); - final KryoNamespace kryos = KryoNamespace.newBuilder() - .register(new MastershipBasedTimestampSerializer(), MastershipBasedTimestamp.class) - .build(); - - kryos.serialize(TS_1_2, buffer); - buffer.flip(); - Timestamp copy = kryos.deserialize(buffer); - - new EqualsTester() - .addEqualityGroup(TS_1_2, copy) - .testEquals(); - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/TimestampedTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/TimestampedTest.java deleted file mode 100644 index c47eb27a..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/impl/TimestampedTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.impl; - -import static org.junit.Assert.*; - -import java.nio.ByteBuffer; - -import org.junit.Test; -import org.onosproject.store.Timestamp; -import org.onlab.util.KryoNamespace; - -import com.google.common.testing.EqualsTester; - -/** - * Test of {@link Timestamped}. - */ -public class TimestampedTest { - - private static final Timestamp TS_1_1 = new MastershipBasedTimestamp(1, 1); - private static final Timestamp TS_1_2 = new MastershipBasedTimestamp(1, 2); - private static final Timestamp TS_2_1 = new MastershipBasedTimestamp(2, 1); - - @Test - public final void testHashCode() { - Timestamped<String> a = new Timestamped<>("a", TS_1_1); - Timestamped<String> b = new Timestamped<>("b", TS_1_1); - assertTrue("value does not impact hashCode", - a.hashCode() == b.hashCode()); - } - - @Test - public final void testEquals() { - Timestamped<String> a = new Timestamped<>("a", TS_1_1); - Timestamped<String> b = new Timestamped<>("b", TS_1_1); - assertTrue("value does not impact equality", - a.equals(b)); - - new EqualsTester() - .addEqualityGroup(new Timestamped<>("a", TS_1_1), - new Timestamped<>("b", TS_1_1), - new Timestamped<>("c", TS_1_1)) - .addEqualityGroup(new Timestamped<>("a", TS_1_2), - new Timestamped<>("b", TS_1_2), - new Timestamped<>("c", TS_1_2)) - .addEqualityGroup(new Timestamped<>("a", TS_2_1), - new Timestamped<>("b", TS_2_1), - new Timestamped<>("c", TS_2_1)) - .testEquals(); - - } - - @Test - public final void testValue() { - final Integer n = 42; - Timestamped<Integer> tsv = new Timestamped<>(n, TS_1_1); - assertSame(n, tsv.value()); - - } - - @Test(expected = NullPointerException.class) - public final void testValueNonNull() { - new Timestamped<>(null, TS_1_1); - } - - @Test(expected = NullPointerException.class) - public final void testTimestampNonNull() { - new Timestamped<>("Foo", null); - } - - @Test - public final void testIsNewer() { - Timestamped<String> a = new Timestamped<>("a", TS_1_2); - Timestamped<String> b = new Timestamped<>("b", TS_1_1); - assertTrue(a.isNewer(b)); - assertFalse(b.isNewer(a)); - } - - @Test - public final void testKryoSerializable() { - final ByteBuffer buffer = ByteBuffer.allocate(1 * 1024 * 1024); - final KryoNamespace kryos = KryoNamespace.newBuilder() - .register(Timestamped.class, - MastershipBasedTimestamp.class) - .build(); - - Timestamped<String> original = new Timestamped<>("foobar", TS_1_1); - kryos.serialize(original, buffer); - buffer.flip(); - Timestamped<String> copy = kryos.deserialize(buffer); - - new EqualsTester() - .addEqualityGroup(original, copy) - .testEquals(); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/GossipIntentStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/GossipIntentStoreTest.java deleted file mode 100644 index a74c3a2f..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/GossipIntentStoreTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.intent.impl; - -import java.util.LinkedList; -import java.util.List; -import java.util.stream.IntStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onosproject.cluster.ClusterServiceAdapter; -import org.onosproject.core.IdGenerator; -import org.onosproject.net.intent.HostToHostIntent; -import org.onosproject.net.intent.Intent; -import org.onosproject.net.intent.IntentData; -import org.onosproject.net.intent.IntentState; -import org.onosproject.net.intent.IntentTestsMocks; -import org.onosproject.net.intent.MockIdGenerator; -import org.onosproject.net.intent.PartitionServiceAdapter; -import org.onosproject.store.service.TestStorageService; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.onosproject.net.NetTestTools.APP_ID; -import static org.onosproject.net.NetTestTools.hid; - -/** - * Gossip Intent Store test using database adapter. - */ -public class GossipIntentStoreTest { - - private GossipIntentStore intentStore; - private IdGenerator idGenerator; - private HostToHostIntent.Builder builder1; - - @Before - public void setUp() { - intentStore = new GossipIntentStore(); - intentStore.storageService = new TestStorageService(); - intentStore.partitionService = new PartitionServiceAdapter(); - intentStore.clusterService = new ClusterServiceAdapter(); - idGenerator = new MockIdGenerator(); - Intent.bindIdGenerator(idGenerator); - builder1 = HostToHostIntent - .builder() - .one(hid("12:34:56:78:91:ab/1")) - .two(hid("12:34:56:78:91:ac/1")) - .appId(APP_ID); - intentStore.activate(); - } - - @After - public void cleanUp() { - intentStore.deactivate(); - Intent.unbindIdGenerator(idGenerator); - } - - /** - * Generates a list of test intent data. - * - * @param count how many intent data objects are needed - * @return list of intent data - */ - private List<IntentData> generateIntentList(int count) { - LinkedList<IntentData> intents = new LinkedList<>(); - IntStream.rangeClosed(1, count) - .forEach(i -> - intents.add( - new IntentData( - builder1 - .priority(i) - .build(), - IntentState.INSTALLED, - new IntentTestsMocks.MockTimestamp(12)))); - return intents; - } - - /** - * Tests the intent count APIs. - */ - @Test - public void testGetIntentCount() { - assertThat(intentStore.getIntentCount(), is(0L)); - - generateIntentList(5).forEach(intentStore::write); - - assertThat(intentStore.getIntentCount(), is(5L)); - } - - /** - * Tests the batch add API. - */ - @Test - public void testBatchAdd() { - assertThat(intentStore.getIntentCount(), is(0L)); - - List<IntentData> intents = generateIntentList(5); - - intentStore.batchWrite(intents); - assertThat(intentStore.getIntentCount(), is(5L)); - } - - - /** - * Tests adding and withdrawing an Intent. - */ - @Test - public void testAddAndWithdrawIntent() { - // build and install one intent - Intent intent = builder1.build(); - IntentData installed = new IntentData( - intent, - IntentState.INSTALLED, - new IntentTestsMocks.MockTimestamp(12)); - intentStore.write(installed); - - // check that the intent count includes the new one - assertThat(intentStore.getIntentCount(), is(1L)); - - // check that the getIntents() API returns the new intent - intentStore.getIntents() - .forEach(item -> assertThat(item, is(intent))); - - // check that the getInstallableIntents() API returns the new intent - intentStore.getInstallableIntents(intent.key()) - .forEach(item -> assertThat(item, is(intent))); - - // check that the getIntent() API can find the new intent - Intent queried = intentStore.getIntent(intent.key()); - assertThat(queried, is(intent)); - - // check that the state of the new intent is correct - IntentState state = intentStore.getIntentState(intent.key()); - assertThat(state, is(IntentState.INSTALLED)); - - // check that the getIntentData() API returns the proper value for the - // new intent - IntentData dataByQuery = intentStore.getIntentData(intent.key()); - assertThat(dataByQuery, is(installed)); - - // check that the getIntentData() API returns the new intent when given - // a time stamp to look for - Iterable<IntentData> dataIteratorByTime = intentStore.getIntentData(true, 10L); - assertThat(dataIteratorByTime.iterator().hasNext(), is(true)); - dataIteratorByTime.forEach( - data -> assertThat(data, is(installed)) - ); - - // check that the getIntentData() API returns the new intent when asked to - // find all intents - Iterable<IntentData> dataIteratorAll = intentStore.getIntentData(false, 0L); - assertThat(dataIteratorAll.iterator().hasNext(), is(true)); - dataIteratorAll.forEach( - data -> assertThat(data, is(installed)) - ); - - // now purge the intent that was created - IntentData purge = new IntentData( - intent, - IntentState.PURGE_REQ, - new IntentTestsMocks.MockTimestamp(12)); - intentStore.write(purge); - - // check that no intents are left - assertThat(intentStore.getIntentCount(), is(0L)); - - // check that a getIntent() operation on the key of the purged intent - // returns null - Intent queriedAfterWithdrawal = intentStore.getIntent(intent.key()); - assertThat(queriedAfterWithdrawal, nullValue()); - } - - /** - * Tests the operation of the APIs for the pending map. - */ - @Test - public void testPending() { - // crete a new intent and add it as pending - Intent intent = builder1.build(); - IntentData installed = new IntentData( - intent, - IntentState.INSTALLED, - new IntentTestsMocks.MockTimestamp(11)); - intentStore.addPending(installed); - - // check that the getPending() API returns the new pending intent - Iterable<Intent> pendingIntentIteratorAll = intentStore.getPending(); - assertThat(pendingIntentIteratorAll.iterator().hasNext(), is(true)); - pendingIntentIteratorAll.forEach( - data -> assertThat(data, is(intent)) - ); - - // check that the getPendingData() API returns the IntentData for the - // new pending intent - Iterable<IntentData> pendingDataIteratorAll = intentStore.getPendingData(); - assertThat(pendingDataIteratorAll.iterator().hasNext(), is(true)); - pendingDataIteratorAll.forEach( - data -> assertThat(data, is(installed)) - ); - - // check that the new pending intent is returned by the getPendingData() - // API when a time stamp is provided - Iterable<IntentData> pendingDataIteratorSelected = - intentStore.getPendingData(true, 10L); - assertThat(pendingDataIteratorSelected.iterator().hasNext(), is(true)); - pendingDataIteratorSelected.forEach( - data -> assertThat(data, is(installed)) - ); - - // check that the new pending intent is returned by the getPendingData() - // API when a time stamp is provided - Iterable<IntentData> pendingDataIteratorAllFromTimestamp = - intentStore.getPendingData(false, 0L); - assertThat(pendingDataIteratorAllFromTimestamp.iterator().hasNext(), is(true)); - pendingDataIteratorSelected.forEach( - data -> assertThat(data, is(installed)) - ); - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/PartitionManagerTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/PartitionManagerTest.java deleted file mode 100644 index 61d1937e..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/intent/impl/PartitionManagerTest.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright 2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.intent.impl; - -import org.junit.Before; -import org.junit.Test; -import org.onlab.junit.NullScheduledExecutor; -import org.onlab.packet.IpAddress; -import org.onosproject.cluster.ClusterServiceAdapter; -import org.onosproject.cluster.ControllerNode; -import org.onosproject.cluster.DefaultControllerNode; -import org.onosproject.cluster.Leadership; -import org.onosproject.cluster.LeadershipEvent; -import org.onosproject.cluster.LeadershipEventListener; -import org.onosproject.cluster.LeadershipService; -import org.onosproject.cluster.LeadershipServiceAdapter; -import org.onosproject.cluster.NodeId; -import org.onosproject.common.event.impl.TestEventDispatcher; -import org.onosproject.net.intent.Key; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.CompletableFuture; - -import static junit.framework.TestCase.assertFalse; -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.anyString; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertTrue; - -/** - * Unit tests for the PartitionManager class. - */ -public class PartitionManagerTest { - - private final LeadershipEvent event - = new LeadershipEvent(LeadershipEvent.Type.LEADER_ELECTED, - new Leadership(ELECTION_PREFIX + "0", - MY_NODE_ID, 0, 0)); - - private static final NodeId MY_NODE_ID = new NodeId("local"); - private static final NodeId OTHER_NODE_ID = new NodeId("other"); - private static final NodeId INACTIVE_NODE_ID = new NodeId("inactive"); - - private static final String ELECTION_PREFIX = "intent-partition-"; - - private LeadershipService leadershipService; - private LeadershipEventListener leaderListener; - - private PartitionManager partitionManager; - - @Before - public void setUp() { - leadershipService = createMock(LeadershipService.class); - - leadershipService.addListener(anyObject(LeadershipEventListener.class)); - expectLastCall().andDelegateTo(new TestLeadershipService()); - for (int i = 0; i < PartitionManager.NUM_PARTITIONS; i++) { - expect(leadershipService.runForLeadership(ELECTION_PREFIX + i)) - .andReturn(CompletableFuture.completedFuture(null)) - .times(1); - } - - partitionManager = new PartitionManager() - .withScheduledExecutor(new NullScheduledExecutor()); - - partitionManager.clusterService = new TestClusterService(); - partitionManager.leadershipService = leadershipService; - partitionManager.eventDispatcher = new TestEventDispatcher(); - } - - /** - * Configures a mock leadership service to have the specified number of - * partitions owned by the local node and all other partitions owned by a - * (fake) remote node. - * - * @param numMine number of partitions that should be owned by the local node - */ - private void setUpLeadershipService(int numMine) { - - Map<String, Leadership> leaderBoard = new HashMap<>(); - - for (int i = 0; i < numMine; i++) { - expect(leadershipService.getLeader(ELECTION_PREFIX + i)) - .andReturn(MY_NODE_ID).anyTimes(); - leaderBoard.put(ELECTION_PREFIX + i, - new Leadership(ELECTION_PREFIX + i, MY_NODE_ID, 0, 0)); - } - - for (int i = numMine; i < PartitionManager.NUM_PARTITIONS; i++) { - expect(leadershipService.getLeader(ELECTION_PREFIX + i)) - .andReturn(OTHER_NODE_ID).anyTimes(); - - leaderBoard.put(ELECTION_PREFIX + i, - new Leadership(ELECTION_PREFIX + i, OTHER_NODE_ID, 0, 0)); - } - - expect(leadershipService.getLeaderBoard()).andReturn(leaderBoard).anyTimes(); - } - - /** - * Tests that the PartitionManager's activate method correctly runs for - * all the leader elections that it should. - */ - @Test - public void testActivate() { - reset(leadershipService); - - leadershipService.addListener(anyObject(LeadershipEventListener.class)); - - for (int i = 0; i < PartitionManager.NUM_PARTITIONS; i++) { - expect(leadershipService.runForLeadership(ELECTION_PREFIX + i)) - .andReturn(CompletableFuture.completedFuture(null)) - .times(1); - } - - replay(leadershipService); - - partitionManager.activate(); - - verify(leadershipService); - } - - /** - * Tests that the isMine method returns the correct result based on the - * underlying leadership service data. - */ - @Test - public void testIsMine() { - // We'll own only the first partition - setUpLeadershipService(1); - replay(leadershipService); - - Key myKey = new ControllableHashKey(0); - Key notMyKey = new ControllableHashKey(1); - - assertTrue(partitionManager.isMine(myKey)); - assertFalse(partitionManager.isMine(notMyKey)); - - // Make us the owner of 4 partitions now - reset(leadershipService); - setUpLeadershipService(4); - replay(leadershipService); - - assertTrue(partitionManager.isMine(myKey)); - // notMyKey is now my key because because we're in control of that - // partition now - assertTrue(partitionManager.isMine(notMyKey)); - - assertFalse(partitionManager.isMine(new ControllableHashKey(4))); - } - - /** - * Tests sending in LeadershipServiceEvents in the case when we have - * too many partitions. The event will trigger the partition manager to - * schedule a rebalancing activity. - */ - @Test - public void testRebalanceScheduling() { - // We have all the partitions so we'll need to relinquish some - setUpLeadershipService(PartitionManager.NUM_PARTITIONS); - - replay(leadershipService); - - partitionManager.activate(); - // Send in the event - leaderListener.event(event); - - assertTrue(partitionManager.rebalanceScheduled.get()); - - verify(leadershipService); - } - - /** - * Tests rebalance will trigger the right now of leadership withdraw calls. - */ - @Test - public void testRebalance() { - // We have all the partitions so we'll need to relinquish some - setUpLeadershipService(PartitionManager.NUM_PARTITIONS); - - expect(leadershipService.withdraw(anyString())) - .andReturn(CompletableFuture.completedFuture(null)) - .times(7); - - replay(leadershipService); - - partitionManager.activate(); - - // trigger rebalance - partitionManager.doRebalance(); - - verify(leadershipService); - } - - /** - * Tests that attempts to rebalance when the paritions are already - * evenly distributed does not result in any relinquish attempts. - */ - @Test - public void testNoRebalance() { - // Partitions are already perfectly balanced among the two active instances - setUpLeadershipService(PartitionManager.NUM_PARTITIONS / 2); - replay(leadershipService); - - partitionManager.activate(); - - // trigger rebalance - partitionManager.doRebalance(); - - verify(leadershipService); - - reset(leadershipService); - // We have a smaller share than we should - setUpLeadershipService(PartitionManager.NUM_PARTITIONS / 2 - 1); - replay(leadershipService); - - // trigger rebalance - partitionManager.doRebalance(); - - verify(leadershipService); - } - - /** - * LeadershipService that allows us to grab a reference to - * PartitionManager's LeadershipEventListener. - */ - public class TestLeadershipService extends LeadershipServiceAdapter { - @Override - public void addListener(LeadershipEventListener listener) { - leaderListener = listener; - } - } - - /** - * ClusterService set up with a very simple cluster - 3 nodes, one is the - * current node, one is a different active node, and one is an inactive node. - */ - private class TestClusterService extends ClusterServiceAdapter { - - private final ControllerNode self = - new DefaultControllerNode(MY_NODE_ID, IpAddress.valueOf(1)); - private final ControllerNode otherNode = - new DefaultControllerNode(OTHER_NODE_ID, IpAddress.valueOf(2)); - private final ControllerNode inactiveNode = - new DefaultControllerNode(INACTIVE_NODE_ID, IpAddress.valueOf(3)); - - Set<ControllerNode> nodes; - - public TestClusterService() { - nodes = new HashSet<>(); - nodes.add(self); - nodes.add(otherNode); - nodes.add(inactiveNode); - } - - @Override - public ControllerNode getLocalNode() { - return self; - } - - @Override - public Set<ControllerNode> getNodes() { - return nodes; - } - - @Override - public ControllerNode getNode(NodeId nodeId) { - return nodes.stream() - .filter(c -> c.id().equals(nodeId)) - .findFirst() - .get(); - } - - @Override - public ControllerNode.State getState(NodeId nodeId) { - return nodeId.equals(INACTIVE_NODE_ID) ? ControllerNode.State.INACTIVE : - ControllerNode.State.ACTIVE; - } - } - - /** - * A key that always hashes to a value provided to the constructor. This - * allows us to control the hash of the key for unit tests. - */ - private class ControllableHashKey extends Key { - - protected ControllableHashKey(long hash) { - super(hash); - } - - @Override - public int hashCode() { - return Objects.hash(hash()); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ControllableHashKey)) { - return false; - } - - ControllableHashKey that = (ControllableHashKey) obj; - - return Objects.equals(this.hash(), that.hash()); - } - - @Override - public int compareTo(Key o) { - Long thisHash = hash(); - return thisHash.compareTo(o.hash()); - } - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/GossipLinkStoreTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/GossipLinkStoreTest.java deleted file mode 100644 index f8b5b860..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/GossipLinkStoreTest.java +++ /dev/null @@ -1,623 +0,0 @@ -/* - * Copyright 2014-2015 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.link.impl; - -import com.google.common.collect.Iterables; - -import org.easymock.Capture; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.onlab.packet.IpAddress; -import org.onosproject.cluster.ControllerNode; -import org.onosproject.cluster.DefaultControllerNode; -import org.onosproject.cluster.NodeId; -import org.onosproject.mastership.MastershipServiceAdapter; -import org.onosproject.net.ConnectPoint; -import org.onosproject.net.DefaultAnnotations; -import org.onosproject.net.DeviceId; -import org.onosproject.net.Link; -import org.onosproject.net.Link.Type; -import org.onosproject.net.LinkKey; -import org.onosproject.net.PortNumber; -import org.onosproject.net.SparseAnnotations; -import org.onosproject.net.device.DeviceClockService; -import org.onosproject.net.device.DeviceClockServiceAdapter; -import org.onosproject.net.link.DefaultLinkDescription; -import org.onosproject.net.link.LinkDescription; -import org.onosproject.net.link.LinkEvent; -import org.onosproject.net.link.LinkStore; -import org.onosproject.net.link.LinkStoreDelegate; -import org.onosproject.net.provider.ProviderId; -import org.onosproject.store.Timestamp; -import org.onosproject.store.cluster.StaticClusterService; -import org.onosproject.store.cluster.messaging.ClusterCommunicationService; -import org.onosproject.store.cluster.messaging.ClusterMessageHandler; -import org.onosproject.store.cluster.messaging.MessageSubject; -import org.onosproject.store.impl.MastershipBasedTimestamp; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Function; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; -import static org.onosproject.cluster.ControllerNode.State.ACTIVE; -import static org.onosproject.net.DeviceId.deviceId; -import static org.onosproject.net.Link.Type.DIRECT; -import static org.onosproject.net.Link.Type.EDGE; -import static org.onosproject.net.Link.Type.INDIRECT; -import static org.onosproject.net.NetTestTools.assertAnnotationsEquals; -import static org.onosproject.net.link.LinkEvent.Type.LINK_ADDED; -import static org.onosproject.net.link.LinkEvent.Type.LINK_REMOVED; -import static org.onosproject.net.link.LinkEvent.Type.LINK_UPDATED; - -/** - * Test of the GossipLinkStoreTest implementation. - */ -public class GossipLinkStoreTest { - - private static final ProviderId PID = new ProviderId("of", "foo"); - private static final ProviderId PIDA = new ProviderId("of", "bar", true); - private static final DeviceId DID1 = deviceId("of:foo"); - private static final DeviceId DID2 = deviceId("of:bar"); - - private static final PortNumber P1 = PortNumber.portNumber(1); - private static final PortNumber P2 = PortNumber.portNumber(2); - private static final PortNumber P3 = PortNumber.portNumber(3); - - private static final SparseAnnotations A1 = DefaultAnnotations.builder() - .set("A1", "a1") - .set("B1", "b1") - .build(); - private static final SparseAnnotations A1_2 = DefaultAnnotations.builder() - .remove("A1") - .set("B3", "b3") - .build(); - private static final SparseAnnotations A2 = DefaultAnnotations.builder() - .set("A2", "a2") - .set("B2", "b2") - .build(); - private static final SparseAnnotations A2_2 = DefaultAnnotations.builder() - .remove("A2") - .set("B4", "b4") - .build(); - - // local node - private static final NodeId NID1 = new NodeId("local"); - private static final ControllerNode ONOS1 = - new DefaultControllerNode(NID1, IpAddress.valueOf("127.0.0.1")); - - // remote node - private static final NodeId NID2 = new NodeId("remote"); - private static final ControllerNode ONOS2 = - new DefaultControllerNode(NID2, IpAddress.valueOf("127.0.0.2")); - - private GossipLinkStore linkStoreImpl; - private LinkStore linkStore; - - private final AtomicLong ticker = new AtomicLong(); - private DeviceClockService deviceClockService; - private ClusterCommunicationService clusterCommunicator; - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - // TODO mock clusterCommunicator - clusterCommunicator = createNiceMock(ClusterCommunicationService.class); - clusterCommunicator.addSubscriber(anyObject(MessageSubject.class), - anyObject(ClusterMessageHandler.class), - anyObject(ExecutorService.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - - linkStoreImpl = new GossipLinkStore(); - linkStoreImpl.deviceClockService = deviceClockService; - linkStoreImpl.clusterCommunicator = clusterCommunicator; - linkStoreImpl.clusterService = new TestClusterService(); - linkStoreImpl.deviceClockService = new TestDeviceClockService(); - linkStoreImpl.mastershipService = new TestMastershipService(); - linkStoreImpl.activate(); - linkStore = linkStoreImpl; - - verify(clusterCommunicator); - reset(clusterCommunicator); - - } - - @After - public void tearDown() throws Exception { - linkStoreImpl.deactivate(); - } - - private void putLink(DeviceId srcId, PortNumber srcNum, - DeviceId dstId, PortNumber dstNum, Type type, - SparseAnnotations... annotations) { - ConnectPoint src = new ConnectPoint(srcId, srcNum); - ConnectPoint dst = new ConnectPoint(dstId, dstNum); - reset(clusterCommunicator); - clusterCommunicator.<InternalLinkEvent>broadcast( - anyObject(InternalLinkEvent.class), anyObject(MessageSubject.class), anyObject(Function.class)); - expectLastCall().anyTimes(); - replay(clusterCommunicator); - linkStore.createOrUpdateLink(PID, new DefaultLinkDescription(src, dst, type, annotations)); - verify(clusterCommunicator); - } - - private <T> void resetCommunicatorExpectingSingleBroadcast( - Capture<T> message, - Capture<MessageSubject> subject, - Capture<Function<T, byte[]>> encoder) { - message.reset(); - subject.reset(); - encoder.reset(); - reset(clusterCommunicator); - clusterCommunicator.broadcast(capture(message), capture(subject), capture(encoder)); - expectLastCall().once(); - replay(clusterCommunicator); - } - - private void putLink(LinkKey key, Type type, SparseAnnotations... annotations) { - putLink(key.src().deviceId(), key.src().port(), - key.dst().deviceId(), key.dst().port(), - type, annotations); - } - - private static void assertLink(DeviceId srcId, PortNumber srcNum, - DeviceId dstId, PortNumber dstNum, Type type, - Link link) { - assertEquals(srcId, link.src().deviceId()); - assertEquals(srcNum, link.src().port()); - assertEquals(dstId, link.dst().deviceId()); - assertEquals(dstNum, link.dst().port()); - assertEquals(type, link.type()); - } - - private static void assertLink(LinkKey key, Type type, Link link) { - assertLink(key.src().deviceId(), key.src().port(), - key.dst().deviceId(), key.dst().port(), - type, link); - } - - @Test - public final void testGetLinkCount() { - assertEquals("initialy empty", 0, linkStore.getLinkCount()); - - putLink(DID1, P1, DID2, P2, DIRECT); - putLink(DID2, P2, DID1, P1, DIRECT); - putLink(DID1, P1, DID2, P2, DIRECT); - - assertEquals("expecting 2 unique link", 2, linkStore.getLinkCount()); - } - - @Test - public final void testGetLinks() { - assertEquals("initialy empty", 0, - Iterables.size(linkStore.getLinks())); - - LinkKey linkId1 = LinkKey.linkKey(new ConnectPoint(DID1, P1), new ConnectPoint(DID2, P2)); - LinkKey linkId2 = LinkKey.linkKey(new ConnectPoint(DID2, P2), new ConnectPoint(DID1, P1)); - - putLink(linkId1, DIRECT); - putLink(linkId2, DIRECT); - putLink(linkId1, DIRECT); - - assertEquals("expecting 2 unique link", 2, - Iterables.size(linkStore.getLinks())); - - Map<LinkKey, Link> links = new HashMap<>(); - for (Link link : linkStore.getLinks()) { - links.put(LinkKey.linkKey(link), link); - } - - assertLink(linkId1, DIRECT, links.get(linkId1)); - assertLink(linkId2, DIRECT, links.get(linkId2)); - } - - @Test - public final void testGetDeviceEgressLinks() { - LinkKey linkId1 = LinkKey.linkKey(new ConnectPoint(DID1, P1), new ConnectPoint(DID2, P2)); - LinkKey linkId2 = LinkKey.linkKey(new ConnectPoint(DID2, P2), new ConnectPoint(DID1, P1)); - LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1, P2), new ConnectPoint(DID2, P3)); - - putLink(linkId1, DIRECT); - putLink(linkId2, DIRECT); - putLink(linkId3, DIRECT); - - // DID1,P1 => DID2,P2 - // DID2,P2 => DID1,P1 - // DID1,P2 => DID2,P3 - - Set<Link> links1 = linkStore.getDeviceEgressLinks(DID1); - assertEquals(2, links1.size()); - // check - - Set<Link> links2 = linkStore.getDeviceEgressLinks(DID2); - assertEquals(1, links2.size()); - assertLink(linkId2, DIRECT, links2.iterator().next()); - } - - @Test - public final void testGetDeviceIngressLinks() { - LinkKey linkId1 = LinkKey.linkKey(new ConnectPoint(DID1, P1), new ConnectPoint(DID2, P2)); - LinkKey linkId2 = LinkKey.linkKey(new ConnectPoint(DID2, P2), new ConnectPoint(DID1, P1)); - LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1, P2), new ConnectPoint(DID2, P3)); - - putLink(linkId1, DIRECT); - putLink(linkId2, DIRECT); - putLink(linkId3, DIRECT); - - // DID1,P1 => DID2,P2 - // DID2,P2 => DID1,P1 - // DID1,P2 => DID2,P3 - - Set<Link> links1 = linkStore.getDeviceIngressLinks(DID2); - assertEquals(2, links1.size()); - // check - - Set<Link> links2 = linkStore.getDeviceIngressLinks(DID1); - assertEquals(1, links2.size()); - assertLink(linkId2, DIRECT, links2.iterator().next()); - } - - @Test - public final void testGetLink() { - ConnectPoint src = new ConnectPoint(DID1, P1); - ConnectPoint dst = new ConnectPoint(DID2, P2); - LinkKey linkId1 = LinkKey.linkKey(src, dst); - - putLink(linkId1, DIRECT); - - Link link = linkStore.getLink(src, dst); - assertLink(linkId1, DIRECT, link); - - assertNull("There shouldn't be reverese link", - linkStore.getLink(dst, src)); - } - - @Test - public final void testGetEgressLinks() { - final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); - final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); - LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); - LinkKey linkId2 = LinkKey.linkKey(d2P2, d1P1); - LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1, P2), new ConnectPoint(DID2, P3)); - - putLink(linkId1, DIRECT); - putLink(linkId2, DIRECT); - putLink(linkId3, DIRECT); - - // DID1,P1 => DID2,P2 - // DID2,P2 => DID1,P1 - // DID1,P2 => DID2,P3 - - Set<Link> links1 = linkStore.getEgressLinks(d1P1); - assertEquals(1, links1.size()); - assertLink(linkId1, DIRECT, links1.iterator().next()); - - Set<Link> links2 = linkStore.getEgressLinks(d2P2); - assertEquals(1, links2.size()); - assertLink(linkId2, DIRECT, links2.iterator().next()); - } - - @Test - public final void testGetIngressLinks() { - final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); - final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); - LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); - LinkKey linkId2 = LinkKey.linkKey(d2P2, d1P1); - LinkKey linkId3 = LinkKey.linkKey(new ConnectPoint(DID1, P2), new ConnectPoint(DID2, P3)); - - putLink(linkId1, DIRECT); - putLink(linkId2, DIRECT); - putLink(linkId3, DIRECT); - - // DID1,P1 => DID2,P2 - // DID2,P2 => DID1,P1 - // DID1,P2 => DID2,P3 - - Set<Link> links1 = linkStore.getIngressLinks(d2P2); - assertEquals(1, links1.size()); - assertLink(linkId1, DIRECT, links1.iterator().next()); - - Set<Link> links2 = linkStore.getIngressLinks(d1P1); - assertEquals(1, links2.size()); - assertLink(linkId2, DIRECT, links2.iterator().next()); - } - - @Test - public final void testCreateOrUpdateLink() { - ConnectPoint src = new ConnectPoint(DID1, P1); - ConnectPoint dst = new ConnectPoint(DID2, P2); - - Capture<InternalLinkEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalLinkEvent, byte[]>> encoder = new Capture<>(); - - // add link - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - final DefaultLinkDescription linkDescription = new DefaultLinkDescription(src, dst, INDIRECT); - LinkEvent event = linkStore.createOrUpdateLink(PID, - linkDescription); - verifyLinkBroadcastMessage(PID, NID1, src, dst, INDIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, INDIRECT, event.subject()); - assertEquals(LINK_ADDED, event.type()); - - // update link type - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event2 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, DIRECT)); - verifyLinkBroadcastMessage(PID, NID1, src, dst, DIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, DIRECT, event2.subject()); - assertEquals(LINK_UPDATED, event2.type()); - - // no change - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event3 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, DIRECT)); - verifyNoBroadcastMessage(message); - - assertNull("No change event expected", event3); - } - - private <T> void verifyNoBroadcastMessage(Capture<T> message) { - assertFalse("No broadcast expected", message.hasCaptured()); - } - - private void verifyLinkBroadcastMessage(ProviderId providerId, - NodeId sender, - ConnectPoint src, - ConnectPoint dst, - Type type, - Capture<InternalLinkEvent> actualLinkEvent, - Capture<MessageSubject> actualSubject, - Capture<Function<InternalLinkEvent, byte[]>> actualEncoder) { - verify(clusterCommunicator); - assertTrue(actualLinkEvent.hasCaptured()); - assertEquals(GossipLinkStoreMessageSubjects.LINK_UPDATE, actualSubject.getValue()); - assertEquals(providerId, actualLinkEvent.getValue().providerId()); - assertLinkDescriptionEquals(src, dst, type, actualLinkEvent.getValue().linkDescription().value()); - } - - private static void assertLinkDescriptionEquals(ConnectPoint src, - ConnectPoint dst, - Type type, - LinkDescription actual) { - assertEquals(src, actual.src()); - assertEquals(dst, actual.dst()); - assertEquals(type, actual.type()); - // TODO check annotations - } - - @Test - public final void testCreateOrUpdateLinkAncillary() { - ConnectPoint src = new ConnectPoint(DID1, P1); - ConnectPoint dst = new ConnectPoint(DID2, P2); - - Capture<InternalLinkEvent> message = new Capture<>(); - Capture<MessageSubject> subject = new Capture<>(); - Capture<Function<InternalLinkEvent, byte[]>> encoder = new Capture<>(); - - // add Ancillary link - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event = linkStore.createOrUpdateLink(PIDA, - new DefaultLinkDescription(src, dst, INDIRECT, A1)); - verifyLinkBroadcastMessage(PIDA, NID1, src, dst, INDIRECT, message, subject, encoder); - - assertNotNull("Ancillary only link is ignored", event); - - // add Primary link - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event2 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, INDIRECT, A2)); - verifyLinkBroadcastMessage(PID, NID1, src, dst, INDIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, INDIRECT, event2.subject()); - assertAnnotationsEquals(event2.subject().annotations(), A2, A1); - assertEquals(LINK_UPDATED, event2.type()); - - // update link type - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event3 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, DIRECT, A2)); - verifyLinkBroadcastMessage(PID, NID1, src, dst, DIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, DIRECT, event3.subject()); - assertAnnotationsEquals(event3.subject().annotations(), A2, A1); - assertEquals(LINK_UPDATED, event3.type()); - - - // no change - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event4 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, DIRECT)); - verifyNoBroadcastMessage(message); - - assertNull("No change event expected", event4); - - // update link annotation (Primary) - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event5 = linkStore.createOrUpdateLink(PID, - new DefaultLinkDescription(src, dst, DIRECT, A2_2)); - verifyLinkBroadcastMessage(PID, NID1, src, dst, DIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, DIRECT, event5.subject()); - assertAnnotationsEquals(event5.subject().annotations(), A2, A2_2, A1); - assertEquals(LINK_UPDATED, event5.type()); - - // update link annotation (Ancillary) - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event6 = linkStore.createOrUpdateLink(PIDA, - new DefaultLinkDescription(src, dst, DIRECT, A1_2)); - verifyLinkBroadcastMessage(PIDA, NID1, src, dst, DIRECT, message, subject, encoder); - - assertLink(DID1, P1, DID2, P2, DIRECT, event6.subject()); - assertAnnotationsEquals(event6.subject().annotations(), A2, A2_2, A1, A1_2); - assertEquals(LINK_UPDATED, event6.type()); - - // update link type (Ancillary) : ignored - resetCommunicatorExpectingSingleBroadcast(message, subject, encoder); - LinkEvent event7 = linkStore.createOrUpdateLink(PIDA, - new DefaultLinkDescription(src, dst, EDGE)); - verifyNoBroadcastMessage(message); - assertNull("Ancillary change other than annotation is ignored", event7); - } - - - @Test - public final void testRemoveLink() { - final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); - final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); - LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); - LinkKey linkId2 = LinkKey.linkKey(d2P2, d1P1); - - putLink(linkId1, DIRECT, A1); - putLink(linkId2, DIRECT, A2); - - // DID1,P1 => DID2,P2 - // DID2,P2 => DID1,P1 - // DID1,P2 => DID2,P3 - - LinkEvent event = linkStore.removeLink(d1P1, d2P2); - assertEquals(LINK_REMOVED, event.type()); - assertAnnotationsEquals(event.subject().annotations(), A1); - LinkEvent event2 = linkStore.removeLink(d1P1, d2P2); - assertNull(event2); - - assertLink(linkId2, DIRECT, linkStore.getLink(d2P2, d1P1)); - assertAnnotationsEquals(linkStore.getLink(d2P2, d1P1).annotations(), A2); - - // annotations, etc. should not survive remove - putLink(linkId1, DIRECT); - assertLink(linkId1, DIRECT, linkStore.getLink(d1P1, d2P2)); - assertAnnotationsEquals(linkStore.getLink(d1P1, d2P2).annotations()); - } - - @Test - public final void testAncillaryVisible() { - ConnectPoint src = new ConnectPoint(DID1, P1); - ConnectPoint dst = new ConnectPoint(DID2, P2); - - // add Ancillary link - linkStore.createOrUpdateLink(PIDA, - new DefaultLinkDescription(src, dst, INDIRECT, A1)); - - // Ancillary only link should not be visible - assertEquals(1, linkStore.getLinkCount()); - assertNotNull(linkStore.getLink(src, dst)); - } - - // If Delegates should be called only on remote events, - // then Simple* should never call them, thus not test required. - @Ignore("Ignore until Delegate spec. is clear.") - @Test - public final void testEvents() throws InterruptedException { - - final ConnectPoint d1P1 = new ConnectPoint(DID1, P1); - final ConnectPoint d2P2 = new ConnectPoint(DID2, P2); - final LinkKey linkId1 = LinkKey.linkKey(d1P1, d2P2); - - final CountDownLatch addLatch = new CountDownLatch(1); - LinkStoreDelegate checkAdd = event -> { - assertEquals(LINK_ADDED, event.type()); - assertLink(linkId1, INDIRECT, event.subject()); - addLatch.countDown(); - }; - final CountDownLatch updateLatch = new CountDownLatch(1); - LinkStoreDelegate checkUpdate = event -> { - assertEquals(LINK_UPDATED, event.type()); - assertLink(linkId1, DIRECT, event.subject()); - updateLatch.countDown(); - }; - final CountDownLatch removeLatch = new CountDownLatch(1); - LinkStoreDelegate checkRemove = event -> { - assertEquals(LINK_REMOVED, event.type()); - assertLink(linkId1, DIRECT, event.subject()); - removeLatch.countDown(); - }; - - linkStore.setDelegate(checkAdd); - putLink(linkId1, INDIRECT); - assertTrue("Add event fired", addLatch.await(1, TimeUnit.SECONDS)); - - linkStore.unsetDelegate(checkAdd); - linkStore.setDelegate(checkUpdate); - putLink(linkId1, DIRECT); - assertTrue("Update event fired", updateLatch.await(1, TimeUnit.SECONDS)); - - linkStore.unsetDelegate(checkUpdate); - linkStore.setDelegate(checkRemove); - linkStore.removeLink(d1P1, d2P2); - assertTrue("Remove event fired", removeLatch.await(1, TimeUnit.SECONDS)); - } - - private static final class TestClusterService extends StaticClusterService { - - public TestClusterService() { - localNode = ONOS1; - nodes.put(NID1, ONOS1); - nodeStates.put(NID1, ACTIVE); - - nodes.put(NID2, ONOS2); - nodeStates.put(NID2, ACTIVE); - } - } - - private final class TestDeviceClockService extends DeviceClockServiceAdapter { - - private final AtomicLong ticker = new AtomicLong(); - - @Override - public Timestamp getTimestamp(DeviceId deviceId) { - if (DID1.equals(deviceId)) { - return new MastershipBasedTimestamp(1, ticker.getAndIncrement()); - } else if (DID2.equals(deviceId)) { - return new MastershipBasedTimestamp(2, ticker.getAndIncrement()); - } else { - throw new IllegalStateException(); - } - } - - @Override - public boolean isTimestampAvailable(DeviceId deviceId) { - return DID1.equals(deviceId) || DID2.equals(deviceId); - } - } - - private final class TestMastershipService extends MastershipServiceAdapter { - @Override - public NodeId getMasterFor(DeviceId deviceId) { - return NID1; - } - } -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/LinkFragmentIdTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/LinkFragmentIdTest.java deleted file mode 100644 index a14b6e60..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/link/impl/LinkFragmentIdTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.link.impl; - -import static org.onosproject.net.DeviceId.deviceId; - -import org.junit.Test; -import org.onosproject.net.ConnectPoint; -import org.onosproject.net.DeviceId; -import org.onosproject.net.LinkKey; -import org.onosproject.net.PortNumber; -import org.onosproject.net.provider.ProviderId; -import com.google.common.testing.EqualsTester; - -public class LinkFragmentIdTest { - - private static final ProviderId PID = new ProviderId("of", "foo"); - private static final ProviderId PIDA = new ProviderId("of", "bar", true); - - private static final DeviceId DID1 = deviceId("of:foo"); - private static final DeviceId DID2 = deviceId("of:bar"); - - private static final PortNumber P1 = PortNumber.portNumber(1); - private static final PortNumber P2 = PortNumber.portNumber(2); - private static final PortNumber P3 = PortNumber.portNumber(3); - - private static final ConnectPoint CP1 = new ConnectPoint(DID1, P1); - private static final ConnectPoint CP2 = new ConnectPoint(DID2, P2); - - private static final ConnectPoint CP3 = new ConnectPoint(DID1, P2); - private static final ConnectPoint CP4 = new ConnectPoint(DID2, P3); - - private static final LinkKey L1 = LinkKey.linkKey(CP1, CP2); - private static final LinkKey L2 = LinkKey.linkKey(CP3, CP4); - - @Test - public void testEquals() { - new EqualsTester() - .addEqualityGroup(new LinkFragmentId(L1, PID), - new LinkFragmentId(L1, PID)) - .addEqualityGroup(new LinkFragmentId(L2, PID), - new LinkFragmentId(L2, PID)) - .addEqualityGroup(new LinkFragmentId(L1, PIDA), - new LinkFragmentId(L1, PIDA)) - .addEqualityGroup(new LinkFragmentId(L2, PIDA), - new LinkFragmentId(L2, PIDA)) - .testEquals(); - } - -} diff --git a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/mastership/impl/RoleValueTest.java b/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/mastership/impl/RoleValueTest.java deleted file mode 100644 index d3b5c764..00000000 --- a/framework/src/onos/core/store/dist/src/test/java/org/onosproject/store/mastership/impl/RoleValueTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2014 Open Networking Laboratory - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.onosproject.store.mastership.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.onosproject.net.MastershipRole.*; - -import org.junit.Test; -import org.onosproject.cluster.NodeId; - -import com.google.common.collect.Sets; - -public class RoleValueTest { - - private static final RoleValue RV = new RoleValue(); - - private static final NodeId NID1 = new NodeId("node1"); - private static final NodeId NID2 = new NodeId("node2"); - private static final NodeId NID3 = new NodeId("node3"); - - @Test - public void add() { - assertEquals("faulty initialization: ", 3, RV.value.size()); - RV.add(MASTER, NID1); - RV.add(STANDBY, NID2); - RV.add(STANDBY, NID3); - - assertEquals("wrong nodeID: ", NID1, RV.get(MASTER)); - assertTrue("wrong nodeIDs: ", - Sets.newHashSet(NID3, NID2).containsAll(RV.nodesOfRole(STANDBY))); - } -} |