diff options
Diffstat (limited to 'framework/src/onos/core/api/src/test/java/org/onosproject')
189 files changed, 18282 insertions, 0 deletions
diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/TestApplicationId.java b/framework/src/onos/core/api/src/test/java/org/onosproject/TestApplicationId.java new file mode 100644 index 00000000..a57d5e8a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/TestApplicationId.java @@ -0,0 +1,48 @@ +/* + * 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; + +import org.onosproject.core.ApplicationId; + +import java.util.Objects; + +/** + * Test application ID. + */ +public class TestApplicationId implements ApplicationId { + + private final String name; + private final short id; + + public TestApplicationId(String name) { + this.name = name; + this.id = (short) Objects.hash(name); + } + + public static ApplicationId create(String name) { + return new TestApplicationId(name); + } + + @Override + public short id() { + return id; + } + + @Override + public String name() { + return name; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/VersionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/VersionTest.java new file mode 100644 index 00000000..ecf5f34e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/VersionTest.java @@ -0,0 +1,83 @@ +/* + * 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; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.core.Version; + +import static org.junit.Assert.*; +import static org.onosproject.core.Version.version; + +/** + * Tests of the version descriptor. + */ +public class VersionTest { + + @Test + public void fromParts() { + Version v = version(1, 2, "3", "4321"); + assertEquals("wrong major", 1, v.major()); + assertEquals("wrong minor", 2, v.minor()); + assertEquals("wrong patch", "3", v.patch()); + assertEquals("wrong build", "4321", v.build()); + } + + @Test + public void fromString() { + Version v = version("1.2.3.4321"); + assertEquals("wrong major", 1, v.major()); + assertEquals("wrong minor", 2, v.minor()); + assertEquals("wrong patch", "3", v.patch()); + assertEquals("wrong build", "4321", v.build()); + } + + @Test + public void snapshot() { + Version v = version("1.2.3-SNAPSHOT"); + assertEquals("wrong major", 1, v.major()); + assertEquals("wrong minor", 2, v.minor()); + assertEquals("wrong patch", "3", v.patch()); + assertEquals("wrong build", "SNAPSHOT", v.build()); + } + + @Test + public void shortNumber() { + Version v = version("1.2.3"); + assertEquals("wrong major", 1, v.major()); + assertEquals("wrong minor", 2, v.minor()); + assertEquals("wrong patch", "3", v.patch()); + assertEquals("wrong build", null, v.build()); + } + + @Test + public void minimal() { + Version v = version("1.4"); + assertEquals("wrong major", 1, v.major()); + assertEquals("wrong minor", 4, v.minor()); + assertEquals("wrong patch", null, v.patch()); + assertEquals("wrong build", null, v.build()); + } + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(version("1.2.3.4321"), version(1, 2, "3", "4321")) + .addEqualityGroup(version("1.9.3.4321"), version(1, 9, "3", "4321")) + .addEqualityGroup(version("1.2.8.4321"), version(1, 2, "8", "4321")) + .addEqualityGroup(version("1.2.3.x"), version(1, 2, "3", "x")) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationAdminServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationAdminServiceAdapter.java new file mode 100644 index 00000000..edcc2094 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationAdminServiceAdapter.java @@ -0,0 +1,78 @@ +/* + * 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.app; + +import org.onosproject.core.Application; +import org.onosproject.core.ApplicationId; +import org.onosproject.security.Permission; + +import java.io.InputStream; +import java.util.Set; + +/** + * Adapter for testing against application admin service. + */ +public class ApplicationAdminServiceAdapter extends ApplicationServiceAdapter + implements ApplicationAdminService { + @Override + public Set<Application> getApplications() { + return null; + } + + @Override + public Application getApplication(ApplicationId appId) { + return null; + } + + @Override + public ApplicationState getState(ApplicationId appId) { + return null; + } + + @Override + public Set<Permission> getPermissions(ApplicationId appId) { + return null; + } + + @Override + public void addListener(ApplicationListener listener) { + } + + @Override + public void removeListener(ApplicationListener listener) { + } + + @Override + public Application install(InputStream appDescStream) { + return null; + } + + @Override + public void uninstall(ApplicationId appId) { + } + + @Override + public void activate(ApplicationId appId) { + } + + @Override + public void deactivate(ApplicationId appId) { + } + + @Override + public void setPermissions(ApplicationId appId, Set<Permission> permissions) { + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationEventTest.java new file mode 100644 index 00000000..d31cc268 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationEventTest.java @@ -0,0 +1,55 @@ +/* + * 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.app; + +import org.junit.Test; +import org.onosproject.core.Application; +import org.onosproject.core.DefaultApplication; +import org.onosproject.event.AbstractEventTest; + +import java.util.Optional; + +import static org.onosproject.app.ApplicationEvent.Type.APP_ACTIVATED; +import static org.onosproject.app.DefaultApplicationDescriptionTest.*; +import static org.onosproject.core.DefaultApplicationTest.APP_ID; + +/** + * Test of the application event. + */ +public class ApplicationEventTest extends AbstractEventTest { + + private Application createApp() { + return new DefaultApplication(APP_ID, VER, DESC, ORIGIN, ROLE, + PERMS, Optional.of(FURL), FEATURES); + } + + @Test + public void withoutTime() { + Application app = createApp(); + ApplicationEvent event = new ApplicationEvent(APP_ACTIVATED, app, 123L); + validateEvent(event, APP_ACTIVATED, app, 123L); + } + + @Test + public void withTime() { + Application app = createApp(); + long before = System.currentTimeMillis(); + ApplicationEvent event = new ApplicationEvent(APP_ACTIVATED, app); + long after = System.currentTimeMillis(); + validateEvent(event, APP_ACTIVATED, app, before, after); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationExceptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationExceptionTest.java new file mode 100644 index 00000000..a0c7ef1c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationExceptionTest.java @@ -0,0 +1,36 @@ +/* + * 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.app; + +import org.onlab.junit.ExceptionTest; + +public class ApplicationExceptionTest extends ExceptionTest { + + @Override + protected Exception getDefault() { + return new ApplicationException(); + } + + @Override + protected Exception getWithMessage() { + return new ApplicationException(MESSAGE); + } + + @Override + protected Exception getWithMessageAndCause() { + return new ApplicationException(MESSAGE, CAUSE); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationServiceAdapter.java new file mode 100644 index 00000000..479cc59a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationServiceAdapter.java @@ -0,0 +1,60 @@ +/* + * 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.app; + +import org.onosproject.core.Application; +import org.onosproject.core.ApplicationId; +import org.onosproject.security.Permission; + +import java.util.Set; + +/** + * Adapter for testing against application service. + */ +public class ApplicationServiceAdapter implements ApplicationService { + @Override + public Set<Application> getApplications() { + return null; + } + + @Override + public ApplicationId getId(String name) { + return null; + } + + @Override + public Application getApplication(ApplicationId appId) { + return null; + } + + @Override + public ApplicationState getState(ApplicationId appId) { + return null; + } + + @Override + public Set<Permission> getPermissions(ApplicationId appId) { + return null; + } + + @Override + public void addListener(ApplicationListener listener) { + } + + @Override + public void removeListener(ApplicationListener listener) { + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationStoreAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationStoreAdapter.java new file mode 100644 index 00000000..1a9ad8d2 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/ApplicationStoreAdapter.java @@ -0,0 +1,78 @@ +/* + * 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.app; + +import org.onosproject.core.Application; +import org.onosproject.core.ApplicationId; +import org.onosproject.security.Permission; +import org.onosproject.store.AbstractStore; + +import java.io.InputStream; +import java.util.Set; + +/** + * Adapter for application testing against application store. + */ +public class ApplicationStoreAdapter + extends AbstractStore<ApplicationEvent, ApplicationStoreDelegate> + implements ApplicationStore { + @Override + public Set<Application> getApplications() { + return null; + } + + @Override + public ApplicationId getId(String name) { + return null; + } + + @Override + public Application getApplication(ApplicationId appId) { + return null; + } + + @Override + public ApplicationState getState(ApplicationId appId) { + return null; + } + + @Override + public Application create(InputStream appDescStream) { + return null; + } + + @Override + public void remove(ApplicationId appId) { + } + + @Override + public void activate(ApplicationId appId) { + } + + @Override + public void deactivate(ApplicationId appId) { + } + + @Override + public Set<Permission> getPermissions(ApplicationId appId) { + return null; + } + + @Override + public void setPermissions(ApplicationId appId, Set<Permission> permissions) { + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/app/DefaultApplicationDescriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/app/DefaultApplicationDescriptionTest.java new file mode 100644 index 00000000..d40d3fea --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/app/DefaultApplicationDescriptionTest.java @@ -0,0 +1,66 @@ +/* + * 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.app; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import org.junit.Test; +import org.onosproject.core.ApplicationRole; +import org.onosproject.core.Version; +import org.onosproject.security.AppPermission; +import org.onosproject.security.Permission; + +import java.net.URI; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +/** + * Basic tests of the default app description. + */ +public class DefaultApplicationDescriptionTest { + + public static final String APP_NAME = "org.foo.app"; + public static final Version VER = Version.version(1, 2, "a", null); + public static final String DESC = "Awesome application from Circus, Inc."; + public static final String ORIGIN = "Circus"; + public static final ApplicationRole ROLE = ApplicationRole.ADMIN; + public static final Set<Permission> PERMS = ImmutableSet.of( + new Permission(AppPermission.class.getName(), "FLOWRULE_WRITE"), + new Permission(AppPermission.class.getName(), "FLOWRULE_READ")); + public static final URI FURL = URI.create("mvn:org.foo-features/1.2a/xml/features"); + public static final List<String> FEATURES = ImmutableList.of("foo", "bar"); + + @Test + public void basics() { + ApplicationDescription app = + new DefaultApplicationDescription(APP_NAME, VER, DESC, ORIGIN, + ROLE, PERMS, FURL, FEATURES); + assertEquals("incorrect id", APP_NAME, app.name()); + assertEquals("incorrect version", VER, app.version()); + assertEquals("incorrect description", DESC, app.description()); + assertEquals("incorrect origin", ORIGIN, app.origin()); + assertEquals("incorect role", ROLE, app.role()); + assertEquals("incorrect permissions", PERMS, app.permissions()); + assertEquals("incorrect features repo", FURL, app.featuresRepo().get()); + assertEquals("incorrect features", FEATURES, app.features()); + assertTrue("incorrect toString", app.toString().contains(APP_NAME)); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ComponentConfigAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ComponentConfigAdapter.java new file mode 100644 index 00000000..a1abd188 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ComponentConfigAdapter.java @@ -0,0 +1,53 @@ +/* + * 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.cfg; + +import java.util.Set; + +/** + * Adapter for testing against component configuration service. + */ +public class ComponentConfigAdapter implements ComponentConfigService { + @Override + public Set<String> getComponentNames() { + return null; + } + + @Override + public void registerProperties(Class<?> componentClass) { + + } + + @Override + public void unregisterProperties(Class<?> componentClass, boolean clear) { + + } + + @Override + public Set<ConfigProperty> getProperties(String componentName) { + return null; + } + + @Override + public void setProperty(String componentName, String name, String value) { + + } + + @Override + public void unsetProperty(String componentName, String name) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ConfigPropertyTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ConfigPropertyTest.java new file mode 100644 index 00000000..b4ba8634 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cfg/ConfigPropertyTest.java @@ -0,0 +1,97 @@ +/* + * 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.cfg; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.cfg.ConfigProperty.Type; + +import static org.junit.Assert.*; +import static org.onosproject.cfg.ConfigProperty.Type.*; +import static org.onosproject.cfg.ConfigProperty.defineProperty; +import static org.onosproject.cfg.ConfigProperty.resetProperty; +import static org.onosproject.cfg.ConfigProperty.setProperty; + +/** + * Set of tests of the configuration property class. + */ +public class ConfigPropertyTest { + + @Test + public void basics() { + ConfigProperty p = defineProperty("foo", STRING, "bar", "Foo Prop"); + validate(p, "foo", STRING, "bar", "bar"); + p = setProperty(p, "BAR"); + validate(p, "foo", STRING, "BAR", "bar"); + p = resetProperty(p); + validate(p, "foo", STRING, "bar", "bar"); + } + + @Test + public void equality() { + new EqualsTester() + .addEqualityGroup(defineProperty("foo", STRING, "bar", "Desc"), + defineProperty("foo", STRING, "goo", "Desc")) + .addEqualityGroup(defineProperty("bar", STRING, "bar", "Desc"), + defineProperty("bar", STRING, "goo", "Desc")) + .testEquals(); + } + + private void validate(ConfigProperty p, String name, Type type, String v, String dv) { + assertEquals("incorrect name", name, p.name()); + assertEquals("incorrect type", type, p.type()); + assertEquals("incorrect value", v, p.value()); + assertEquals("incorrect default", dv, p.defaultValue()); + assertEquals("incorrect description", "Foo Prop", p.description()); + } + + @Test + public void asInteger() { + ConfigProperty p = defineProperty("foo", INTEGER, "123", "Foo Prop"); + validate(p, "foo", INTEGER, "123", "123"); + assertEquals("incorrect value", 123, p.asInteger()); + assertEquals("incorrect value", 123L, p.asLong()); + } + + @Test + public void asLong() { + ConfigProperty p = defineProperty("foo", LONG, "123", "Foo Prop"); + validate(p, "foo", LONG, "123", "123"); + assertEquals("incorrect value", 123L, p.asLong()); + } + + @Test + public void asFloat() { + ConfigProperty p = defineProperty("foo", FLOAT, "123.0", "Foo Prop"); + validate(p, "foo", FLOAT, "123.0", "123.0"); + assertEquals("incorrect value", 123.0, p.asFloat(), 0.01); + assertEquals("incorrect value", 123.0, p.asDouble(), 0.01); + } + + @Test + public void asDouble() { + ConfigProperty p = defineProperty("foo", DOUBLE, "123.0", "Foo Prop"); + validate(p, "foo", DOUBLE, "123.0", "123.0"); + assertEquals("incorrect value", 123.0, p.asDouble(), 0.01); + } + + @Test + public void asBoolean() { + ConfigProperty p = defineProperty("foo", BOOLEAN, "true", "Foo Prop"); + validate(p, "foo", BOOLEAN, "true", "true"); + assertEquals("incorrect value", true, p.asBoolean()); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ClusterServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ClusterServiceAdapter.java new file mode 100644 index 00000000..b88b5ff6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ClusterServiceAdapter.java @@ -0,0 +1,64 @@ +/* + * 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.cluster; + +import java.util.Set; + +import org.joda.time.DateTime; +import org.onlab.packet.IpAddress; + +import com.google.common.collect.ImmutableSet; + +/** + * Test adapter for the cluster service. + */ +public class ClusterServiceAdapter implements ClusterService { + ControllerNode local = new DefaultControllerNode(new NodeId("local"), + IpAddress.valueOf("127.0.0.1")); + + @Override + public ControllerNode getLocalNode() { + return local; + } + + @Override + public Set<ControllerNode> getNodes() { + return ImmutableSet.of(local); + } + + @Override + public ControllerNode getNode(NodeId nodeId) { + return null; + } + + @Override + public ControllerNode.State getState(NodeId nodeId) { + return null; + } + + @Override + public DateTime getLastUpdated(NodeId nodeId) { + return null; + } + + @Override + public void addListener(ClusterEventListener listener) { + } + + @Override + public void removeListener(ClusterEventListener listener) { + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ControllerNodeToNodeIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ControllerNodeToNodeIdTest.java new file mode 100644 index 00000000..0b4d1ef6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/ControllerNodeToNodeIdTest.java @@ -0,0 +1,59 @@ +/* + * 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.cluster; + +import static com.google.common.base.Predicates.notNull; +import static org.junit.Assert.*; +import static org.onosproject.cluster.ControllerNodeToNodeId.toNodeId; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.onlab.packet.IpAddress; + +import com.google.common.collect.FluentIterable; + + +public class ControllerNodeToNodeIdTest { + + private static final NodeId NID1 = new NodeId("foo"); + private static final NodeId NID2 = new NodeId("bar"); + private static final NodeId NID3 = new NodeId("buz"); + + private static final IpAddress IP1 = IpAddress.valueOf("127.0.0.1"); + private static final IpAddress IP2 = IpAddress.valueOf("127.0.0.2"); + private static final IpAddress IP3 = IpAddress.valueOf("127.0.0.3"); + + private static final ControllerNode CN1 = new DefaultControllerNode(NID1, IP1); + private static final ControllerNode CN2 = new DefaultControllerNode(NID2, IP2); + private static final ControllerNode CN3 = new DefaultControllerNode(NID3, IP3); + + + @Test + public final void testToNodeId() { + + final Iterable<ControllerNode> nodes = Arrays.asList(CN1, CN2, CN3, null); + final List<NodeId> nodeIds = Arrays.asList(NID1, NID2, NID3); + + assertEquals(nodeIds, + FluentIterable.from(nodes) + .transform(toNodeId()) + .filter(notNull()) + .toList()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipEventTest.java new file mode 100644 index 00000000..be0321bf --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipEventTest.java @@ -0,0 +1,76 @@ +/* + * 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.cluster; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +/** + * Unit tests for the leadership event test. + */ +public class LeadershipEventTest { + private final NodeId node1 = new NodeId("1"); + private final NodeId node2 = new NodeId("2"); + private final Leadership lead1 = new Leadership("topic1", node1, 1L, 2L); + private final Leadership lead2 = new Leadership("topic1", node2, 1L, 2L); + private final LeadershipEvent event1 = + new LeadershipEvent(LeadershipEvent.Type.LEADER_ELECTED, lead1); + private final long time = System.currentTimeMillis(); + private final LeadershipEvent event2 = + new LeadershipEvent(LeadershipEvent.Type.CANDIDATES_CHANGED, + lead2, time); + private final LeadershipEvent sameAsEvent2 = + new LeadershipEvent(LeadershipEvent.Type.CANDIDATES_CHANGED, + lead2, time); + private final LeadershipEvent event3 = + new LeadershipEvent(LeadershipEvent.Type.LEADER_BOOTED, lead1); + private final LeadershipEvent event4 = + new LeadershipEvent(LeadershipEvent.Type.LEADER_REELECTED, lead1); + private final LeadershipEvent event5 = + new LeadershipEvent(LeadershipEvent.Type.LEADER_REELECTED, lead2); + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(event1) + .addEqualityGroup(event2, sameAsEvent2) + .addEqualityGroup(event3) + .addEqualityGroup(event4) + .addEqualityGroup(event5) + .testEquals(); + } + + /** + * Tests that objects are created properly. + */ + @Test + public void checkConstruction() { + assertThat(event1.type(), is(LeadershipEvent.Type.LEADER_ELECTED)); + assertThat(event1.subject(), is(lead1)); + + assertThat(event2.time(), is(time)); + assertThat(event2.type(), is(LeadershipEvent.Type.CANDIDATES_CHANGED)); + assertThat(event2.subject(), is(lead2)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipServiceAdapter.java new file mode 100644 index 00000000..e1d421d0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipServiceAdapter.java @@ -0,0 +1,87 @@ +/* + * 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.cluster; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +/** + * Test adapter for leadership service. + */ +public class LeadershipServiceAdapter implements LeadershipService { + + @Override + public NodeId getLeader(String path) { + return null; + } + + @Override + public Leadership getLeadership(String path) { + return null; + } + + @Override + public Set<String> ownedTopics(NodeId nodeId) { + return null; + } + + @Override + public CompletableFuture<Leadership> runForLeadership(String path) { + return null; + } + + @Override + public CompletableFuture<Void> withdraw(String path) { + return null; + } + + @Override + public Map<String, Leadership> getLeaderBoard() { + return null; + } + + @Override + public void addListener(LeadershipEventListener listener) { + + } + + @Override + public void removeListener(LeadershipEventListener listener) { + + } + + @Override + public Map<String, List<NodeId>> getCandidates() { + return null; + } + + @Override + public List<NodeId> getCandidates(String path) { + return null; + } + + @Override + public boolean stepdown(String path) { + return false; + } + + @Override + public boolean makeTopCandidate(String path, NodeId nodeId) { + return false; + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipTest.java new file mode 100644 index 00000000..e2a86587 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/LeadershipTest.java @@ -0,0 +1,75 @@ +/* + * 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.cluster; + +import org.junit.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +/** + * Unit tests for the Leadership class. + */ +public class LeadershipTest { + private final NodeId node1 = new NodeId("1"); + private final NodeId node2 = new NodeId("2"); + private final Leadership lead1 = new Leadership("topic1", node1, 1L, 2L); + private final Leadership sameAsLead1 = new Leadership("topic1", node1, 1L, 2L); + private final Leadership lead2 = new Leadership("topic2", node1, 1L, 2L); + private final Leadership lead3 = new Leadership("topic1", node1, 2L, 2L); + private final Leadership lead4 = new Leadership("topic1", node1, 3L, 2L); + private final Leadership lead5 = new Leadership("topic1", node1, 3L, 3L); + private final Leadership lead6 = new Leadership("topic1", node1, + ImmutableList.of(node2), 1L, 2L); + private final Leadership lead7 = new Leadership("topic1", + ImmutableList.of(node2), 1L, 2L); + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(lead1, sameAsLead1) + .addEqualityGroup(lead2) + .addEqualityGroup(lead3) + .addEqualityGroup(lead4) + .addEqualityGroup(lead5) + .addEqualityGroup(lead6) + .addEqualityGroup(lead7) + .testEquals(); + } + + /** + * Tests that objects are created properly and accessor methods return + * the correct vsalues. + */ + @Test + public void checkConstruction() { + assertThat(lead6.electedTime(), is(2L)); + assertThat(lead6.epoch(), is(1L)); + assertThat(lead6.leader(), is(node1)); + assertThat(lead6.topic(), is("topic1")); + assertThat(lead6.candidates(), hasSize(1)); + assertThat(lead6.candidates(), contains(node2)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/RoleInfoTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/RoleInfoTest.java new file mode 100644 index 00000000..4998bf5a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/cluster/RoleInfoTest.java @@ -0,0 +1,60 @@ +/* + * 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.cluster; + +import java.util.List; + +import org.junit.Test; + +import com.google.common.collect.Lists; +import com.google.common.testing.EqualsTester; + +import static org.junit.Assert.assertEquals; + +/** + * Test to check behavioral correctness of the RoleInfo structure. + */ +public class RoleInfoTest { + private static final NodeId N1 = new NodeId("n1"); + private static final NodeId N2 = new NodeId("n2"); + private static final NodeId N3 = new NodeId("n3"); + private static final NodeId N4 = new NodeId("n4"); + + private static final List<NodeId> BKUP1 = Lists.newArrayList(N2, N3); + private static final List<NodeId> BKUP2 = Lists.newArrayList(N3, N4); + + private static final RoleInfo RI1 = new RoleInfo(N1, BKUP1); + private static final RoleInfo RI2 = new RoleInfo(N1, BKUP2); + private static final RoleInfo RI3 = new RoleInfo(N2, BKUP1); + private static final RoleInfo RI4 = new RoleInfo(null, BKUP2); + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(RI1, new RoleInfo(new NodeId("n1"), Lists.newArrayList(N2, N3))) + .addEqualityGroup(RI3); + } + + @Test + public void basics() { + assertEquals("wrong master", new NodeId("n1"), RI1.master()); + assertEquals("wrong Backups", RI1.backups(), Lists.newArrayList(N2, N3)); + assertEquals("wrong empty master", RI4.master(), null); + + List<NodeId> bkup3 = Lists.newArrayList(N3, new NodeId("n4")); + assertEquals("equals() broken", new RoleInfo(N1, bkup3), RI2); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/codec/JsonCodecTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/codec/JsonCodecTest.java new file mode 100644 index 00000000..eb04d9a5 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/codec/JsonCodecTest.java @@ -0,0 +1,99 @@ +/* + * 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.codec; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableList; +import org.junit.Test; + +import java.util.List; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; + +/** + * Test of the base JSON codec abstraction. + */ +public class JsonCodecTest { + + private static class Foo { + final String name; + + Foo(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final Foo other = (Foo) obj; + return Objects.equals(this.name, other.name); + } + } + + private static class FooCodec extends JsonCodec<Foo> { + @Override + public ObjectNode encode(Foo entity, CodecContext context) { + return context.mapper().createObjectNode().put("name", entity.name); + } + + @Override + public Foo decode(ObjectNode json, CodecContext context) { + return new Foo(json.get("name").asText()); + } + } + + @Test + public void encode() { + Foo f1 = new Foo("foo"); + Foo f2 = new Foo("bar"); + FooCodec codec = new FooCodec(); + ImmutableList<Foo> entities = ImmutableList.of(f1, f2); + ArrayNode json = codec.encode(entities, new TestContext()); + List<Foo> foos = codec.decode(json, new TestContext()); + assertEquals("incorrect encode/decode", entities, foos); + } + + private class TestContext implements CodecContext { + private ObjectMapper mapper = new ObjectMapper(); + @Override + public ObjectMapper mapper() { + return mapper; + } + + @Override + public <T> JsonCodec<T> codec(Class<T> entityClass) { + return null; + } + + @Override + public <T> T getService(Class<T> serviceClass) { + return null; + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/core/ApplicationIdStoreAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/core/ApplicationIdStoreAdapter.java new file mode 100644 index 00000000..c3d0f237 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/core/ApplicationIdStoreAdapter.java @@ -0,0 +1,43 @@ +/* + * 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.core; + +import java.util.Set; + +/** + * Adapter for testing against app id store. + */ +public class ApplicationIdStoreAdapter implements ApplicationIdStore { + @Override + public Set<ApplicationId> getAppIds() { + return null; + } + + @Override + public ApplicationId getAppId(Short id) { + return null; + } + + @Override + public ApplicationId getAppId(String name) { + return null; + } + + @Override + public ApplicationId registerApplication(String identifier) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/core/CoreServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/core/CoreServiceAdapter.java new file mode 100644 index 00000000..0f6abd68 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/core/CoreServiceAdapter.java @@ -0,0 +1,54 @@ +/* + * 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.core; + +import java.util.Set; + +/** + * Test adapter for core service. + */ +public class CoreServiceAdapter implements CoreService { + @Override + public Version version() { + return null; + } + + @Override + public Set<ApplicationId> getAppIds() { + return null; + } + + @Override + public ApplicationId getAppId(Short id) { + return null; + } + + @Override + public ApplicationId getAppId(String name) { + return null; + } + + @Override + public ApplicationId registerApplication(String identifier) { + return null; + } + + @Override + public IdGenerator getIdGenerator(String topic) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultApplicationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultApplicationTest.java new file mode 100644 index 00000000..cbedb79c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultApplicationTest.java @@ -0,0 +1,63 @@ +/* + * 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.core; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.app.DefaultApplicationDescriptionTest.*; + +/** + * Basic tests of the default app descriptor. + */ +public class DefaultApplicationTest { + + public static final ApplicationId APP_ID = new DefaultApplicationId(2, APP_NAME); + + @Test + public void basics() { + Application app = new DefaultApplication(APP_ID, VER, DESC, ORIGIN, ROLE, + PERMS, Optional.of(FURL), FEATURES); + assertEquals("incorrect id", APP_ID, app.id()); + assertEquals("incorrect version", VER, app.version()); + assertEquals("incorrect description", DESC, app.description()); + assertEquals("incorrect origin", ORIGIN, app.origin()); + assertEquals("incorrect role", ROLE, app.role()); + assertEquals("incorrect permissions", PERMS, app.permissions()); + assertEquals("incorrect features repo", FURL, app.featuresRepo().get()); + assertEquals("incorrect features", FEATURES, app.features()); + assertTrue("incorrect toString", app.toString().contains(APP_NAME)); + } + + @Test + public void testEquality() { + Application a1 = new DefaultApplication(APP_ID, VER, DESC, ORIGIN, ROLE, + PERMS, Optional.of(FURL), FEATURES); + Application a2 = new DefaultApplication(APP_ID, VER, DESC, ORIGIN, ROLE, + PERMS, Optional.of(FURL), FEATURES); + Application a3 = new DefaultApplication(APP_ID, VER, DESC, ORIGIN, ROLE, + PERMS, Optional.empty(), FEATURES); + Application a4 = new DefaultApplication(APP_ID, VER, DESC, ORIGIN + "asd", ROLE, + PERMS, Optional.of(FURL), FEATURES); + new EqualsTester().addEqualityGroup(a1, a2) + .addEqualityGroup(a3).addEqualityGroup(a4).testEquals(); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultGroupIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultGroupIdTest.java new file mode 100644 index 00000000..21dea86b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/core/DefaultGroupIdTest.java @@ -0,0 +1,41 @@ +/* + * 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.core; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +/** + * Test for DefaultGroupId. + */ +public class DefaultGroupIdTest { + + /** + * Tests the equality of the instances. + */ + @Test + public void testEquality() { + DefaultGroupId id1 = new DefaultGroupId((short) 1); + DefaultGroupId id2 = new DefaultGroupId((short) 1); + DefaultGroupId id3 = new DefaultGroupId((short) 2); + + new EqualsTester() + .addEqualityGroup(id1, id2) + .addEqualityGroup(id3) + .testEquals(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/core/UnavailableIdExceptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/core/UnavailableIdExceptionTest.java new file mode 100644 index 00000000..ac565d80 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/core/UnavailableIdExceptionTest.java @@ -0,0 +1,36 @@ +/* + * 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.core; + +import org.onlab.junit.ExceptionTest; + +public class UnavailableIdExceptionTest extends ExceptionTest { + + @Override + protected Exception getDefault() { + return new UnavailableIdException(); + } + + @Override + protected Exception getWithMessage() { + return new UnavailableIdException(MESSAGE); + } + + @Override + protected Exception getWithMessageAndCause() { + return new UnavailableIdException(MESSAGE, CAUSE); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/AbstractEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/AbstractEventTest.java new file mode 100644 index 00000000..c66c4b84 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/AbstractEventTest.java @@ -0,0 +1,79 @@ +/* + * 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.event; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.event.TestEvent.Type.FOO; + +/** + * Tests of the base event abstraction. + */ +public class AbstractEventTest { + + /** + * Validates the base attributes of an event. + * + * @param event event to validate + * @param type event type + * @param subject event subject + * @param time event time + * @param <T> type of event + * @param <S> type of subject + */ + protected static <T extends Enum, S> + void validateEvent(Event<T, S> event, T type, S subject, long time) { + assertEquals("incorrect type", type, event.type()); + assertEquals("incorrect subject", subject, event.subject()); + assertEquals("incorrect time", time, event.time()); + } + + /** + * Validates the base attributes of an event. + * + * @param event event to validate + * @param type event type + * @param subject event subject + * @param minTime minimum event time inclusive + * @param maxTime maximum event time inclusive + * @param <T> type of event + * @param <S> type of subject + */ + protected static <T extends Enum, S> + void validateEvent(Event<T, S> event, T type, S subject, + long minTime, long maxTime) { + assertEquals("incorrect type", type, event.type()); + assertEquals("incorrect subject", subject, event.subject()); + assertTrue("incorrect time", minTime <= event.time() && event.time() <= maxTime); + } + + @Test + public void withTime() { + TestEvent event = new TestEvent(FOO, "foo", 123L); + validateEvent(event, FOO, "foo", 123L); + } + + @Test + public void withoutTime() { + long before = System.currentTimeMillis(); + TestEvent event = new TestEvent(FOO, "foo"); + long after = System.currentTimeMillis(); + validateEvent(event, FOO, "foo", before, after); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/BrokenListener.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/BrokenListener.java new file mode 100644 index 00000000..1a013ada --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/BrokenListener.java @@ -0,0 +1,28 @@ +/* + * 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.event; + +/** + * Test event listener fixture. + */ +public class BrokenListener extends TestListener { + + public void event(TestEvent event) { + throw new IllegalStateException("boom"); + } + +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/DefaultEventSinkRegistryTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/DefaultEventSinkRegistryTest.java new file mode 100644 index 00000000..2e24228a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/DefaultEventSinkRegistryTest.java @@ -0,0 +1,71 @@ +/* + * 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.event; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Tests of the default event sink registry. + */ +public class DefaultEventSinkRegistryTest { + + private DefaultEventSinkRegistry registry; + + private static class FooEvent extends TestEvent { + public FooEvent(String subject) { + super(Type.FOO, subject); + } + } + + private static class BarEvent extends TestEvent { + public BarEvent(String subject) { + super(Type.BAR, subject); + } + } + + private static class FooSink implements EventSink<FooEvent> { + @Override public void process(FooEvent event) {} + } + + private static class BarSink implements EventSink<BarEvent> { + @Override public void process(BarEvent event) {} + } + + @Before + public void setUp() { + registry = new DefaultEventSinkRegistry(); + } + + @Test + public void basics() { + FooSink fooSink = new FooSink(); + BarSink barSink = new BarSink(); + registry.addSink(FooEvent.class, fooSink); + registry.addSink(BarEvent.class, barSink); + + assertEquals("incorrect sink count", 2, registry.getSinks().size()); + assertEquals("incorrect sink", fooSink, registry.getSink(FooEvent.class)); + assertEquals("incorrect sink", barSink, registry.getSink(BarEvent.class)); + + registry.removeSink(FooEvent.class); + assertNull("incorrect sink", registry.getSink(FooEvent.class)); + assertEquals("incorrect sink", barSink, registry.getSink(BarEvent.class)); + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/EventDeliveryServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/EventDeliveryServiceAdapter.java new file mode 100644 index 00000000..6d5e8934 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/EventDeliveryServiceAdapter.java @@ -0,0 +1,60 @@ +/* + * 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.event; + +import java.util.Set; + +import static org.junit.Assert.*; + +/** + * Testing adapter for the event delivery service. + */ +public class EventDeliveryServiceAdapter implements EventDeliveryService { + @Override + public void setDispatchTimeLimit(long millis) { + + } + + @Override + public long getDispatchTimeLimit() { + return 0; + } + + @Override + public void post(Event event) { + + } + + @Override + public <E extends Event> void addSink(Class<E> eventClass, EventSink<E> sink) { + + } + + @Override + public <E extends Event> void removeSink(Class<E> eventClass) { + + } + + @Override + public <E extends Event> EventSink<E> getSink(Class<E> eventClass) { + return null; + } + + @Override + public Set<Class<? extends Event>> getSinks() { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/ListenerRegistryTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/ListenerRegistryTest.java new file mode 100644 index 00000000..8cce6417 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/ListenerRegistryTest.java @@ -0,0 +1,74 @@ +/* + * 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.event; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link ListenerRegistry}. + */ +public class ListenerRegistryTest { + + private static final TestEvent FOO_EVENT = + new TestEvent(TestEvent.Type.FOO, "foo"); + private static final TestEvent BAR_EVENT = + new TestEvent(TestEvent.Type.BAR, "bar"); + + private TestListener listener; + private TestListener secondListener; + private TestListenerRegistry manager; + + @Before + public void setUp() { + listener = new TestListener(); + secondListener = new TestListener(); + manager = new TestListenerRegistry(); + } + + @Test + public void basics() { + manager.addListener(listener); + manager.addListener(secondListener); + + manager.process(BAR_EVENT); + assertTrue("BAR not processed", listener.events.contains(BAR_EVENT)); + assertTrue("BAR not processed", secondListener.events.contains(BAR_EVENT)); + + manager.removeListener(listener); + + manager.process(FOO_EVENT); + assertFalse("FOO processed", listener.events.contains(FOO_EVENT)); + assertTrue("FOO not processed", secondListener.events.contains(FOO_EVENT)); + } + + @Test + public void badListener() { + listener = new BrokenListener(); + + manager.addListener(listener); + manager.addListener(secondListener); + + manager.process(BAR_EVENT); + assertFalse("BAR processed", listener.events.contains(BAR_EVENT)); + assertFalse("error not reported", manager.errors.isEmpty()); + assertTrue("BAR not processed", secondListener.events.contains(BAR_EVENT)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestEvent.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestEvent.java new file mode 100644 index 00000000..8a507151 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestEvent.java @@ -0,0 +1,34 @@ +/* + * 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.event; + +/** + * Test event fixture. + */ +public class TestEvent extends AbstractEvent<TestEvent.Type, String> { + + public enum Type { FOO, BAR } + + public TestEvent(Type type, String subject) { + super(type, subject); + } + + public TestEvent(Type type, String subject, long timestamp) { + super(type, subject, timestamp); + } + +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListener.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListener.java new file mode 100644 index 00000000..213f8c59 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListener.java @@ -0,0 +1,34 @@ +/* + * 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.event; + +import java.util.ArrayList; +import java.util.List; + +/** + * Test event listener fixture. + */ +public class TestListener implements EventListener<TestEvent> { + + public final List<TestEvent> events = new ArrayList<>(); + + @Override + public void event(TestEvent event) { + events.add(event); + } + +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListenerRegistry.java b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListenerRegistry.java new file mode 100644 index 00000000..fd9b6d08 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/event/TestListenerRegistry.java @@ -0,0 +1,36 @@ +/* + * 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.event; + +import java.util.ArrayList; +import java.util.List; + +/** + * Test event listener manager fixture. + */ +public class TestListenerRegistry + extends ListenerRegistry<TestEvent, TestListener> { + + public final List<Throwable> errors = new ArrayList<>(); + + @Override + protected void reportProblem(TestEvent event, Throwable error) { + super.reportProblem(event, error); + errors.add(error); + } + +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipServiceAdapter.java new file mode 100644 index 00000000..7db9b38b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipServiceAdapter.java @@ -0,0 +1,67 @@ +/* + * 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.mastership; + +import org.onosproject.cluster.NodeId; +import org.onosproject.cluster.RoleInfo; +import org.onosproject.net.DeviceId; +import org.onosproject.net.MastershipRole; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; + +/** + * Test adapter for mastership service. + */ +public class MastershipServiceAdapter implements MastershipService { + @Override + public MastershipRole getLocalRole(DeviceId deviceId) { + return null; + } + + @Override + public CompletableFuture<MastershipRole> requestRoleFor(DeviceId deviceId) { + return null; + } + + @Override + public CompletableFuture<Void> relinquishMastership(DeviceId deviceId) { + return null; + } + + @Override + public NodeId getMasterFor(DeviceId deviceId) { + return null; + } + + @Override + public Set<DeviceId> getDevicesOf(NodeId nodeId) { + return null; + } + + @Override + public void addListener(MastershipListener listener) { + } + + @Override + public void removeListener(MastershipListener listener) { + } + + @Override + public RoleInfo getNodesFor(DeviceId deviceId) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipTermTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipTermTest.java new file mode 100644 index 00000000..0ca9436b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/mastership/MastershipTermTest.java @@ -0,0 +1,57 @@ +/* + * 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.mastership; + +import static org.junit.Assert.assertEquals; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +import org.junit.Test; +import org.onosproject.cluster.NodeId; + +import com.google.common.testing.EqualsTester; + +public class MastershipTermTest { + + private static final NodeId N1 = new NodeId("foo"); + private static final NodeId N2 = new NodeId("bar"); + + private static final MastershipTerm TERM1 = MastershipTerm.of(N1, 0); + private static final MastershipTerm TERM2 = MastershipTerm.of(N2, 1); + private static final MastershipTerm TERM3 = MastershipTerm.of(N2, 1); + private static final MastershipTerm TERM4 = MastershipTerm.of(N1, 1); + + @Test + public void basics() { + assertEquals("incorrect term number", 0, TERM1.termNumber()); + assertEquals("incorrect master", new NodeId("foo"), TERM1.master()); + } + + @Test + public void testEquality() { + new EqualsTester().addEqualityGroup(MastershipTerm.of(N1, 0), TERM1) + .addEqualityGroup(TERM2, TERM3) + .addEqualityGroup(TERM4) + .testEquals(); + } + + /** + * Checks that the MembershipTerm class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(MastershipTerm.class); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/ConnectPointTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/ConnectPointTest.java new file mode 100644 index 00000000..2aecabd4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/ConnectPointTest.java @@ -0,0 +1,110 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the connection point entity. + */ +public class ConnectPointTest { + + private static final DeviceId DID1 = deviceId("1"); + private static final DeviceId DID2 = deviceId("2"); + private static final PortNumber P1 = portNumber(1); + private static final PortNumber P2 = portNumber(2); + + @Test + public void basics() { + ConnectPoint p = new ConnectPoint(DID1, P2); + assertEquals("incorrect element id", DID1, p.deviceId()); + assertEquals("incorrect element id", P2, p.port()); + } + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(new ConnectPoint(DID1, P1), new ConnectPoint(DID1, P1)) + .addEqualityGroup(new ConnectPoint(DID1, P2), new ConnectPoint(DID1, P2)) + .addEqualityGroup(new ConnectPoint(DID2, P1), new ConnectPoint(DID2, P1)) + .testEquals(); + } + + @Test + public void testParseDeviceConnectPoint() { + String cp = "of:0011223344556677/1"; + + ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(cp); + assertEquals("of:0011223344556677", connectPoint.deviceId().toString()); + assertEquals("1", connectPoint.port().toString()); + + expectDeviceParseException(""); + expectDeviceParseException("1/"); + expectDeviceParseException("1/1/1"); + expectDeviceParseException("of:0011223344556677/word"); + } + + /** + * Parse a device connect point and expect an exception to be thrown. + * + * @param string string to parse + */ + private static void expectDeviceParseException(String string) { + try { + ConnectPoint.deviceConnectPoint(string); + fail("Expected exception was not thrown"); + } catch (Exception e) { + assertTrue(true); + } + } + + @Test + public void testParseHostConnectPoint() { + String cp = "16:3A:BD:6E:31:E4/-1/1"; + + ConnectPoint connectPoint = ConnectPoint.hostConnectPoint(cp); + assertEquals("16:3A:BD:6E:31:E4/-1", connectPoint.hostId().toString()); + assertEquals("1", connectPoint.port().toString()); + + expectHostParseException(""); + expectHostParseException("1/"); + expectHostParseException("1/1"); + expectHostParseException("1/1/1/1"); + expectHostParseException("16:3A:BD:6E:31:E4/word/1"); + expectHostParseException("16:3A:BD:6E:31:E4/1/word"); + } + + /** + * Parse a host connect point and expect an exception to be thrown. + * + * @param string string to parse + */ + private static void expectHostParseException(String string) { + try { + ConnectPoint.hostConnectPoint(string); + fail("Expected exception was not thrown"); + } catch (Exception e) { + assertTrue(true); + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultAnnotationsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultAnnotationsTest.java new file mode 100644 index 00000000..1bac285d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultAnnotationsTest.java @@ -0,0 +1,100 @@ +/* + * 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.net; + +import org.junit.Test; + +import static com.google.common.collect.ImmutableSet.of; +import static org.junit.Assert.*; +import static org.onosproject.net.DefaultAnnotations.builder; + +/** + * Tests of the default annotations. + */ +public class DefaultAnnotationsTest { + + private DefaultAnnotations annotations; + + @Test + public void basics() { + annotations = builder().set("foo", "1").set("bar", "2").build(); + assertEquals("incorrect keys", of("foo", "bar"), annotations.keys()); + assertEquals("incorrect value", "1", annotations.value("foo")); + assertEquals("incorrect value", "2", annotations.value("bar")); + } + + @Test + public void empty() { + annotations = builder().build(); + assertTrue("incorrect keys", annotations.keys().isEmpty()); + } + + @Test + public void remove() { + annotations = builder().remove("foo").set("bar", "2").build(); + assertEquals("incorrect keys", of("foo", "bar"), annotations.keys()); + assertNull("incorrect value", annotations.value("foo")); + assertEquals("incorrect value", "2", annotations.value("bar")); + } + + @Test + public void union() { + annotations = builder().set("foo", "1").set("bar", "2").remove("buz").build(); + assertEquals("incorrect keys", of("foo", "bar", "buz"), annotations.keys()); + + SparseAnnotations updates = builder().remove("foo").set("bar", "3").set("goo", "4").remove("fuzz").build(); + + SparseAnnotations result = DefaultAnnotations.union(annotations, updates); + + assertTrue("remove instruction in original remains", result.isRemoved("buz")); + assertTrue("remove instruction in update remains", result.isRemoved("fuzz")); + assertEquals("incorrect keys", of("buz", "goo", "bar", "fuzz"), result.keys()); + assertNull("incorrect value", result.value("foo")); + assertEquals("incorrect value", "3", result.value("bar")); + assertEquals("incorrect value", "4", result.value("goo")); + } + + @Test + public void merge() { + annotations = builder().set("foo", "1").set("bar", "2").build(); + assertEquals("incorrect keys", of("foo", "bar"), annotations.keys()); + + SparseAnnotations updates = builder().remove("foo").set("bar", "3").set("goo", "4").build(); + + annotations = DefaultAnnotations.merge(annotations, updates); + assertEquals("incorrect keys", of("goo", "bar"), annotations.keys()); + assertNull("incorrect value", annotations.value("foo")); + assertEquals("incorrect value", "3", annotations.value("bar")); + } + + @Test + public void noopMerge() { + annotations = builder().set("foo", "1").set("bar", "2").build(); + assertEquals("incorrect keys", of("foo", "bar"), annotations.keys()); + + SparseAnnotations updates = builder().build(); + assertSame("same annotations expected", annotations, + DefaultAnnotations.merge(annotations, updates)); + assertSame("same annotations expected", annotations, + DefaultAnnotations.merge(annotations, null)); + } + + @Test(expected = NullPointerException.class) + public void badMerge() { + DefaultAnnotations.merge(null, null); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultDeviceTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultDeviceTest.java new file mode 100644 index 00000000..1b0319a5 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultDeviceTest.java @@ -0,0 +1,79 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.provider.ProviderId; +import org.onlab.packet.ChassisId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.Device.Type.SWITCH; +import static org.onosproject.net.DeviceId.deviceId; + +/** + * Test of the default device model entity. + */ +public class DefaultDeviceTest { + + static final ProviderId PID = new ProviderId("of", "foo"); + static final DeviceId DID1 = deviceId("of:foo"); + static final DeviceId DID2 = deviceId("of:bar"); + static final String MFR = "whitebox"; + static final String HW = "1.1.x"; + static final String SW = "3.9.1"; + static final String SN1 = "43311-12345"; + static final String SN2 = "42346-43512"; + static final ChassisId CID = new ChassisId(); + + @Test + public void testEquality() { + Device d1 = new DefaultDevice(PID, DID1, SWITCH, MFR, HW, SW, SN1, CID); + Device d2 = new DefaultDevice(PID, DID1, SWITCH, MFR, HW, SW, SN1, CID); + Device d3 = new DefaultDevice(PID, DID2, SWITCH, MFR, HW, SW, SN2, CID); + Device d4 = new DefaultDevice(PID, DID2, SWITCH, MFR, HW, SW, SN2, CID); + Device d5 = new DefaultDevice(PID, DID2, SWITCH, MFR, HW, SW, SN1, CID); + + new EqualsTester().addEqualityGroup(d1, d2) + .addEqualityGroup(d3, d4) + .addEqualityGroup(d5) + .testEquals(); + } + + @Test + public void basics() { + Device device = new DefaultDevice(PID, DID1, SWITCH, MFR, HW, SW, SN1, CID); + validate(device); + } + + @Test + public void annotations() { + Device device = new DefaultDevice(PID, DID1, SWITCH, MFR, HW, SW, SN1, CID, + DefaultAnnotations.builder().set("foo", "bar").build()); + validate(device); + assertEquals("incorrect provider", "bar", device.annotations().value("foo")); + } + + private void validate(Device device) { + assertEquals("incorrect provider", PID, device.providerId()); + assertEquals("incorrect id", DID1, device.id()); + assertEquals("incorrect type", SWITCH, device.type()); + assertEquals("incorrect manufacturer", MFR, device.manufacturer()); + assertEquals("incorrect hw", HW, device.hwVersion()); + assertEquals("incorrect sw", SW, device.swVersion()); + assertEquals("incorrect serial", SN1, device.serialNumber()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultEdgeLinkTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultEdgeLinkTest.java new file mode 100644 index 00000000..ee5b0e32 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultEdgeLinkTest.java @@ -0,0 +1,90 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.provider.ProviderId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DefaultEdgeLink.createEdgeLink; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.HostId.hostId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the default edge link model entity. + */ +public class DefaultEdgeLinkTest { + + private static final ProviderId PID = new ProviderId("of", "foo"); + private static final DeviceId DID1 = deviceId("of:foo"); + private static final HostId HID1 = hostId("00:00:00:00:00:01/-1"); + private static final HostId HID2 = hostId("00:00:00:00:00:01/-1"); + private static final PortNumber P0 = portNumber(0); + private static final PortNumber P1 = portNumber(1); + + @Test + public void testEquality() { + EdgeLink l1 = new DefaultEdgeLink(PID, cp(HID1, P0), + new HostLocation(DID1, P1, 123L), true); + EdgeLink l2 = new DefaultEdgeLink(PID, cp(HID1, P0), + new HostLocation(DID1, P1, 123L), true); + + EdgeLink l3 = new DefaultEdgeLink(PID, cp(HID2, P0), + new HostLocation(DID1, P1, 123L), false); + EdgeLink l4 = new DefaultEdgeLink(PID, cp(HID2, P0), + new HostLocation(DID1, P1, 123L), false); + + new EqualsTester().addEqualityGroup(l1, l2) + .addEqualityGroup(l3, l4) + .testEquals(); + } + + @Test + public void basics() { + HostLocation hostLocation = new HostLocation(DID1, P1, 123L); + EdgeLink link = new DefaultEdgeLink(PID, cp(HID1, P0), hostLocation, false); + assertEquals("incorrect src", cp(HID1, P0), link.dst()); + assertEquals("incorrect dst", hostLocation, link.src()); + assertEquals("incorrect type", Link.Type.EDGE, link.type()); + assertEquals("incorrect hostId", HID1, link.hostId()); + assertEquals("incorrect connect point", hostLocation, link.hostLocation()); + assertEquals("incorrect time", 123L, link.hostLocation().time()); + } + + @Test + public void phantomIngress() { + HostLocation hostLocation = new HostLocation(DID1, P1, 123L); + EdgeLink link = createEdgeLink(hostLocation, true); + assertEquals("incorrect dst", hostLocation, link.dst()); + assertEquals("incorrect type", Link.Type.EDGE, link.type()); + assertEquals("incorrect connect point", hostLocation, link.hostLocation()); + assertEquals("incorrect time", 123L, link.hostLocation().time()); + } + + @Test + public void phantomEgress() { + ConnectPoint hostLocation = new ConnectPoint(DID1, P1); + EdgeLink link = createEdgeLink(hostLocation, false); + assertEquals("incorrect src", hostLocation, link.src()); + assertEquals("incorrect type", Link.Type.EDGE, link.type()); + assertEquals("incorrect connect point", hostLocation, link.hostLocation()); + assertEquals("incorrect time", 0L, link.hostLocation().time()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultHostTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultHostTest.java new file mode 100644 index 00000000..1fb6da5a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultHostTest.java @@ -0,0 +1,51 @@ +/* + * 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.net; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +public class DefaultHostTest extends TestDeviceParams { + + @Test + public void testEquality() { + Host h1 = new DefaultHost(PID, HID1, MAC1, VLAN1, LOC1, IPSET1); + Host h2 = new DefaultHost(PID, HID1, MAC1, VLAN1, LOC1, IPSET1); + Host h3 = new DefaultHost(PID, HID2, MAC2, VLAN2, LOC2, IPSET2); + Host h4 = new DefaultHost(PID, HID2, MAC2, VLAN2, LOC2, IPSET2); + Host h5 = new DefaultHost(PID, HID2, MAC2, VLAN1, LOC2, IPSET1); + + new EqualsTester().addEqualityGroup(h1, h2) + .addEqualityGroup(h3, h4) + .addEqualityGroup(h5) + .testEquals(); + } + + @Test + public void basics() { + Host host = new DefaultHost(PID, HID1, MAC1, VLAN1, LOC1, IPSET1); + assertEquals("incorrect provider", PID, host.providerId()); + assertEquals("incorrect id", HID1, host.id()); + assertEquals("incorrect type", MAC1, host.mac()); + assertEquals("incorrect VLAN", VLAN1, host.vlan()); + assertEquals("incorrect location", LOC1, host.location()); + assertEquals("incorrect IP's", IPSET1, host.ipAddresses()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultLinkTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultLinkTest.java new file mode 100644 index 00000000..bd5821bb --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultLinkTest.java @@ -0,0 +1,65 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.provider.ProviderId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; +import static org.onosproject.net.Link.Type.INDIRECT; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the default link model entity. + */ +public class DefaultLinkTest { + + private static final ProviderId PID = new ProviderId("of", "foo"); + private static final DeviceId DID1 = deviceId("of:foo"); + private static final DeviceId DID2 = deviceId("of:bar"); + private static final PortNumber P1 = portNumber(1); + private static final PortNumber P2 = portNumber(2); + + public static ConnectPoint cp(ElementId id, PortNumber pn) { + return new ConnectPoint(id, pn); + } + + @Test + public void testEquality() { + Link l1 = new DefaultLink(PID, cp(DID1, P1), cp(DID2, P2), DIRECT); + Link l2 = new DefaultLink(PID, cp(DID1, P1), cp(DID2, P2), DIRECT); + Link l3 = new DefaultLink(PID, cp(DID1, P2), cp(DID2, P2), DIRECT); + Link l4 = new DefaultLink(PID, cp(DID1, P2), cp(DID2, P2), DIRECT); + Link l5 = new DefaultLink(PID, cp(DID1, P2), cp(DID2, P2), INDIRECT); + + new EqualsTester().addEqualityGroup(l1, l2) + .addEqualityGroup(l3, l4) + .addEqualityGroup(l5) + .testEquals(); + } + + @Test + public void basics() { + Link link = new DefaultLink(PID, cp(DID1, P1), cp(DID2, P2), DIRECT); + assertEquals("incorrect src", cp(DID1, P1), link.src()); + assertEquals("incorrect dst", cp(DID2, P2), link.dst()); + assertEquals("incorrect type", DIRECT, link.type()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultPortTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultPortTest.java new file mode 100644 index 00000000..592115d7 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DefaultPortTest.java @@ -0,0 +1,70 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.provider.ProviderId; +import org.onlab.packet.ChassisId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.Device.Type.SWITCH; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Port.Type.COPPER; +import static org.onosproject.net.Port.Type.FIBER; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the default port model entity. + */ +public class DefaultPortTest { + + private static final ProviderId PID = new ProviderId("of", "foo"); + private static final DeviceId DID1 = deviceId("of:foo"); + private static final DeviceId DID2 = deviceId("of:bar"); + private static final PortNumber P1 = portNumber(1); + private static final PortNumber P2 = portNumber(2); + private static final long SP1 = 1_000_000; + + @Test + public void testEquality() { + Device device = new DefaultDevice(PID, DID1, SWITCH, "m", "h", "s", "n", + new ChassisId()); + Port p1 = new DefaultPort(device, portNumber(1), true, COPPER, SP1); + Port p2 = new DefaultPort(device, portNumber(1), true, COPPER, SP1); + Port p3 = new DefaultPort(device, portNumber(2), true, FIBER, SP1); + Port p4 = new DefaultPort(device, portNumber(2), true, FIBER, SP1); + Port p5 = new DefaultPort(device, portNumber(1), false); + + new EqualsTester().addEqualityGroup(p1, p2) + .addEqualityGroup(p3, p4) + .addEqualityGroup(p5) + .testEquals(); + } + + @Test + public void basics() { + Device device = new DefaultDevice(PID, DID1, SWITCH, "m", "h", "s", "n", + new ChassisId()); + Port port = new DefaultPort(device, portNumber(1), true, FIBER, SP1); + assertEquals("incorrect element", device, port.element()); + assertEquals("incorrect number", portNumber(1), port.number()); + assertEquals("incorrect state", true, port.isEnabled()); + assertEquals("incorrect speed", SP1, port.portSpeed()); + assertEquals("incorrect type", FIBER, port.type()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java new file mode 100644 index 00000000..ab5373f8 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/DeviceIdTest.java @@ -0,0 +1,37 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static org.onosproject.net.DeviceId.deviceId; + +/** + * Test of the device identifier. + */ +public class DeviceIdTest { + + @Test + public void basics() { + new EqualsTester() + .addEqualityGroup(deviceId("of:foo"), + deviceId("of:foo")) + .addEqualityGroup(deviceId("of:bar")) + .testEquals(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/HostIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/HostIdTest.java new file mode 100644 index 00000000..43425e21 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/HostIdTest.java @@ -0,0 +1,44 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; + +import org.junit.Test; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; + +import static org.onosproject.net.HostId.hostId; + +/** + * Test for the host identifier. + */ +public class HostIdTest { + + private static final MacAddress MAC1 = MacAddress.valueOf("00:11:00:00:00:01"); + private static final MacAddress MAC2 = MacAddress.valueOf("00:22:00:00:00:02"); + private static final VlanId VLAN1 = VlanId.vlanId((short) 11); + private static final VlanId VLAN2 = VlanId.vlanId((short) 22); + + @Test + public void basics() { + new EqualsTester() + .addEqualityGroup(hostId(MAC1, VLAN1), hostId(MAC1, VLAN1)) + .addEqualityGroup(hostId(MAC2, VLAN2), hostId(MAC2, VLAN2)) + .testEquals(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/IndexedLambdaTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/IndexedLambdaTest.java new file mode 100644 index 00000000..8cbe8232 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/IndexedLambdaTest.java @@ -0,0 +1,35 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +/** + * Test for IndexedLambda. + */ +public class IndexedLambdaTest { + /** + * Tests equality of IndexedLambda instances. + */ + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(Lambda.indexedLambda(10), Lambda.indexedLambda(10)) + .addEqualityGroup(Lambda.indexedLambda(11), Lambda.indexedLambda(11), Lambda.indexedLambda(11)) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/LinkKeyTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/LinkKeyTest.java new file mode 100644 index 00000000..4dfc1399 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/LinkKeyTest.java @@ -0,0 +1,129 @@ +/* + * 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.net; + +import org.junit.Test; + +import static org.hamcrest.CoreMatchers.allOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Unit tests for the LinkKey class. + */ +public class LinkKeyTest { + + static final DeviceId D1 = deviceId("1"); + static final DeviceId D2 = deviceId("2"); + static final PortNumber P1 = portNumber(1); + static final PortNumber P2 = portNumber(2); + + static final ConnectPoint SRC1 = new ConnectPoint(D1, P1); + static final ConnectPoint DST1 = new ConnectPoint(D2, P1); + static final ConnectPoint DST2 = new ConnectPoint(D2, P2); + + + /** + * Checks that the LinkKey class is immutable. + */ + @Test + public void testLinkKeyImmutability() { + assertThatClassIsImmutable(LinkKey.class); + } + + /** + * Check null source connection. + */ + @Test(expected = NullPointerException.class) + public void testNullSrc() { + LinkKey key = LinkKey.linkKey(null, DST1); + } + + /** + * Check null destination connection. + */ + @Test(expected = NullPointerException.class) + public void testNullDst() { + LinkKey key = LinkKey.linkKey(SRC1, null); + } + + /** + * Check that two LinkKeys based on the same source/destination pair compare + * equal. + */ + @Test + public void testCompareEquals() { + LinkKey k1 = LinkKey.linkKey(SRC1, DST2); + LinkKey k2 = LinkKey.linkKey(SRC1, DST2); + + assertThat(k1, is(equalTo(k2))); + } + + /** + * Check that two LinkKeys based on different source/destination pairs compare + * not equal. + */ + @Test + public void testCompareNotEquals() { + LinkKey k1 = LinkKey.linkKey(SRC1, DST1); + LinkKey k2 = LinkKey.linkKey(SRC1, DST2); + + assertThat(k1, is(not(equalTo(k2)))); + assertThat(k1, is(not(equalTo(new Object())))); + } + + /** + * Check that two LinkKeys based on the same source/destination pair compare + * equal. + */ + @Test + public void testHashCodeEquals() { + LinkKey k1 = LinkKey.linkKey(SRC1, DST2); + LinkKey k2 = LinkKey.linkKey(SRC1, DST2); + + assertThat(k1.hashCode(), is(equalTo(k2.hashCode()))); + } + + /** + * Check that two LinkKeys based on different source/destination pairs compare + * not equal. + */ + @Test + public void testHashCodeNotEquals() { + LinkKey k1 = LinkKey.linkKey(SRC1, DST1); + LinkKey k2 = LinkKey.linkKey(SRC1, DST2); + + assertThat(k1.hashCode(), is(not(equalTo(k2.hashCode())))); + } + + /** + * Check the toString() method of LinkKey. + */ + @Test + public void testToString() { + LinkKey k1 = LinkKey.linkKey(SRC1, DST1); + String k1String = k1.toString(); + assertThat(k1String, allOf(containsString("LinkKey{"), + containsString("src=ConnectPoint{elementId=1, portNumber=1}"), + containsString("dst=ConnectPoint{elementId=2, portNumber=1}"))); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/NetTestTools.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/NetTestTools.java new file mode 100644 index 00000000..176fe40c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/NetTestTools.java @@ -0,0 +1,138 @@ +/* + * 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.net; + +import org.onlab.junit.TestUtils; +import org.onlab.packet.ChassisId; +import org.onosproject.TestApplicationId; +import org.onosproject.core.ApplicationId; +import org.onosproject.event.EventDeliveryService; +import org.onosproject.net.provider.ProviderId; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.onlab.packet.MacAddress.valueOf; +import static org.onlab.packet.VlanId.vlanId; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.HostId.hostId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Miscellaneous tools for testing core related to the network model. + */ +public final class NetTestTools { + + private NetTestTools() { + } + + public static final ProviderId PID = new ProviderId("of", "foo"); + public static final ApplicationId APP_ID = new TestApplicationId("foo"); + + // Short-hand for producing a device id from a string + public static DeviceId did(String id) { + return deviceId("of:" + id); + } + + + // Short-hand for producing a host id from a string + public static HostId hid(String id) { + return hostId(id); + } + + // Crates a new device with the specified id + public static Device device(String id) { + return new DefaultDevice(PID, did(id), Device.Type.SWITCH, + "mfg", "1.0", "1.1", "1234", new ChassisId()); + } + + // Crates a new host with the specified id + public static Host host(String id, String did) { + return new DefaultHost(PID, hid(id), valueOf(1234), vlanId((short) 2), + new HostLocation(did(did), portNumber(1), 321), + new HashSet<>()); + } + + // Short-hand for creating a connection point. + public static ConnectPoint connectPoint(String id, int port) { + return new ConnectPoint(did(id), portNumber(port)); + } + + // Short-hand for creating a link. + public static Link link(String src, int sp, String dst, int dp) { + return new DefaultLink(PID, + connectPoint(src, sp), + connectPoint(dst, dp), + Link.Type.DIRECT); + } + + // Creates a path that leads through the given devices. + public static Path createPath(String... ids) { + List<Link> links = new ArrayList<>(); + for (int i = 0; i < ids.length - 1; i++) { + links.add(link(ids[i], i, ids[i + 1], i)); + } + return new DefaultPath(PID, links, ids.length); + } + + // Creates OCh signal + public static OchSignal createLambda() { + return new OchSignal(GridType.DWDM, ChannelSpacing.CHL_6P25GHZ, 8, 4); + } + + /** + * Verifies that Annotations created by merging {@code annotations} is + * equal to actual Annotations. + * + * @param actual annotations to check + * @param annotations expected annotations + */ + public static void assertAnnotationsEquals(Annotations actual, SparseAnnotations... annotations) { + DefaultAnnotations expected = DefaultAnnotations.builder().build(); + for (SparseAnnotations a : annotations) { + expected = DefaultAnnotations.merge(expected, a); + } + assertEquals(expected.keys(), actual.keys()); + for (String key : expected.keys()) { + assertEquals(expected.value(key), actual.value(key)); + } + } + + /** + * Injects the given event delivery service into the specified manager + * component. + * + * @param manager manager component + * @param svc service reference to be injected + */ + public static void injectEventDispatcher(Object manager, EventDeliveryService svc) { + Class mc = manager.getClass(); + for (Field f : mc.getSuperclass().getDeclaredFields()) { + if (f.getType().equals(EventDeliveryService.class)) { + try { + TestUtils.setField(manager, f.getName(), svc); + } catch (TestUtils.TestUtilsException e) { + throw new IllegalArgumentException("Unable to inject reference", e); + } + break; + } + } + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/OchSignalTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/OchSignalTest.java new file mode 100644 index 00000000..c171d523 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/OchSignalTest.java @@ -0,0 +1,40 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Test for OchSignal. + */ +public class OchSignalTest { + + private final Lambda och1 = Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 1, 1); + private final Lambda sameOch1 = Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 1, 1); + private final Lambda och2 = Lambda.ochSignal(GridType.CWDM, ChannelSpacing.CHL_6P25GHZ, 4, 1); + private final Lambda sameOch2 = Lambda.ochSignal(GridType.CWDM, ChannelSpacing.CHL_6P25GHZ, 4, 1); + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(och1, sameOch1) + .addEqualityGroup(och2, sameOch2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/PortNumberTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/PortNumberTest.java new file mode 100644 index 00000000..6f7b2c2d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/PortNumberTest.java @@ -0,0 +1,43 @@ +/* + * 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.net; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the port number. + */ +public class PortNumberTest { + + @Test + public void basics() { + new EqualsTester() + .addEqualityGroup(portNumber(123), portNumber("123")) + .addEqualityGroup(portNumber(321), portNumber(321, "LIM-3-2-1")) + .testEquals(); + } + + @Test + public void number() { + assertEquals("incorrect long value", 12345, portNumber(12345).toLong()); + } + + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/TestDeviceParams.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/TestDeviceParams.java new file mode 100644 index 00000000..2d8aae3c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/TestDeviceParams.java @@ -0,0 +1,55 @@ +/* + * 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.net; + +import static org.onosproject.net.DeviceId.deviceId; + +import java.util.Set; + +import org.onosproject.net.provider.ProviderId; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; + +import com.google.common.collect.Sets; + +/** + * Provides a set of test DefaultDevice parameters for use with Host- + * related tests. + */ +public abstract class TestDeviceParams { + + protected static final ProviderId PID = new ProviderId("of", "foo"); + protected static final DeviceId DID1 = deviceId("of:foo"); + protected static final DeviceId DID2 = deviceId("of:bar"); + protected static final MacAddress MAC1 = MacAddress.valueOf("00:11:00:00:00:01"); + protected static final MacAddress MAC2 = MacAddress.valueOf("00:22:00:00:00:02"); + protected static final VlanId VLAN1 = VlanId.vlanId((short) 11); + protected static final VlanId VLAN2 = VlanId.vlanId((short) 22); + protected static final IpAddress IP1 = IpAddress.valueOf("10.0.0.1"); + protected static final IpAddress IP2 = IpAddress.valueOf("10.0.0.2"); + protected static final IpAddress IP3 = IpAddress.valueOf("10.0.0.3"); + + protected static final PortNumber P1 = PortNumber.portNumber(100); + protected static final PortNumber P2 = PortNumber.portNumber(200); + protected static final HostId HID1 = HostId.hostId(MAC1, VLAN1); + protected static final HostId HID2 = HostId.hostId(MAC2, VLAN2); + protected static final HostLocation LOC1 = new HostLocation(DID1, P1, 123L); + protected static final HostLocation LOC2 = new HostLocation(DID2, P2, 123L); + protected static final Set<IpAddress> IPSET1 = Sets.newHashSet(IP1, IP2); + protected static final Set<IpAddress> IPSET2 = Sets.newHashSet(IP1, IP3); + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigRegistryAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigRegistryAdapter.java new file mode 100644 index 00000000..6201c0b6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigRegistryAdapter.java @@ -0,0 +1,42 @@ +/* + * 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.net.config; + +import java.util.Set; + +/** + * Test adapter for network configuration service registry. + */ +public class NetworkConfigRegistryAdapter extends NetworkConfigServiceAdapter implements NetworkConfigRegistry { + + public void registerConfigFactory(ConfigFactory configFactory) { + } + + public void unregisterConfigFactory(ConfigFactory configFactory) { + } + + public Set<ConfigFactory> getConfigFactories() { + return null; + } + + public <S, C extends Config<S>> Set<ConfigFactory<S, C>> getConfigFactories(Class<S> subjectClass) { + return null; + } + + public <S, C extends Config<S>> ConfigFactory<S, C> getConfigFactory(Class<C> configClass) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigServiceAdapter.java new file mode 100644 index 00000000..b70d14e8 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/config/NetworkConfigServiceAdapter.java @@ -0,0 +1,90 @@ +/* + * 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.net.config; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.Set; + +/** + * Test adapter for network configuration service. + */ +public class NetworkConfigServiceAdapter implements NetworkConfigService { + @Override + public Set<Class> getSubjectClasses() { + return null; + } + + @Override + public SubjectFactory getSubjectFactory(String subjectKey) { + return null; + } + + @Override + public SubjectFactory getSubjectFactory(Class subjectClass) { + return null; + } + + @Override + public Class<? extends Config> getConfigClass(String subjectKey, String configKey) { + return null; + } + + @Override + public <S> Set<S> getSubjects(Class<S> subjectClass) { + return null; + } + + @Override + public <S, C extends Config<S>> Set<S> getSubjects(Class<S> subjectClass, Class<C> configClass) { + return null; + } + + @Override + public <S> Set<? extends Config<S>> getConfigs(S subject) { + return null; + } + + @Override + public <S, C extends Config<S>> C getConfig(S subject, Class<C> configClass) { + return null; + } + + @Override + public <S, C extends Config<S>> C addConfig(S subject, Class<C> configClass) { + return null; + } + + @Override + public <S, C extends Config<S>> C applyConfig(S subject, Class<C> configClass, JsonNode json) { + return null; + } + + @Override + public <S, C extends Config<S>> void removeConfig(S subject, Class<C> configClass) { + + } + + @Override + public void addListener(NetworkConfigListener listener) { + + } + + @Override + public void removeListener(NetworkConfigListener listener) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultDeviceDescriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultDeviceDescriptionTest.java new file mode 100644 index 00000000..3dcdc22d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultDeviceDescriptionTest.java @@ -0,0 +1,54 @@ +/* + * 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.net.device; + +import org.junit.Test; +import org.onlab.packet.ChassisId; + +import java.net.URI; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.net.Device.Type.SWITCH; + +/** + * Test of the default device description. + */ +public class DefaultDeviceDescriptionTest { + + private static final URI DURI = URI.create("of:foo"); + private static final String MFR = "whitebox"; + private static final String HW = "1.1.x"; + private static final String SW = "3.9.1"; + private static final String SN = "43311-12345"; + private static final ChassisId CID = new ChassisId(); + + + @Test + public void basics() { + DeviceDescription device = + new DefaultDeviceDescription(DURI, SWITCH, MFR, HW, SW, SN, CID); + assertEquals("incorrect uri", DURI, device.deviceURI()); + assertEquals("incorrect type", SWITCH, device.type()); + assertEquals("incorrect manufacturer", MFR, device.manufacturer()); + assertEquals("incorrect hw", HW, device.hwVersion()); + assertEquals("incorrect sw", SW, device.swVersion()); + assertEquals("incorrect serial", SN, device.serialNumber()); + assertTrue("incorrect toString", device.toString().contains("uri=of:foo")); + assertTrue("Incorrect chassis", device.chassisId().value() == 0); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultPortStatisticsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultPortStatisticsTest.java new file mode 100644 index 00000000..b691ebc3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DefaultPortStatisticsTest.java @@ -0,0 +1,126 @@ +/* + * 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.net.device; + +import java.lang.reflect.Constructor; +import java.util.Arrays; + +import org.junit.Assert; +import org.junit.Test; +import org.onosproject.net.NetTestTools; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * DefaultPortStatistics unit tests. + */ +public class DefaultPortStatisticsTest { + + private final PortStatistics stats1 = DefaultPortStatistics.builder() + .setBytesReceived(1) + .setBytesSent(2) + .setDurationNano(3) + .setDurationSec(4) + .setPacketsReceived(5) + .setPacketsSent(6) + .setPacketsRxDropped(7) + .setPacketsRxErrors(8) + .setPacketsTxDropped(9) + .setPacketsTxErrors(10) + .setPort(80) + .setDeviceId(NetTestTools.did("1")) + .build(); + + private final PortStatistics stats2 = DefaultPortStatistics.builder() + .setBytesReceived(1) + .setBytesSent(2) + .setDurationNano(3) + .setDurationSec(4) + .setPacketsReceived(5) + .setPacketsSent(6) + .setPacketsRxDropped(7) + .setPacketsRxErrors(8) + .setPacketsTxDropped(9) + .setPacketsTxErrors(11) + .setPort(80) + .setDeviceId(NetTestTools.did("1")) + .build(); + + /** + * Checks that the GroupOperation class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(DefaultPortStatistics.class); + } + + @Test + public void testConstruction() { + assertThat(stats1.bytesReceived(), is(1L)); + assertThat(stats1.bytesSent(), is(2L)); + assertThat(stats1.durationNano(), is(3L)); + assertThat(stats1.durationSec(), is(4L)); + assertThat(stats1.packetsReceived(), is(5L)); + assertThat(stats1.packetsSent(), is(6L)); + assertThat(stats1.packetsRxDropped(), is(7L)); + assertThat(stats1.packetsRxErrors(), is(8L)); + assertThat(stats1.packetsTxDropped(), is(9L)); + assertThat(stats1.packetsTxErrors(), is(10L)); + assertThat(stats1.port(), is(80)); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(stats1, stats1) + .addEqualityGroup(stats2) + .testEquals(); + } + + /** + * Tests that the empty argument list constructor for serialization + * is present and creates a proper object. + */ + @Test + public void testSerializerConstructor() { + try { + Constructor[] constructors = DefaultPortStatistics.class.getDeclaredConstructors(); + assertThat(constructors, notNullValue()); + Arrays.stream(constructors).filter(ctor -> + ctor.getParameterTypes().length == 0) + .forEach(noParamsCtor -> { + try { + noParamsCtor.setAccessible(true); + DefaultPortStatistics stats = + (DefaultPortStatistics) noParamsCtor.newInstance(); + assertThat(stats, notNullValue()); + } catch (Exception e) { + Assert.fail("Exception instantiating no parameters constructor"); + } + }); + } catch (Exception e) { + Assert.fail("Exception looking up constructors"); + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceClockServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceClockServiceAdapter.java new file mode 100644 index 00000000..5bfdd76b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceClockServiceAdapter.java @@ -0,0 +1,21 @@ +package org.onosproject.net.device; + +import org.onosproject.net.DeviceId; +import org.onosproject.store.Timestamp; + +/** + * Test adapter for device clock service. + */ +public class DeviceClockServiceAdapter implements DeviceClockService { + + @Override + public boolean isTimestampAvailable(DeviceId deviceId) { + return false; + } + + @Override + public Timestamp getTimestamp(DeviceId deviceId) { + return null; + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceEventTest.java new file mode 100644 index 00000000..a0fb9358 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceEventTest.java @@ -0,0 +1,63 @@ +/* + * 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.net.device; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DeviceId.deviceId; + +import org.junit.Test; +import org.onosproject.event.AbstractEventTest; +import org.onosproject.net.DefaultDevice; +import org.onosproject.net.DefaultPort; +import org.onosproject.net.Device; +import org.onosproject.net.Port; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; +import org.onlab.packet.ChassisId; + +/** + * Tests of the device event. + */ +public class DeviceEventTest extends AbstractEventTest { + + private Device createDevice() { + return new DefaultDevice(new ProviderId("of", "foo"), deviceId("of:foo"), + Device.Type.SWITCH, "box", "hw", "sw", "sn", new ChassisId()); + } + + @Override + @Test + public void withTime() { + Device device = createDevice(); + Port port = new DefaultPort(device, PortNumber.portNumber(123), true); + DeviceEvent event = new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, + device, port, 123L); + validateEvent(event, DeviceEvent.Type.DEVICE_ADDED, device, 123L); + assertEquals("incorrect port", port, event.port()); + } + + @Override + @Test + public void withoutTime() { + Device device = createDevice(); + Port port = new DefaultPort(device, PortNumber.portNumber(123), true); + long before = System.currentTimeMillis(); + DeviceEvent event = new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, device, port); + long after = System.currentTimeMillis(); + validateEvent(event, DeviceEvent.Type.DEVICE_ADDED, device, before, after); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceServiceAdapter.java new file mode 100644 index 00000000..795e4c0a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/device/DeviceServiceAdapter.java @@ -0,0 +1,110 @@ +/* + * 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.net.device; + +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; + +import org.onosproject.net.Device; +import org.onosproject.net.Device.Type; +import org.onosproject.net.DeviceId; +import org.onosproject.net.MastershipRole; +import org.onosproject.net.Port; +import org.onosproject.net.PortNumber; + +import java.util.Collections; +import java.util.List; + +/** + * Test adapter for device service. + */ +public class DeviceServiceAdapter implements DeviceService { + @Override + public int getDeviceCount() { + return 0; + } + + @Override + public Iterable<Device> getDevices() { + return Collections.emptyList(); + } + + @Override + public Iterable<Device> getAvailableDevices() { + return FluentIterable.from(getDevices()) + .filter(new Predicate<Device>() { + + @Override + public boolean apply(Device input) { + return isAvailable(input.id()); + } + }); + } + + @Override + public Device getDevice(DeviceId deviceId) { + return null; + } + + @Override + public MastershipRole getRole(DeviceId deviceId) { + return MastershipRole.NONE; + } + + @Override + public List<Port> getPorts(DeviceId deviceId) { + return Collections.emptyList(); + } + + @Override + public List<PortStatistics> getPortStatistics(DeviceId deviceId) { + return null; + } + + @Override + public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) { + return null; + } + + @Override + public Port getPort(DeviceId deviceId, PortNumber portNumber) { + return null; + } + + @Override + public boolean isAvailable(DeviceId deviceId) { + return false; + } + + @Override + public void addListener(DeviceListener listener) { + } + + @Override + public void removeListener(DeviceListener listener) { + } + + @Override + public Iterable<Device> getDevices(Type type) { + return Collections.emptyList(); + } + + @Override + public Iterable<Device> getAvailableDevices(Type type) { + return Collections.emptyList(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverDataTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverDataTest.java new file mode 100644 index 00000000..e3d69109 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverDataTest.java @@ -0,0 +1,78 @@ +/* + * 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.net.driver; + +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.DeviceId; + +import static org.junit.Assert.*; +import static org.onosproject.net.DeviceId.deviceId; + +public class DefaultDriverDataTest { + + public static final DeviceId DEVICE_ID = deviceId("of:0011223344556677"); + + DefaultDriver ddc; + DefaultDriverData data; + + @Before + public void setUp() { + ddc = new DefaultDriver("foo.bar", null, "Circus", "lux", "1.2a", + ImmutableMap.of(TestBehaviour.class, + TestBehaviourImpl.class), + ImmutableMap.of("foo", "bar")); + data = new DefaultDriverData(ddc, DEVICE_ID); + } + + @Test + public void basics() { + assertSame("incorrect driver", ddc, data.driver()); + assertEquals("incorrect device id", DEVICE_ID, data.deviceId()); + assertTrue("incorrect toString", data.toString().contains("foo.bar")); + } + + @Test + public void behaviour() { + TestBehaviour behaviour = data.behaviour(TestBehaviour.class); + assertTrue("incorrect behaviour", behaviour instanceof TestBehaviourImpl); + } + + @Test + public void setAndClearAnnotations() { + data.set("croc", "aqua"); + data.set("roo", "mars"); + data.set("dingo", "bat"); + assertEquals("incorrect property", "bat", data.value("dingo")); + data.clear("dingo", "roo"); + assertNull("incorrect property", data.value("dingo")); + assertNull("incorrect property", data.value("root")); + assertEquals("incorrect property", "aqua", data.value("croc")); + assertEquals("incorrect properties", 1, data.keys().size()); + } + + @Test + public void clearAllAnnotations() { + data.set("croc", "aqua"); + data.set("roo", "mars"); + data.set("dingo", "bat"); + assertEquals("incorrect property", "bat", data.value("dingo")); + data.clear(); + assertEquals("incorrect properties", 0, data.keys().size()); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverHandlerTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverHandlerTest.java new file mode 100644 index 00000000..717cda2e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverHandlerTest.java @@ -0,0 +1,55 @@ +/* + * 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.net.driver; + +import com.google.common.collect.ImmutableMap; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +public class DefaultDriverHandlerTest { + + DefaultDriver ddc; + DefaultDriverData data; + DefaultDriverHandler handler; + + @Before + public void setUp() { + ddc = new DefaultDriver("foo.bar", null, "Circus", "lux", "1.2a", + ImmutableMap.of(TestBehaviour.class, + TestBehaviourImpl.class, + TestBehaviourTwo.class, + TestBehaviourTwoImpl.class), + ImmutableMap.of("foo", "bar")); + data = new DefaultDriverData(ddc, DefaultDriverDataTest.DEVICE_ID); + handler = new DefaultDriverHandler(data); + } + + @Test + public void basics() { + assertSame("incorrect data", data, handler.data()); + assertTrue("incorrect toString", handler.toString().contains("1.2a")); + } + + @Test + public void behaviour() { + TestBehaviourTwo behaviour = handler.behaviour(TestBehaviourTwo.class); + assertTrue("incorrect behaviour", behaviour instanceof TestBehaviourTwoImpl); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverProviderTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverProviderTest.java new file mode 100644 index 00000000..4568fd92 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverProviderTest.java @@ -0,0 +1,49 @@ +/* + * 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.net.driver; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; + +import java.util.Set; + +import static com.google.common.collect.ImmutableSet.of; +import static org.junit.Assert.assertEquals; + +public class DefaultDriverProviderTest { + + @Test + public void basics() { + DefaultDriverProvider ddp = new DefaultDriverProvider(); + DefaultDriver one = new DefaultDriver("foo.bar", null, "Circus", "lux", "1.2a", + ImmutableMap.of(TestBehaviour.class, + TestBehaviourImpl.class), + ImmutableMap.of("foo", "bar")); + DefaultDriver two = new DefaultDriver("foo.bar", null, "", "", "", + ImmutableMap.of(TestBehaviourTwo.class, + TestBehaviourTwoImpl.class), + ImmutableMap.of("goo", "wee")); + DefaultDriver three = new DefaultDriver("goo.foo", null, "BigTop", "better", "2.2", + ImmutableMap.of(TestBehaviourTwo.class, + TestBehaviourTwoImpl.class), + ImmutableMap.of("goo", "gee")); + + ddp.addDrivers(of(one, two, three)); + + Set<Driver> drivers = ddp.getDrivers(); + assertEquals("incorrect types", 2, drivers.size()); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverTest.java new file mode 100644 index 00000000..01cc7a16 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/DefaultDriverTest.java @@ -0,0 +1,89 @@ +/* + * 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.net.driver; + +import com.google.common.collect.ImmutableMap; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.net.driver.DefaultDriverDataTest.DEVICE_ID; + +public class DefaultDriverTest { + + @Test + public void basics() { + DefaultDriver ddp = new DefaultDriver("foo.base", null, "Circus", "lux", "1.2a", + ImmutableMap.of(TestBehaviour.class, + TestBehaviourImpl.class, + TestBehaviourTwo.class, + TestBehaviourTwoImpl.class), + ImmutableMap.of("foo", "bar")); + + DefaultDriver ddc = new DefaultDriver("foo.bar", ddp, "Circus", "lux", "1.2a", + ImmutableMap.of(), + ImmutableMap.of("foo", "bar")); + assertEquals("incorrect name", "foo.bar", ddc.name()); + assertEquals("incorrect parent", ddp, ddc.parent()); + assertEquals("incorrect mfr", "Circus", ddc.manufacturer()); + assertEquals("incorrect hw", "lux", ddc.hwVersion()); + assertEquals("incorrect sw", "1.2a", ddc.swVersion()); + + assertEquals("incorrect behaviour count", 2, ddp.behaviours().size()); + assertEquals("incorrect behaviour count", 0, ddc.behaviours().size()); + assertTrue("incorrect behaviour", ddc.hasBehaviour(TestBehaviour.class)); + + Behaviour b1 = ddc.createBehaviour(new DefaultDriverData(ddc, DEVICE_ID), TestBehaviour.class); + assertTrue("incorrect behaviour class", b1 instanceof TestBehaviourImpl); + + Behaviour b2 = ddc.createBehaviour(new DefaultDriverHandler(new DefaultDriverData(ddc, DEVICE_ID)), + TestBehaviourTwo.class); + assertTrue("incorrect behaviour class", b2 instanceof TestBehaviourTwoImpl); + + assertEquals("incorrect property count", 1, ddc.properties().size()); + assertEquals("incorrect key count", 1, ddc.keys().size()); + assertEquals("incorrect property", "bar", ddc.value("foo")); + + assertTrue("incorrect toString", ddc.toString().contains("lux")); + } + + @Test + public void merge() { + DefaultDriver one = new DefaultDriver("foo.bar", null, "Circus", "lux", "1.2a", + ImmutableMap.of(TestBehaviour.class, + TestBehaviourImpl.class), + ImmutableMap.of("foo", "bar")); + Driver ddc = + one.merge(new DefaultDriver("foo.bar", null, "", "", "", + ImmutableMap.of(TestBehaviourTwo.class, + TestBehaviourTwoImpl.class), + ImmutableMap.of("goo", "wee"))); + + assertEquals("incorrect name", "foo.bar", ddc.name()); + assertEquals("incorrect mfr", "Circus", ddc.manufacturer()); + assertEquals("incorrect hw", "lux", ddc.hwVersion()); + assertEquals("incorrect sw", "1.2a", ddc.swVersion()); + + assertEquals("incorrect behaviour count", 2, ddc.behaviours().size()); + assertTrue("incorrect behaviour", ddc.hasBehaviour(TestBehaviourTwo.class)); + + assertEquals("incorrect property count", 2, ddc.properties().size()); + assertEquals("incorrect key count", 2, ddc.keys().size()); + assertEquals("incorrect property", "wee", ddc.value("goo")); + + assertTrue("incorrect toString", ddc.toString().contains("Circus")); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviour.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviour.java new file mode 100644 index 00000000..632fae15 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviour.java @@ -0,0 +1,22 @@ +/* + * 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.net.driver; + +/** + * Test behaviour. + */ +public interface TestBehaviour extends Behaviour { +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourImpl.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourImpl.java new file mode 100644 index 00000000..ec5c66bc --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourImpl.java @@ -0,0 +1,22 @@ +/* + * 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.net.driver; + +/** + * Test behaviour. + */ +public class TestBehaviourImpl extends AbstractBehaviour implements TestBehaviour { +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourNoConstructorImpl.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourNoConstructorImpl.java new file mode 100644 index 00000000..20452368 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourNoConstructorImpl.java @@ -0,0 +1,26 @@ +/* + * 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.net.driver; + +/** + * Bad test behaviour. + */ +public final class TestBehaviourNoConstructorImpl + extends AbstractBehaviour implements TestBehaviour { + private TestBehaviourNoConstructorImpl() { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwo.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwo.java new file mode 100644 index 00000000..3399f00c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwo.java @@ -0,0 +1,22 @@ +/* + * 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.net.driver; + +/** + * Test behaviour. + */ +public interface TestBehaviourTwo extends HandlerBehaviour { +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwoImpl.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwoImpl.java new file mode 100644 index 00000000..746bcc87 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/TestBehaviourTwoImpl.java @@ -0,0 +1,22 @@ +/* + * 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.net.driver; + +/** + * Test behaviour. + */ +public class TestBehaviourTwoImpl extends AbstractHandlerBehaviour implements TestBehaviourTwo { +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/XmlDriverLoaderTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/XmlDriverLoaderTest.java new file mode 100644 index 00000000..f54e7411 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/driver/XmlDriverLoaderTest.java @@ -0,0 +1,80 @@ +/* + * 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.net.driver; + +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.net.driver.DefaultDriverDataTest.DEVICE_ID; + +/** + * Tests of the XML driver loader implementation. + */ +public class XmlDriverLoaderTest { + + @Test + public void basics() throws IOException { + XmlDriverLoader loader = new XmlDriverLoader(getClass().getClassLoader()); + InputStream stream = getClass().getResourceAsStream("drivers.1.xml"); + DriverProvider provider = loader.loadDrivers(stream, null); + System.out.println(provider); + assertEquals("incorrect driver count", 2, provider.getDrivers().size()); + + Iterator<Driver> iterator = provider.getDrivers().iterator(); + Driver driver = iterator.next(); + if (!driver.name().equals("foo.1")) { + driver = iterator.next(); + } + + assertEquals("incorrect driver name", "foo.1", driver.name()); + assertEquals("incorrect driver mfg", "Circus", driver.manufacturer()); + assertEquals("incorrect driver hw", "1.2a", driver.hwVersion()); + assertEquals("incorrect driver sw", "2.2", driver.swVersion()); + + assertEquals("incorrect driver behaviours", 1, driver.behaviours().size()); + assertTrue("incorrect driver behaviour", driver.hasBehaviour(TestBehaviour.class)); + + assertEquals("incorrect driver properties", 2, driver.properties().size()); + assertTrue("incorrect driver property", driver.properties().containsKey("p1")); + } + + @Test(expected = IOException.class) + public void badXML() throws IOException { + XmlDriverLoader loader = new XmlDriverLoader(getClass().getClassLoader()); + loader.loadDrivers(getClass().getResourceAsStream("drivers.bad.xml"), null); + } + + @Test(expected = IllegalArgumentException.class) + public void noClass() throws IOException { + XmlDriverLoader loader = new XmlDriverLoader(getClass().getClassLoader()); + loader.loadDrivers(getClass().getResourceAsStream("drivers.noclass.xml"), null); + } + + @Test(expected = IllegalArgumentException.class) + public void noConstructor() throws IOException { + XmlDriverLoader loader = new XmlDriverLoader(getClass().getClassLoader()); + InputStream stream = getClass().getResourceAsStream("drivers.noconstructor.xml"); + DriverProvider provider = loader.loadDrivers(stream, null); + Driver driver = provider.getDrivers().iterator().next(); + driver.createBehaviour(new DefaultDriverData(driver, DEVICE_ID), TestBehaviour.class); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/BatchOperationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/BatchOperationTest.java new file mode 100644 index 00000000..9e142e59 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/BatchOperationTest.java @@ -0,0 +1,153 @@ +/* + * 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.net.flow; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; + +/** + * Unit tests for the BatchOperationTest object. + */ +public class BatchOperationTest { + + private enum TestType { + OP1, + OP2, + OP3 + } + + final TestEntry entry1 = new TestEntry(TestType.OP1, new TestTarget(1)); + final TestEntry entry2 = new TestEntry(TestType.OP2, new TestTarget(2)); + + + private static final class TestTarget { + private int id; + + private TestTarget(int id) { + this.id = id; + } + + @Override + public int hashCode() { + return id; + } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (o == null) { + return false; + } + + if (getClass() != o.getClass()) { + return false; + } + TestTarget that = (TestTarget) o; + return this.id == that.id; + } + + } + + private static final class TestEntry extends BatchOperationEntry<TestType, TestTarget> { + public TestEntry(TestType operator, TestTarget target) { + super(operator, target); + } + } + + private static final class TestOperation extends BatchOperation<TestEntry> { + private TestOperation() { + super(); + } + + private TestOperation(Collection<TestEntry> batchOperations) { + super(batchOperations); + } + } + + /** + * Checks that the DefaultFlowRule class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutableBaseClass(BatchOperation.class); + } + + /** + * Tests the equals(), hashCode() and toString() operations. + */ + @Test + public void testEquals() { + final List<TestEntry> ops1 = new LinkedList<>(); + ops1.add(entry1); + final List<TestEntry> ops2 = new LinkedList<>(); + ops2.add(entry2); + + final TestOperation op1 = new TestOperation(ops1); + final TestOperation sameAsOp1 = new TestOperation(ops1); + final TestOperation op2 = new TestOperation(ops2); + + new EqualsTester() + .addEqualityGroup(op1, sameAsOp1) + .addEqualityGroup(op2) + .testEquals(); + } + + /** + * Tests the constructors for a BatchOperation. + */ + @Test + public void testConstruction() { + final List<TestEntry> ops = new LinkedList<>(); + ops.add(entry2); + + final TestOperation op1 = new TestOperation(); + assertThat(op1.size(), is(0)); + assertThat(op1.getOperations(), hasSize(0)); + + final TestOperation op2 = new TestOperation(ops); + op1.addOperation(entry1); + op1.addAll(op2); + assertThat(op1.size(), is(2)); + assertThat(op1.getOperations(), hasSize(2)); + + op2.clear(); + assertThat(op2.size(), is(0)); + assertThat(op2.getOperations(), hasSize(0)); + } + + /** + * Tests the constructor for BatchOperationEntries. + */ + @Test + public void testEntryConstruction() { + final TestEntry entry = new TestEntry(TestType.OP3, new TestTarget(3)); + + assertThat(entry.operator(), is(TestType.OP3)); + assertThat(entry.target().id, is(3)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowEntryTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowEntryTest.java new file mode 100644 index 00000000..412acb62 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowEntryTest.java @@ -0,0 +1,161 @@ +/* + * 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.net.flow; + +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.onosproject.net.intent.IntentTestsMocks; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.onosproject.net.NetTestTools.did; + +/** + * Unit tests for the DefaultFlowEntry class. + */ +public class DefaultFlowEntryTest { + private static final IntentTestsMocks.MockSelector SELECTOR = + new IntentTestsMocks.MockSelector(); + private static final IntentTestsMocks.MockTreatment TREATMENT = + new IntentTestsMocks.MockTreatment(); + + private static DefaultFlowEntry makeFlowEntry(int uniqueValue) { + FlowRule rule = DefaultFlowRule.builder() + .forDevice(did("id" + Integer.toString(uniqueValue))) + .withSelector(SELECTOR) + .withTreatment(TREATMENT) + .withPriority(uniqueValue) + .withCookie(uniqueValue) + .makeTemporary(uniqueValue) + .build(); + + return new DefaultFlowEntry(rule, FlowEntry.FlowEntryState.ADDED, + uniqueValue, uniqueValue, uniqueValue); + } + + final DefaultFlowEntry defaultFlowEntry1 = makeFlowEntry(1); + final DefaultFlowEntry sameAsDefaultFlowEntry1 = makeFlowEntry(1); + final DefaultFlowEntry defaultFlowEntry2 = makeFlowEntry(2); + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(defaultFlowEntry1, sameAsDefaultFlowEntry1) + .addEqualityGroup(defaultFlowEntry2) + .testEquals(); + } + + /** + * Tests the construction of a default flow entry from a device id. + */ + @Test + public void testDeviceBasedObject() { + assertThat(defaultFlowEntry1.deviceId(), is(did("id1"))); + assertThat(defaultFlowEntry1.selector(), is(SELECTOR)); + assertThat(defaultFlowEntry1.treatment(), is(TREATMENT)); + assertThat(defaultFlowEntry1.timeout(), is(1)); + assertThat(defaultFlowEntry1.life(), is(1L)); + assertThat(defaultFlowEntry1.packets(), is(1L)); + assertThat(defaultFlowEntry1.bytes(), is(1L)); + assertThat(defaultFlowEntry1.state(), is(FlowEntry.FlowEntryState.ADDED)); + assertThat(defaultFlowEntry1.lastSeen(), + greaterThan(System.currentTimeMillis() - + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS))); + } + + /** + * Tests the setters on a default flow entry object. + */ + @Test + public void testSetters() { + final DefaultFlowEntry entry = makeFlowEntry(1); + + entry.setLastSeen(); + entry.setState(FlowEntry.FlowEntryState.PENDING_REMOVE); + entry.setPackets(11); + entry.setBytes(22); + entry.setLife(33); + + assertThat(entry.deviceId(), is(did("id1"))); + assertThat(entry.selector(), is(SELECTOR)); + assertThat(entry.treatment(), is(TREATMENT)); + assertThat(entry.timeout(), is(1)); + assertThat(entry.life(), is(33L)); + assertThat(entry.packets(), is(11L)); + assertThat(entry.bytes(), is(22L)); + assertThat(entry.state(), is(FlowEntry.FlowEntryState.PENDING_REMOVE)); + assertThat(entry.lastSeen(), + greaterThan(System.currentTimeMillis() - + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS))); + } + + /** + * Tests a default flow rule built for an error. + */ + @Test + public void testErrorObject() { + final DefaultFlowEntry errorEntry = + new DefaultFlowEntry(new IntentTestsMocks.MockFlowRule(1), + 111, + 222); + assertThat(errorEntry.errType(), is(111)); + assertThat(errorEntry.errCode(), is(222)); + assertThat(errorEntry.state(), is(FlowEntry.FlowEntryState.FAILED)); + assertThat(errorEntry.lastSeen(), + greaterThan(System.currentTimeMillis() - + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS))); + } + + /** + * Tests a default flow entry constructed from a flow rule. + */ + @Test + public void testFlowBasedObject() { + final DefaultFlowEntry entry = + new DefaultFlowEntry(new IntentTestsMocks.MockFlowRule(1)); + assertThat(entry.priority(), is(1)); + assertThat(entry.appId(), is((short) 0)); + assertThat(entry.lastSeen(), + greaterThan(System.currentTimeMillis() - + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS))); + } + + /** + * Tests a default flow entry constructed from a flow rule plus extra + * parameters. + */ + @Test + public void testFlowBasedObjectWithParameters() { + final DefaultFlowEntry entry = + new DefaultFlowEntry(new IntentTestsMocks.MockFlowRule(33), + FlowEntry.FlowEntryState.REMOVED, + 101, 102, 103); + assertThat(entry.state(), is(FlowEntry.FlowEntryState.REMOVED)); + assertThat(entry.life(), is(101L)); + assertThat(entry.packets(), is(102L)); + assertThat(entry.bytes(), is(103L)); + assertThat(entry.lastSeen(), + greaterThan(System.currentTimeMillis() - + TimeUnit.MILLISECONDS.convert(1, TimeUnit.SECONDS))); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowRuleTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowRuleTest.java new file mode 100644 index 00000000..62acd16a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultFlowRuleTest.java @@ -0,0 +1,161 @@ +/* + * 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.net.flow; + +import org.junit.Test; +import org.onosproject.core.DefaultGroupId; +import org.onosproject.net.intent.IntentTestsMocks; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.did; + +/** + * Unit tests for the default flow rule class. + */ +public class DefaultFlowRuleTest { + private static final IntentTestsMocks.MockSelector SELECTOR = + new IntentTestsMocks.MockSelector(); + private static final IntentTestsMocks.MockTreatment TREATMENT = + new IntentTestsMocks.MockTreatment(); + + private static byte [] b = new byte[3]; + private static FlowRuleExtPayLoad payLoad = FlowRuleExtPayLoad.flowRuleExtPayLoad(b); + final FlowRule flowRule1 = new IntentTestsMocks.MockFlowRule(1, payLoad); + final FlowRule sameAsFlowRule1 = new IntentTestsMocks.MockFlowRule(1, payLoad); + final DefaultFlowRule defaultFlowRule1 = new DefaultFlowRule(flowRule1); + final DefaultFlowRule sameAsDefaultFlowRule1 = new DefaultFlowRule(sameAsFlowRule1); + + /** + * Checks that the DefaultFlowRule class is immutable but can be inherited + * from. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutableBaseClass(DefaultFlowRule.class); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(defaultFlowRule1, sameAsDefaultFlowRule1) + .testEquals(); + } + + /** + * Tests creation of a DefaultFlowRule using a FlowRule constructor. + */ + @Test + public void testCreationFromFlowRule() { + assertThat(defaultFlowRule1.deviceId(), is(flowRule1.deviceId())); + assertThat(defaultFlowRule1.appId(), is(flowRule1.appId())); + assertThat(defaultFlowRule1.id(), is(flowRule1.id())); + assertThat(defaultFlowRule1.isPermanent(), is(flowRule1.isPermanent())); + assertThat(defaultFlowRule1.priority(), is(flowRule1.priority())); + assertThat(defaultFlowRule1.selector(), is(flowRule1.selector())); + assertThat(defaultFlowRule1.treatment(), is(flowRule1.treatment())); + assertThat(defaultFlowRule1.timeout(), is(flowRule1.timeout())); + assertThat(defaultFlowRule1.payLoad(), is(flowRule1.payLoad())); + } + + /** + * Tests creation of a DefaultFlowRule using a FlowId constructor. + */ + + @Test + public void testCreationWithFlowId() { + final FlowRule rule = + DefaultFlowRule.builder() + .forDevice(did("1")) + .withSelector(SELECTOR) + .withTreatment(TREATMENT) + .withPriority(22) + .makeTemporary(44) + .fromApp(APP_ID) + .build(); + + assertThat(rule.deviceId(), is(did("1"))); + assertThat(rule.isPermanent(), is(false)); + assertThat(rule.priority(), is(22)); + assertThat(rule.selector(), is(SELECTOR)); + assertThat(rule.treatment(), is(TREATMENT)); + assertThat(rule.timeout(), is(44)); + } + + + /** + * Tests creation of a DefaultFlowRule using a PayLoad constructor. + */ + @Test + public void testCreationWithPayLoadByFlowTable() { + final DefaultFlowRule rule = + new DefaultFlowRule(did("1"), null, + null, 22, APP_ID, + 44, false, payLoad); + assertThat(rule.deviceId(), is(did("1"))); + assertThat(rule.isPermanent(), is(false)); + assertThat(rule.priority(), is(22)); + assertThat(rule.timeout(), is(44)); + assertThat(defaultFlowRule1.payLoad(), is(payLoad)); + } + + /** + * Tests creation of a DefaultFlowRule using a PayLoad constructor. + */ + @Test + public void testCreationWithPayLoadByGroupTable() { + final DefaultFlowRule rule = + new DefaultFlowRule(did("1"), null, + null, 22, APP_ID, new DefaultGroupId(0), + 44, false, payLoad); + assertThat(rule.deviceId(), is(did("1"))); + assertThat(rule.isPermanent(), is(false)); + assertThat(rule.priority(), is(22)); + assertThat(rule.timeout(), is(44)); + assertThat(rule.groupId(), is(new DefaultGroupId(0))); + assertThat(defaultFlowRule1.payLoad(), is(payLoad)); + } + /** + * Tests the creation of a DefaultFlowRule using an AppId constructor. + */ + @Test + public void testCreationWithAppId() { + final FlowRule rule = + DefaultFlowRule.builder() + .forDevice(did("1")) + .withSelector(SELECTOR) + .withTreatment(TREATMENT) + .withPriority(22) + .fromApp(APP_ID) + .makeTemporary(44) + .build(); + + assertThat(rule.deviceId(), is(did("1"))); + assertThat(rule.isPermanent(), is(false)); + assertThat(rule.priority(), is(22)); + assertThat(rule.selector(), is(SELECTOR)); + assertThat(rule.treatment(), is(TREATMENT)); + assertThat(rule.timeout(), is(44)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficSelectorTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficSelectorTest.java new file mode 100644 index 00000000..b871397b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficSelectorTest.java @@ -0,0 +1,295 @@ +/* + * 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.net.flow; + +import java.util.Set; + +import org.hamcrest.Description; +import org.hamcrest.Factory; +import org.hamcrest.Matcher; +import org.hamcrest.TypeSafeMatcher; +import org.junit.Test; +import org.onlab.packet.Ip6Address; +import org.onlab.packet.IpPrefix; +import org.onlab.packet.MacAddress; +import org.onlab.packet.MplsLabel; +import org.onlab.packet.TpPort; +import org.onlab.packet.VlanId; +import org.onosproject.net.IndexedLambda; +import org.onosproject.net.PortNumber; +import org.onosproject.net.flow.criteria.Criteria; +import org.onosproject.net.flow.criteria.Criterion; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.flow.criteria.Criterion.Type; + +/** + * Unit tests for default traffic selector class. + */ +public class DefaultTrafficSelectorTest { + + /** + * Checks that the DefaultFlowRule class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(DefaultTrafficSelector.class); + } + + /** + * Tests equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + final short one = 1; + final short two = 2; + + final TrafficSelector selector1 = DefaultTrafficSelector.builder() + .add(Criteria.matchLambda(new IndexedLambda(one))) + .build(); + final TrafficSelector sameAsSelector1 = DefaultTrafficSelector.builder() + .add(Criteria.matchLambda(new IndexedLambda(one))) + .build(); + final TrafficSelector selector2 = DefaultTrafficSelector.builder() + .add(Criteria.matchLambda(new IndexedLambda(two))) + .build(); + + new EqualsTester() + .addEqualityGroup(selector1, sameAsSelector1) + .addEqualityGroup(selector2) + .testEquals(); + } + + /** + * Hamcrest matcher to check that a selector contains a + * Criterion with the specified type. + */ + public static final class CriterionExistsMatcher + extends TypeSafeMatcher<TrafficSelector> { + private final Criterion.Type type; + + /** + * Constructs a matcher for the given criterion type. + * + * @param typeValue criterion type to match + */ + public CriterionExistsMatcher(Criterion.Type typeValue) { + type = typeValue; + } + + @Override + public boolean matchesSafely(TrafficSelector selector) { + final Set<Criterion> criteria = selector.criteria(); + + return notNullValue().matches(criteria) && + hasSize(1).matches(criteria) && + notNullValue().matches(selector.getCriterion(type)); + } + + @Override + public void describeTo(Description description) { + description.appendText("a criterion with type \" "). + appendText(type.toString()). + appendText("\""); + } + } + + + /** + * Creates a criterion type matcher. Returns a matcher + * for a criterion with the given type. + * + * @param type type of Criterion to match + * @return Matcher object + */ + @Factory + public static Matcher<TrafficSelector> hasCriterionWithType(Criterion.Type type) { + return new CriterionExistsMatcher(type); + } + + + /** + * Tests the builder functions that add specific criteria. + */ + @Test + public void testCriteriaCreation() { + TrafficSelector selector; + + final long longValue = 0x12345678; + final int intValue = 22; + final short shortValue = 33; + final byte byteValue = 44; + final byte dscpValue = 0xf; + final byte ecnValue = 3; + final MacAddress macValue = MacAddress.valueOf("11:22:33:44:55:66"); + final IpPrefix ipPrefixValue = IpPrefix.valueOf("192.168.1.0/24"); + final IpPrefix ipv6PrefixValue = IpPrefix.valueOf("fe80::1/64"); + final Ip6Address ipv6AddressValue = Ip6Address.valueOf("fe80::1"); + + selector = DefaultTrafficSelector.builder() + .matchInPort(PortNumber.portNumber(11)).build(); + assertThat(selector, hasCriterionWithType(Type.IN_PORT)); + + selector = DefaultTrafficSelector.builder() + .matchInPhyPort(PortNumber.portNumber(11)).build(); + assertThat(selector, hasCriterionWithType(Type.IN_PHY_PORT)); + + selector = DefaultTrafficSelector.builder() + .matchMetadata(longValue).build(); + assertThat(selector, hasCriterionWithType(Type.METADATA)); + + selector = DefaultTrafficSelector.builder() + .matchEthDst(macValue).build(); + assertThat(selector, hasCriterionWithType(Type.ETH_DST)); + + selector = DefaultTrafficSelector.builder() + .matchEthSrc(macValue).build(); + assertThat(selector, hasCriterionWithType(Type.ETH_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchEthType(shortValue).build(); + assertThat(selector, hasCriterionWithType(Type.ETH_TYPE)); + + selector = DefaultTrafficSelector.builder() + .matchVlanId(VlanId.vlanId(shortValue)).build(); + assertThat(selector, hasCriterionWithType(Type.VLAN_VID)); + + selector = DefaultTrafficSelector.builder() + .matchVlanPcp(byteValue).build(); + assertThat(selector, hasCriterionWithType(Type.VLAN_PCP)); + + selector = DefaultTrafficSelector.builder() + .matchIPDscp(dscpValue).build(); + assertThat(selector, hasCriterionWithType(Type.IP_DSCP)); + + selector = DefaultTrafficSelector.builder() + .matchIPEcn(ecnValue).build(); + assertThat(selector, hasCriterionWithType(Type.IP_ECN)); + + selector = DefaultTrafficSelector.builder() + .matchIPProtocol(byteValue).build(); + assertThat(selector, hasCriterionWithType(Type.IP_PROTO)); + + selector = DefaultTrafficSelector.builder() + .matchIPSrc(ipPrefixValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV4_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchIPDst(ipPrefixValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV4_DST)); + + selector = DefaultTrafficSelector.builder() + .matchTcpSrc(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.TCP_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchTcpDst(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.TCP_DST)); + + selector = DefaultTrafficSelector.builder() + .matchUdpSrc(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.UDP_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchUdpDst(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.UDP_DST)); + + selector = DefaultTrafficSelector.builder() + .matchSctpSrc(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.SCTP_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchSctpDst(TpPort.tpPort(intValue)).build(); + assertThat(selector, hasCriterionWithType(Type.SCTP_DST)); + + selector = DefaultTrafficSelector.builder() + .matchIcmpType(byteValue).build(); + assertThat(selector, hasCriterionWithType(Type.ICMPV4_TYPE)); + + selector = DefaultTrafficSelector.builder() + .matchIcmpCode(byteValue).build(); + assertThat(selector, hasCriterionWithType(Type.ICMPV4_CODE)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6Src(ipv6PrefixValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_SRC)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6Dst(ipv6PrefixValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_DST)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6FlowLabel(intValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_FLABEL)); + + selector = DefaultTrafficSelector.builder() + .matchIcmpv6Type(byteValue).build(); + assertThat(selector, hasCriterionWithType(Type.ICMPV6_TYPE)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6NDTargetAddress(ipv6AddressValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_ND_TARGET)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6NDSourceLinkLayerAddress(macValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_ND_SLL)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6NDTargetLinkLayerAddress(macValue).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_ND_TLL)); + + selector = DefaultTrafficSelector.builder() + .matchMplsLabel(MplsLabel.mplsLabel(3)).build(); + assertThat(selector, hasCriterionWithType(Type.MPLS_LABEL)); + + selector = DefaultTrafficSelector.builder() + .matchIPv6ExthdrFlags(Criterion.IPv6ExthdrFlags.NONEXT.getValue()).build(); + assertThat(selector, hasCriterionWithType(Type.IPV6_EXTHDR)); + + selector = DefaultTrafficSelector.builder() + .add(Criteria.matchLambda(new IndexedLambda(shortValue))).build(); + assertThat(selector, hasCriterionWithType(Type.OCH_SIGID)); + + selector = DefaultTrafficSelector.builder() + .add(Criteria.matchOpticalSignalType(shortValue)).build(); + assertThat(selector, hasCriterionWithType(Type.OCH_SIGTYPE)); + } + + /** + * Tests the traffic selector builder. + */ + @Test + public void testTrafficSelectorBuilder() { + TrafficSelector selector; + final short shortValue = 33; + + final TrafficSelector baseSelector = DefaultTrafficSelector.builder() + .add(Criteria.matchLambda(new IndexedLambda(shortValue))).build(); + selector = DefaultTrafficSelector.builder(baseSelector) + .build(); + assertThat(selector, hasCriterionWithType(Type.OCH_SIGID)); + + final Criterion criterion = Criteria.matchLambda(shortValue); + selector = DefaultTrafficSelector.builder() + .add(criterion).build(); + assertThat(selector, hasCriterionWithType(Type.OCH_SIGID)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficTreatmentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficTreatmentTest.java new file mode 100644 index 00000000..288f5f2f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/DefaultTrafficTreatmentTest.java @@ -0,0 +1,124 @@ +/* + * 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.net.flow; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; +import org.onosproject.net.IndexedLambda; +import org.onosproject.net.PortNumber; +import org.onosproject.net.flow.instructions.Instruction; +import org.onosproject.net.flow.instructions.Instructions; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; + +/** + * Unit tests for the DefaultTrafficTreatment class. + */ +public class DefaultTrafficTreatmentTest { + + // Tests for the nested Builder class + + /** + * Tests that the Builder constructors return equivalent objects + * when given the same data. + */ + @Test + public void testTreatmentBuilderConstructors() { + final TrafficTreatment treatment1 = + DefaultTrafficTreatment.builder() + .add(Instructions.modL0Lambda(new IndexedLambda(4))) + .build(); + final TrafficTreatment treatment2 = + DefaultTrafficTreatment.builder(treatment1).build(); + assertThat(treatment1, is(equalTo(treatment2))); + } + + /** + * Tests methods defined on the Builder. + */ + @Test + public void testBuilderMethods() { + final Instruction instruction1 = + Instructions.modL0Lambda(new IndexedLambda(4)); + + final TrafficTreatment.Builder builder1 = + DefaultTrafficTreatment.builder() + .add(instruction1) + .setEthDst(MacAddress.BROADCAST) + .setEthSrc(MacAddress.BROADCAST) + .setIpDst(IpAddress.valueOf("1.1.1.1")) + .setIpSrc(IpAddress.valueOf("2.2.2.2")) + .add(Instructions.modL0Lambda(new IndexedLambda(4))) + .setOutput(PortNumber.portNumber(2)) + .setVlanId(VlanId.vlanId((short) 4)) + .setVlanPcp((byte) 3); + + final TrafficTreatment treatment1 = builder1.build(); + + final List<Instruction> instructions1 = treatment1.immediate(); + assertThat(instructions1, hasSize(9)); + + builder1.drop(); + builder1.add(instruction1); + + final List<Instruction> instructions2 = builder1.build().immediate(); + assertThat(instructions2, hasSize(11)); + + builder1.deferred() + .popVlan() + .pushVlan() + .setVlanId(VlanId.vlanId((short) 5)); + + final List<Instruction> instructions3 = builder1.build().immediate(); + assertThat(instructions3, hasSize(11)); + final List<Instruction> instructions4 = builder1.build().deferred(); + assertThat(instructions4, hasSize(3)); + } + + /** + * Tests equals(), hashCode() and toString() methods of + * DefaultTrafficTreatment. + */ + @Test + public void testEquals() { + final IndexedLambda lambda1 = new IndexedLambda(4); + final IndexedLambda lambda2 = new IndexedLambda(5); + final TrafficTreatment treatment1 = + DefaultTrafficTreatment.builder() + .add(Instructions.modL0Lambda(lambda1)) + .build(); + final TrafficTreatment sameAsTreatment1 = + DefaultTrafficTreatment.builder() + .add(Instructions.modL0Lambda(lambda1)) + .build(); + final TrafficTreatment treatment2 = + DefaultTrafficTreatment.builder() + .add(Instructions.modL0Lambda(lambda2)) + .build(); + new EqualsTester() + .addEqualityGroup(treatment1, sameAsTreatment1) + .addEqualityGroup(treatment2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowIdTest.java new file mode 100644 index 00000000..263d4031 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowIdTest.java @@ -0,0 +1,65 @@ +/* + * 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.net.flow; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Unit tests for flow id class. + */ +public class FlowIdTest { + + final FlowId flowId1 = FlowId.valueOf(1); + final FlowId sameAsFlowId1 = FlowId.valueOf(1); + final FlowId flowId2 = FlowId.valueOf(2); + + /** + * Checks that the FlowId class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(FlowId.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(flowId1, sameAsFlowId1) + .addEqualityGroup(flowId2) + .testEquals(); + } + + /** + * Checks the construction of a FlowId object. + */ + @Test + public void testConstruction() { + final long flowIdValue = 7777L; + final FlowId flowId = FlowId.valueOf(flowIdValue); + assertThat(flowId, is(notNullValue())); + assertThat(flowId.value(), is(flowIdValue)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchOperationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchOperationTest.java new file mode 100644 index 00000000..4fa3492a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchOperationTest.java @@ -0,0 +1,60 @@ +/* + * 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.net.flow; + +import java.util.LinkedList; + +import org.junit.Test; +import org.onosproject.net.intent.IntentTestsMocks; + +import com.google.common.testing.EqualsTester; + +/** + * Unit tests for flow rule batch classes. + */ +public class FlowRuleBatchOperationTest { + + /** + * Tests the equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + final FlowRule rule = new IntentTestsMocks.MockFlowRule(1); + final FlowRuleBatchEntry entry1 = new FlowRuleBatchEntry( + FlowRuleBatchEntry.FlowRuleOperation.ADD, rule); + final FlowRuleBatchEntry entry2 = new FlowRuleBatchEntry( + FlowRuleBatchEntry.FlowRuleOperation.MODIFY, rule); + final FlowRuleBatchEntry entry3 = new FlowRuleBatchEntry( + FlowRuleBatchEntry.FlowRuleOperation.REMOVE, rule); + final LinkedList<FlowRuleBatchEntry> ops1 = new LinkedList<>(); + ops1.add(entry1); + final LinkedList<FlowRuleBatchEntry> ops2 = new LinkedList<>(); + ops1.add(entry2); + final LinkedList<FlowRuleBatchEntry> ops3 = new LinkedList<>(); + ops3.add(entry3); + + final FlowRuleBatchOperation operation1 = new FlowRuleBatchOperation(ops1, null, 0); + final FlowRuleBatchOperation sameAsOperation1 = new FlowRuleBatchOperation(ops1, null, 0); + final FlowRuleBatchOperation operation2 = new FlowRuleBatchOperation(ops2, null, 0); + final FlowRuleBatchOperation operation3 = new FlowRuleBatchOperation(ops3, null, 0); + + new EqualsTester() + .addEqualityGroup(operation1, sameAsOperation1) + .addEqualityGroup(operation2) + .addEqualityGroup(operation3) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchRequestTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchRequestTest.java new file mode 100644 index 00000000..b379a6ec --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleBatchRequestTest.java @@ -0,0 +1,63 @@ +/* + * 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.net.flow; + +import org.junit.Test; +import org.onosproject.net.intent.IntentTestsMocks; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation.ADD; +import static org.onosproject.net.flow.FlowRuleBatchEntry.FlowRuleOperation.REMOVE; + +/** + * Unit tests for the FlowRuleBatchRequest class. + */ +public class FlowRuleBatchRequestTest { + + /** + * Tests that construction of FlowRuleBatchRequest objects returns the + * correct objects. + */ + @Test + public void testConstruction() { + final FlowRule rule1 = new IntentTestsMocks.MockFlowRule(1); + final FlowRule rule2 = new IntentTestsMocks.MockFlowRule(2); + final Set<FlowRuleBatchEntry> batch = new HashSet<>(); + batch.add(new FlowRuleBatchEntry(ADD, rule1)); + + batch.add(new FlowRuleBatchEntry(REMOVE, rule2)); + + + final FlowRuleBatchRequest request = + new FlowRuleBatchRequest(1, batch); + + assertThat(request.ops(), hasSize(2)); + assertThat(request.batchId(), is(1L)); + + final FlowRuleBatchOperation op = request.asBatchOperation(rule1.deviceId()); + assertThat(op.size(), is(2)); + + final List<FlowRuleBatchEntry> ops = op.getOperations(); + assertThat(ops, hasSize(2)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleEventTest.java new file mode 100644 index 00000000..2d79c893 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleEventTest.java @@ -0,0 +1,77 @@ +/* + * 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.net.flow; + +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.onosproject.event.AbstractEventTest; +import org.onosproject.net.intent.IntentTestsMocks; + +import com.google.common.testing.EqualsTester; + +/** + * Unit Tests for the FlowRuleEvent class. + */ +public class FlowRuleEventTest extends AbstractEventTest { + + @Test + public void testEquals() { + final FlowRule flowRule1 = new IntentTestsMocks.MockFlowRule(1); + final FlowRule flowRule2 = new IntentTestsMocks.MockFlowRule(2); + final long time = 123L; + final FlowRuleEvent event1 = + new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, flowRule1, time); + final FlowRuleEvent sameAsEvent1 = + new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADDED, flowRule1, time); + final FlowRuleEvent event2 = + new FlowRuleEvent(FlowRuleEvent.Type.RULE_ADD_REQUESTED, + flowRule2, time); + + // Equality for events is based on Object, these should all compare + // as different. + new EqualsTester() + .addEqualityGroup(event1) + .addEqualityGroup(sameAsEvent1) + .addEqualityGroup(event2) + .testEquals(); + } + + /** + * Tests the constructor where a time is passed in. + */ + @Test + public void testTimeConstructor() { + final long time = 123L; + final FlowRule flowRule = new IntentTestsMocks.MockFlowRule(1); + final FlowRuleEvent event = + new FlowRuleEvent(FlowRuleEvent.Type.RULE_REMOVE_REQUESTED, flowRule, time); + validateEvent(event, FlowRuleEvent.Type.RULE_REMOVE_REQUESTED, flowRule, time); + } + + /** + * Tests the constructor with the default time value. + */ + @Test + public void testConstructor() { + final long time = System.currentTimeMillis(); + final FlowRule flowRule = new IntentTestsMocks.MockFlowRule(1); + final FlowRuleEvent event = + new FlowRuleEvent(FlowRuleEvent.Type.RULE_UPDATED, flowRule); + validateEvent(event, FlowRuleEvent.Type.RULE_UPDATED, flowRule, time, + time + TimeUnit.SECONDS.toMillis(30)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleExtPayLoadTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleExtPayLoadTest.java new file mode 100644 index 00000000..30326a2e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleExtPayLoadTest.java @@ -0,0 +1,36 @@ +package org.onosproject.net.flow; + +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; +/** + * Test for FlowRuleExtPayLoad. + */ +public class FlowRuleExtPayLoadTest { + final byte[] b = new byte[3]; + final byte[] b1 = new byte[5]; + final FlowRuleExtPayLoad payLoad1 = FlowRuleExtPayLoad.flowRuleExtPayLoad(b); + final FlowRuleExtPayLoad sameAsPayLoad1 = FlowRuleExtPayLoad.flowRuleExtPayLoad(b); + final FlowRuleExtPayLoad payLoad2 = FlowRuleExtPayLoad.flowRuleExtPayLoad(b1); + + /** + * Checks that the FlowRuleExtPayLoad class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(FlowRuleExtPayLoad.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(payLoad1, sameAsPayLoad1) + .addEqualityGroup(payLoad2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleServiceAdapter.java new file mode 100644 index 00000000..c7b78791 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/FlowRuleServiceAdapter.java @@ -0,0 +1,75 @@ +/* + * 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.net.flow; + +import org.onosproject.core.ApplicationId; +import org.onosproject.net.DeviceId; + +/** + * Test adapter for flow rule service. + */ +public class FlowRuleServiceAdapter implements FlowRuleService { + @Override + public int getFlowRuleCount() { + return 0; + } + + @Override + public Iterable<FlowEntry> getFlowEntries(DeviceId deviceId) { + return null; + } + + @Override + public void applyFlowRules(FlowRule... flowRules) { + + } + + @Override + public void removeFlowRules(FlowRule... flowRules) { + + } + + @Override + public void removeFlowRulesById(ApplicationId appId) { + + } + + @Override + public Iterable<FlowRule> getFlowRulesById(ApplicationId id) { + return null; + } + + @Override + public Iterable<FlowRule> getFlowRulesByGroupId(ApplicationId appId, short groupId) { + return null; + } + + @Override + public void apply(FlowRuleOperations ops) { + + } + + @Override + public void addListener(FlowRuleListener listener) { + + } + + @Override + public void removeListener(FlowRuleListener listener) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/criteria/CriteriaTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/criteria/CriteriaTest.java new file mode 100644 index 00000000..ee294f6f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/criteria/CriteriaTest.java @@ -0,0 +1,1138 @@ +/* + * 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.net.flow.criteria; + +import org.junit.Test; +import org.onlab.packet.EthType; +import org.onlab.packet.Ip6Address; +import org.onlab.packet.IpPrefix; +import org.onlab.packet.MacAddress; +import org.onlab.packet.MplsLabel; +import org.onlab.packet.TpPort; +import org.onlab.packet.VlanId; +import org.onosproject.net.ChannelSpacing; +import org.onosproject.net.GridType; +import org.onosproject.net.Lambda; +import org.onosproject.net.PortNumber; + +import com.google.common.testing.EqualsTester; +import org.onosproject.net.OchSignalType; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onlab.junit.UtilityClassChecker.assertThatClassIsUtility; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Unit tests for the Criteria class and its subclasses. + */ +public class CriteriaTest { + + final PortNumber port1 = portNumber(1); + final PortNumber port2 = portNumber(2); + + Criterion matchInPort1 = Criteria.matchInPort(port1); + Criterion sameAsMatchInPort1 = Criteria.matchInPort(port1); + Criterion matchInPort2 = Criteria.matchInPort(port2); + + Criterion matchInPhyPort1 = Criteria.matchInPhyPort(port1); + Criterion sameAsMatchInPhyPort1 = Criteria.matchInPhyPort(port1); + Criterion matchInPhyPort2 = Criteria.matchInPhyPort(port2); + + long metadata1 = 1; + long metadata2 = 2; + Criterion matchMetadata1 = Criteria.matchMetadata(metadata1); + Criterion sameAsMatchMetadata1 = Criteria.matchMetadata(metadata1); + Criterion matchMetadata2 = Criteria.matchMetadata(metadata2); + + private static final String MAC1 = "00:00:00:00:00:01"; + private static final String MAC2 = "00:00:00:00:00:02"; + private MacAddress mac1 = MacAddress.valueOf(MAC1); + private MacAddress mac2 = MacAddress.valueOf(MAC2); + Criterion matchEth1 = Criteria.matchEthSrc(mac1); + Criterion sameAsMatchEth1 = Criteria.matchEthSrc(mac1); + Criterion matchEth2 = Criteria.matchEthDst(mac2); + + int ethType1 = 1; + int ethType2 = 2; + Criterion matchEthType1 = Criteria.matchEthType(ethType1); + Criterion sameAsMatchEthType1 = Criteria.matchEthType(ethType1); + Criterion matchEthType2 = Criteria.matchEthType(ethType2); + + short vlan1 = 1; + short vlan2 = 2; + VlanId vlanId1 = VlanId.vlanId(vlan1); + VlanId vlanId2 = VlanId.vlanId(vlan2); + Criterion matchVlanId1 = Criteria.matchVlanId(vlanId1); + Criterion sameAsMatchVlanId1 = Criteria.matchVlanId(vlanId1); + Criterion matchVlanId2 = Criteria.matchVlanId(vlanId2); + + byte vlanPcp1 = 1; + byte vlanPcp2 = 2; + Criterion matchVlanPcp1 = Criteria.matchVlanPcp(vlanPcp1); + Criterion sameAsMatchVlanPcp1 = Criteria.matchVlanPcp(vlanPcp1); + Criterion matchVlanPcp2 = Criteria.matchVlanPcp(vlanPcp2); + + byte ipDscp1 = 1; + byte ipDscp2 = 2; + Criterion matchIpDscp1 = Criteria.matchIPDscp(ipDscp1); + Criterion sameAsMatchIpDscp1 = Criteria.matchIPDscp(ipDscp1); + Criterion matchIpDscp2 = Criteria.matchIPDscp(ipDscp2); + + byte ipEcn1 = 1; + byte ipEcn2 = 2; + Criterion matchIpEcn1 = Criteria.matchIPEcn(ipEcn1); + Criterion sameAsMatchIpEcn1 = Criteria.matchIPEcn(ipEcn1); + Criterion matchIpEcn2 = Criteria.matchIPEcn(ipEcn2); + + short protocol1 = 1; + short protocol2 = 2; + Criterion matchIpProtocol1 = Criteria.matchIPProtocol(protocol1); + Criterion sameAsMatchIpProtocol1 = Criteria.matchIPProtocol(protocol1); + Criterion matchIpProtocol2 = Criteria.matchIPProtocol(protocol2); + + private static final String IP1 = "1.2.3.4/24"; + private static final String IP2 = "5.6.7.8/24"; + private static final String IPV61 = "fe80::1/64"; + private static final String IPV62 = "fc80::2/64"; + private IpPrefix ip1 = IpPrefix.valueOf(IP1); + private IpPrefix ip2 = IpPrefix.valueOf(IP2); + private IpPrefix ipv61 = IpPrefix.valueOf(IPV61); + private IpPrefix ipv62 = IpPrefix.valueOf(IPV62); + Criterion matchIp1 = Criteria.matchIPSrc(ip1); + Criterion sameAsMatchIp1 = Criteria.matchIPSrc(ip1); + Criterion matchIp2 = Criteria.matchIPSrc(ip2); + Criterion matchIpv61 = Criteria.matchIPSrc(ipv61); + Criterion sameAsMatchIpv61 = Criteria.matchIPSrc(ipv61); + Criterion matchIpv62 = Criteria.matchIPSrc(ipv62); + + private TpPort tpPort1 = TpPort.tpPort(1); + private TpPort tpPort2 = TpPort.tpPort(2); + Criterion matchTcpPort1 = Criteria.matchTcpSrc(tpPort1); + Criterion sameAsMatchTcpPort1 = Criteria.matchTcpSrc(tpPort1); + Criterion matchTcpPort2 = Criteria.matchTcpDst(tpPort2); + + Criterion matchUdpPort1 = Criteria.matchUdpSrc(tpPort1); + Criterion sameAsMatchUdpPort1 = Criteria.matchUdpSrc(tpPort1); + Criterion matchUdpPort2 = Criteria.matchUdpDst(tpPort2); + + Criterion matchSctpPort1 = Criteria.matchSctpSrc(tpPort1); + Criterion sameAsMatchSctpPort1 = Criteria.matchSctpSrc(tpPort1); + Criterion matchSctpPort2 = Criteria.matchSctpDst(tpPort2); + + short icmpType1 = 1; + short icmpType2 = 2; + Criterion matchIcmpType1 = Criteria.matchIcmpType(icmpType1); + Criterion sameAsMatchIcmpType1 = Criteria.matchIcmpType(icmpType1); + Criterion matchIcmpType2 = Criteria.matchIcmpType(icmpType2); + + short icmpCode1 = 1; + short icmpCode2 = 2; + Criterion matchIcmpCode1 = Criteria.matchIcmpCode(icmpCode1); + Criterion sameAsMatchIcmpCode1 = Criteria.matchIcmpCode(icmpCode1); + Criterion matchIcmpCode2 = Criteria.matchIcmpCode(icmpCode2); + + int flowLabel1 = 1; + int flowLabel2 = 2; + Criterion matchFlowLabel1 = Criteria.matchIPv6FlowLabel(flowLabel1); + Criterion sameAsMatchFlowLabel1 = Criteria.matchIPv6FlowLabel(flowLabel1); + Criterion matchFlowLabel2 = Criteria.matchIPv6FlowLabel(flowLabel2); + + short icmpv6Type1 = 1; + short icmpv6Type2 = 2; + Criterion matchIcmpv6Type1 = Criteria.matchIcmpv6Type(icmpv6Type1); + Criterion sameAsMatchIcmpv6Type1 = Criteria.matchIcmpv6Type(icmpv6Type1); + Criterion matchIcmpv6Type2 = Criteria.matchIcmpv6Type(icmpv6Type2); + + short icmpv6Code1 = 1; + short icmpv6Code2 = 2; + Criterion matchIcmpv6Code1 = Criteria.matchIcmpv6Code(icmpv6Code1); + Criterion sameAsMatchIcmpv6Code1 = Criteria.matchIcmpv6Code(icmpv6Code1); + Criterion matchIcmpv6Code2 = Criteria.matchIcmpv6Code(icmpv6Code2); + + private static final String IPV6_ADDR1 = "fe80::1"; + private static final String IPV6_ADDR2 = "fe80::2"; + private Ip6Address ip6TargetAddress1 = Ip6Address.valueOf(IPV6_ADDR1); + private Ip6Address ip6TargetAddress2 = Ip6Address.valueOf(IPV6_ADDR2); + Criterion matchIpv6TargetAddr1 = + Criteria.matchIPv6NDTargetAddress(ip6TargetAddress1); + Criterion sameAsMatchIpv6TargetAddr1 = + Criteria.matchIPv6NDTargetAddress(ip6TargetAddress1); + Criterion matchIpv6TargetAddr2 = + Criteria.matchIPv6NDTargetAddress(ip6TargetAddress2); + + private static final String LL_MAC1 = "00:00:00:00:00:01"; + private static final String LL_MAC2 = "00:00:00:00:00:02"; + private MacAddress llMac1 = MacAddress.valueOf(LL_MAC1); + private MacAddress llMac2 = MacAddress.valueOf(LL_MAC2); + Criterion matchSrcLlAddr1 = + Criteria.matchIPv6NDSourceLinkLayerAddress(llMac1); + Criterion sameAsMatchSrcLlAddr1 = + Criteria.matchIPv6NDSourceLinkLayerAddress(llMac1); + Criterion matchSrcLlAddr2 = + Criteria.matchIPv6NDSourceLinkLayerAddress(llMac2); + Criterion matchTargetLlAddr1 = + Criteria.matchIPv6NDTargetLinkLayerAddress(llMac1); + Criterion sameAsMatchTargetLlAddr1 = + Criteria.matchIPv6NDTargetLinkLayerAddress(llMac1); + Criterion matchTargetLlAddr2 = + Criteria.matchIPv6NDTargetLinkLayerAddress(llMac2); + + MplsLabel mpls1 = MplsLabel.mplsLabel(1); + MplsLabel mpls2 = MplsLabel.mplsLabel(2); + Criterion matchMpls1 = Criteria.matchMplsLabel(mpls1); + Criterion sameAsMatchMpls1 = Criteria.matchMplsLabel(mpls1); + Criterion matchMpls2 = Criteria.matchMplsLabel(mpls2); + + long tunnelId1 = 1; + long tunnelId2 = 2; + Criterion matchTunnelId1 = Criteria.matchTunnelId(tunnelId1); + Criterion sameAsMatchTunnelId1 = Criteria.matchTunnelId(tunnelId1); + Criterion matchTunnelId2 = Criteria.matchTunnelId(tunnelId2); + + int ipv6ExthdrFlags1 = + Criterion.IPv6ExthdrFlags.NONEXT.getValue() | + Criterion.IPv6ExthdrFlags.ESP.getValue() | + Criterion.IPv6ExthdrFlags.AUTH.getValue() | + Criterion.IPv6ExthdrFlags.DEST.getValue() | + Criterion.IPv6ExthdrFlags.FRAG.getValue() | + Criterion.IPv6ExthdrFlags.ROUTER.getValue() | + Criterion.IPv6ExthdrFlags.HOP.getValue() | + Criterion.IPv6ExthdrFlags.UNREP.getValue(); + int ipv6ExthdrFlags2 = ipv6ExthdrFlags1 | + Criterion.IPv6ExthdrFlags.UNSEQ.getValue(); + Criterion matchIpv6ExthdrFlags1 = + Criteria.matchIPv6ExthdrFlags(ipv6ExthdrFlags1); + Criterion sameAsMatchIpv6ExthdrFlags1 = + Criteria.matchIPv6ExthdrFlags(ipv6ExthdrFlags1); + Criterion matchIpv6ExthdrFlags2 = + Criteria.matchIPv6ExthdrFlags(ipv6ExthdrFlags2); + + int lambda1 = 1; + int lambda2 = 2; + Criterion matchLambda1 = Criteria.matchLambda(lambda1); + Criterion sameAsMatchLambda1 = Criteria.matchLambda(lambda1); + Criterion matchLambda2 = Criteria.matchLambda(lambda2); + + Criterion matchOchSignalType1 = Criteria.matchOchSignalType(OchSignalType.FIXED_GRID); + Criterion sameAsMatchOchSignalType1 = Criteria.matchOchSignalType(OchSignalType.FIXED_GRID); + Criterion matchOchSignalType2 = Criteria.matchOchSignalType(OchSignalType.FLEX_GRID); + + Criterion matchIndexedLambda1 = Criteria.matchLambda(Lambda.indexedLambda(1)); + Criterion sameAsMatchIndexedLambda1 = Criteria.matchLambda(Lambda.indexedLambda(1)); + Criterion matchIndexedLambda2 = Criteria.matchLambda(Lambda.indexedLambda(2)); + + short signalLambda1 = 1; + short signalLambda2 = 2; + Criterion matchSignalLambda1 = Criteria.matchOpticalSignalType(signalLambda1); + Criterion sameAsMatchSignalLambda1 = Criteria.matchOpticalSignalType(signalLambda1); + Criterion matchSignalLambda2 = Criteria.matchOpticalSignalType(signalLambda2); + + Criterion matchOchSignal1 = + Criteria.matchLambda(Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 4, 8)); + Criterion sameAsMatchOchSignal1 = + Criteria.matchLambda(Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 4, 8)); + Criterion matchOchSignal2 = + Criteria.matchLambda(Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, 4, 8)); + + /** + * Checks that a Criterion object has the proper type, and then converts + * it to the proper type. + * + * @param criterion Criterion object to convert + * @param type Enumerated type value for the Criterion class + * @param clazz Desired Criterion class + * @param <T> The type the caller wants returned + * @return converted object + */ + @SuppressWarnings("unchecked") + private <T> T checkAndConvert(Criterion criterion, Criterion.Type type, Class clazz) { + assertThat(criterion, is(notNullValue())); + assertThat(criterion.type(), is(equalTo(type))); + assertThat(criterion, instanceOf(clazz)); + return (T) criterion; + } + + /** + * Check that the Criteria class is a valid utility class. + */ + @Test + public void testCriteriaUtility() { + assertThatClassIsUtility(Criteria.class); + } + + /** + * Check that the Criteria implementations are immutable. + */ + @Test + public void testCriteriaImmutability() { + assertThatClassIsImmutable(PortCriterion.class); + assertThatClassIsImmutable(MetadataCriterion.class); + assertThatClassIsImmutable(EthCriterion.class); + assertThatClassIsImmutable(EthTypeCriterion.class); + assertThatClassIsImmutable(VlanIdCriterion.class); + assertThatClassIsImmutable(VlanPcpCriterion.class); + assertThatClassIsImmutable(IPDscpCriterion.class); + assertThatClassIsImmutable(IPEcnCriterion.class); + assertThatClassIsImmutable(IPProtocolCriterion.class); + assertThatClassIsImmutable(IPCriterion.class); + assertThatClassIsImmutable(TcpPortCriterion.class); + assertThatClassIsImmutable(UdpPortCriterion.class); + assertThatClassIsImmutable(SctpPortCriterion.class); + assertThatClassIsImmutable(IcmpTypeCriterion.class); + assertThatClassIsImmutable(IcmpCodeCriterion.class); + assertThatClassIsImmutable(IPv6FlowLabelCriterion.class); + assertThatClassIsImmutable(Icmpv6TypeCriterion.class); + assertThatClassIsImmutable(Icmpv6CodeCriterion.class); + assertThatClassIsImmutable(IPv6NDTargetAddressCriterion.class); + assertThatClassIsImmutable(IPv6NDLinkLayerAddressCriterion.class); + assertThatClassIsImmutable(MplsCriterion.class); + assertThatClassIsImmutable(IPv6ExthdrFlagsCriterion.class); + assertThatClassIsImmutable(LambdaCriterion.class); + assertThatClassIsImmutable(OpticalSignalTypeCriterion.class); + } + + // PortCriterion class + + /** + * Test the matchInPort method. + */ + @Test + public void testMatchInPortMethod() { + PortNumber p1 = portNumber(1); + Criterion matchInPort = Criteria.matchInPort(p1); + PortCriterion portCriterion = + checkAndConvert(matchInPort, + Criterion.Type.IN_PORT, + PortCriterion.class); + assertThat(portCriterion.port(), is(equalTo(p1))); + } + + /** + * Test the matchInPhyPort method. + */ + @Test + public void testMatchInPhyPortMethod() { + PortNumber p1 = portNumber(1); + Criterion matchInPhyPort = Criteria.matchInPhyPort(p1); + PortCriterion portCriterion = + checkAndConvert(matchInPhyPort, + Criterion.Type.IN_PHY_PORT, + PortCriterion.class); + assertThat(portCriterion.port(), is(equalTo(p1))); + } + + /** + * Test the equals() method of the PortCriterion class. + */ + @Test + public void testPortCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchInPort1, sameAsMatchInPort1) + .addEqualityGroup(matchInPort2) + .testEquals(); + + new EqualsTester() + .addEqualityGroup(matchInPhyPort1, sameAsMatchInPhyPort1) + .addEqualityGroup(matchInPhyPort2) + .testEquals(); + } + + // MetadataCriterion class + + /** + * Test the matchMetadata method. + */ + @Test + public void testMatchMetadataMethod() { + Long metadata = 12L; + Criterion matchMetadata = Criteria.matchMetadata(metadata); + MetadataCriterion metadataCriterion = + checkAndConvert(matchMetadata, + Criterion.Type.METADATA, + MetadataCriterion.class); + assertThat(metadataCriterion.metadata(), is(equalTo(metadata))); + } + + /** + * Test the equals() method of the MetadataCriterion class. + */ + @Test + public void testMetadataCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchMetadata1, sameAsMatchMetadata1) + .addEqualityGroup(matchMetadata2) + .testEquals(); + } + + // EthCriterion class + + /** + * Test the matchEthDst method. + */ + @Test + public void testMatchEthDstMethod() { + Criterion matchEthDst = Criteria.matchEthDst(mac1); + EthCriterion ethCriterion = + checkAndConvert(matchEthDst, + Criterion.Type.ETH_DST, + EthCriterion.class); + assertThat(ethCriterion.mac(), is(equalTo(mac1))); + } + + /** + * Test the matchEthSrc method. + */ + @Test + public void testMatchEthSrcMethod() { + Criterion matchEthSrc = Criteria.matchEthSrc(mac1); + EthCriterion ethCriterion = + checkAndConvert(matchEthSrc, + Criterion.Type.ETH_SRC, + EthCriterion.class); + assertThat(ethCriterion.mac(), is(mac1)); + } + + /** + * Test the equals() method of the EthCriterion class. + */ + @Test + public void testEthCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchEth1, sameAsMatchEth1) + .addEqualityGroup(matchEth2) + .testEquals(); + } + + // EthTypeCriterion class + + /** + * Test the matchEthType method. + */ + @Test + public void testMatchEthTypeMethod() { + EthType ethType = new EthType(12); + Criterion matchEthType = Criteria.matchEthType(new EthType(12)); + EthTypeCriterion ethTypeCriterion = + checkAndConvert(matchEthType, + Criterion.Type.ETH_TYPE, + EthTypeCriterion.class); + assertThat(ethTypeCriterion.ethType(), is(equalTo(ethType))); + } + + /** + * Test the equals() method of the EthTypeCriterion class. + */ + @Test + public void testEthTypeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchEthType1, sameAsMatchEthType1) + .addEqualityGroup(matchEthType2) + .testEquals(); + } + + // VlanIdCriterion class + + /** + * Test the matchVlanId method. + */ + @Test + public void testMatchVlanIdMethod() { + Criterion matchVlanId = Criteria.matchVlanId(vlanId1); + VlanIdCriterion vlanIdCriterion = + checkAndConvert(matchVlanId, + Criterion.Type.VLAN_VID, + VlanIdCriterion.class); + assertThat(vlanIdCriterion.vlanId(), is(equalTo(vlanId1))); + } + + /** + * Test the equals() method of the VlanIdCriterion class. + */ + @Test + public void testVlanIdCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchVlanId1, sameAsMatchVlanId1) + .addEqualityGroup(matchVlanId2) + .testEquals(); + } + + // VlanPcpCriterion class + + /** + * Test the matchVlanPcp method. + */ + @Test + public void testMatchVlanPcpMethod() { + Criterion matchVlanPcp = Criteria.matchVlanPcp(vlanPcp1); + VlanPcpCriterion vlanPcpCriterion = + checkAndConvert(matchVlanPcp, + Criterion.Type.VLAN_PCP, + VlanPcpCriterion.class); + assertThat(vlanPcpCriterion.priority(), is(equalTo(vlanPcp1))); + } + + /** + * Test the equals() method of the VlanPcpCriterion class. + */ + @Test + public void testVlanPcpCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchVlanPcp1, sameAsMatchVlanPcp1) + .addEqualityGroup(matchVlanPcp2) + .testEquals(); + } + + // IPDscpCriterion class + + /** + * Test the matchIPDscp method. + */ + @Test + public void testMatchIPDscpMethod() { + Criterion matchIPDscp = Criteria.matchIPDscp(ipDscp1); + IPDscpCriterion ipDscpCriterion = + checkAndConvert(matchIPDscp, + Criterion.Type.IP_DSCP, + IPDscpCriterion.class); + assertThat(ipDscpCriterion.ipDscp(), is(equalTo(ipDscp1))); + } + + /** + * Test the equals() method of the IPDscpCriterion class. + */ + @Test + public void testIPDscpCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIpDscp1, sameAsMatchIpDscp1) + .addEqualityGroup(matchIpDscp2) + .testEquals(); + } + + // IPEcnCriterion class + + /** + * Test the matchIPEcn method. + */ + @Test + public void testMatchIPEcnMethod() { + Criterion matchIPEcn = Criteria.matchIPEcn(ipEcn1); + IPEcnCriterion ipEcnCriterion = + checkAndConvert(matchIPEcn, + Criterion.Type.IP_ECN, + IPEcnCriterion.class); + assertThat(ipEcnCriterion.ipEcn(), is(equalTo(ipEcn1))); + } + + /** + * Test the equals() method of the IPEcnCriterion class. + */ + @Test + public void testIPEcnCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIpEcn1, sameAsMatchIpEcn1) + .addEqualityGroup(matchIpEcn2) + .testEquals(); + } + + // IpProtocolCriterion class + + /** + * Test the matchIpProtocol method. + */ + @Test + public void testMatchIpProtocolMethod() { + Criterion matchIPProtocol = Criteria.matchIPProtocol(protocol1); + IPProtocolCriterion ipProtocolCriterion = + checkAndConvert(matchIPProtocol, + Criterion.Type.IP_PROTO, + IPProtocolCriterion.class); + assertThat(ipProtocolCriterion.protocol(), is(equalTo(protocol1))); + } + + /** + * Test the equals() method of the IpProtocolCriterion class. + */ + @Test + public void testIpProtocolCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIpProtocol1, sameAsMatchIpProtocol1) + .addEqualityGroup(matchIpProtocol2) + .testEquals(); + } + + // IPCriterion class + + /** + * Test the matchIPSrc method: IPv4. + */ + @Test + public void testMatchIPSrcMethod() { + Criterion matchIpSrc = Criteria.matchIPSrc(ip1); + IPCriterion ipCriterion = + checkAndConvert(matchIpSrc, + Criterion.Type.IPV4_SRC, + IPCriterion.class); + assertThat(ipCriterion.ip(), is(ip1)); + } + + /** + * Test the matchIPDst method: IPv4. + */ + @Test + public void testMatchIPDstMethod() { + Criterion matchIPDst = Criteria.matchIPDst(ip1); + IPCriterion ipCriterion = + checkAndConvert(matchIPDst, + Criterion.Type.IPV4_DST, + IPCriterion.class); + assertThat(ipCriterion.ip(), is(equalTo(ip1))); + } + + /** + * Test the matchIPSrc method: IPv6. + */ + @Test + public void testMatchIPv6SrcMethod() { + Criterion matchIpv6Src = Criteria.matchIPv6Src(ipv61); + IPCriterion ipCriterion = + checkAndConvert(matchIpv6Src, + Criterion.Type.IPV6_SRC, + IPCriterion.class); + assertThat(ipCriterion.ip(), is(ipv61)); + } + + /** + * Test the matchIPDst method: IPv6. + */ + @Test + public void testMatchIPv6DstMethod() { + Criterion matchIPv6Dst = Criteria.matchIPv6Dst(ipv61); + IPCriterion ipCriterion = + checkAndConvert(matchIPv6Dst, + Criterion.Type.IPV6_DST, + IPCriterion.class); + assertThat(ipCriterion.ip(), is(equalTo(ipv61))); + } + + /** + * Test the equals() method of the IpCriterion class. + */ + @Test + public void testIPCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIp1, sameAsMatchIp1) + .addEqualityGroup(matchIp2) + .testEquals(); + + new EqualsTester() + .addEqualityGroup(matchIpv61, sameAsMatchIpv61) + .addEqualityGroup(matchIpv62) + .testEquals(); + } + + // TcpPortCriterion class + + /** + * Test the matchTcpSrc method. + */ + @Test + public void testMatchTcpSrcMethod() { + Criterion matchTcpSrc = Criteria.matchTcpSrc(tpPort1); + TcpPortCriterion tcpPortCriterion = + checkAndConvert(matchTcpSrc, + Criterion.Type.TCP_SRC, + TcpPortCriterion.class); + assertThat(tcpPortCriterion.tcpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the matchTcpDst method. + */ + @Test + public void testMatchTcpDstMethod() { + Criterion matchTcpDst = Criteria.matchTcpDst(tpPort1); + TcpPortCriterion tcpPortCriterion = + checkAndConvert(matchTcpDst, + Criterion.Type.TCP_DST, + TcpPortCriterion.class); + assertThat(tcpPortCriterion.tcpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the equals() method of the TcpPortCriterion class. + */ + @Test + public void testTcpPortCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchTcpPort1, sameAsMatchTcpPort1) + .addEqualityGroup(matchTcpPort2) + .testEquals(); + } + + // UdpPortCriterion class + + /** + * Test the matchUdpSrc method. + */ + @Test + public void testMatchUdpSrcMethod() { + Criterion matchUdpSrc = Criteria.matchUdpSrc(tpPort1); + UdpPortCriterion udpPortCriterion = + checkAndConvert(matchUdpSrc, + Criterion.Type.UDP_SRC, + UdpPortCriterion.class); + assertThat(udpPortCriterion.udpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the matchUdpDst method. + */ + @Test + public void testMatchUdpDstMethod() { + Criterion matchUdpDst = Criteria.matchUdpDst(tpPort1); + UdpPortCriterion udpPortCriterion = + checkAndConvert(matchUdpDst, + Criterion.Type.UDP_DST, + UdpPortCriterion.class); + assertThat(udpPortCriterion.udpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the equals() method of the UdpPortCriterion class. + */ + @Test + public void testUdpPortCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchUdpPort1, sameAsMatchUdpPort1) + .addEqualityGroup(matchUdpPort2) + .testEquals(); + } + + // SctpPortCriterion class + + /** + * Test the matchSctpSrc method. + */ + @Test + public void testMatchSctpSrcMethod() { + Criterion matchSctpSrc = Criteria.matchSctpSrc(tpPort1); + SctpPortCriterion sctpPortCriterion = + checkAndConvert(matchSctpSrc, + Criterion.Type.SCTP_SRC, + SctpPortCriterion.class); + assertThat(sctpPortCriterion.sctpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the matchSctpDst method. + */ + @Test + public void testMatchSctpDstMethod() { + Criterion matchSctpDst = Criteria.matchSctpDst(tpPort1); + SctpPortCriterion sctpPortCriterion = + checkAndConvert(matchSctpDst, + Criterion.Type.SCTP_DST, + SctpPortCriterion.class); + assertThat(sctpPortCriterion.sctpPort(), is(equalTo(tpPort1))); + } + + /** + * Test the equals() method of the SctpPortCriterion class. + */ + @Test + public void testSctpPortCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchSctpPort1, sameAsMatchSctpPort1) + .addEqualityGroup(matchSctpPort2) + .testEquals(); + } + + // IcmpTypeCriterion class + + /** + * Test the matchIcmpType method. + */ + @Test + public void testMatchIcmpTypeMethod() { + short icmpType = 12; + Criterion matchIcmpType = Criteria.matchIcmpType(icmpType); + IcmpTypeCriterion icmpTypeCriterion = + checkAndConvert(matchIcmpType, + Criterion.Type.ICMPV4_TYPE, + IcmpTypeCriterion.class); + assertThat(icmpTypeCriterion.icmpType(), is(equalTo(icmpType))); + } + + /** + * Test the equals() method of the IcmpTypeCriterion class. + */ + @Test + public void testIcmpTypeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIcmpType1, sameAsMatchIcmpType1) + .addEqualityGroup(matchIcmpType2) + .testEquals(); + } + + // IcmpCodeCriterion class + + /** + * Test the matchIcmpCode method. + */ + @Test + public void testMatchIcmpCodeMethod() { + short icmpCode = 12; + Criterion matchIcmpCode = Criteria.matchIcmpCode(icmpCode); + IcmpCodeCriterion icmpCodeCriterion = + checkAndConvert(matchIcmpCode, + Criterion.Type.ICMPV4_CODE, + IcmpCodeCriterion.class); + assertThat(icmpCodeCriterion.icmpCode(), is(equalTo(icmpCode))); + } + + /** + * Test the equals() method of the IcmpCodeCriterion class. + */ + @Test + public void testIcmpCodeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIcmpCode1, sameAsMatchIcmpCode1) + .addEqualityGroup(matchIcmpCode2) + .testEquals(); + } + + // IPv6FlowLabelCriterion class + + /** + * Test the matchIPv6FlowLabel method. + */ + @Test + public void testMatchIPv6FlowLabelMethod() { + int flowLabel = 12; + Criterion matchFlowLabel = Criteria.matchIPv6FlowLabel(flowLabel); + IPv6FlowLabelCriterion flowLabelCriterion = + checkAndConvert(matchFlowLabel, + Criterion.Type.IPV6_FLABEL, + IPv6FlowLabelCriterion.class); + assertThat(flowLabelCriterion.flowLabel(), is(equalTo(flowLabel))); + } + + /** + * Test the equals() method of the IPv6FlowLabelCriterion class. + */ + @Test + public void testIPv6FlowLabelCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchFlowLabel1, sameAsMatchFlowLabel1) + .addEqualityGroup(matchFlowLabel2) + .testEquals(); + } + + // Icmpv6TypeCriterion class + + /** + * Test the matchIcmpv6Type method. + */ + @Test + public void testMatchIcmpv6TypeMethod() { + short icmpv6Type = 12; + Criterion matchIcmpv6Type = Criteria.matchIcmpv6Type(icmpv6Type); + Icmpv6TypeCriterion icmpv6TypeCriterion = + checkAndConvert(matchIcmpv6Type, + Criterion.Type.ICMPV6_TYPE, + Icmpv6TypeCriterion.class); + assertThat(icmpv6TypeCriterion.icmpv6Type(), is(equalTo(icmpv6Type))); + } + + /** + * Test the equals() method of the Icmpv6TypeCriterion class. + */ + @Test + public void testIcmpv6TypeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIcmpv6Type1, sameAsMatchIcmpv6Type1) + .addEqualityGroup(matchIcmpv6Type2) + .testEquals(); + } + + // Icmpv6CodeCriterion class + + /** + * Test the matchIcmpv6Code method. + */ + @Test + public void testMatchIcmpv6CodeMethod() { + short icmpv6Code = 12; + Criterion matchIcmpv6Code = Criteria.matchIcmpv6Code(icmpv6Code); + Icmpv6CodeCriterion icmpv6CodeCriterion = + checkAndConvert(matchIcmpv6Code, + Criterion.Type.ICMPV6_CODE, + Icmpv6CodeCriterion.class); + assertThat(icmpv6CodeCriterion.icmpv6Code(), is(equalTo(icmpv6Code))); + } + + /** + * Test the equals() method of the Icmpv6CodeCriterion class. + */ + @Test + public void testIcmpv6CodeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIcmpv6Code1, sameAsMatchIcmpv6Code1) + .addEqualityGroup(matchIcmpv6Code2) + .testEquals(); + } + + // IPv6NDTargetAddressCriterion class + + /** + * Test the matchIPv6NDTargetAddress method. + */ + @Test + public void testMatchIPv6NDTargetAddressMethod() { + Criterion matchTargetAddress = + Criteria.matchIPv6NDTargetAddress(ip6TargetAddress1); + IPv6NDTargetAddressCriterion targetAddressCriterion = + checkAndConvert(matchTargetAddress, + Criterion.Type.IPV6_ND_TARGET, + IPv6NDTargetAddressCriterion.class); + assertThat(targetAddressCriterion.targetAddress(), + is(ip6TargetAddress1)); + } + + /** + * Test the equals() method of the IPv6NDTargetAddressCriterion class. + */ + @Test + public void testIPv6NDTargetAddressCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIpv6TargetAddr1, + sameAsMatchIpv6TargetAddr1) + .addEqualityGroup(matchIpv6TargetAddr2) + .testEquals(); + } + + // IPv6NDLinkLayerAddressCriterion class + + /** + * Test the matchIPv6NDSourceLinkLayerAddress method. + */ + @Test + public void testMatchIPv6NDSourceLinkLayerAddressMethod() { + Criterion matchSrcLlAddr = + Criteria.matchIPv6NDSourceLinkLayerAddress(llMac1); + IPv6NDLinkLayerAddressCriterion srcLlCriterion = + checkAndConvert(matchSrcLlAddr, + Criterion.Type.IPV6_ND_SLL, + IPv6NDLinkLayerAddressCriterion.class); + assertThat(srcLlCriterion.mac(), is(equalTo(llMac1))); + } + + /** + * Test the matchIPv6NDTargetLinkLayerAddress method. + */ + @Test + public void testMatchIPv6NDTargetLinkLayerAddressMethod() { + Criterion matchTargetLlAddr = + Criteria.matchIPv6NDTargetLinkLayerAddress(llMac1); + IPv6NDLinkLayerAddressCriterion targetLlCriterion = + checkAndConvert(matchTargetLlAddr, + Criterion.Type.IPV6_ND_TLL, + IPv6NDLinkLayerAddressCriterion.class); + assertThat(targetLlCriterion.mac(), is(equalTo(llMac1))); + } + + /** + * Test the equals() method of the IPv6NDLinkLayerAddressCriterion class. + */ + @Test + public void testIPv6NDLinkLayerAddressCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchSrcLlAddr1, sameAsMatchSrcLlAddr1) + .addEqualityGroup(matchSrcLlAddr2) + .testEquals(); + + new EqualsTester() + .addEqualityGroup(matchTargetLlAddr1, sameAsMatchTargetLlAddr1) + .addEqualityGroup(matchTargetLlAddr2) + .testEquals(); + } + + // MplsCriterion class + + /** + * Test the matchMplsLabel method. + */ + @Test + public void testMatchMplsLabelMethod() { + Criterion matchMplsLabel = Criteria.matchMplsLabel(mpls1); + MplsCriterion mplsCriterion = + checkAndConvert(matchMplsLabel, + Criterion.Type.MPLS_LABEL, + MplsCriterion.class); + assertThat(mplsCriterion.label(), is(equalTo(mpls1))); + } + + /** + * Test the equals() method of the MplsCriterion class. + */ + @Test + public void testMplsCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchMpls1, sameAsMatchMpls1) + .addEqualityGroup(matchMpls2) + .testEquals(); + } + + // TunnelIdCriterion class + + /** + * Test the matchTunnelId method. + */ + @Test + public void testMatchTunnelIdMethod() { + Criterion matchTunnelId = Criteria.matchTunnelId(tunnelId1); + TunnelIdCriterion tunnelIdCriterion = + checkAndConvert(matchTunnelId, + Criterion.Type.TUNNEL_ID, + TunnelIdCriterion.class); + assertThat(tunnelIdCriterion.tunnelId(), is(equalTo(tunnelId1))); + + } + + /** + * Test the equals() method of the TunnelIdCriterion class. + */ + @Test + public void testTunnelIdCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchTunnelId1, sameAsMatchTunnelId1) + .addEqualityGroup(matchTunnelId2) + .testEquals(); + } + + // IPv6ExthdrFlagsCriterion class + + /** + * Test the matchIPv6ExthdrFlags method. + */ + @Test + public void testMatchIPv6ExthdrFlagsMethod() { + Criterion matchExthdrFlags = + Criteria.matchIPv6ExthdrFlags(ipv6ExthdrFlags1); + IPv6ExthdrFlagsCriterion exthdrFlagsCriterion = + checkAndConvert(matchExthdrFlags, + Criterion.Type.IPV6_EXTHDR, + IPv6ExthdrFlagsCriterion.class); + assertThat(exthdrFlagsCriterion.exthdrFlags(), + is(equalTo(ipv6ExthdrFlags1))); + } + + /** + * Test the equals() method of the IPv6ExthdrFlagsCriterion class. + */ + @Test + public void testIPv6ExthdrFlagsCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIpv6ExthdrFlags1, + sameAsMatchIpv6ExthdrFlags1) + .addEqualityGroup(matchIpv6ExthdrFlags2) + .testEquals(); + } + + // LambdaCriterion class + + /** + * Test the matchLambda method. + */ + @Test + public void testMatchLambdaMethod() { + Criterion matchLambda = Criteria.matchLambda(lambda1); + LambdaCriterion lambdaCriterion = + checkAndConvert(matchLambda, + Criterion.Type.OCH_SIGID, + LambdaCriterion.class); + assertThat(lambdaCriterion.lambda(), is(equalTo(lambda1))); + } + + /** + * Test the equals() method of the LambdaCriterion class. + */ + @Test + public void testLambdaCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchLambda1, sameAsMatchLambda1) + .addEqualityGroup(matchLambda2) + .testEquals(); + } + + @Test + public void testIndexedLambdaCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchIndexedLambda1, sameAsMatchIndexedLambda1) + .addEqualityGroup(matchIndexedLambda2) + .testEquals(); + } + + @Test + public void testOchSignalCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchOchSignal1, sameAsMatchOchSignal1) + .addEqualityGroup(matchOchSignal2) + .testEquals(); + } + + /** + * Test the equals() method of the OchSignalTypeCriterion class. + */ + @Test + public void testOchSignalTypeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchOchSignalType1, sameAsMatchOchSignalType1) + .addEqualityGroup(matchOchSignalType2) + .testEquals(); + } + + // OpticalSignalTypeCriterion class + + /** + * Test the matchOpticalSignalType method. + */ + @Test + public void testMatchOpticalSignalTypeMethod() { + Criterion matchLambda = Criteria.matchOpticalSignalType(signalLambda1); + OpticalSignalTypeCriterion opticalSignalTypeCriterion = + checkAndConvert(matchLambda, + Criterion.Type.OCH_SIGTYPE, + OpticalSignalTypeCriterion.class); + assertThat(opticalSignalTypeCriterion.signalType(), is(equalTo(signalLambda1))); + } + + /** + * Test the equals() method of the OpticalSignalTypeCriterion class. + */ + @Test + public void testOpticalSignalTypeCriterionEquals() { + new EqualsTester() + .addEqualityGroup(matchSignalLambda1, sameAsMatchSignalLambda1) + .addEqualityGroup(matchSignalLambda2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/instructions/InstructionsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/instructions/InstructionsTest.java new file mode 100644 index 00000000..410349b5 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flow/instructions/InstructionsTest.java @@ -0,0 +1,725 @@ +/* + * 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.net.flow.instructions; + +import org.junit.Test; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.MplsLabel; +import org.onlab.packet.TpPort; +import org.onlab.packet.VlanId; +import org.onosproject.net.ChannelSpacing; +import org.onosproject.net.GridType; +import org.onosproject.net.IndexedLambda; +import org.onosproject.net.Lambda; +import org.onosproject.net.PortNumber; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onlab.junit.UtilityClassChecker.assertThatClassIsUtility; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Unit tests for the Instructions class. + */ +public class InstructionsTest { + + /** + * Checks that a Criterion object has the proper type, and then converts + * it to the proper type. + * + * @param instruction Instruction object to convert + * @param type Enumerated type value for the Criterion class + * @param clazz Desired Criterion class + * @param <T> The type the caller wants returned + * @return converted object + */ + @SuppressWarnings("unchecked") + private <T> T checkAndConvert(Instruction instruction, Instruction.Type type, Class clazz) { + assertThat(instruction, is(notNullValue())); + assertThat(instruction.type(), is(equalTo(type))); + assertThat(instruction, instanceOf(clazz)); + return (T) instruction; + } + + /** + * Checks the equals() and toString() methods of a Criterion class. + * + * @param c1 first object to compare + * @param c1match object that should be equal to the first + * @param c2 object that should be not equal to the first + * @param <T> type of the arguments + */ + private <T extends Instruction> void checkEqualsAndToString(T c1, T c1match, + T c2) { + + new EqualsTester() + .addEqualityGroup(c1, c1match) + .addEqualityGroup(c2) + .testEquals(); + } + + /** + * Checks that Instructions is a proper utility class. + */ + @Test + public void testInstructionsUtilityClass() { + assertThatClassIsUtility(Instructions.class); + } + + /** + * Checks that the Instruction class implementations are immutable. + */ + @Test + public void testImmutabilityOfInstructions() { + assertThatClassIsImmutable(Instructions.DropInstruction.class); + assertThatClassIsImmutable(Instructions.OutputInstruction.class); + assertThatClassIsImmutable(L0ModificationInstruction.ModLambdaInstruction.class); + assertThatClassIsImmutable(L0ModificationInstruction.ModOchSignalInstruction.class); + assertThatClassIsImmutable(L2ModificationInstruction.ModEtherInstruction.class); + assertThatClassIsImmutable(L2ModificationInstruction.ModVlanIdInstruction.class); + assertThatClassIsImmutable(L2ModificationInstruction.ModVlanPcpInstruction.class); + assertThatClassIsImmutable(L3ModificationInstruction.ModIPInstruction.class); + assertThatClassIsImmutable(L3ModificationInstruction.ModIPv6FlowLabelInstruction.class); + assertThatClassIsImmutable(L2ModificationInstruction.ModMplsLabelInstruction.class); + assertThatClassIsImmutable(L2ModificationInstruction.PushHeaderInstructions.class); + } + + // DropInstruction + + private final Instructions.DropInstruction drop1 = Instructions.createDrop(); + private final Instructions.DropInstruction drop2 = Instructions.createDrop(); + + /** + * Test the createDrop method. + */ + @Test + public void testCreateDropMethod() { + Instructions.DropInstruction instruction = Instructions.createDrop(); + checkAndConvert(instruction, + Instruction.Type.DROP, + Instructions.DropInstruction.class); + } + + /** + * Test the equals() method of the DropInstruction class. + */ + + @Test + public void testDropInstructionEquals() throws Exception { + assertThat(drop1, is(equalTo(drop2))); + } + + /** + * Test the hashCode() method of the DropInstruction class. + */ + + @Test + public void testDropInstructionHashCode() { + assertThat(drop1.hashCode(), is(equalTo(drop2.hashCode()))); + } + + // OutputInstruction + + private final PortNumber port1 = portNumber(1); + private final PortNumber port2 = portNumber(2); + private final Instructions.OutputInstruction output1 = Instructions.createOutput(port1); + private final Instructions.OutputInstruction sameAsOutput1 = Instructions.createOutput(port1); + private final Instructions.OutputInstruction output2 = Instructions.createOutput(port2); + + /** + * Test the createOutput method. + */ + @Test + public void testCreateOutputMethod() { + final Instruction instruction = Instructions.createOutput(port2); + final Instructions.OutputInstruction outputInstruction = + checkAndConvert(instruction, + Instruction.Type.OUTPUT, + Instructions.OutputInstruction.class); + assertThat(outputInstruction.port(), is(equalTo(port2))); + } + + + /** + * Test the equals() method of the OutputInstruction class. + */ + + @Test + public void testOutputInstructionEquals() throws Exception { + checkEqualsAndToString(output1, sameAsOutput1, output2); + } + + /** + * Test the hashCode() method of the OutputInstruction class. + */ + + @Test + public void testOutputInstructionHashCode() { + assertThat(output1.hashCode(), is(equalTo(sameAsOutput1.hashCode()))); + assertThat(output1.hashCode(), is(not(equalTo(output2.hashCode())))); + } + + // ModLambdaInstruction + + private final IndexedLambda lambda1 = new IndexedLambda(1); + private final IndexedLambda lambda2 = new IndexedLambda(2); + private final Instruction lambdaInstruction1 = Instructions.modL0Lambda(lambda1); + private final Instruction sameAsLambdaInstruction1 = Instructions.modL0Lambda(lambda1); + private final Instruction lambdaInstruction2 = Instructions.modL0Lambda(lambda2); + + /** + * Test the modL0Lambda method. + */ + @Test + public void testCreateLambdaMethod() { + final Instruction instruction = Instructions.modL0Lambda(lambda1); + final L0ModificationInstruction.ModLambdaInstruction lambdaInstruction = + checkAndConvert(instruction, + Instruction.Type.L0MODIFICATION, + L0ModificationInstruction.ModLambdaInstruction.class); + assertThat(lambdaInstruction.lambda(), is(equalTo((short) lambda1.index()))); + } + + /** + * Test the equals() method of the ModLambdaInstruction class. + */ + + @Test + public void testModLambdaInstructionEquals() throws Exception { + checkEqualsAndToString(lambdaInstruction1, + sameAsLambdaInstruction1, + lambdaInstruction2); + } + + /** + * Test the hashCode() method of the ModLambdaInstruction class. + */ + + @Test + public void testModLambdaInstructionHashCode() { + assertThat(lambdaInstruction1.hashCode(), + is(equalTo(sameAsLambdaInstruction1.hashCode()))); + assertThat(lambdaInstruction1.hashCode(), + is(not(equalTo(lambdaInstruction2.hashCode())))); + } + + private final Lambda och1 = Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 4, 8); + private final Lambda och2 = Lambda.ochSignal(GridType.CWDM, ChannelSpacing.CHL_100GHZ, 4, 8); + private final Instruction ochInstruction1 = Instructions.modL0Lambda(och1); + private final Instruction sameAsOchInstruction1 = Instructions.modL0Lambda(och1); + private final Instruction ochInstruction2 = Instructions.modL0Lambda(och2); + + /** + * Test the modL0Lambda(). + */ + @Test + public void testModL0LambdaMethod() { + Instruction instruction = Instructions.modL0Lambda(och1); + L0ModificationInstruction.ModOchSignalInstruction ochInstruction = + checkAndConvert(instruction, Instruction.Type.L0MODIFICATION, + L0ModificationInstruction.ModOchSignalInstruction.class); + assertThat(ochInstruction.lambda(), is(och1)); + } + + /** + * Test the equals() method of the ModOchSignalInstruction class. + */ + @Test + public void testModOchSignalInstructionEquals() { + checkEqualsAndToString(ochInstruction1, sameAsOchInstruction1, ochInstruction2); + } + + /** + * Test the hashCode() method of the ModOchSignalInstruction class. + */ + @Test + public void testModOchSignalInstructionHashCode() { + assertThat(ochInstruction1.hashCode(), is(sameAsOchInstruction1.hashCode())); + assertThat(ochInstruction1.hashCode(), is(not(ochInstruction2.hashCode()))); + } + + // ModEtherInstruction + + private static final String MAC1 = "00:00:00:00:00:01"; + private static final String MAC2 = "00:00:00:00:00:02"; + private final MacAddress mac1 = MacAddress.valueOf(MAC1); + private final MacAddress mac2 = MacAddress.valueOf(MAC2); + private final Instruction modEtherInstruction1 = Instructions.modL2Src(mac1); + private final Instruction sameAsModEtherInstruction1 = Instructions.modL2Src(mac1); + private final Instruction modEtherInstruction2 = Instructions.modL2Src(mac2); + + /** + * Test the modL2Src method. + */ + @Test + public void testModL2SrcMethod() { + final Instruction instruction = Instructions.modL2Src(mac1); + final L2ModificationInstruction.ModEtherInstruction modEtherInstruction = + checkAndConvert(instruction, + Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModEtherInstruction.class); + assertThat(modEtherInstruction.mac(), is(equalTo(mac1))); + assertThat(modEtherInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.ETH_SRC))); + } + + /** + * Test the modL2Dst method. + */ + @Test + public void testModL2DstMethod() { + final Instruction instruction = Instructions.modL2Dst(mac1); + final L2ModificationInstruction.ModEtherInstruction modEtherInstruction = + checkAndConvert(instruction, + Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModEtherInstruction.class); + assertThat(modEtherInstruction.mac(), is(equalTo(mac1))); + assertThat(modEtherInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.ETH_DST))); + } + + /** + * Test the equals() method of the ModEtherInstruction class. + */ + + @Test + public void testModEtherInstructionEquals() throws Exception { + checkEqualsAndToString(modEtherInstruction1, + sameAsModEtherInstruction1, + modEtherInstruction2); + } + + /** + * Test the hashCode() method of the ModEtherInstruction class. + */ + + @Test + public void testModEtherInstructionHashCode() { + assertThat(modEtherInstruction1.hashCode(), + is(equalTo(sameAsModEtherInstruction1.hashCode()))); + assertThat(modEtherInstruction1.hashCode(), + is(not(equalTo(modEtherInstruction2.hashCode())))); + } + + + // ModVlanIdInstruction + + private final short vlan1 = 1; + private final short vlan2 = 2; + private final VlanId vlanId1 = VlanId.vlanId(vlan1); + private final VlanId vlanId2 = VlanId.vlanId(vlan2); + private final Instruction modVlanId1 = Instructions.modVlanId(vlanId1); + private final Instruction sameAsModVlanId1 = Instructions.modVlanId(vlanId1); + private final Instruction modVlanId2 = Instructions.modVlanId(vlanId2); + + /** + * Test the modVlanId method. + */ + @Test + public void testModVlanIdMethod() { + final Instruction instruction = Instructions.modVlanId(vlanId1); + final L2ModificationInstruction.ModVlanIdInstruction modEtherInstruction = + checkAndConvert(instruction, + Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModVlanIdInstruction.class); + assertThat(modEtherInstruction.vlanId(), is(equalTo(vlanId1))); + assertThat(modEtherInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.VLAN_ID))); + } + + /** + * Test the equals() method of the ModVlanIdInstruction class. + */ + + @Test + public void testModVlanIdInstructionEquals() throws Exception { + checkEqualsAndToString(modVlanId1, + sameAsModVlanId1, + modVlanId2); + } + + /** + * Test the hashCode() method of the ModEtherInstruction class. + */ + + @Test + public void testModVlanIdInstructionHashCode() { + assertThat(modVlanId1.hashCode(), + is(equalTo(sameAsModVlanId1.hashCode()))); + assertThat(modVlanId1.hashCode(), + is(not(equalTo(modVlanId2.hashCode())))); + } + + + // ModVlanPcpInstruction + + private final byte vlanPcp1 = 1; + private final byte vlanPcp2 = 2; + private final Instruction modVlanPcp1 = Instructions.modVlanPcp(vlanPcp1); + private final Instruction sameAsModVlanPcp1 = Instructions.modVlanPcp(vlanPcp1); + private final Instruction modVlanPcp2 = Instructions.modVlanPcp(vlanPcp2); + + /** + * Test the modVlanPcp method. + */ + @Test + public void testModVlanPcpMethod() { + final Instruction instruction = Instructions.modVlanPcp(vlanPcp1); + final L2ModificationInstruction.ModVlanPcpInstruction modEtherInstruction = + checkAndConvert(instruction, + Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModVlanPcpInstruction.class); + assertThat(modEtherInstruction.vlanPcp(), is(equalTo(vlanPcp1))); + assertThat(modEtherInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.VLAN_PCP))); + } + + /** + * Test the equals() method of the ModVlanPcpInstruction class. + */ + + @Test + public void testModVlanPcpInstructionEquals() throws Exception { + checkEqualsAndToString(modVlanPcp1, + sameAsModVlanPcp1, + modVlanPcp2); + } + + /** + * Test the hashCode() method of the ModEtherInstruction class. + */ + + @Test + public void testModVlanPcpInstructionHashCode() { + assertThat(modVlanPcp1.hashCode(), + is(equalTo(sameAsModVlanPcp1.hashCode()))); + assertThat(modVlanPcp1.hashCode(), + is(not(equalTo(modVlanPcp2.hashCode())))); + } + + // ModIPInstruction + + private static final String IP41 = "1.2.3.4"; + private static final String IP42 = "5.6.7.8"; + private IpAddress ip41 = IpAddress.valueOf(IP41); + private IpAddress ip42 = IpAddress.valueOf(IP42); + private final Instruction modIPInstruction1 = Instructions.modL3Src(ip41); + private final Instruction sameAsModIPInstruction1 = Instructions.modL3Src(ip41); + private final Instruction modIPInstruction2 = Instructions.modL3Src(ip42); + + private static final String IP61 = "1111::2222"; + private static final String IP62 = "3333::4444"; + private IpAddress ip61 = IpAddress.valueOf(IP61); + private IpAddress ip62 = IpAddress.valueOf(IP62); + private final Instruction modIPv6Instruction1 = + Instructions.modL3IPv6Src(ip61); + private final Instruction sameAsModIPv6Instruction1 = + Instructions.modL3IPv6Src(ip61); + private final Instruction modIPv6Instruction2 = + Instructions.modL3IPv6Src(ip62); + + /** + * Test the modL3Src method. + */ + @Test + public void testModL3SrcMethod() { + final Instruction instruction = Instructions.modL3Src(ip41); + final L3ModificationInstruction.ModIPInstruction modIPInstruction = + checkAndConvert(instruction, + Instruction.Type.L3MODIFICATION, + L3ModificationInstruction.ModIPInstruction.class); + assertThat(modIPInstruction.ip(), is(equalTo(ip41))); + assertThat(modIPInstruction.subtype(), + is(equalTo(L3ModificationInstruction.L3SubType.IPV4_SRC))); + } + + /** + * Test the modL3Dst method. + */ + @Test + public void testModL3DstMethod() { + final Instruction instruction = Instructions.modL3Dst(ip41); + final L3ModificationInstruction.ModIPInstruction modIPInstruction = + checkAndConvert(instruction, + Instruction.Type.L3MODIFICATION, + L3ModificationInstruction.ModIPInstruction.class); + assertThat(modIPInstruction.ip(), is(equalTo(ip41))); + assertThat(modIPInstruction.subtype(), + is(equalTo(L3ModificationInstruction.L3SubType.IPV4_DST))); + } + + /** + * Test the modL3IPv6Src method. + */ + @Test + public void testModL3IPv6SrcMethod() { + final Instruction instruction = Instructions.modL3IPv6Src(ip61); + final L3ModificationInstruction.ModIPInstruction modIPInstruction = + checkAndConvert(instruction, + Instruction.Type.L3MODIFICATION, + L3ModificationInstruction.ModIPInstruction.class); + assertThat(modIPInstruction.ip(), is(equalTo(ip61))); + assertThat(modIPInstruction.subtype(), + is(equalTo(L3ModificationInstruction.L3SubType.IPV6_SRC))); + } + + /** + * Test the modL3IPv6Dst method. + */ + @Test + public void testModL3IPv6DstMethod() { + final Instruction instruction = Instructions.modL3IPv6Dst(ip61); + final L3ModificationInstruction.ModIPInstruction modIPInstruction = + checkAndConvert(instruction, + Instruction.Type.L3MODIFICATION, + L3ModificationInstruction.ModIPInstruction.class); + assertThat(modIPInstruction.ip(), is(equalTo(ip61))); + assertThat(modIPInstruction.subtype(), + is(equalTo(L3ModificationInstruction.L3SubType.IPV6_DST))); + } + + /** + * Test the equals() method of the ModIPInstruction class. + */ + @Test + public void testModIPInstructionEquals() throws Exception { + checkEqualsAndToString(modIPInstruction1, + sameAsModIPInstruction1, + modIPInstruction2); + } + + /** + * Test the hashCode() method of the ModIPInstruction class. + */ + @Test + public void testModIPInstructionHashCode() { + assertThat(modIPInstruction1.hashCode(), + is(equalTo(sameAsModIPInstruction1.hashCode()))); + assertThat(modIPInstruction1.hashCode(), + is(not(equalTo(modIPInstruction2.hashCode())))); + } + + private final int flowLabel1 = 0x11111; + private final int flowLabel2 = 0x22222; + private final Instruction modIPv6FlowLabelInstruction1 = + Instructions.modL3IPv6FlowLabel(flowLabel1); + private final Instruction sameAsModIPv6FlowLabelInstruction1 = + Instructions.modL3IPv6FlowLabel(flowLabel1); + private final Instruction modIPv6FlowLabelInstruction2 = + Instructions.modL3IPv6FlowLabel(flowLabel2); + + /** + * Test the modL3IPv6FlowLabel method. + */ + @Test + public void testModL3IPv6FlowLabelMethod() { + final Instruction instruction = + Instructions.modL3IPv6FlowLabel(flowLabel1); + final L3ModificationInstruction.ModIPv6FlowLabelInstruction + modIPv6FlowLabelInstruction = + checkAndConvert(instruction, + Instruction.Type.L3MODIFICATION, + L3ModificationInstruction.ModIPv6FlowLabelInstruction.class); + assertThat(modIPv6FlowLabelInstruction.flowLabel(), + is(equalTo(flowLabel1))); + assertThat(modIPv6FlowLabelInstruction.subtype(), + is(equalTo(L3ModificationInstruction.L3SubType.IPV6_FLABEL))); + } + + /** + * Test the equals() method of the ModIPv6FlowLabelInstruction class. + */ + @Test + public void testModIPv6FlowLabelInstructionEquals() throws Exception { + checkEqualsAndToString(modIPv6FlowLabelInstruction1, + sameAsModIPv6FlowLabelInstruction1, + modIPv6FlowLabelInstruction2); + } + + /** + * Test the hashCode() method of the ModIPv6FlowLabelInstruction class. + */ + @Test + public void testModIPv6FlowLabelInstructionHashCode() { + assertThat(modIPv6FlowLabelInstruction1.hashCode(), + is(equalTo(sameAsModIPv6FlowLabelInstruction1.hashCode()))); + assertThat(modIPv6FlowLabelInstruction1.hashCode(), + is(not(equalTo(modIPv6FlowLabelInstruction2.hashCode())))); + } + + private Instruction modMplsLabelInstruction1 = Instructions.modMplsLabel(MplsLabel.mplsLabel(1)); + private Instruction sameAsModMplsLabelInstruction1 = Instructions.modMplsLabel(MplsLabel.mplsLabel(1)); + private Instruction modMplsLabelInstruction2 = Instructions.modMplsLabel(MplsLabel.mplsLabel(2)); + + /** + * Test the modMplsLabel method. + */ + @Test + public void testModMplsMethod() { + final MplsLabel mplsLabel = MplsLabel.mplsLabel(33); + final Instruction instruction = Instructions.modMplsLabel(mplsLabel); + final L2ModificationInstruction.ModMplsLabelInstruction modMplsLabelInstruction = + checkAndConvert(instruction, + Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModMplsLabelInstruction.class); + assertThat(modMplsLabelInstruction.mplsLabel(), is(equalTo(mplsLabel))); + assertThat(modMplsLabelInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.MPLS_LABEL))); + } + + /** + * Test the equals(), hashCode and toString() methods of the + * ModMplsLabelInstruction class. + */ + @Test + public void testModMplsLabelInstructionEquals() throws Exception { + checkEqualsAndToString(modMplsLabelInstruction1, + sameAsModMplsLabelInstruction1, + modMplsLabelInstruction2); + } + + // ModTunnelIdInstruction + + private final long tunnelId1 = 1L; + private final long tunnelId2 = 2L; + private final Instruction modTunnelId1 = Instructions.modTunnelId(tunnelId1); + private final Instruction sameAsModTunnelId1 = Instructions.modTunnelId(tunnelId1); + private final Instruction modTunnelId2 = Instructions.modTunnelId(tunnelId2); + + /** + * Test the modTunnelId method. + */ + @Test + public void testModTunnelIdMethod() { + final Instruction instruction = Instructions.modTunnelId(tunnelId1); + final L2ModificationInstruction.ModTunnelIdInstruction modTunnelIdInstruction = + checkAndConvert(instruction, Instruction.Type.L2MODIFICATION, + L2ModificationInstruction.ModTunnelIdInstruction.class); + assertThat(modTunnelIdInstruction.tunnelId(), is(equalTo(tunnelId1))); + assertThat(modTunnelIdInstruction.subtype(), + is(equalTo(L2ModificationInstruction.L2SubType.TUNNEL_ID))); + } + + /*** + * Test the equals() method of the ModTunnelIdInstruction class. + */ + @Test + public void testModTunnelIdInstructionEquals() throws Exception { + checkEqualsAndToString(modTunnelId1, sameAsModTunnelId1, modTunnelId2); + } + + /** + * Test the hashCode() method of the ModTunnelIdInstruction class. + */ + @Test + public void testModTunnelIdInstructionHashCode() { + assertThat(modTunnelId1.hashCode(), is(equalTo(sameAsModTunnelId1.hashCode()))); + assertThat(modTunnelId1.hashCode(), is(not(equalTo(modTunnelId2.hashCode())))); + } + + // ModTransportPortInstruction + + private final TpPort tpPort1 = TpPort.tpPort(1); + private final TpPort tpPort2 = TpPort.tpPort(2); + private final Instruction modTransportPortInstruction1 = Instructions.modTcpSrc(tpPort1); + private final Instruction sameAsModTransportPortInstruction1 = Instructions.modTcpSrc(tpPort1); + private final Instruction modTransportPortInstruction2 = Instructions.modTcpSrc(tpPort2); + + /** + * Test the modTcpSrc() method. + */ + @Test + public void testModTcpSrcMethod() { + final Instruction instruction = Instructions.modTcpSrc(tpPort1); + final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction = + checkAndConvert(instruction, Instruction.Type.L4MODIFICATION, + L4ModificationInstruction.ModTransportPortInstruction.class); + assertThat(modTransportPortInstruction.port(), is(equalTo(tpPort1))); + assertThat(modTransportPortInstruction.subtype(), + is(equalTo(L4ModificationInstruction.L4SubType.TCP_SRC))); + } + + /** + * Test the modTcpDst() method. + */ + @Test + public void testModTcpDstMethod() { + final Instruction instruction = Instructions.modTcpDst(tpPort1); + final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction = + checkAndConvert(instruction, Instruction.Type.L4MODIFICATION, + L4ModificationInstruction.ModTransportPortInstruction.class); + assertThat(modTransportPortInstruction.port(), is(equalTo(tpPort1))); + assertThat(modTransportPortInstruction.subtype(), + is(equalTo(L4ModificationInstruction.L4SubType.TCP_DST))); + } + + /** + * Test the modUdpSrc() method. + */ + @Test + public void testModUdpSrcMethod() { + final Instruction instruction = Instructions.modUdpSrc(tpPort1); + final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction = + checkAndConvert(instruction, Instruction.Type.L4MODIFICATION, + L4ModificationInstruction.ModTransportPortInstruction.class); + assertThat(modTransportPortInstruction.port(), is(equalTo(tpPort1))); + assertThat(modTransportPortInstruction.subtype(), + is(equalTo(L4ModificationInstruction.L4SubType.UDP_SRC))); + } + + /** + * Test the modUdpDst() method. + */ + @Test + public void testModUdpDstMethod() { + final Instruction instruction = Instructions.modUdpDst(tpPort1); + final L4ModificationInstruction.ModTransportPortInstruction modTransportPortInstruction = + checkAndConvert(instruction, Instruction.Type.L4MODIFICATION, + L4ModificationInstruction.ModTransportPortInstruction.class); + assertThat(modTransportPortInstruction.port(), is(equalTo(tpPort1))); + assertThat(modTransportPortInstruction.subtype(), + is(equalTo(L4ModificationInstruction.L4SubType.UDP_DST))); + } + + /** + * Test the equals() method of the ModTransportPortInstruction class. + */ + @Test + public void testModTransportPortInstructionEquals() throws Exception { + checkEqualsAndToString(modTransportPortInstruction1, + sameAsModTransportPortInstruction1, + modTransportPortInstruction2); + } + + /** + * Test the hashCode() method of the ModTransportPortInstruction class. + */ + @Test + public void testModTransportPortInstructionHashCode() { + assertThat(modTransportPortInstruction1.hashCode(), + is(equalTo(sameAsModTransportPortInstruction1.hashCode()))); + assertThat(modTransportPortInstruction1.hashCode(), + is(not(equalTo(modTransportPortInstruction2.hashCode())))); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/flowobjective/ObjectiveTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flowobjective/ObjectiveTest.java new file mode 100644 index 00000000..850582b0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/flowobjective/ObjectiveTest.java @@ -0,0 +1,313 @@ +/* + * 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.net.flowobjective; + +import org.junit.Test; +import org.onosproject.net.flow.DefaultTrafficSelector; +import org.onosproject.net.flow.DefaultTrafficTreatment; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; +import org.onosproject.net.flow.criteria.Criteria; +import org.onosproject.net.flow.criteria.Criterion; + +import static org.hamcrest.CoreMatchers.hasItem; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.not; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.flowobjective.FilteringObjective.Type.DENY; +import static org.onosproject.net.flowobjective.ForwardingObjective.Flag.SPECIFIC; +import static org.onosproject.net.flowobjective.NextObjective.Type.HASHED; +import static org.onosproject.net.flowobjective.Objective.Operation.ADD; +import static org.onosproject.net.flowobjective.Objective.Operation.REMOVE; + +/** + * Unit tests for forwarding objective class. + */ +public class ObjectiveTest { + + private final TrafficTreatment treatment = + DefaultTrafficTreatment.emptyTreatment(); + private final TrafficSelector selector = + DefaultTrafficSelector.emptySelector(); + private final Criterion criterion = Criteria.dummy(); + private final Criterion key = Criteria.dummy(); + + /** + * Mock objective context. + */ + private static class MockObjectiveContext implements ObjectiveContext { + @Override + public void onSuccess(Objective objective) { + // stub + } + + @Override + public void onError(Objective objective, ObjectiveError error) { + // stub + } + } + + /** + * Checks immutability of objective classes. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(DefaultFilteringObjective.class); + assertThatClassIsImmutable(DefaultForwardingObjective.class); + assertThatClassIsImmutable(DefaultNextObjective.class); + } + + // Forwarding Objectives + + /** + * Makes a forwarding objective builder with a set of default values. + * + * @return forwarding objective builder + */ + private ForwardingObjective.Builder baseForwardingBuilder() { + return DefaultForwardingObjective.builder() + .withSelector(selector) + .withTreatment(treatment) + .withFlag(SPECIFIC) + .fromApp(APP_ID) + .withPriority(22) + .makeTemporary(5) + .nextStep(33); + } + + /** + * Checks the default values of a forwarding objective object. + * + * @param objective forwarding objective to check + */ + private void checkForwardingBase(ForwardingObjective objective, + Objective.Operation op, + ObjectiveContext expectedContext) { + assertThat(objective.permanent(), is(false)); + assertThat(objective.timeout(), is(5)); + assertThat(objective.selector(), is(selector)); + assertThat(objective.treatment(), is(treatment)); + assertThat(objective.flag(), is(SPECIFIC)); + assertThat(objective.appId(), is(APP_ID)); + assertThat(objective.nextId(), is(33)); + assertThat(objective.id(), is(not(0))); + assertThat(objective.priority(), is(22)); + assertThat(objective.op(), is(op)); + if (objective.context().isPresent()) { + assertThat(objective.context().get(), is(expectedContext)); + } else { + assertThat(expectedContext, nullValue()); + } + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add() method. + */ + @Test + public void testForwardingAdd() { + checkForwardingBase(baseForwardingBuilder().add(), ADD, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add(context) method. + */ + @Test + public void testForwardingAddWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkForwardingBase(baseForwardingBuilder().add(context), ADD, context); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove() method. + */ + @Test + public void testForwardingRemove() { + checkForwardingBase(baseForwardingBuilder().remove(), REMOVE, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove(context) method. + */ + @Test + public void testForwardingRemoveWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkForwardingBase(baseForwardingBuilder().remove(context), REMOVE, context); + } + + // Filtering objectives + + /** + * Makes a filtering objective builder with a set of default values. + * + * @return filtering objective builder + */ + private FilteringObjective.Builder baseFilteringBuilder() { + return DefaultFilteringObjective.builder() + .withKey(key) + .withPriority(5) + .addCondition(criterion) + .fromApp(APP_ID) + .makeTemporary(2) + .deny(); + } + + /** + * Checks the default values of a filtering objective object. + * + * @param objective filtering objective to check + */ + private void checkFilteringBase(FilteringObjective objective, + Objective.Operation op, + ObjectiveContext expectedContext) { + assertThat(objective.key(), is(key)); + assertThat(objective.conditions(), hasItem(criterion)); + assertThat(objective.permanent(), is(false)); + assertThat(objective.timeout(), is(2)); + assertThat(objective.priority(), is(5)); + assertThat(objective.appId(), is(APP_ID)); + assertThat(objective.type(), is(DENY)); + assertThat(objective.id(), is(not(0))); + assertThat(objective.op(), is(op)); + if (objective.context().isPresent()) { + assertThat(objective.context().get(), is(expectedContext)); + } else { + assertThat(expectedContext, nullValue()); + } + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add() method. + */ + @Test + public void testFilteringAdd() { + checkFilteringBase(baseFilteringBuilder().add(), ADD, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add(context) method. + */ + @Test + public void testFilteringAddWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkFilteringBase(baseFilteringBuilder().add(context), ADD, context); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove() method. + */ + @Test + public void testFilteringRemove() { + checkFilteringBase(baseFilteringBuilder().remove(), REMOVE, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove(context) method. + */ + @Test + public void testFilteringRemoveWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkFilteringBase(baseFilteringBuilder().remove(context), REMOVE, context); + } + + // Next objectives + + /** + * Makes a next objective builder with a set of default values. + * + * @return next objective builder + */ + private NextObjective.Builder baseNextBuilder() { + return DefaultNextObjective.builder() + .addTreatment(treatment) + .withId(12) + .withType(HASHED) + .makeTemporary(777) + .withPriority(33) + .fromApp(APP_ID); + } + + /** + * Checks the default values of a next objective object. + * + * @param objective next objective to check + */ + private void checkNextBase(NextObjective objective, + Objective.Operation op, + ObjectiveContext expectedContext) { + assertThat(objective.id(), is(12)); + assertThat(objective.appId(), is(APP_ID)); + assertThat(objective.type(), is(HASHED)); + assertThat(objective.next(), hasItem(treatment)); + assertThat(objective.permanent(), is(false)); + assertThat(objective.timeout(), is(0)); + assertThat(objective.priority(), is(0)); + assertThat(objective.op(), is(op)); + if (objective.context().isPresent()) { + assertThat(objective.context().get(), is(expectedContext)); + } else { + assertThat(expectedContext, nullValue()); + } + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add() method. + */ + @Test + public void testNextAdd() { + checkNextBase(baseNextBuilder().add(), ADD, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * add(context) method. + */ + @Test + public void testNextAddWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkNextBase(baseNextBuilder().add(context), ADD, context); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove() method. + */ + @Test + public void testNextRemove() { + checkNextBase(baseNextBuilder().remove(), REMOVE, null); + } + + /** + * Tests that forwarding objective objects are built correctly using the + * remove(context) method. + */ + @Test + public void testNextRemoveWithContext() { + ObjectiveContext context = new MockObjectiveContext(); + checkNextBase(baseNextBuilder().remove(context), REMOVE, context); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupDescriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupDescriptionTest.java new file mode 100644 index 00000000..66b0089e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupDescriptionTest.java @@ -0,0 +1,96 @@ +/* + * 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.net.group; + +import org.junit.Test; +import org.onosproject.net.flow.DefaultTrafficTreatment; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.collect.ImmutableList; +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.did; + +/** + * Default group description unit tests. + */ +public class DefaultGroupDescriptionTest { + byte[] keyData = "abcdefg".getBytes(); + private final GroupKey key = new DefaultGroupKey(keyData); + private final TrafficTreatment treatment = + DefaultTrafficTreatment.emptyTreatment(); + private final GroupBucket bucket = + DefaultGroupBucket.createSelectGroupBucket(treatment); + private final GroupBuckets groupBuckets = + new GroupBuckets(ImmutableList.of(bucket)); + private final DefaultGroupDescription d1 = + new DefaultGroupDescription(did("2"), + GroupDescription.Type.FAILOVER, + groupBuckets); + private final DefaultGroupDescription sameAsD1 = + new DefaultGroupDescription(d1); + private final DefaultGroupDescription d2 = + new DefaultGroupDescription(did("2"), + GroupDescription.Type.INDIRECT, + groupBuckets); + private final DefaultGroupDescription d3 = + new DefaultGroupDescription(did("3"), + GroupDescription.Type.FAILOVER, + groupBuckets, + key, + 711, + APP_ID); + + /** + * Checks that the Default group description class is immutable and can be + * inherited from. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutableBaseClass(DefaultGroupDescription.class); + } + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(d1, sameAsD1) + .addEqualityGroup(d2) + .addEqualityGroup(d3) + .testEquals(); + } + + /** + * Checks that construction of an object was correct. + */ + @Test + public void testConstruction() { + assertThat(d3.deviceId(), is(did("3"))); + assertThat(d3.type(), is(GroupDescription.Type.FAILOVER)); + assertThat(d3.buckets(), is(groupBuckets)); + assertThat(d3.appId(), is(APP_ID)); + assertThat(d3.givenGroupId(), is(711)); + assertThat(key.key(), is(keyData)); + assertThat(d3.appCookie().key(), is(keyData)); + } +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupTest.java new file mode 100644 index 00000000..f27f266b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/DefaultGroupTest.java @@ -0,0 +1,97 @@ +/* + * 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.net.group; + +import org.junit.Test; +import org.onosproject.core.DefaultGroupId; +import org.onosproject.core.GroupId; +import org.onosproject.net.NetTestTools; +import org.onosproject.net.flow.DefaultTrafficTreatment; + +import com.google.common.collect.ImmutableList; +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.*; +import static org.onosproject.net.NetTestTools.did; + +/** + * Unit tests for DefaultGroup class. + */ +public class DefaultGroupTest { + private final GroupId id1 = new DefaultGroupId(6); + private final GroupId id2 = new DefaultGroupId(7); + private final GroupBucket bucket = + DefaultGroupBucket.createSelectGroupBucket( + DefaultTrafficTreatment.emptyTreatment()); + private final GroupBuckets groupBuckets = + new GroupBuckets(ImmutableList.of(bucket)); + private final GroupDescription groupDesc1 = + new DefaultGroupDescription(did("1"), + GroupDescription.Type.FAILOVER, + groupBuckets); + private final GroupDescription groupDesc2 = + new DefaultGroupDescription(did("2"), + GroupDescription.Type.FAILOVER, + groupBuckets); + + DefaultGroup group1 = new DefaultGroup(id1, groupDesc1); + DefaultGroup sameAsGroup1 = new DefaultGroup(id1, groupDesc1); + DefaultGroup group2 = new DefaultGroup(id1, groupDesc2); + DefaultGroup group3 = new DefaultGroup(id2, groupDesc2); + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(group1, sameAsGroup1) + .addEqualityGroup(group2) + .addEqualityGroup(group3) + .testEquals(); + } + + /** + * Tests that objects are created properly. + */ + @Test + public void checkConstruction() { + assertThat(group1.id(), is(id1)); + assertThat(group1.bytes(), is(0L)); + assertThat(group1.life(), is(0L)); + assertThat(group1.packets(), is(0L)); + assertThat(group1.referenceCount(), is(0L)); + assertThat(group1.buckets(), is(groupBuckets)); + assertThat(group1.state(), is(Group.GroupState.PENDING_ADD)); + } + + /** + * Tests that objects are created properly using the device based constructor. + */ + @Test + public void checkConstructionWithDid() { + DefaultGroup group = new DefaultGroup(id2, NetTestTools.did("1"), + GroupDescription.Type.INDIRECT, groupBuckets); + assertThat(group.id(), is(id2)); + assertThat(group.bytes(), is(0L)); + assertThat(group.life(), is(0L)); + assertThat(group.packets(), is(0L)); + assertThat(group.referenceCount(), is(0L)); + assertThat(group.deviceId(), is(NetTestTools.did("1"))); + assertThat(group.buckets(), is(groupBuckets)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupBucketTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupBucketTest.java new file mode 100644 index 00000000..0672ebf3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupBucketTest.java @@ -0,0 +1,133 @@ +/* + * 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.net.group; + +import org.junit.Test; +import org.onosproject.core.DefaultGroupId; +import org.onosproject.core.GroupId; +import org.onosproject.net.PortNumber; +import org.onosproject.net.flow.DefaultTrafficTreatment; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onosproject.net.group.GroupDescription.Type.FAILOVER; +import static org.onosproject.net.group.GroupDescription.Type.INDIRECT; +import static org.onosproject.net.group.GroupDescription.Type.SELECT; + +/** + * Unit tests for the group bucket class. + */ +public class GroupBucketTest { + + private final GroupId groupId = new DefaultGroupId(7); + private final GroupId nullGroup = null; + + private final PortNumber nullPort = null; + + private final TrafficTreatment treatment = + DefaultTrafficTreatment.emptyTreatment(); + private final GroupBucket selectGroupBucket = + DefaultGroupBucket.createSelectGroupBucket(treatment); + private final GroupBucket sameAsSelectGroupBucket = + DefaultGroupBucket.createSelectGroupBucket(treatment); + private final GroupBucket failoverGroupBucket = + DefaultGroupBucket.createFailoverGroupBucket(treatment, + PortNumber.IN_PORT, groupId); + private final GroupBucket indirectGroupBucket = + DefaultGroupBucket.createIndirectGroupBucket(treatment); + private final GroupBucket selectGroupBucketWithWeight = + DefaultGroupBucket.createSelectGroupBucket(treatment, (short) 5); + + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(selectGroupBucket, + sameAsSelectGroupBucket, + selectGroupBucketWithWeight) + .addEqualityGroup(failoverGroupBucket) + .addEqualityGroup(indirectGroupBucket) + .testEquals(); + } + + private void checkValues(GroupBucket bucket, GroupDescription.Type type, + long bytes, long packets, short weight, + GroupId groupId, PortNumber portNumber) { + assertThat(bucket.type(), is(type)); + assertThat(bucket.bytes(), is(bytes)); + assertThat(bucket.packets(), is(packets)); + assertThat(bucket.treatment(), is(treatment)); + assertThat(bucket.weight(), is(weight)); + assertThat(bucket.watchGroup(), is(groupId)); + assertThat(bucket.watchPort(), is(portNumber)); + } + + /** + * Checks that construction of a select group was correct. + */ + @Test + public void checkSelectGroup() { + // Casting needed because only the store accesses the set methods. + ((DefaultGroupBucket) selectGroupBucket).setBytes(4); + ((DefaultGroupBucket) selectGroupBucket).setPackets(44); + + checkValues(selectGroupBucket, SELECT, 4L, 44L, (short) 1, + nullGroup, nullPort); + } + + /** + * Checks that construction of a select group with a weight was correct. + */ + @Test + public void checkSelectGroupWithPriority() { + checkValues(selectGroupBucketWithWeight, SELECT, 0L, 0L, (short) 5, + nullGroup, nullPort); + } + + /** + * Checks that construction of an indirect group was correct. + */ + @Test + public void checkFailoverGroup() { + checkValues(failoverGroupBucket, FAILOVER, 0L, 0L, (short) -1, + groupId, PortNumber.IN_PORT); + } + /** + * Checks that construction of an indirect group was correct. + */ + @Test + public void checkIndirectGroup() { + checkValues(indirectGroupBucket, INDIRECT, 0L, 0L, (short) -1, + nullGroup, nullPort); + } + + /** + * Checks that a weight of 0 results in no group getting created. + */ + @Test + public void checkZeroWeight() { + GroupBucket bucket = + DefaultGroupBucket.createSelectGroupBucket(treatment, (short) 0); + assertThat(bucket, nullValue()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupOperationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupOperationTest.java new file mode 100644 index 00000000..5ee3a7ec --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/group/GroupOperationTest.java @@ -0,0 +1,89 @@ +/* + * 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.net.group; + +import org.junit.Test; +import org.onosproject.core.DefaultGroupId; +import org.onosproject.core.GroupId; +import org.onosproject.net.flow.DefaultTrafficTreatment; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.collect.ImmutableList; +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.group.GroupDescription.Type.ALL; +import static org.onosproject.net.group.GroupDescription.Type.INDIRECT; +import static org.onosproject.net.group.GroupOperation.Type.ADD; + +/** + * Tests for the group operation class. + */ +public class GroupOperationTest { + + private final GroupId groupId = new DefaultGroupId(6); + private final TrafficTreatment treatment = + DefaultTrafficTreatment.emptyTreatment(); + private final GroupBucket bucket = + DefaultGroupBucket.createSelectGroupBucket(treatment); + private final GroupBuckets groupBuckets = + new GroupBuckets(ImmutableList.of(bucket)); + private final GroupOperation op1 = + GroupOperation.createAddGroupOperation(groupId, ALL, groupBuckets); + private final GroupOperation sameAsOp1 = + GroupOperation.createAddGroupOperation(groupId, ALL, groupBuckets); + private final GroupOperation op2 = + GroupOperation.createAddGroupOperation(groupId, INDIRECT, groupBuckets); + private final GroupOperation op3 = + GroupOperation.createDeleteGroupOperation(groupId, INDIRECT); + private final GroupOperation op4 = + GroupOperation.createModifyGroupOperation(groupId, INDIRECT, groupBuckets); + + /** + * Checks that the GroupOperation class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(GroupOperation.class); + } + + /** + * Tests for proper operation of equals(), hashCode() and toString() methods. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(op1, sameAsOp1) + .addEqualityGroup(op2) + .addEqualityGroup(op3) + .addEqualityGroup(op4) + .testEquals(); + } + + /** + * Checks that the construction of the add operation is correct. + */ + @Test + public void testAddGroupOperation() { + assertThat(op1.buckets(), is(groupBuckets)); + assertThat(op1.groupId(), is(groupId)); + assertThat(op1.groupType(), is(ALL)); + assertThat(op1.opType(), is(ADD)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/DefaultHostDecriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/DefaultHostDecriptionTest.java new file mode 100644 index 00000000..496269b6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/DefaultHostDecriptionTest.java @@ -0,0 +1,57 @@ +/* + * 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.net.host; + +import org.junit.Test; +import org.onosproject.net.DeviceId; +import org.onosproject.net.HostLocation; +import org.onosproject.net.PortNumber; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; + +import com.google.common.collect.ImmutableSet; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Test for the default host description. + */ +public class DefaultHostDecriptionTest { + + private static final MacAddress MAC = MacAddress.valueOf("00:00:11:00:00:01"); + private static final VlanId VLAN = VlanId.vlanId((short) 10); + private static final IpAddress IP = IpAddress.valueOf("10.0.0.1"); + + private static final HostLocation LOC = new HostLocation( + DeviceId.deviceId("of:foo"), + PortNumber.portNumber(100), + 123L + ); + + @Test + public void basics() { + HostDescription host = + new DefaultHostDescription(MAC, VLAN, LOC, IP); + assertEquals("incorrect mac", MAC, host.hwAddress()); + assertEquals("incorrect vlan", VLAN, host.vlan()); + assertEquals("incorrect location", LOC, host.location()); + assertEquals("incorrect ip's", ImmutableSet.of(IP), host.ipAddress()); + assertTrue("incorrect toString", host.toString().contains("vlan=10")); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostEventTest.java new file mode 100644 index 00000000..4a55d638 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostEventTest.java @@ -0,0 +1,72 @@ +/* + * 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.net.host; + +import java.util.Set; + +import org.junit.Test; +import org.onosproject.event.AbstractEventTest; +import org.onosproject.net.DefaultHost; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Host; +import org.onosproject.net.HostId; +import org.onosproject.net.HostLocation; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; + +import com.google.common.collect.Sets; + +public class HostEventTest extends AbstractEventTest { + + private Host createHost() { + MacAddress mac = MacAddress.valueOf("00:00:11:00:00:01"); + VlanId vlan = VlanId.vlanId((short) 10); + HostLocation loc = new HostLocation( + DeviceId.deviceId("of:foo"), + PortNumber.portNumber(100), + 123L + ); + Set<IpAddress> ipset = Sets.newHashSet( + IpAddress.valueOf("10.0.0.1"), + IpAddress.valueOf("10.0.0.2") + ); + HostId hid = HostId.hostId(mac, vlan); + + return new DefaultHost( + new ProviderId("of", "foo"), hid, mac, vlan, loc, ipset); + } + + @Override + @Test + public void withTime() { + Host host = createHost(); + HostEvent event = new HostEvent(HostEvent.Type.HOST_ADDED, host, 123L); + validateEvent(event, HostEvent.Type.HOST_ADDED, host, 123L); + } + + @Override + @Test + public void withoutTime() { + Host host = createHost(); + long before = System.currentTimeMillis(); + HostEvent event = new HostEvent(HostEvent.Type.HOST_ADDED, host, before); + long after = System.currentTimeMillis(); + validateEvent(event, HostEvent.Type.HOST_ADDED, host, before, after); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostServiceAdapter.java new file mode 100644 index 00000000..226dad06 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/HostServiceAdapter.java @@ -0,0 +1,102 @@ +/* + * 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.net.host; + +import java.util.Set; + +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Host; +import org.onosproject.net.HostId; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; + +/** + * Test adapter for host service. + */ +public class HostServiceAdapter implements HostService { + @Override + public int getHostCount() { + return 0; + } + + @Override + public Iterable<Host> getHosts() { + return null; + } + + @Override + public Host getHost(HostId hostId) { + return null; + } + + @Override + public Set<Host> getHostsByVlan(VlanId vlanId) { + return null; + } + + @Override + public Set<Host> getHostsByMac(MacAddress mac) { + return null; + } + + @Override + public Set<Host> getHostsByIp(IpAddress ip) { + return null; + } + + @Override + public Set<Host> getConnectedHosts(ConnectPoint connectPoint) { + return null; + } + + @Override + public Set<Host> getConnectedHosts(DeviceId deviceId) { + return null; + } + + @Override + public void startMonitoringIp(IpAddress ip) { + } + + @Override + public void stopMonitoringIp(IpAddress ip) { + } + + @Override + public void requestMac(IpAddress ip) { + } + + @Override + public void addListener(HostListener listener) { + } + + @Override + public void removeListener(HostListener listener) { + } + + @Override + public Set<PortAddresses> getAddressBindings() { + return null; + } + + @Override + public Set<PortAddresses> getAddressBindingsForPort(ConnectPoint connectPoint) { + return null; + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/InterfaceIpAddressTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/InterfaceIpAddressTest.java new file mode 100644 index 00000000..6120b7ce --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/InterfaceIpAddressTest.java @@ -0,0 +1,246 @@ +/* + * 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.net.host; + +import org.junit.Test; +import org.onlab.packet.IpAddress; +import org.onlab.packet.IpPrefix; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + * Tests for class {@link InterfaceIpAddress}. + */ +public class InterfaceIpAddressTest { + private static final IpAddress IP_ADDRESS = IpAddress.valueOf("1.2.3.4"); + private static final IpPrefix SUBNET_ADDRESS = + IpPrefix.valueOf("1.2.0.0/16"); + private static final IpAddress BROADCAST_ADDRESS = + IpAddress.valueOf("1.2.0.255"); // NOTE: non-default broadcast + private static final IpAddress PEER_ADDRESS = IpAddress.valueOf("5.6.7.8"); + + private static final IpAddress IP_ADDRESS2 = IpAddress.valueOf("10.2.3.4"); + private static final IpPrefix SUBNET_ADDRESS2 = + IpPrefix.valueOf("10.2.0.0/16"); + private static final IpAddress BROADCAST_ADDRESS2 = + IpAddress.valueOf("10.2.0.255"); // NOTE: non-default broadcast + private static final IpAddress PEER_ADDRESS2 = + IpAddress.valueOf("50.6.7.8"); + + /** + * Tests valid class copy constructor. + */ + @Test + public void testCopyConstructor() { + InterfaceIpAddress fromAddr; + InterfaceIpAddress toAddr; + + // Regular interface address with default broadcast address + fromAddr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + toAddr = new InterfaceIpAddress(fromAddr); + assertThat(toAddr.ipAddress(), is(fromAddr.ipAddress())); + assertThat(toAddr.subnetAddress(), is(fromAddr.subnetAddress())); + assertThat(toAddr.broadcastAddress(), is(fromAddr.broadcastAddress())); + assertThat(toAddr.peerAddress(), is(fromAddr.peerAddress())); + + // Interface address with non-default broadcast address + fromAddr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + toAddr = new InterfaceIpAddress(fromAddr); + assertThat(toAddr.ipAddress(), is(fromAddr.ipAddress())); + assertThat(toAddr.subnetAddress(), is(fromAddr.subnetAddress())); + assertThat(toAddr.broadcastAddress(), is(fromAddr.broadcastAddress())); + assertThat(toAddr.peerAddress(), is(fromAddr.peerAddress())); + + // Point-to-point address with peer IP address + fromAddr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + toAddr = new InterfaceIpAddress(fromAddr); + assertThat(toAddr.ipAddress(), is(fromAddr.ipAddress())); + assertThat(toAddr.subnetAddress(), is(fromAddr.subnetAddress())); + assertThat(toAddr.broadcastAddress(), is(fromAddr.broadcastAddress())); + assertThat(toAddr.peerAddress(), is(fromAddr.peerAddress())); + } + + /** + * Tests invalid class copy constructor for a null object to copy from. + */ + @Test(expected = NullPointerException.class) + public void testInvalidConstructorNullObject() { + InterfaceIpAddress fromAddr = null; + InterfaceIpAddress toAddr = new InterfaceIpAddress(fromAddr); + } + + /** + * Tests valid class constructor for regular interface address with + * default broadcast address. + */ + @Test + public void testConstructorForDefaultBroadcastAddress() { + InterfaceIpAddress addr = + new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + assertThat(addr.ipAddress(), is(IP_ADDRESS)); + assertThat(addr.subnetAddress(), is(SUBNET_ADDRESS)); + assertThat(addr.broadcastAddress(), nullValue()); + assertThat(addr.peerAddress(), nullValue()); + } + + /** + * Tests valid class constructor for interface address with + * non-default broadcast address. + */ + @Test + public void testConstructorForNonDefaultBroadcastAddress() { + InterfaceIpAddress addr = + new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + + assertThat(addr.ipAddress(), is(IP_ADDRESS)); + assertThat(addr.subnetAddress(), is(SUBNET_ADDRESS)); + assertThat(addr.broadcastAddress(), is(BROADCAST_ADDRESS)); + assertThat(addr.peerAddress(), nullValue()); + } + + /** + * Tests valid class constructor for point-to-point interface address with + * peer address. + */ + @Test + public void testConstructorForPointToPointAddress() { + InterfaceIpAddress addr = + new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + + assertThat(addr.ipAddress(), is(IP_ADDRESS)); + assertThat(addr.subnetAddress(), is(SUBNET_ADDRESS)); + assertThat(addr.broadcastAddress(), nullValue()); + assertThat(addr.peerAddress(), is(PEER_ADDRESS)); + } + + /** + * Tests getting the fields of an interface address. + */ + @Test + public void testGetFields() { + InterfaceIpAddress addr; + + // Regular interface address with default broadcast address + addr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + assertThat(addr.ipAddress().toString(), is("1.2.3.4")); + assertThat(addr.subnetAddress().toString(), is("1.2.0.0/16")); + assertThat(addr.broadcastAddress(), is(nullValue())); // TODO: Fix + assertThat(addr.peerAddress(), is(nullValue())); + + // Interface address with non-default broadcast address + addr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + assertThat(addr.ipAddress().toString(), is("1.2.3.4")); + assertThat(addr.subnetAddress().toString(), is("1.2.0.0/16")); + assertThat(addr.broadcastAddress().toString(), is("1.2.0.255")); + assertThat(addr.peerAddress(), is(nullValue())); + + // Point-to-point address with peer IP address + addr = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + assertThat(addr.ipAddress().toString(), is("1.2.3.4")); + assertThat(addr.subnetAddress().toString(), is("1.2.0.0/16")); + assertThat(addr.broadcastAddress(), is(nullValue())); + assertThat(addr.peerAddress().toString(), is("5.6.7.8")); + } + + /** + * Tests equality of {@link InterfaceIpAddress}. + */ + @Test + public void testEquality() { + InterfaceIpAddress addr1, addr2; + + // Regular interface address with default broadcast address + addr1 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + addr2 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + assertThat(addr1, is(addr2)); + + // Interface address with non-default broadcast address + addr1 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + addr2 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + assertThat(addr1, is(addr2)); + + // Point-to-point address with peer IP address + addr1 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + addr2 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + assertThat(addr1, is(addr2)); + } + + /** + * Tests non-equality of {@link InterfaceIpAddress}. + */ + @Test + public void testNonEquality() { + InterfaceIpAddress addr1, addr2, addr3, addr4; + + // Regular interface address with default broadcast address + addr1 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS); + // Interface address with non-default broadcast address + addr2 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + // Point-to-point address with peer IP address + addr3 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS); + + // Test interface addresses with different properties: + // - default-broadcast vs non-default broadcast + // - regular vs point-to-point + assertThat(addr1, is(not(addr2))); + assertThat(addr1, is(not(addr3))); + assertThat(addr2, is(not(addr3))); + + // Test regular interface address with default broadcast address + addr4 = new InterfaceIpAddress(IP_ADDRESS2, SUBNET_ADDRESS); + assertThat(addr1, is(not(addr4))); + addr4 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS2); + assertThat(addr1, is(not(addr4))); + + // Test interface address with non-default broadcast address + addr4 = new InterfaceIpAddress(IP_ADDRESS2, SUBNET_ADDRESS, + BROADCAST_ADDRESS); + assertThat(addr2, is(not(addr4))); + addr4 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS2, + BROADCAST_ADDRESS); + assertThat(addr2, is(not(addr4))); + addr4 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, + BROADCAST_ADDRESS2); + assertThat(addr2, is(not(addr4))); + + // Test point-to-point address with peer IP address + addr4 = new InterfaceIpAddress(IP_ADDRESS2, SUBNET_ADDRESS, null, + PEER_ADDRESS); + assertThat(addr3, is(not(addr4))); + addr4 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS2, null, + PEER_ADDRESS); + assertThat(addr3, is(not(addr4))); + addr4 = new InterfaceIpAddress(IP_ADDRESS, SUBNET_ADDRESS, null, + PEER_ADDRESS2); + assertThat(addr3, is(not(addr4))); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/PortAddressesTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/PortAddressesTest.java new file mode 100644 index 00000000..7c10cd15 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/host/PortAddressesTest.java @@ -0,0 +1,113 @@ +/* + * 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.net.host; + +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.onlab.packet.IpAddress; +import org.onlab.packet.IpPrefix; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.NetTestTools; + +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +import com.google.common.collect.ImmutableSet; +import com.google.common.testing.EqualsTester; +import static org.hamcrest.MatcherAssert.assertThat; + +/** + * Unit tests for port addresses class. + */ +public class PortAddressesTest { + + PortAddresses addresses1; + PortAddresses sameAsAddresses1; + PortAddresses addresses2; + PortAddresses addresses3; + + private static final ConnectPoint CONNECT_POINT1 = + NetTestTools.connectPoint("cp1", 1); + private static final IpAddress IP_ADDRESS1 = IpAddress.valueOf("1.2.3.4"); + private static final IpPrefix SUBNET_ADDRESS1 = + IpPrefix.valueOf("1.2.0.0/16"); + private static final InterfaceIpAddress INTERFACE_ADDRESS_1 = + new InterfaceIpAddress(IP_ADDRESS1, SUBNET_ADDRESS1); + + private static final ConnectPoint CONNECT_POINT2 = + NetTestTools.connectPoint("cp2", 1); + private static final IpAddress IP_ADDRESS2 = IpAddress.valueOf("1.2.3.5"); + private static final IpPrefix SUBNET_ADDRESS2 = + IpPrefix.valueOf("1.3.0.0/16"); + private static final InterfaceIpAddress INTERFACE_ADDRESS_2 = + new InterfaceIpAddress(IP_ADDRESS2, SUBNET_ADDRESS2); + + Set<InterfaceIpAddress> ipAddresses; + + + /** + * Initializes local data used by all test cases. + */ + @Before + public void setUpAddresses() { + ipAddresses = ImmutableSet.of(INTERFACE_ADDRESS_1, + INTERFACE_ADDRESS_2); + addresses1 = new PortAddresses(CONNECT_POINT1, ipAddresses, + MacAddress.BROADCAST, VlanId.NONE); + sameAsAddresses1 = new PortAddresses(CONNECT_POINT1, ipAddresses, + MacAddress.BROADCAST, VlanId.NONE); + addresses2 = new PortAddresses(CONNECT_POINT2, ipAddresses, + MacAddress.BROADCAST, VlanId.NONE); + addresses3 = new PortAddresses(CONNECT_POINT2, ipAddresses, + MacAddress.ZERO, VlanId.NONE); + } + + /** + * Checks that the PortAddresses class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(PortAddresses.class); + } + + /** + * Checks the operation of the equals(), hash() and toString() + * methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(addresses1, sameAsAddresses1) + .addEqualityGroup(addresses2) + .addEqualityGroup(addresses3) + .testEquals(); + } + + /** + * Tests that object are created correctly. + */ + @Test + public void testConstruction() { + assertThat(addresses1.mac(), is(MacAddress.BROADCAST)); + assertThat(addresses1.connectPoint(), is(CONNECT_POINT1)); + assertThat(addresses1.ipAddresses(), is(ipAddresses)); + assertThat(addresses1.vlan(), is(VlanId.NONE)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/AbstractIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/AbstractIntentTest.java new file mode 100644 index 00000000..6bb7e28f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/AbstractIntentTest.java @@ -0,0 +1,35 @@ +/* + * 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.net.intent; + +import org.junit.After; +import org.junit.Before; +import org.onosproject.core.IdGenerator; + +public abstract class AbstractIntentTest { + + protected IdGenerator idGenerator = new MockIdGenerator(); + + @Before + public void setUp() throws Exception { + Intent.bindIdGenerator(idGenerator); + } + + @After + public void tearDown() { + Intent.unbindIdGenerator(idGenerator); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/ConnectivityIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/ConnectivityIntentTest.java new file mode 100644 index 00000000..e03ed850 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/ConnectivityIntentTest.java @@ -0,0 +1,47 @@ +/* + * 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.net.intent; + +import java.util.Set; + +import org.onosproject.core.ApplicationId; +import org.onosproject.TestApplicationId; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.PortNumber; +import org.onosproject.net.flow.DefaultTrafficSelector; +import org.onosproject.net.flow.DefaultTrafficTreatment; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; + +/** + * Base facilities to test various connectivity tests. + */ +public abstract class ConnectivityIntentTest extends IntentTest { + + public static final ApplicationId APPID = new TestApplicationId("foo"); + + public static final IntentId IID = new IntentId(123); + public static final TrafficSelector MATCH = DefaultTrafficSelector.emptySelector(); + public static final TrafficTreatment NOP = DefaultTrafficTreatment.emptyTreatment(); + + public static final ConnectPoint P1 = new ConnectPoint(DeviceId.deviceId("111"), PortNumber.portNumber(0x1)); + public static final ConnectPoint P2 = new ConnectPoint(DeviceId.deviceId("222"), PortNumber.portNumber(0x2)); + public static final ConnectPoint P3 = new ConnectPoint(DeviceId.deviceId("333"), PortNumber.portNumber(0x3)); + + public static final Set<ConnectPoint> PS1 = itemSet(new ConnectPoint[]{P1, P3}); + public static final Set<ConnectPoint> PS2 = itemSet(new ConnectPoint[]{P2, P3}); +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/FakeIntentManager.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/FakeIntentManager.java new file mode 100644 index 00000000..9b9f7cec --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/FakeIntentManager.java @@ -0,0 +1,268 @@ +/* + * 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.net.intent; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * Fake implementation of the intent service to assist in developing tests of + * the interface contract. + */ +public class FakeIntentManager implements TestableIntentService { + + private final Map<Key, Intent> intents = new HashMap<>(); + private final Map<Key, IntentState> intentStates = new HashMap<>(); + private final Map<Key, List<Intent>> installables = new HashMap<>(); + private final Set<IntentListener> listeners = new HashSet<>(); + + private final Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> compilers = new HashMap<>(); + + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + private final List<IntentException> exceptions = new ArrayList<>(); + + @Override + public List<IntentException> getExceptions() { + return exceptions; + } + + // Provides an out-of-thread simulation of intent submit life-cycle + private void executeSubmit(final Intent intent) { + registerSubclassCompilerIfNeeded(intent); + executor.execute(new Runnable() { + @Override + public void run() { + try { + executeCompilingPhase(intent); + } catch (IntentException e) { + exceptions.add(e); + } + } + }); + } + + // Provides an out-of-thread simulation of intent withdraw life-cycle + private void executeWithdraw(final Intent intent) { + executor.execute(new Runnable() { + @Override + public void run() { + try { + List<Intent> installable = getInstallable(intent.key()); + executeWithdrawingPhase(intent, installable); + } catch (IntentException e) { + exceptions.add(e); + } + + } + }); + } + + private <T extends Intent> IntentCompiler<T> getCompiler(T intent) { + @SuppressWarnings("unchecked") + IntentCompiler<T> compiler = (IntentCompiler<T>) compilers.get(intent.getClass()); + if (compiler == null) { + throw new IntentException("no compiler for class " + intent.getClass()); + } + return compiler; + } + + private <T extends Intent> void executeCompilingPhase(T intent) { + setState(intent, IntentState.COMPILING); + try { + // For the fake, we compile using a single level pass + List<Intent> installable = new ArrayList<>(); + for (Intent compiled : getCompiler(intent).compile(intent, null, null)) { + installable.add(compiled); + } + executeInstallingPhase(intent, installable); + + } catch (IntentException e) { + setState(intent, IntentState.FAILED); + dispatch(new IntentEvent(IntentEvent.Type.FAILED, intent)); + } + } + + private void executeInstallingPhase(Intent intent, + List<Intent> installable) { + setState(intent, IntentState.INSTALLING); + try { + setState(intent, IntentState.INSTALLED); + putInstallable(intent.key(), installable); + dispatch(new IntentEvent(IntentEvent.Type.INSTALLED, intent)); + + } catch (IntentException e) { + setState(intent, IntentState.FAILED); + dispatch(new IntentEvent(IntentEvent.Type.FAILED, intent)); + } + } + + private void executeWithdrawingPhase(Intent intent, + List<Intent> installable) { + setState(intent, IntentState.WITHDRAWING); + try { + removeInstallable(intent.key()); + setState(intent, IntentState.WITHDRAWN); + dispatch(new IntentEvent(IntentEvent.Type.WITHDRAWN, intent)); + } catch (IntentException e) { + // FIXME: Rework this to always go from WITHDRAWING to WITHDRAWN! + setState(intent, IntentState.FAILED); + dispatch(new IntentEvent(IntentEvent.Type.FAILED, intent)); + } + } + + // Sets the internal state for the given intent and dispatches an event + private void setState(Intent intent, IntentState state) { + intentStates.put(intent.key(), state); + } + + private void putInstallable(Key key, List<Intent> installable) { + installables.put(key, installable); + } + + private void removeInstallable(Key key) { + installables.remove(key); + } + + private List<Intent> getInstallable(Key key) { + List<Intent> installable = installables.get(key); + if (installable != null) { + return installable; + } else { + return Collections.emptyList(); + } + } + + @Override + public void submit(Intent intent) { + intents.put(intent.key(), intent); + setState(intent, IntentState.INSTALL_REQ); + dispatch(new IntentEvent(IntentEvent.Type.INSTALL_REQ, intent)); + executeSubmit(intent); + } + + @Override + public void withdraw(Intent intent) { + intents.remove(intent.key()); + executeWithdraw(intent); + } + + @Override + public void purge(Intent intent) { + IntentState currentState = intentStates.get(intent.key()); + if (currentState == IntentState.WITHDRAWN + || currentState == IntentState.FAILED) { + intents.remove(intent.key()); + installables.remove(intent.key()); + intentStates.remove(intent.key()); + } + } + + @Override + public Set<Intent> getIntents() { + return Collections.unmodifiableSet(new HashSet<>(intents.values())); + } + + @Override + public Iterable<IntentData> getIntentData() { + throw new UnsupportedOperationException(); + } + + @Override + public long getIntentCount() { + return intents.size(); + } + + @Override + public Intent getIntent(Key intentKey) { + return intents.get(intentKey); + } + + @Override + public IntentState getIntentState(Key intentKey) { + return intentStates.get(intentKey); + } + + @Override + public List<Intent> getInstallableIntents(Key intentKey) { + return installables.get(intentKey); + } + + @Override + public boolean isLocal(Key intentKey) { + return true; + } + + @Override + public Iterable<Intent> getPending() { + return Collections.emptyList(); + } + + @Override + public void addListener(IntentListener listener) { + listeners.add(listener); + } + + @Override + public void removeListener(IntentListener listener) { + listeners.remove(listener); + } + + private void dispatch(IntentEvent event) { + for (IntentListener listener : listeners) { + listener.event(event); + } + } + + @Override + public <T extends Intent> void registerCompiler(Class<T> cls, + IntentCompiler<T> compiler) { + compilers.put(cls, compiler); + } + + @Override + public <T extends Intent> void unregisterCompiler(Class<T> cls) { + compilers.remove(cls); + } + + @Override + public Map<Class<? extends Intent>, IntentCompiler<? extends Intent>> getCompilers() { + return Collections.unmodifiableMap(compilers); + } + + private void registerSubclassCompilerIfNeeded(Intent intent) { + if (!compilers.containsKey(intent.getClass())) { + Class<?> cls = intent.getClass(); + while (cls != Object.class) { + // As long as we're within the Intent class descendants + if (Intent.class.isAssignableFrom(cls)) { + IntentCompiler<?> compiler = compilers.get(cls); + if (compiler != null) { + compilers.put(intent.getClass(), compiler); + return; + } + } + cls = cls.getSuperclass(); + } + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/HostToHostIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/HostToHostIntentTest.java new file mode 100644 index 00000000..3f7650e4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/HostToHostIntentTest.java @@ -0,0 +1,126 @@ +/* + * 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.net.intent; + +import org.junit.Test; +import org.onosproject.TestApplicationId; +import org.onosproject.core.ApplicationId; +import org.onosproject.net.HostId; +import org.onosproject.net.flow.TrafficSelector; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.hid; + +/** + * Unit tests for the HostToHostIntent class. + */ +public class HostToHostIntentTest extends IntentTest { + private final TrafficSelector selector = new IntentTestsMocks.MockSelector(); + private final IntentTestsMocks.MockTreatment treatment = new IntentTestsMocks.MockTreatment(); + private final HostId id1 = hid("12:34:56:78:91:ab/1"); + private final HostId id2 = hid("12:34:56:78:92:ab/1"); + private final HostId id3 = hid("12:34:56:78:93:ab/1"); + + private static final ApplicationId APPID = new TestApplicationId("foo"); + + private HostToHostIntent makeHostToHost(HostId one, HostId two) { + return HostToHostIntent.builder() + .appId(APPID) + .one(one) + .two(two) + .selector(selector) + .treatment(treatment) + .build(); + } + + /** + * Tests the equals() method where two HostToHostIntents have references + * to the same hosts. These should compare equal. + */ + @Test + public void testSameEquals() { + + HostId one = hid("00:00:00:00:00:01/-1"); + HostId two = hid("00:00:00:00:00:02/-1"); + HostToHostIntent i1 = makeHostToHost(one, two); + HostToHostIntent i2 = makeHostToHost(one, two); + + assertThat(i1.one(), is(equalTo(i2.one()))); + assertThat(i1.two(), is(equalTo(i2.two()))); + } + + /** + * Checks that the HostToHostIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(HostToHostIntent.class); + } + + /** + * Tests equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + final HostToHostIntent intent1 = HostToHostIntent.builder() + .appId(APPID) + .one(id1) + .two(id2) + .selector(selector) + .treatment(treatment) + .build(); + + final HostToHostIntent intent2 = HostToHostIntent.builder() + .appId(APPID) + .one(id2) + .two(id3) + .selector(selector) + .treatment(treatment) + .build(); + + new EqualsTester() + .addEqualityGroup(intent1) + .addEqualityGroup(intent2) + .testEquals(); + } + + @Override + protected Intent createOne() { + return HostToHostIntent.builder() + .appId(APPID) + .one(id1) + .two(id2) + .selector(selector) + .treatment(treatment) + .build(); + } + + @Override + protected Intent createAnother() { + return HostToHostIntent.builder() + .appId(APPID) + .one(id1) + .two(id3) + .selector(selector) + .treatment(treatment) + .build(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentDataTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentDataTest.java new file mode 100644 index 00000000..9c4cf7e0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentDataTest.java @@ -0,0 +1,179 @@ +/* + * 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.net.intent; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.core.IdGenerator; +import org.onosproject.store.Timestamp; + +import com.google.common.testing.EqualsTester; + +import static junit.framework.TestCase.assertFalse; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertTrue; +import static org.onosproject.net.intent.IntentTestsMocks.MockIntent; +import static org.onosproject.net.intent.IntentTestsMocks.MockTimestamp; + +/** + * Unit tests for intent data objects. + */ +public class IntentDataTest { + + private Timestamp timestamp1; + private Timestamp timestamp2; + private Timestamp timestamp3; + + private Intent intent1; + private Intent intent2; + private Intent intent3; + + private IntentData data1; + private IntentData data1Copy; + private IntentData data2; + private IntentData data2Copy; + private IntentData data3; + private IntentData data3Copy; + + IdGenerator idGenerator; + + @Before + public void setUpTest() { + idGenerator = new MockIdGenerator(); + Intent.bindIdGenerator(idGenerator); + + timestamp1 = new MockTimestamp(1); + timestamp2 = new MockTimestamp(2); + timestamp3 = new MockTimestamp(3); + + intent1 = new MockIntent(1L); + intent2 = new MockIntent(2L); + intent3 = new MockIntent(3L); + + data1 = new IntentData(intent1, IntentState.INSTALLED, timestamp1); + data1Copy = new IntentData(intent1, IntentState.INSTALLED, timestamp1); + data2 = new IntentData(intent2, IntentState.INSTALLED, timestamp2); + data2Copy = new IntentData(intent2, IntentState.INSTALLED, timestamp2); + data3 = new IntentData(intent3, IntentState.INSTALLED, timestamp3); + data3Copy = new IntentData(intent3, IntentState.INSTALLED, timestamp3); + } + + @After + public void tearDownTest() { + Intent.unbindIdGenerator(idGenerator); + } + + /** + * Checks that intent data objects are properly constructed. + */ + @Test + public void checkConstruction() { + assertThat(data1.state(), is(IntentState.INSTALLED)); + assertThat(data1.version(), is(timestamp1)); + assertThat(data1.intent(), is(intent1)); + } + + /** + * Checks equals() for intent data objects. + */ + @Test + public void checkEquals() { + new EqualsTester() + .addEqualityGroup(data1, data1Copy) + .addEqualityGroup(data2, data2Copy) + .addEqualityGroup(data3, data3Copy) + .testEquals(); + } + + @Test + public void testIsUpdateAcceptable() { + // Going from null to something is always allowed + assertTrue(IntentData.isUpdateAcceptable(null, data1)); + + // we can go from older version to newer but not they other way + assertTrue(IntentData.isUpdateAcceptable(data1, data2)); + assertFalse(IntentData.isUpdateAcceptable(data2, data1)); + + IntentData installing = new IntentData(intent1, IntentState.INSTALLING, timestamp1); + IntentData installed = new IntentData(intent1, IntentState.INSTALLED, timestamp1); + IntentData withdrawing = new IntentData(intent1, IntentState.WITHDRAWING, timestamp1); + IntentData withdrawn = new IntentData(intent1, IntentState.WITHDRAWN, timestamp1); + + IntentData failed = new IntentData(intent1, IntentState.FAILED, timestamp1); + IntentData purgeReq = new IntentData(intent1, IntentState.PURGE_REQ, timestamp1); + + IntentData compiling = new IntentData(intent1, IntentState.COMPILING, timestamp1); + IntentData recompiling = new IntentData(intent1, IntentState.RECOMPILING, timestamp1); + IntentData installReq = new IntentData(intent1, IntentState.INSTALL_REQ, timestamp1); + IntentData withdrawReq = new IntentData(intent1, IntentState.WITHDRAW_REQ, timestamp1); + + // We can't change to the same state + assertFalse(IntentData.isUpdateAcceptable(installing, installing)); + assertFalse(IntentData.isUpdateAcceptable(installed, installed)); + + // From installing we can change to installed + assertTrue(IntentData.isUpdateAcceptable(installing, installed)); + + // Sanity checks in case the manager submits bogus state transitions + assertFalse(IntentData.isUpdateAcceptable(installing, withdrawing)); + assertFalse(IntentData.isUpdateAcceptable(installing, withdrawn)); + assertFalse(IntentData.isUpdateAcceptable(installed, withdrawing)); + assertFalse(IntentData.isUpdateAcceptable(installed, withdrawn)); + + // We can't change to the same state + assertFalse(IntentData.isUpdateAcceptable(withdrawing, withdrawing)); + assertFalse(IntentData.isUpdateAcceptable(withdrawn, withdrawn)); + + // From withdrawing we can change to withdrawn + assertTrue(IntentData.isUpdateAcceptable(withdrawing, withdrawn)); + + // Sanity checks in case the manager submits bogus state transitions + assertFalse(IntentData.isUpdateAcceptable(withdrawing, installing)); + assertFalse(IntentData.isUpdateAcceptable(withdrawing, installed)); + assertFalse(IntentData.isUpdateAcceptable(withdrawn, installing)); + assertFalse(IntentData.isUpdateAcceptable(withdrawn, installed)); + + // We can't go from failed to failed + assertFalse(IntentData.isUpdateAcceptable(failed, failed)); + + // But we can go from any install* or withdraw* state to failed + assertTrue(IntentData.isUpdateAcceptable(installing, failed)); + assertTrue(IntentData.isUpdateAcceptable(installed, failed)); + assertTrue(IntentData.isUpdateAcceptable(withdrawing, failed)); + assertTrue(IntentData.isUpdateAcceptable(withdrawn, failed)); + + // We can go from anything to purgeReq + assertTrue(IntentData.isUpdateAcceptable(installing, purgeReq)); + assertTrue(IntentData.isUpdateAcceptable(installed, purgeReq)); + assertTrue(IntentData.isUpdateAcceptable(withdrawing, purgeReq)); + assertTrue(IntentData.isUpdateAcceptable(withdrawn, purgeReq)); + assertTrue(IntentData.isUpdateAcceptable(failed, purgeReq)); + + // We can't go from purgeReq back to anything else + assertFalse(IntentData.isUpdateAcceptable(purgeReq, withdrawn)); + assertFalse(IntentData.isUpdateAcceptable(purgeReq, withdrawing)); + assertFalse(IntentData.isUpdateAcceptable(purgeReq, installed)); + assertFalse(IntentData.isUpdateAcceptable(purgeReq, installing)); + + // We're never allowed to store transient states + assertFalse(IntentData.isUpdateAcceptable(installing, compiling)); + assertFalse(IntentData.isUpdateAcceptable(installing, recompiling)); + assertFalse(IntentData.isUpdateAcceptable(installing, installReq)); + assertFalse(IntentData.isUpdateAcceptable(installing, withdrawReq)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentExceptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentExceptionTest.java new file mode 100644 index 00000000..f26ee639 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentExceptionTest.java @@ -0,0 +1,48 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Test of the intent exception. + */ +public class IntentExceptionTest { + + @Test + public void basics() { + validate(new IntentException(), null, null); + validate(new IntentException("foo"), "foo", null); + + Throwable cause = new NullPointerException("bar"); + validate(new IntentException("foo", cause), "foo", cause); + } + + /** + * Validates that the specified exception has the correct message and cause. + * + * @param e exception to test + * @param message expected message + * @param cause expected cause + */ + protected void validate(RuntimeException e, String message, Throwable cause) { + assertEquals("incorrect message", message, e.getMessage()); + assertEquals("incorrect cause", cause, e.getCause()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentIdTest.java new file mode 100644 index 00000000..e2987b54 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentIdTest.java @@ -0,0 +1,95 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * This class tests the immutability, equality, and non-equality of + * {@link IntentId}. + */ +public class IntentIdTest { + /** + * Tests the immutability of {@link IntentId}. + */ + @Test + public void intentIdFollowsGuidelineForImmutableObject() { + assertThatClassIsImmutable(IntentId.class); + } + + /** + * Tests equality of {@link IntentId}. + */ + @Test + public void testEquality() { + IntentId id1 = new IntentId(1L); + IntentId id2 = new IntentId(1L); + + assertThat(id1, is(id2)); + } + + /** + * Tests non-equality of {@link IntentId}. + */ + @Test + public void testNonEquality() { + IntentId id1 = new IntentId(1L); + IntentId id2 = new IntentId(2L); + + assertThat(id1, is(not(id2))); + } + + @Test + public void valueOf() { + IntentId id = new IntentId(0xdeadbeefL); + assertEquals("incorrect valueOf", id, IntentId.valueOf(0xdeadbeefL)); + } + + /** + * Tests the equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + final IntentId id1 = new IntentId(11111L); + final IntentId sameAsId1 = new IntentId(11111L); + final IntentId id2 = new IntentId(22222L); + + new EqualsTester() + .addEqualityGroup(id1, sameAsId1) + .addEqualityGroup(id2) + .testEquals(); + } + + /** + * Tests construction of an IntentId object. + */ + @Test + public void testConstruction() { + final IntentId id1 = new IntentId(987654321L); + assertEquals(id1.fingerprint(), 987654321L); + + final IntentId emptyId = new IntentId(); + assertEquals(emptyId.fingerprint(), 0L); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceAdapter.java new file mode 100644 index 00000000..13786b4e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceAdapter.java @@ -0,0 +1,89 @@ +/* + * 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.net.intent; + +import java.util.List; + +/** + * Test adapter for intent service. + */ +public class IntentServiceAdapter implements IntentService { + @Override + public void submit(Intent intent) { + + } + + @Override + public void withdraw(Intent intent) { + + } + + @Override + public void purge(Intent intent) { + + } + + @Override + public Iterable<Intent> getIntents() { + return null; + } + + @Override + public Iterable<IntentData> getIntentData() { + return null; + } + + @Override + public long getIntentCount() { + return 0; + } + + @Override + public Intent getIntent(Key intentKey) { + return null; + } + + @Override + public IntentState getIntentState(Key intentKey) { + return IntentState.INSTALLED; + } + + @Override + public List<Intent> getInstallableIntents(Key intentKey) { + return null; + } + + @Override + public boolean isLocal(Key intentKey) { + return false; + } + + @Override + public Iterable<Intent> getPending() { + return null; + } + + @Override + public void addListener(IntentListener listener) { + + } + + @Override + public void removeListener(IntentListener listener) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceTest.java new file mode 100644 index 00000000..60857cac --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentServiceTest.java @@ -0,0 +1,252 @@ +/* + * 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.net.intent; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.core.IdGenerator; +import org.onosproject.net.resource.link.LinkResourceAllocations; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.*; +import static org.onosproject.net.intent.IntentEvent.Type.*; + +/** + * Suite of tests for the intent service contract. + */ +public class IntentServiceTest { + + public static final int IID = 123; + public static final int INSTALLABLE_IID = 234; + + protected static final int GRACE_MS = 500; // millis + + protected TestableIntentService service; + protected TestListener listener = new TestListener(); + protected IdGenerator idGenerator = new MockIdGenerator(); + + @Before + public void setUp() { + service = createIntentService(); + service.addListener(listener); + Intent.bindIdGenerator(idGenerator); + } + + @After + public void tearDown() { + service.removeListener(listener); + Intent.unbindIdGenerator(idGenerator); + } + + /** + * Creates a service instance appropriately instrumented for testing. + * + * @return testable intent service + */ + protected TestableIntentService createIntentService() { + return new FakeIntentManager(); + } + + @Test + public void basics() { + // Make sure there are no intents + assertEquals("incorrect intent count", 0, service.getIntentCount()); + + // Register a compiler and an installer both setup for success. + service.registerCompiler(TestIntent.class, new TestCompiler(new TestInstallableIntent(INSTALLABLE_IID))); + + final Intent intent = new TestIntent(IID); + service.submit(intent); + + // Allow a small window of time until the intent is in the expected state + TestTools.assertAfter(GRACE_MS, new Runnable() { + @Override + public void run() { + assertEquals("incorrect intent state", IntentState.INSTALLED, + service.getIntentState(intent.key())); + } + }); + + // Make sure that all expected events have been emitted + validateEvents(intent, INSTALL_REQ, INSTALLED); + + // Make sure there is just one intent (and is ours) + assertEquals("incorrect intent count", 1, service.getIntentCount()); + + // Reset the listener events + listener.events.clear(); + + // Now withdraw the intent + service.withdraw(intent); + + // Allow a small window of time until the event is in the expected state + TestTools.assertAfter(GRACE_MS, new Runnable() { + @Override + public void run() { + assertEquals("incorrect intent state", IntentState.WITHDRAWN, + service.getIntentState(intent.key())); + } + }); + + // Make sure that all expected events have been emitted + validateEvents(intent, WITHDRAWN); + + // TODO: discuss what is the fate of intents after they have been withdrawn + // Make sure that the intent is no longer in the system +// assertEquals("incorrect intent count", 0, service.getIntents().size()); +// assertNull("intent should not be found", service.getIntent(intent.id())); +// assertNull("intent state should not be found", service.getIntentState(intent.id())); + } + + @Test + public void failedCompilation() { + // Register a compiler programmed for success + service.registerCompiler(TestIntent.class, new TestCompiler(true)); + + // Submit an intent + final Intent intent = new TestIntent(IID); + service.submit(intent); + + // Allow a small window of time until the intent is in the expected state + TestTools.assertAfter(GRACE_MS, new Runnable() { + @Override + public void run() { + assertEquals("incorrect intent state", IntentState.FAILED, + service.getIntentState(intent.key())); + } + }); + + // Make sure that all expected events have been emitted + validateEvents(intent, INSTALL_REQ, FAILED); + } + + /** + * Validates that the test event listener has received the following events + * for the specified intent. Events received for other intents will not be + * considered. + * + * @param intent intent subject + * @param types list of event types for which events are expected + */ + protected void validateEvents(Intent intent, IntentEvent.Type... types) { + Iterator<IntentEvent> events = listener.events.iterator(); + for (IntentEvent.Type type : types) { + IntentEvent event = events.hasNext() ? events.next() : null; + if (event == null) { + fail("expected event not found: " + type); + } else if (intent.equals(event.subject())) { + assertEquals("incorrect state", type, event.type()); + } + } + + // Remainder of events should not apply to this intent; make sure. + while (events.hasNext()) { + assertFalse("unexpected event for intent", + intent.equals(events.next().subject())); + } + } + + @Test + public void compilerBasics() { + // Make sure there are no compilers + assertEquals("incorrect compiler count", 0, service.getCompilers().size()); + + // Add a compiler and make sure that it appears in the map + IntentCompiler<TestIntent> compiler = new TestCompiler(false); + service.registerCompiler(TestIntent.class, compiler); + assertEquals("incorrect compiler", compiler, + service.getCompilers().get(TestIntent.class)); + + // Remove the same and make sure that it no longer appears in the map + service.unregisterCompiler(TestIntent.class); + assertNull("compiler should not be registered", + service.getCompilers().get(TestIntent.class)); + } + + @Test + public void implicitRegistration() { + // Add a compiler and make sure that it appears in the map + IntentCompiler<TestIntent> compiler = new TestCompiler(new TestSubclassInstallableIntent(INSTALLABLE_IID)); + service.registerCompiler(TestIntent.class, compiler); + assertEquals("incorrect compiler", compiler, + service.getCompilers().get(TestIntent.class)); + + // Submit an intent which is a subclass of the one we registered + final Intent intent = new TestSubclassIntent(IID); + service.submit(intent); + + // Allow some time for the intent to be compiled and installed + TestTools.assertAfter(GRACE_MS, new Runnable() { + @Override + public void run() { + assertEquals("incorrect intent state", IntentState.INSTALLED, + service.getIntentState(intent.key())); + } + }); + + // Make sure that now we have an implicit registration of the compiler + // under the intent subclass + assertEquals("incorrect compiler", compiler, + service.getCompilers().get(TestSubclassIntent.class)); + + // TODO: discuss whether or if implicit registration should require implicit unregistration + // perhaps unregister by compiler or installer itself, rather than by class would be better + } + + + // Fixture to track emitted intent events + protected class TestListener implements IntentListener { + final List<IntentEvent> events = new ArrayList<>(); + + @Override + public void event(IntentEvent event) { + events.add(event); + } + } + + // Controllable compiler + private class TestCompiler implements IntentCompiler<TestIntent> { + private final boolean fail; + private final List<Intent> result; + + TestCompiler(boolean fail) { + this.fail = fail; + this.result = Collections.emptyList(); + } + + TestCompiler(Intent... result) { + this.fail = false; + this.result = Arrays.asList(result); + } + + @Override + public List<Intent> compile(TestIntent intent, List<Intent> installable, + Set<LinkResourceAllocations> resources) { + if (fail) { + throw new IntentException("compile failed by design"); + } + List<Intent> compiled = new ArrayList<>(result); + return compiled; + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTest.java new file mode 100644 index 00000000..d713b8aa --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTest.java @@ -0,0 +1,52 @@ +/* + * 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.net.intent; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * Base facilities to test various intent tests. + */ +public abstract class IntentTest extends AbstractIntentTest { + /** + * Produces a set of items from the supplied items. + * + * @param items items to be placed in set + * @param <T> item type + * @return set of items + */ + protected static <T> Set<T> itemSet(T[] items) { + return new HashSet<>(Arrays.asList(items)); + } + + /** + * Creates a new intent, but always a like intent, i.e. all instances will + * be equal, but should not be the same. + * + * @return intent + */ + protected abstract Intent createOne(); + + /** + * Creates another intent, not equals to the one created by + * {@link #createOne()} and with a different hash code. + * + * @return another intent + */ + protected abstract Intent createAnother(); +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTestsMocks.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTestsMocks.java new file mode 100644 index 00000000..ac4ecff3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/IntentTestsMocks.java @@ -0,0 +1,496 @@ +/* + * 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.net.intent; + +import com.google.common.base.MoreObjects; +import com.google.common.collect.ImmutableSet; + +import org.onlab.util.Bandwidth; +import org.onosproject.core.DefaultGroupId; +import org.onosproject.core.GroupId; +import org.onosproject.net.DeviceId; +import org.onosproject.net.ElementId; +import org.onosproject.net.Link; +import org.onosproject.net.NetTestTools; +import org.onosproject.net.NetworkResource; +import org.onosproject.net.Path; +import org.onosproject.net.flow.FlowId; +import org.onosproject.net.flow.FlowRule; +import org.onosproject.net.flow.FlowRuleExtPayLoad; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; +import org.onosproject.net.flow.criteria.Criterion; +import org.onosproject.net.flow.criteria.Criterion.Type; +import org.onosproject.net.flow.instructions.Instruction; +import org.onosproject.net.flow.instructions.Instructions; +import org.onosproject.net.flow.instructions.Instructions.MetadataInstruction; +import org.onosproject.net.resource.link.BandwidthResource; +import org.onosproject.net.resource.link.BandwidthResourceRequest; +import org.onosproject.net.resource.link.LambdaResource; +import org.onosproject.net.resource.link.LambdaResourceAllocation; +import org.onosproject.net.resource.link.LambdaResourceRequest; +import org.onosproject.net.resource.link.LinkResourceAllocations; +import org.onosproject.net.resource.link.LinkResourceListener; +import org.onosproject.net.resource.link.LinkResourceRequest; +import org.onosproject.net.resource.link.LinkResourceService; +import org.onosproject.net.resource.link.MplsLabel; +import org.onosproject.net.resource.link.MplsLabelResourceAllocation; +import org.onosproject.net.resource.ResourceAllocation; +import org.onosproject.net.resource.ResourceRequest; +import org.onosproject.net.resource.ResourceType; +import org.onosproject.net.topology.DefaultTopologyEdge; +import org.onosproject.net.topology.DefaultTopologyVertex; +import org.onosproject.net.topology.LinkWeight; +import org.onosproject.net.topology.PathService; +import org.onosproject.net.topology.TopologyVertex; +import org.onosproject.store.Timestamp; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import static org.onosproject.net.NetTestTools.createPath; +import static org.onosproject.net.NetTestTools.did; +import static org.onosproject.net.NetTestTools.link; + +/** + * Common mocks used by the intent framework tests. + */ +public class IntentTestsMocks { + /** + * Mock traffic selector class used for satisfying API requirements. + */ + public static class MockSelector implements TrafficSelector { + @Override + public Set<Criterion> criteria() { + return new HashSet<>(); + } + + @Override + public Criterion getCriterion(Type type) { + return null; + } + } + + /** + * Mock traffic treatment class used for satisfying API requirements. + */ + public static class MockTreatment implements TrafficTreatment { + @Override + public List<Instruction> deferred() { + return Collections.emptyList(); + } + + @Override + public List<Instruction> immediate() { + return Collections.emptyList(); + } + + @Override + public List<Instruction> allInstructions() { + return Collections.emptyList(); + } + + @Override + public Instructions.TableTypeTransition tableTransition() { + return null; + } + + @Override + public boolean clearedDeferred() { + return false; + } + + @Override + public MetadataInstruction writeMetadata() { + return null; + } + + @Override + public Instructions.MeterInstruction metered() { + return null; + } + } + + /** + * Mock path service for creating paths within the test. + */ + public static class MockPathService implements PathService { + + final String[] pathHops; + final String[] reversePathHops; + + /** + * Constructor that provides a set of hops to mock. + * + * @param pathHops path hops to mock + */ + public MockPathService(String[] pathHops) { + this.pathHops = pathHops; + String[] reversed = pathHops.clone(); + Collections.reverse(Arrays.asList(reversed)); + reversePathHops = reversed; + } + + @Override + public Set<Path> getPaths(ElementId src, ElementId dst) { + Set<Path> result = new HashSet<>(); + + String[] allHops = new String[pathHops.length]; + + if (src.toString().endsWith(pathHops[0])) { + System.arraycopy(pathHops, 0, allHops, 0, pathHops.length); + } else { + System.arraycopy(reversePathHops, 0, allHops, 0, pathHops.length); + } + + result.add(createPath(allHops)); + return result; + } + + @Override + public Set<Path> getPaths(ElementId src, ElementId dst, LinkWeight weight) { + final Set<Path> paths = getPaths(src, dst); + + for (Path path : paths) { + final DeviceId srcDevice = path.src().deviceId(); + final DeviceId dstDevice = path.dst().deviceId(); + final TopologyVertex srcVertex = new DefaultTopologyVertex(srcDevice); + final TopologyVertex dstVertex = new DefaultTopologyVertex(dstDevice); + final Link link = link(src.toString(), 1, dst.toString(), 1); + + final double weightValue = weight.weight(new DefaultTopologyEdge(srcVertex, dstVertex, link)); + if (weightValue < 0) { + return new HashSet<>(); + } + } + return paths; + } + } + + public static class MockLinkResourceAllocations implements LinkResourceAllocations { + @Override + public Set<ResourceAllocation> getResourceAllocation(Link link) { + return ImmutableSet.of( + new LambdaResourceAllocation(LambdaResource.valueOf(77)), + new MplsLabelResourceAllocation(MplsLabel.valueOf(10))); + } + + public IntentId intentId() { + return null; + } + + public Collection<Link> links() { + return null; + } + + public Set<ResourceRequest> resources() { + return null; + } + + @Override + public ResourceType type() { + return null; + } + } + + public static class MockedAllocationFailure extends RuntimeException { } + + public static class MockResourceService implements LinkResourceService { + + double availableBandwidth = -1.0; + int availableLambda = -1; + + /** + * Allocates a resource service that will allow bandwidth allocations + * up to a limit. + * + * @param bandwidth available bandwidth limit + * @return resource manager for bandwidth requests + */ + public static MockResourceService makeBandwidthResourceService(double bandwidth) { + final MockResourceService result = new MockResourceService(); + result.availableBandwidth = bandwidth; + return result; + } + + /** + * Allocates a resource service that will allow lambda allocations. + * + * @param lambda Lambda to return for allocation requests. Currently unused + * @return resource manager for lambda requests + */ + public static MockResourceService makeLambdaResourceService(int lambda) { + final MockResourceService result = new MockResourceService(); + result.availableLambda = lambda; + return result; + } + + public void setAvailableBandwidth(double availableBandwidth) { + this.availableBandwidth = availableBandwidth; + } + + public void setAvailableLambda(int availableLambda) { + this.availableLambda = availableLambda; + } + + + @Override + public LinkResourceAllocations requestResources(LinkResourceRequest req) { + int lambda = -1; + double bandwidth = -1.0; + + for (ResourceRequest resourceRequest : req.resources()) { + if (resourceRequest.type() == ResourceType.BANDWIDTH) { + final BandwidthResourceRequest brr = (BandwidthResourceRequest) resourceRequest; + bandwidth = brr.bandwidth().toDouble(); + } else if (resourceRequest.type() == ResourceType.LAMBDA) { + lambda = 1; + } + } + + if (availableBandwidth < bandwidth) { + throw new MockedAllocationFailure(); + } + if (lambda > 0 && availableLambda == 0) { + throw new MockedAllocationFailure(); + } + + return new IntentTestsMocks.MockLinkResourceAllocations(); + } + + @Override + public void releaseResources(LinkResourceAllocations allocations) { + // Mock + } + + @Override + public LinkResourceAllocations updateResources(LinkResourceRequest req, + LinkResourceAllocations oldAllocations) { + return null; + } + + @Override + public Iterable<LinkResourceAllocations> getAllocations() { + return ImmutableSet.of( + new IntentTestsMocks.MockLinkResourceAllocations()); + } + + @Override + public Iterable<LinkResourceAllocations> getAllocations(Link link) { + return ImmutableSet.of( + new IntentTestsMocks.MockLinkResourceAllocations()); + } + + @Override + public LinkResourceAllocations getAllocations(IntentId intentId) { + return new IntentTestsMocks.MockLinkResourceAllocations(); + } + + @Override + public Iterable<ResourceRequest> getAvailableResources(Link link) { + final List<ResourceRequest> result = new LinkedList<>(); + if (availableBandwidth > 0.0) { + result.add(new BandwidthResourceRequest( + new BandwidthResource(Bandwidth.bps(availableBandwidth)))); + } + if (availableLambda > 0) { + result.add(new LambdaResourceRequest()); + } + return result; + } + + @Override + public Iterable<ResourceRequest> getAvailableResources(Link link, LinkResourceAllocations allocations) { + return null; + } + + @Override + public void addListener(LinkResourceListener listener) { + + } + + @Override + public void removeListener(LinkResourceListener listener) { + + } + } + + private static final IntentTestsMocks.MockSelector SELECTOR = + new IntentTestsMocks.MockSelector(); + private static final IntentTestsMocks.MockTreatment TREATMENT = + new IntentTestsMocks.MockTreatment(); + + public static class MockFlowRule implements FlowRule { + static int nextId = 0; + + int priority; + int tableId; + long timestamp; + int id; + FlowRuleExtPayLoad payLoad; + + public MockFlowRule(int priority) { + this.priority = priority; + this.tableId = 0; + this.timestamp = System.currentTimeMillis(); + this.id = nextId++; + this.payLoad = null; + } + + public MockFlowRule(int priority, FlowRuleExtPayLoad payLoad) { + this.priority = priority; + this.timestamp = System.currentTimeMillis(); + this.id = nextId++; + this.payLoad = payLoad; + } + + @Override + public FlowId id() { + return FlowId.valueOf(id); + } + + @Override + public short appId() { + return 0; + } + + @Override + public GroupId groupId() { + return new DefaultGroupId(0); + } + + @Override + public int priority() { + return priority; + } + + @Override + public DeviceId deviceId() { + return did("1"); + } + + @Override + public TrafficSelector selector() { + return SELECTOR; + } + + @Override + public TrafficTreatment treatment() { + return TREATMENT; + } + + @Override + public int timeout() { + return 0; + } + + @Override + public boolean isPermanent() { + return false; + } + + @Override + public int hashCode() { + return Objects.hash(priority); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + final MockFlowRule other = (MockFlowRule) obj; + return Objects.equals(this.timestamp, other.timestamp) && + this.id == other.id; + } + + @Override + public boolean exactMatch(FlowRule rule) { + return this.equals(rule); + } + + @Override + public int tableId() { + return tableId; + } + + @Override + public FlowRuleExtPayLoad payLoad() { + return payLoad; + } + } + + public static class MockIntent extends Intent { + private static AtomicLong counter = new AtomicLong(0); + + private final Long number; + + public MockIntent(Long number) { + super(NetTestTools.APP_ID, null, Collections.emptyList(), + Intent.DEFAULT_INTENT_PRIORITY); + this.number = number; + } + + public MockIntent(Long number, Collection<NetworkResource> resources) { + super(NetTestTools.APP_ID, null, resources, Intent.DEFAULT_INTENT_PRIORITY); + this.number = number; + } + + public Long number() { + return number; + } + + public static Long nextId() { + return counter.getAndIncrement(); + } + + @Override + public String toString() { + return MoreObjects.toStringHelper(getClass()) + .add("id", id()) + .add("appId", appId()) + .toString(); + } + } + + public static class MockTimestamp implements Timestamp { + final int value; + + public MockTimestamp(int value) { + this.value = value; + } + + @Override + public int compareTo(Timestamp o) { + if (!(o instanceof MockTimestamp)) { + return -1; + } + MockTimestamp that = (MockTimestamp) o; + return this.value - that.value; + } + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/KeyTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/KeyTest.java new file mode 100644 index 00000000..dfc73442 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/KeyTest.java @@ -0,0 +1,121 @@ +/* + * 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.net.intent; + +import org.junit.Test; +import org.onosproject.net.NetTestTools; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Unit tests for the intent key class. + */ +public class KeyTest { + + private static final String KEY_1 = "key1"; + private static final String KEY_2 = "key2"; + private static final String KEY_3 = "key3"; + + private static final long LONG_KEY_1 = 0x1111; + private static final long LONG_KEY_2 = 0x2222; + private static final long LONG_KEY_3 = 0x3333; + + /** + * Tests that keys are properly immutable. + */ + @Test + public void keysAreImmutable() { + assertThatClassIsImmutableBaseClass(Key.class); + + // Will be a long based key, class is private so cannot be + // accessed directly + Key longKey = Key.of(0xabcdefL, NetTestTools.APP_ID); + assertThatClassIsImmutable(longKey.getClass()); + + // Will be a String based key, class is private so cannot be + // accessed directly. + Key stringKey = Key.of("some key", NetTestTools.APP_ID); + assertThatClassIsImmutable(stringKey.getClass()); + } + + /** + * Tests string key construction. + */ + @Test + public void stringKeyConstruction() { + Key stringKey1 = Key.of(KEY_3, NetTestTools.APP_ID); + assertThat(stringKey1, notNullValue()); + Key stringKey2 = Key.of(KEY_3, NetTestTools.APP_ID); + assertThat(stringKey2, notNullValue()); + + assertThat(stringKey1.hash(), is(stringKey2.hash())); + } + + /** + * Tests long key construction. + */ + @Test + public void longKeyConstruction() { + Key longKey1 = Key.of(LONG_KEY_3, NetTestTools.APP_ID); + assertThat(longKey1, notNullValue()); + Key longKey2 = Key.of(LONG_KEY_3, NetTestTools.APP_ID); + assertThat(longKey2, notNullValue()); + + assertThat(longKey1.hash(), is(longKey2.hash())); + } + + /** + * Tests equals for string based keys. + */ + @Test + public void stringKey() { + Key stringKey1 = Key.of(KEY_1, NetTestTools.APP_ID); + Key copyOfStringKey1 = Key.of(KEY_1, NetTestTools.APP_ID); + Key stringKey2 = Key.of(KEY_2, NetTestTools.APP_ID); + Key copyOfStringKey2 = Key.of(KEY_2, NetTestTools.APP_ID); + Key stringKey3 = Key.of(KEY_3, NetTestTools.APP_ID); + + new EqualsTester() + .addEqualityGroup(stringKey1, copyOfStringKey1) + .addEqualityGroup(stringKey2, copyOfStringKey2) + .addEqualityGroup(stringKey3) + .testEquals(); + } + + /** + * Tests equals for long based keys. + */ + @Test + public void longKey() { + Key longKey1 = Key.of(LONG_KEY_1, NetTestTools.APP_ID); + Key copyOfLongKey1 = Key.of(LONG_KEY_1, NetTestTools.APP_ID); + Key longKey2 = Key.of(LONG_KEY_2, NetTestTools.APP_ID); + Key copyOfLongKey2 = Key.of(LONG_KEY_2, NetTestTools.APP_ID); + Key longKey3 = Key.of(LONG_KEY_3, NetTestTools.APP_ID); + + new EqualsTester() + .addEqualityGroup(longKey1, copyOfLongKey1) + .addEqualityGroup(longKey2, copyOfLongKey2) + .addEqualityGroup(longKey3) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/LinkCollectionIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/LinkCollectionIntentTest.java new file mode 100644 index 00000000..88fa7f4f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/LinkCollectionIntentTest.java @@ -0,0 +1,209 @@ +/* + * 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.net.intent; + +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.junit.Test; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.Link; +import org.onosproject.net.NetTestTools; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.intent.constraint.LambdaConstraint; +import org.onosproject.net.resource.link.LambdaResource; + +import com.google.common.collect.ImmutableSet; +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.startsWith; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.link; + +/** + * Unit tests for the LinkCollectionIntent class. + */ +public class LinkCollectionIntentTest extends IntentTest { + + final ConnectPoint ingress = NetTestTools.connectPoint("ingress", 2); + final ConnectPoint egress = NetTestTools.connectPoint("egress", 3); + final TrafficSelector selector = new IntentTestsMocks.MockSelector(); + final IntentTestsMocks.MockTreatment treatment = new IntentTestsMocks.MockTreatment(); + + /** + * Checks that the LinkCollectionIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(LinkCollectionIntent.class); + } + + /** + * Tests equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + + final HashSet<Link> links1 = new HashSet<>(); + links1.add(link("src", 1, "dst", 2)); + final LinkCollectionIntent collectionIntent1 = + LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links1) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .build(); + + final HashSet<Link> links2 = new HashSet<>(); + links2.add(link("src", 1, "dst", 3)); + final LinkCollectionIntent collectionIntent2 = + LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links2) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .build(); + + new EqualsTester() + .addEqualityGroup(collectionIntent1) + .addEqualityGroup(collectionIntent2) + .testEquals(); + } + + /** + * Tests constructor without constraints. + */ + @Test + public void testConstructor() { + final HashSet<Link> links1 = new HashSet<>(); + links1.add(link("src", 1, "dst", 2)); + final LinkCollectionIntent collectionIntent = + LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links1) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .build(); + + final Set<Link> createdLinks = collectionIntent.links(); + assertThat(createdLinks, hasSize(1)); + assertThat(collectionIntent.isInstallable(), is(false)); + assertThat(collectionIntent.treatment(), is(treatment)); + assertThat(collectionIntent.selector(), is(selector)); + assertThat(collectionIntent.ingressPoints(), is(ImmutableSet.of(ingress))); + assertThat(collectionIntent.egressPoints(), is(ImmutableSet.of(egress))); + assertThat(collectionIntent.resources(), hasSize(1)); + final List<Constraint> createdConstraints = collectionIntent.constraints(); + assertThat(createdConstraints, hasSize(0)); + } + + /** + * Tests constructor with constraints. + */ + @Test + public void testConstructorWithConstraints() { + final HashSet<Link> links1 = new HashSet<>(); + final LinkedList<Constraint> constraints = new LinkedList<>(); + + links1.add(link("src", 1, "dst", 2)); + constraints.add(new LambdaConstraint(LambdaResource.valueOf(23))); + final LinkCollectionIntent collectionIntent = + LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links1) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .constraints(constraints) + .priority(8888) + .build(); + + final Set<Link> createdLinks = collectionIntent.links(); + assertThat(createdLinks, hasSize(1)); + assertThat(collectionIntent.isInstallable(), is(false)); + assertThat(collectionIntent.treatment(), is(treatment)); + assertThat(collectionIntent.selector(), is(selector)); + assertThat(collectionIntent.ingressPoints(), is(ImmutableSet.of(ingress))); + assertThat(collectionIntent.egressPoints(), is(ImmutableSet.of(egress))); + + final List<Constraint> createdConstraints = collectionIntent.constraints(); + assertThat(createdConstraints, hasSize(1)); + assertThat(createdConstraints.get(0).toString(), startsWith("LambdaConstraint")); + } + + /** + * Tests constructor with constraints. + */ + @Test + public void testSerializerConstructor() { + + final LinkCollectionIntent collectionIntent = + new LinkCollectionIntent(); + + final Set<Link> createdLinks = collectionIntent.links(); + assertThat(createdLinks, nullValue()); + assertThat(collectionIntent.isInstallable(), is(false)); + assertThat(collectionIntent.treatment(), nullValue()); + assertThat(collectionIntent.selector(), nullValue()); + assertThat(collectionIntent.ingressPoints(), nullValue()); + assertThat(collectionIntent.egressPoints(), nullValue()); + + final List<Constraint> createdConstraints = collectionIntent.constraints(); + assertThat(createdConstraints, hasSize(0)); + } + + @Override + protected Intent createOne() { + HashSet<Link> links1 = new HashSet<>(); + links1.add(link("src", 1, "dst", 2)); + return LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links1) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .build(); + } + + @Override + protected Intent createAnother() { + HashSet<Link> links2 = new HashSet<>(); + links2.add(link("src", 1, "dst", 3)); + return LinkCollectionIntent.builder() + .appId(APP_ID) + .selector(selector) + .treatment(treatment) + .links(links2) + .ingressPoints(ImmutableSet.of(ingress)) + .egressPoints(ImmutableSet.of(egress)) + .build(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java new file mode 100644 index 00000000..5e84cd8c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MockIdGenerator.java @@ -0,0 +1,32 @@ +/* + * 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.net.intent; + +import org.onosproject.core.IdGenerator; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Mock id generator for testing. + */ +public class MockIdGenerator implements IdGenerator { + private AtomicLong nextId = new AtomicLong(0); + + @Override + public long getNewId() { + return nextId.getAndIncrement(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsIntentTest.java new file mode 100644 index 00000000..196d6ad4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsIntentTest.java @@ -0,0 +1,117 @@ +/* + * 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.net.intent; + +import java.util.Optional; + +import org.junit.Before; +import org.junit.Test; +import org.onlab.packet.MplsLabel; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.connectPoint; + +/** + * Unit tests for the MplsIntent class. + */ + +public class MplsIntentTest extends AbstractIntentTest { + static final int PRIORITY = 22; + + MplsIntent intent1; + MplsIntent intent2; + + Optional<MplsLabel> label1; + Optional<MplsLabel> label2; + + TrafficSelector selector; + TrafficTreatment treatment; + + @Before + public void mplsIntentTestSetUp() throws Exception { + + label1 = Optional.of(MplsLabel.mplsLabel(1)); + label2 = Optional.of(MplsLabel.mplsLabel(2)); + + selector = new IntentTestsMocks.MockSelector(); + treatment = new IntentTestsMocks.MockTreatment(); + + intent1 = MplsIntent.builder() + .appId(APP_ID) + .ingressLabel(label1) + .egressLabel(label2) + .ingressPoint(connectPoint("in", 1)) + .egressPoint(connectPoint("out", 1)) + .selector(selector) + .treatment(treatment) + .priority(PRIORITY) + .build(); + + intent2 = MplsIntent.builder() + .appId(APP_ID) + .ingressLabel(label1) + .egressLabel(label2) + .ingressPoint(connectPoint("in", 2)) + .egressPoint(connectPoint("out", 2)) + .selector(selector) + .treatment(treatment) + .priority(PRIORITY) + .build(); + } + + /** + * Checks that the MplsIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(MplsIntent.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(intent1) + .addEqualityGroup(intent2) + .testEquals(); + } + + /** + * Checks that the MplsIntent objects are created correctly. + */ + @Test + public void testContents() { + assertThat(intent1.appId(), equalTo(APP_ID)); + assertThat(intent1.ingressLabel(), equalTo(label1)); + assertThat(intent1.egressLabel(), equalTo(label2)); + assertThat(intent1.ingressPoint(), equalTo(connectPoint("in", 1))); + assertThat(intent1.egressPoint(), equalTo(connectPoint("out", 1))); + assertThat(intent1.selector(), equalTo(intent2.selector())); + assertThat(intent1.treatment(), equalTo(intent2.treatment())); + assertThat(intent1.priority(), is(PRIORITY)); + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsPathIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsPathIntentTest.java new file mode 100644 index 00000000..551f19eb --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MplsPathIntentTest.java @@ -0,0 +1,110 @@ +/* + * 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.net.intent; + +import java.util.Optional; + +import org.junit.Before; +import org.junit.Test; +import org.onlab.packet.MplsLabel; +import org.onosproject.net.Path; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.createPath; + +/** + * Unit tests for the MplsPathIntent class. + */ +public class MplsPathIntentTest extends AbstractIntentTest { + + static final int PRIORITY = 777; + + MplsPathIntent intent1; + MplsPathIntent intent2; + Path defaultPath; + Optional<MplsLabel> label1; + Optional<MplsLabel> label2; + TrafficSelector selector; + TrafficTreatment treatment; + + @Before + public void mplsPathIntentTestSetUp() { + defaultPath = createPath("a", "b", "c"); + selector = new IntentTestsMocks.MockSelector(); + treatment = new IntentTestsMocks.MockTreatment(); + + label1 = Optional.of(MplsLabel.mplsLabel(1)); + label2 = Optional.of(MplsLabel.mplsLabel(2)); + intent1 = MplsPathIntent.builder() + .appId(APP_ID) + .ingressLabel(label1) + .egressLabel(label2) + .path(defaultPath) + .priority(PRIORITY) + .build(); + + intent2 = MplsPathIntent.builder() + .appId(APP_ID) + .ingressLabel(label1) + .egressLabel(label2) + .path(defaultPath) + .priority(PRIORITY) + .build(); + } + + + /** + * Checks that the MplsPathIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(MplsPathIntent.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(intent1) + .addEqualityGroup(intent2) + .testEquals(); + } + + /** + * Checks that the MPLS path intent objects are created correctly. + */ + @Test + public void testContents() { + assertThat(intent1.appId(), equalTo(APP_ID)); + assertThat(intent1.ingressLabel(), equalTo(label1)); + assertThat(intent1.egressLabel(), equalTo(label2)); + assertThat(intent1.selector(), equalTo(intent2.selector())); + assertThat(intent1.treatment(), equalTo(intent2.treatment())); + assertThat(intent1.priority(), is(PRIORITY)); + assertThat(intent1.path(), is(defaultPath)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MultiPointToSinglePointIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MultiPointToSinglePointIntentTest.java new file mode 100644 index 00000000..00be3101 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/MultiPointToSinglePointIntentTest.java @@ -0,0 +1,66 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Suite of tests of the multi-to-single point intent descriptor. + */ +public class MultiPointToSinglePointIntentTest extends ConnectivityIntentTest { + + /** + * Checks that the MultiPointToSinglePointIntent class is immutable. + */ + @Test + public void checkImmutability() { + assertThatClassIsImmutable(MultiPointToSinglePointIntent.class); + } + + @Test + public void basics() { + MultiPointToSinglePointIntent intent = createOne(); + assertEquals("incorrect id", APPID, intent.appId()); + assertEquals("incorrect match", MATCH, intent.selector()); + assertEquals("incorrect ingress", PS1, intent.ingressPoints()); + assertEquals("incorrect egress", P2, intent.egressPoint()); + } + + @Override + protected MultiPointToSinglePointIntent createOne() { + return MultiPointToSinglePointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoints(PS1) + .egressPoint(P2) + .build(); + } + + @Override + protected MultiPointToSinglePointIntent createAnother() { + return MultiPointToSinglePointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoints(PS2) + .egressPoint(P1) + .build(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalConnectivityIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalConnectivityIntentTest.java new file mode 100644 index 00000000..7df220c3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalConnectivityIntentTest.java @@ -0,0 +1,35 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Unit tests for the OpticalConnectivityIntent class. + */ +public class OpticalConnectivityIntentTest { + + /** + * Checks that the HostToHostIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(OpticalConnectivityIntent.class); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalPathIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalPathIntentTest.java new file mode 100644 index 00000000..36e018a9 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/OpticalPathIntentTest.java @@ -0,0 +1,97 @@ +/* + * 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.net.intent; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.OchSignalType; +import org.onosproject.net.Path; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.connectPoint; +import static org.onosproject.net.NetTestTools.createLambda; +import static org.onosproject.net.NetTestTools.createPath; + +public class OpticalPathIntentTest extends AbstractIntentTest { + + static final int PRIORITY = 777; + + OpticalPathIntent intent1; + OpticalPathIntent intent2; + Path defaultPath; + + @Before + public void opticalPathIntentTestSetUp() { + defaultPath = createPath("a", "b", "c"); + intent1 = OpticalPathIntent.builder() + .appId(APP_ID) + .src(connectPoint("one", 1)) + .dst(connectPoint("two", 2)) + .path(defaultPath) + .lambda(createLambda()) + .signalType(OchSignalType.FIXED_GRID) + .priority(PRIORITY) + .build(); + + intent2 = OpticalPathIntent.builder() + .appId(APP_ID) + .src(connectPoint("two", 1)) + .dst(connectPoint("one", 2)) + .path(defaultPath) + .lambda(createLambda()) + .signalType(OchSignalType.FIXED_GRID) + .priority(PRIORITY) + .build(); + } + + /** + * Checks that the OpticalPathIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(OpticalPathIntent.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(intent1) + .addEqualityGroup(intent2) + .testEquals(); + } + + /** + * Checks that the optical path intent objects are created correctly. + */ + @Test + public void testContents() { + assertThat(intent1.appId(), equalTo(APP_ID)); + assertThat(intent1.src(), Matchers.equalTo(connectPoint("one", 1))); + assertThat(intent1.dst(), Matchers.equalTo(connectPoint("two", 2))); + assertThat(intent1.priority(), is(PRIORITY)); + assertThat(intent1.path(), is(defaultPath)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PartitionServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PartitionServiceAdapter.java new file mode 100644 index 00000000..ffb2635e --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PartitionServiceAdapter.java @@ -0,0 +1,45 @@ +/* + * 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.net.intent; + +import org.onosproject.cluster.NodeId; + +import static org.junit.Assert.*; + +/** + * Testing adapter for the partition service. + */ +public class PartitionServiceAdapter implements PartitionService { + @Override + public boolean isMine(Key intentKey) { + return true; + } + + @Override + public NodeId getLeader(Key intentKey) { + return null; + } + + @Override + public void addListener(PartitionEventListener listener) { + + } + + @Override + public void removeListener(PartitionEventListener listener) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PathIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PathIntentTest.java new file mode 100644 index 00000000..dfbc1846 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PathIntentTest.java @@ -0,0 +1,115 @@ +/* + * 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.net.intent; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DefaultPath; +import org.onosproject.net.DeviceId; +import org.onosproject.net.NetTestTools; +import org.onosproject.net.Path; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; +import static org.onosproject.net.PortNumber.portNumber; + +public class PathIntentTest extends ConnectivityIntentTest { + // 111:11 --> 222:22 + private static final Path PATH1 = NetTestTools.createPath("111", "222"); + + // 111:11 --> 333:33 + private static final Path PATH2 = NetTestTools.createPath("222", "333"); + + private final ProviderId provider1 = new ProviderId("of", "1"); + private final DeviceId device1 = deviceId("1"); + private final DeviceId device2 = deviceId("2"); + private final PortNumber port1 = portNumber(1); + private final PortNumber port2 = portNumber(2); + private final PortNumber port3 = portNumber(3); + private final PortNumber port4 = portNumber(4); + private final ConnectPoint cp1 = new ConnectPoint(device1, port1); + private final ConnectPoint cp2 = new ConnectPoint(device1, port2); + private final ConnectPoint cp3 = new ConnectPoint(device2, port3); + private final ConnectPoint cp4 = new ConnectPoint(device2, port4); + private final DefaultLink link1 = new DefaultLink(provider1, cp1, cp2, DIRECT); + private final DefaultLink link2 = new DefaultLink(provider1, cp1, cp2, DIRECT); + private final double cost = 1; + + @Test + public void basics() { + PathIntent intent = createOne(); + assertEquals("incorrect id", APPID, intent.appId()); + assertEquals("incorrect match", MATCH, intent.selector()); + assertEquals("incorrect action", NOP, intent.treatment()); + assertEquals("incorrect path", PATH1, intent.path()); + } + + @Override + protected PathIntent createOne() { + return PathIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .path(PATH1) + .build(); + } + + @Override + protected PathIntent createAnother() { + return PathIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .path(PATH2) + .build(); + } + + /** + * Tests the constructor raises IllegalArgumentException when the same device is specified in + * source and destination of a link. + */ + @Test(expected = IllegalArgumentException.class) + public void testRaiseExceptionWhenSameDevices() { + PathIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .path(new DefaultPath(provider1, Collections.singletonList(link1), cost)) + .build(); + } + + /** + * Tests the constructor raises IllegalArgumentException when the different elements are specified + * in source element of the first link and destination element of the second link. + */ + @Test(expected = IllegalArgumentException.class) + public void testRaiseExceptionWhenDifferentDevice() { + PathIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .path(new DefaultPath(provider1, Arrays.asList(link1, link2), cost)) + .build(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PointToPointIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PointToPointIntentTest.java new file mode 100644 index 00000000..46772f9f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/PointToPointIntentTest.java @@ -0,0 +1,66 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; + +/** + * Suite of tests of the point-to-point intent descriptor. + */ +public class PointToPointIntentTest extends ConnectivityIntentTest { + + /** + * Checks that the MultiPointToSinglePointIntent class is immutable. + */ + @Test + public void checkImmutability() { + assertThatClassIsImmutableBaseClass(PointToPointIntent.class); + } + + @Test + public void basics() { + PointToPointIntent intent = createOne(); + assertEquals("incorrect id", APPID, intent.appId()); + assertEquals("incorrect match", MATCH, intent.selector()); + assertEquals("incorrect ingress", P1, intent.ingressPoint()); + assertEquals("incorrect egress", P2, intent.egressPoint()); + } + + @Override + protected PointToPointIntent createOne() { + return PointToPointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoint(P1) + .egressPoint(P2) + .build(); + } + + @Override + protected PointToPointIntent createAnother() { + return PointToPointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoint(P2) + .egressPoint(P1) + .build(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/SinglePointToMultiPointIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/SinglePointToMultiPointIntentTest.java new file mode 100644 index 00000000..18c6d7bc --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/SinglePointToMultiPointIntentTest.java @@ -0,0 +1,66 @@ +/* + * 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.net.intent; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Suite of tests of the single-to-multi point intent descriptor. + */ +public class SinglePointToMultiPointIntentTest extends ConnectivityIntentTest { + + /** + * Checks that the SinglePointToMultiPointIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(SinglePointToMultiPointIntent.class); + } + + @Test + public void basics() { + SinglePointToMultiPointIntent intent = createOne(); + assertEquals("incorrect id", APPID, intent.appId()); + assertEquals("incorrect match", MATCH, intent.selector()); + assertEquals("incorrect ingress", P1, intent.ingressPoint()); + assertEquals("incorrect egress", PS2, intent.egressPoints()); + } + + @Override + protected SinglePointToMultiPointIntent createOne() { + return SinglePointToMultiPointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoint(P1) + .egressPoints(PS2) + .build(); + } + + @Override + protected SinglePointToMultiPointIntent createAnother() { + return SinglePointToMultiPointIntent.builder() + .appId(APPID) + .selector(MATCH) + .treatment(NOP) + .ingressPoint(P2) + .egressPoints(PS1) + .build(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestInstallableIntent.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestInstallableIntent.java new file mode 100644 index 00000000..d949ee16 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestInstallableIntent.java @@ -0,0 +1,53 @@ +/* + * 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.net.intent; + +import org.onosproject.TestApplicationId; + +import java.util.Collections; + +/** + * An installable intent used in the unit test. + */ +public class TestInstallableIntent extends Intent { + + private final int value; + + /** + * Constructs an instance with the specified intent ID. + * + * @param value intent ID + */ + public TestInstallableIntent(int value) { // FIXME + super(new TestApplicationId("foo"), null, Collections.emptyList(), + Intent.DEFAULT_INTENT_PRIORITY); + this.value = value; + } + + /** + * Constructor for serializer. + */ + protected TestInstallableIntent() { + super(); + value = -1; + } + + @Override + public boolean isInstallable() { + return true; + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestIntent.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestIntent.java new file mode 100644 index 00000000..857fc8b5 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestIntent.java @@ -0,0 +1,47 @@ +/* + * 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.net.intent; + +import org.onosproject.TestApplicationId; + +import java.util.Collections; + +/** + * An intent used in the unit test. + */ +public class TestIntent extends Intent { + + private final int value; + + /** + * Constructs an instance with the specified intent ID. + * + * @param value intent ID + */ + public TestIntent(int value) { // FIXME + super(new TestApplicationId("foo"), null, Collections.emptyList(), + Intent.DEFAULT_INTENT_PRIORITY); + this.value = value; + } + + /** + * Constructor for serializer. + */ + protected TestIntent() { + super(); + value = -1; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassInstallableIntent.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassInstallableIntent.java new file mode 100644 index 00000000..82c14843 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassInstallableIntent.java @@ -0,0 +1,37 @@ +/* + * 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.net.intent; + +/** + * An intent used in the unit test. + */ +public class TestSubclassInstallableIntent extends TestInstallableIntent { + /** + * Constructs an instance with the specified intent ID. + * + * @param id intent ID + */ + public TestSubclassInstallableIntent(int id) { //FIXME + super(id); + } + + /** + * Constructor for serializer. + */ + protected TestSubclassInstallableIntent() { + super(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassIntent.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassIntent.java new file mode 100644 index 00000000..44c81189 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestSubclassIntent.java @@ -0,0 +1,37 @@ +/* + * 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.net.intent; + +/** + * An intent used in the unit test. + */ +public class TestSubclassIntent extends TestIntent { + /** + * Constructs an instance with the specified intent ID. + * + * @param id intent ID + */ + public TestSubclassIntent(int id) { //FIXME + super(id); + } + + /** + * Constructor for serializer. + */ + protected TestSubclassIntent() { + super(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestTools.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestTools.java new file mode 100644 index 00000000..80ae180d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestTools.java @@ -0,0 +1,141 @@ +/* + * 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.net.intent; + +import static org.junit.Assert.fail; + +/** + * Set of test tools. + */ +public final class TestTools { + + // Disallow construction + private TestTools() { + } + + /** + * Utility method to pause the current thread for the specified number of + * milliseconds. + * + * @param ms number of milliseconds to pause + */ + public static void delay(int ms) { + try { + Thread.sleep(ms); + } catch (InterruptedException e) { + fail("unexpected interrupt"); + } + } + + /** + * Periodically runs the given runnable, which should contain a series of + * test assertions until all the assertions succeed, in which case it will + * return, or until the the time expires, in which case it will throw the + * first failed assertion error. + * + * @param start start time, in millis since start of epoch from which the + * duration will be measured + * @param delay initial delay (in milliseconds) before the first assertion + * attempt + * @param step delay (in milliseconds) between successive assertion + * attempts + * @param duration number of milliseconds beyond the given start time, + * after which the failed assertions will be propagated and allowed + * to fail the test + * @param assertions runnable housing the test assertions + */ + public static void assertAfter(long start, int delay, int step, + int duration, Runnable assertions) { + delay(delay); + while (true) { + try { + assertions.run(); + break; + } catch (AssertionError e) { + if (System.currentTimeMillis() - start > duration) { + throw e; + } + } + delay(step); + } + } + + /** + * Periodically runs the given runnable, which should contain a series of + * test assertions until all the assertions succeed, in which case it will + * return, or until the the time expires, in which case it will throw the + * first failed assertion error. + * <p> + * The start of the period is the current time. + * + * @param delay initial delay (in milliseconds) before the first assertion + * attempt + * @param step delay (in milliseconds) between successive assertion + * attempts + * @param duration number of milliseconds beyond the current time time, + * after which the failed assertions will be propagated and allowed + * to fail the test + * @param assertions runnable housing the test assertions + */ + public static void assertAfter(int delay, int step, int duration, + Runnable assertions) { + assertAfter(System.currentTimeMillis(), delay, step, duration, + assertions); + } + + /** + * Periodically runs the given runnable, which should contain a series of + * test assertions until all the assertions succeed, in which case it will + * return, or until the the time expires, in which case it will throw the + * first failed assertion error. + * <p> + * The start of the period is the current time and the first assertion + * attempt is delayed by the value of {@code step} parameter. + * + * @param step delay (in milliseconds) between successive assertion + * attempts + * @param duration number of milliseconds beyond the current time time, + * after which the failed assertions will be propagated and allowed + * to fail the test + * @param assertions runnable housing the test assertions + */ + public static void assertAfter(int step, int duration, + Runnable assertions) { + assertAfter(step, step, duration, assertions); + } + + /** + * Periodically runs the given runnable, which should contain a series of + * test assertions until all the assertions succeed, in which case it will + * return, or until the the time expires, in which case it will throw the + * first failed assertion error. + * <p> + * The start of the period is the current time and each successive + * assertion attempt is delayed by at least 10 milliseconds unless the + * {@code duration} is less than that, in which case the one and only + * assertion is made after that delay. + * + * @param duration number of milliseconds beyond the current time, + * after which the failed assertions will be propagated and allowed + * to fail the test + * @param assertions runnable housing the test assertions + */ + public static void assertAfter(int duration, Runnable assertions) { + int step = Math.min(duration, Math.max(10, duration / 10)); + assertAfter(step, duration, assertions); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestableIntentService.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestableIntentService.java new file mode 100644 index 00000000..792c0ff8 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TestableIntentService.java @@ -0,0 +1,27 @@ +/* + * 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.net.intent; + +import java.util.List; + +/** + * Abstraction of an extensible intent service enabled for unit tests. + */ +public interface TestableIntentService extends IntentService, IntentExtensionService { + + List<IntentException> getExceptions(); + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TwoWayP2PIntentTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TwoWayP2PIntentTest.java new file mode 100644 index 00000000..0986216a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/TwoWayP2PIntentTest.java @@ -0,0 +1,100 @@ +/* + * 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.net.intent; + +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.flow.TrafficSelector; +import org.onosproject.net.flow.TrafficTreatment; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.connectPoint; +/** + * Unit tests for the TwoWayP2PIntent class. + */ +public class TwoWayP2PIntentTest extends AbstractIntentTest { + + TrafficSelector selector; + TrafficTreatment treatment; + + TwoWayP2PIntent intent1; + TwoWayP2PIntent intent2; + + static final int PRIORITY = 12; + + @Before + public void twoWatP2PIntentTestSetUp() { + selector = new IntentTestsMocks.MockSelector(); + treatment = new IntentTestsMocks.MockTreatment(); + + intent1 = TwoWayP2PIntent.builder() + .appId(APP_ID) + .priority(PRIORITY) + .selector(selector) + .treatment(treatment) + .one(connectPoint("one", 1)) + .two(connectPoint("two", 2)) + .build(); + + intent2 = TwoWayP2PIntent.builder() + .appId(APP_ID) + .priority(PRIORITY) + .selector(selector) + .treatment(treatment) + .one(connectPoint("two", 2)) + .two(connectPoint("three", 2)) + .build(); + } + + /** + * Checks that the TwoWayP2PIntent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(TwoWayP2PIntent.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(intent1) + .addEqualityGroup(intent2) + .testEquals(); + } + + /** + * Checks that the optical path ntent objects are created correctly. + */ + @Test + public void testContents() { + assertThat(intent1.appId(), equalTo(APP_ID)); + assertThat(intent1.one(), Matchers.equalTo(connectPoint("one", 1))); + assertThat(intent1.two(), Matchers.equalTo(connectPoint("two", 2))); + assertThat(intent1.priority(), is(PRIORITY)); + assertThat(intent1.selector(), is(selector)); + assertThat(intent1.treatment(), is(treatment)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/AnnotationConstraintTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/AnnotationConstraintTest.java new file mode 100644 index 00000000..b87dc12b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/AnnotationConstraintTest.java @@ -0,0 +1,97 @@ +/* + * 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.net.intent.constraint; + +import com.google.common.testing.EqualsTester; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.DefaultAnnotations; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; +import org.onosproject.net.resource.link.LinkResourceService; + +import static org.easymock.EasyMock.createMock; +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.lessThan; +import static org.junit.Assert.assertThat; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test for link annotated value threshold. + */ +public class AnnotationConstraintTest { + + private static final ProviderId PID = new ProviderId("of", "foo"); + private static final DeviceId DID1 = deviceId("of:1"); + private static final DeviceId DID2 = deviceId("of:2"); + private static final PortNumber PID1 = portNumber(1); + private static final PortNumber PID2 = portNumber(2); + private static final String KEY = "distance"; + private static final double VALUE = 100; + + private AnnotationConstraint sut; + private Link link; + private LinkResourceService linkResourceService; + + @Before + public void setUp() { + linkResourceService = createMock(LinkResourceService.class); + + DefaultAnnotations annotations = DefaultAnnotations.builder().set(KEY, String.valueOf(VALUE)).build(); + + link = new DefaultLink(PID, cp(DID1, PID1), cp(DID2, PID2), DIRECT, annotations); + } + + /** + * Tests the specified annotated value is less than the threshold. + */ + @Test + public void testLessThanThreshold() { + double value = 120; + sut = new AnnotationConstraint(KEY, value); + + assertThat(sut.isValid(link, linkResourceService), is(true)); + assertThat(sut.cost(link, linkResourceService), is(closeTo(VALUE, 1.0e-6))); + } + + /** + * Tests the specified annotated value is more than the threshold. + */ + @Test + public void testMoreThanThreshold() { + double value = 80; + sut = new AnnotationConstraint(KEY, value); + + assertThat(sut.isValid(link, linkResourceService), is(false)); + assertThat(sut.cost(link, linkResourceService), is(lessThan(0.0))); + } + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(new AnnotationConstraint(KEY, 100), new AnnotationConstraint(KEY, 100)) + .addEqualityGroup(new AnnotationConstraint(KEY, 120)) + .addEqualityGroup(new AnnotationConstraint("latency", 100)) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ConstraintObjectsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ConstraintObjectsTest.java new file mode 100644 index 00000000..743fc252 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ConstraintObjectsTest.java @@ -0,0 +1,135 @@ +/* + * 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.net.intent.constraint; + +import org.junit.Test; +import org.onlab.util.Bandwidth; +import org.onosproject.net.Link; +import org.onosproject.net.resource.link.BandwidthResource; +import org.onosproject.net.resource.link.LambdaResource; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; + +/** + * Unit tests for Constraint objects. + */ +public class ConstraintObjectsTest { + + // Bandwidth Constraint + + private final Bandwidth bandwidth1 = Bandwidth.bps(100.0); + private final Bandwidth sameAsBandwidth1 = Bandwidth.bps(100.0); + private final Bandwidth bandwidth2 = Bandwidth.bps(200.0); + + final BandwidthConstraint bandwidthConstraint1 = + new BandwidthConstraint(new BandwidthResource(bandwidth1)); + final BandwidthConstraint bandwidthConstraintSameAs1 = + new BandwidthConstraint(new BandwidthResource(sameAsBandwidth1)); + final BandwidthConstraint bandwidthConstraint2 = + new BandwidthConstraint(new BandwidthResource(bandwidth2)); + + /** + * Checks that the objects were created properly. + */ + @Test + public void testBandwidthConstraintCreation() { + assertThat(bandwidthConstraint1.bandwidth().toDouble(), is(equalTo(100.0))); + assertThat(bandwidthConstraintSameAs1.bandwidth().toDouble(), is(equalTo(100.0))); + assertThat(bandwidthConstraint2.bandwidth().toDouble(), is(equalTo(200.0))); + } + + /** + * Checks the correctness of the equals() method. + */ + @Test + public void testBandwidthConstraintEquals() { + new EqualsTester() + .addEqualityGroup(bandwidthConstraint1, bandwidthConstraintSameAs1) + .addEqualityGroup(bandwidthConstraint2) + .testEquals(); + } + + // Lambda Constraint + + final LambdaConstraint lambdaConstraint1 = + new LambdaConstraint(LambdaResource.valueOf(100)); + final LambdaConstraint lambdaConstraintSameAs1 = + new LambdaConstraint(LambdaResource.valueOf(100)); + final LambdaConstraint lambdaConstraint2 = + new LambdaConstraint(LambdaResource.valueOf(200)); + + /** + * Checks that the objects were created properly. + */ + @Test + public void testLambdaConstraintCreation() { + assertThat(lambdaConstraint1.lambda().toInt(), is(equalTo(100))); + assertThat(lambdaConstraintSameAs1.lambda().toInt(), is(equalTo(100))); + assertThat(lambdaConstraint2.lambda().toInt(), is(equalTo(200))); + } + + /** + * Checks the correctness of the equals() method. + */ + @Test + public void testLambdaConstraintEquals() { + new EqualsTester() + .addEqualityGroup(lambdaConstraint1, lambdaConstraintSameAs1) + .addEqualityGroup(lambdaConstraint2) + .testEquals(); + } + + // LinkType Constraint + + final LinkTypeConstraint linkTypeConstraint1 = + new LinkTypeConstraint(true, Link.Type.OPTICAL, Link.Type.TUNNEL); + final LinkTypeConstraint linkTypeConstraintSameAs1 = + new LinkTypeConstraint(true, Link.Type.OPTICAL, Link.Type.TUNNEL); + final LinkTypeConstraint linkTypeConstraint2 = + new LinkTypeConstraint(true, Link.Type.OPTICAL, Link.Type.DIRECT); + + /** + * Checks that the objects were created properly. + */ + @Test + public void testLinkTypeConstraintCreation() { + assertThat(linkTypeConstraint1.isInclusive(), is(true)); + assertThat(linkTypeConstraint1.types(), + contains(Link.Type.OPTICAL, Link.Type.TUNNEL)); + assertThat(linkTypeConstraintSameAs1.isInclusive(), is(true)); + assertThat(linkTypeConstraintSameAs1.types(), + contains(Link.Type.OPTICAL, Link.Type.TUNNEL)); + assertThat(linkTypeConstraint2.isInclusive(), is(true)); + assertThat(linkTypeConstraint2.types(), + contains(Link.Type.OPTICAL, Link.Type.DIRECT)); + } + + /** + * Checks the correctness of the equals() method. + */ + @Test + public void testLinkTypeConstraintEquals() { + new EqualsTester() + .addEqualityGroup(linkTypeConstraint1, linkTypeConstraintSameAs1) + .addEqualityGroup(linkTypeConstraint2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/LatencyConstraintTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/LatencyConstraintTest.java new file mode 100644 index 00000000..bab17495 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/LatencyConstraintTest.java @@ -0,0 +1,124 @@ +/* + * 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.net.intent.constraint; + +import com.google.common.testing.EqualsTester; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.Annotations; +import org.onosproject.net.DefaultAnnotations; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DefaultPath; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.Path; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; +import org.onosproject.net.resource.link.LinkResourceService; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; + +import static org.easymock.EasyMock.createMock; +import static org.hamcrest.Matchers.closeTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.onosproject.net.AnnotationKeys.LATENCY; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; + +public class LatencyConstraintTest { + + private static final DeviceId DID1 = deviceId("of:1"); + private static final DeviceId DID2 = deviceId("of:2"); + private static final DeviceId DID3 = deviceId("of:3"); + private static final PortNumber PN1 = PortNumber.portNumber(1); + private static final PortNumber PN2 = PortNumber.portNumber(2); + private static final PortNumber PN3 = PortNumber.portNumber(3); + private static final PortNumber PN4 = PortNumber.portNumber(4); + private static final ProviderId PROVIDER_ID = new ProviderId("of", "foo"); + private static final String LATENCY1 = "3.0"; + private static final String LATENCY2 = "4.0"; + + private LatencyConstraint sut; + private LinkResourceService linkResourceService; + + private Path path; + private Link link1; + private Link link2; + + @Before + public void setUp() { + linkResourceService = createMock(LinkResourceService.class); + + Annotations annotations1 = DefaultAnnotations.builder().set(LATENCY, LATENCY1).build(); + Annotations annotations2 = DefaultAnnotations.builder().set(LATENCY, LATENCY2).build(); + + link1 = new DefaultLink(PROVIDER_ID, cp(DID1, PN1), cp(DID2, PN2), DIRECT, annotations1); + link2 = new DefaultLink(PROVIDER_ID, cp(DID2, PN3), cp(DID3, PN4), DIRECT, annotations2); + path = new DefaultPath(PROVIDER_ID, Arrays.asList(link1, link2), 10); + } + + /** + * Tests the path latency is less than the supplied constraint. + */ + @Test + public void testLessThanLatency() { + sut = new LatencyConstraint(Duration.of(10, ChronoUnit.MICROS)); + + assertThat(sut.validate(path, linkResourceService), is(true)); + } + + /** + * Tests the path latency is more than the supplied constraint. + */ + @Test + public void testMoreThanLatency() { + sut = new LatencyConstraint(Duration.of(3, ChronoUnit.MICROS)); + + assertThat(sut.validate(path, linkResourceService), is(false)); + } + + /** + * Tests the link latency is equal to "latency" annotated value. + */ + @Test + public void testCost() { + sut = new LatencyConstraint(Duration.of(10, ChronoUnit.MICROS)); + + assertThat(sut.cost(link1, linkResourceService), is(closeTo(Double.parseDouble(LATENCY1), 1.0e-6))); + assertThat(sut.cost(link2, linkResourceService), is(closeTo(Double.parseDouble(LATENCY2), 1.0e-6))); + } + + /** + * Tests equality of the instances. + */ + @Test + public void testEquality() { + LatencyConstraint c1 = new LatencyConstraint(Duration.of(1, ChronoUnit.SECONDS)); + LatencyConstraint c2 = new LatencyConstraint(Duration.of(1000, ChronoUnit.MILLIS)); + + LatencyConstraint c3 = new LatencyConstraint(Duration.of(2, ChronoUnit.SECONDS)); + LatencyConstraint c4 = new LatencyConstraint(Duration.of(2000, ChronoUnit.MILLIS)); + + new EqualsTester() + .addEqualityGroup(c1, c2) + .addEqualityGroup(c3, c4) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ObstacleConstraintTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ObstacleConstraintTest.java new file mode 100644 index 00000000..f02787f3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/ObstacleConstraintTest.java @@ -0,0 +1,102 @@ +/* + * 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.net.intent.constraint; + +/** + * Test for constraint of intermediate nodes not passed. + */ +import com.google.common.testing.EqualsTester; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DefaultPath; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Path; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; +import org.onosproject.net.resource.link.LinkResourceService; + +import java.util.Arrays; + +import static org.easymock.EasyMock.createMock; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.*; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; + +public class ObstacleConstraintTest { + + private static final DeviceId DID1 = deviceId("of:1"); + private static final DeviceId DID2 = deviceId("of:2"); + private static final DeviceId DID3 = deviceId("of:3"); + private static final DeviceId DID4 = deviceId("of:4"); + private static final PortNumber PN1 = PortNumber.portNumber(1); + private static final PortNumber PN2 = PortNumber.portNumber(2); + private static final PortNumber PN3 = PortNumber.portNumber(3); + private static final PortNumber PN4 = PortNumber.portNumber(4); + private static final ProviderId PROVIDER_ID = new ProviderId("of", "foo"); + + private LinkResourceService linkResourceService; + + private Path path; + private DefaultLink link2; + private DefaultLink link1; + + private ObstacleConstraint sut; + + @Before + public void setUp() { + linkResourceService = createMock(LinkResourceService.class); + + link1 = new DefaultLink(PROVIDER_ID, cp(DID1, PN1), cp(DID2, PN2), DIRECT); + link2 = new DefaultLink(PROVIDER_ID, cp(DID2, PN3), cp(DID3, PN4), DIRECT); + path = new DefaultPath(PROVIDER_ID, Arrays.asList(link1, link2), 10); + } + + @Test + public void testEquality() { + ObstacleConstraint o1 = new ObstacleConstraint(DID1, DID2, DID3); + ObstacleConstraint o2 = new ObstacleConstraint(DID3, DID2, DID1); + ObstacleConstraint o3 = new ObstacleConstraint(DID1, DID2); + ObstacleConstraint o4 = new ObstacleConstraint(DID2, DID1); + + new EqualsTester() + .addEqualityGroup(o1, o2) + .addEqualityGroup(o3, o4) + .testEquals(); + } + + /** + * Tests the specified path avoids the specified obstacle. + */ + @Test + public void testPathNotThroughObstacles() { + sut = new ObstacleConstraint(DID4); + + assertThat(sut.validate(path, linkResourceService), is(true)); + } + + /** + * Test the specified path does not avoid the specified obstacle. + */ + @Test + public void testPathThroughObstacle() { + sut = new ObstacleConstraint(DID1); + + assertThat(sut.validate(path, linkResourceService), is(false)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/WaypointConstraintTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/WaypointConstraintTest.java new file mode 100644 index 00000000..f7e212a3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/intent/constraint/WaypointConstraintTest.java @@ -0,0 +1,104 @@ +/* + * 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.net.intent.constraint; + +import com.google.common.testing.EqualsTester; +import org.junit.Before; +import org.junit.Test; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DefaultPath; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Path; +import org.onosproject.net.PortNumber; +import org.onosproject.net.intent.Constraint; +import org.onosproject.net.provider.ProviderId; +import org.onosproject.net.resource.link.LinkResourceService; + +import java.util.Arrays; + +import static org.easymock.EasyMock.createMock; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; + +/** + * Test for constraint of intermediate elements. + */ +public class WaypointConstraintTest { + + private static final DeviceId DID1 = deviceId("of:1"); + private static final DeviceId DID2 = deviceId("of:2"); + private static final DeviceId DID3 = deviceId("of:3"); + private static final DeviceId DID4 = deviceId("of:4"); + private static final PortNumber PN1 = PortNumber.portNumber(1); + private static final PortNumber PN2 = PortNumber.portNumber(2); + private static final PortNumber PN3 = PortNumber.portNumber(3); + private static final PortNumber PN4 = PortNumber.portNumber(4); + private static final ProviderId PROVIDER_ID = new ProviderId("of", "foo"); + + private WaypointConstraint sut; + private LinkResourceService linkResourceService; + + private Path path; + private DefaultLink link2; + private DefaultLink link1; + + @Before + public void setUp() { + linkResourceService = createMock(LinkResourceService.class); + + link1 = new DefaultLink(PROVIDER_ID, cp(DID1, PN1), cp(DID2, PN2), DIRECT); + link2 = new DefaultLink(PROVIDER_ID, cp(DID2, PN3), cp(DID3, PN4), DIRECT); + path = new DefaultPath(PROVIDER_ID, Arrays.asList(link1, link2), 10); + } + + /** + * Tests that all of the specified waypoints are included in the specified path in order. + */ + @Test + public void testSatisfyWaypoints() { + sut = new WaypointConstraint(DID1, DID2, DID3); + + assertThat(sut.validate(path, linkResourceService), is(true)); + } + + /** + * Tests that the specified path does not includes the specified waypoint. + */ + @Test + public void testNotSatisfyWaypoint() { + sut = new WaypointConstraint(DID4); + + assertThat(sut.validate(path, linkResourceService), is(false)); + } + + @Test + public void testEquality() { + Constraint c1 = new WaypointConstraint(DID1, DID2); + Constraint c2 = new WaypointConstraint(DID1, DID2); + + Constraint c3 = new WaypointConstraint(DID2); + Constraint c4 = new WaypointConstraint(DID3); + + new EqualsTester() + .addEqualityGroup(c1, c2) + .addEqualityGroup(c3) + .addEqualityGroup(c4) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/DefaultLinkDescriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/DefaultLinkDescriptionTest.java new file mode 100644 index 00000000..3b98c5ba --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/DefaultLinkDescriptionTest.java @@ -0,0 +1,45 @@ +/* + * 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.net.link; + +import org.junit.Test; +import org.onosproject.net.DeviceId; +import org.onosproject.net.PortNumber; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DefaultLinkTest.cp; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.Link.Type.DIRECT; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Test of the default link description. + */ +public class DefaultLinkDescriptionTest { + + private static final DeviceId DID1 = deviceId("of:foo"); + private static final DeviceId DID2 = deviceId("of:bar"); + private static final PortNumber P1 = portNumber(1); + + @Test + public void basics() { + LinkDescription desc = new DefaultLinkDescription(cp(DID1, P1), cp(DID2, P1), DIRECT); + assertEquals("incorrect src", cp(DID1, P1), desc.src()); + assertEquals("incorrect dst", cp(DID2, P1), desc.dst()); + assertEquals("incorrect type", DIRECT, desc.type()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkEventTest.java new file mode 100644 index 00000000..307fa69a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkEventTest.java @@ -0,0 +1,56 @@ +/* + * 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.net.link; + +import org.junit.Test; +import org.onosproject.event.AbstractEventTest; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.Link; +import org.onosproject.net.provider.ProviderId; + +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Tests of the device event. + */ +public class LinkEventTest extends AbstractEventTest { + + private Link createLink() { + return new DefaultLink(new ProviderId("of", "foo"), + new ConnectPoint(deviceId("of:foo"), portNumber(1)), + new ConnectPoint(deviceId("of:bar"), portNumber(2)), + Link.Type.INDIRECT); + } + + @Test + public void withTime() { + Link link = createLink(); + LinkEvent event = new LinkEvent(LinkEvent.Type.LINK_ADDED, link, 123L); + validateEvent(event, LinkEvent.Type.LINK_ADDED, link, 123L); + } + + @Test + public void withoutTime() { + Link link = createLink(); + long before = System.currentTimeMillis(); + LinkEvent event = new LinkEvent(LinkEvent.Type.LINK_ADDED, link); + long after = System.currentTimeMillis(); + validateEvent(event, LinkEvent.Type.LINK_ADDED, link, before, after); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkServiceAdapter.java new file mode 100644 index 00000000..5cb84b31 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/link/LinkServiceAdapter.java @@ -0,0 +1,97 @@ +/* + * 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.net.link; + +import java.util.Set; + +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.Link.State; + +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; + +/** + * Test adapter for link service. + */ +public class LinkServiceAdapter implements LinkService { + @Override + public int getLinkCount() { + return 0; + } + + @Override + public Iterable<Link> getLinks() { + return null; + } + + @Override + public Iterable<Link> getActiveLinks() { + return FluentIterable.from(getLinks()) + .filter(new Predicate<Link>() { + + @Override + public boolean apply(Link input) { + return input.state() == State.ACTIVE; + } + }); + } + + @Override + public Set<Link> getDeviceLinks(DeviceId deviceId) { + return null; + } + + @Override + public Set<Link> getDeviceEgressLinks(DeviceId deviceId) { + return null; + } + + @Override + public Set<Link> getDeviceIngressLinks(DeviceId deviceId) { + return null; + } + + @Override + public Set<Link> getLinks(ConnectPoint connectPoint) { + return null; + } + + @Override + public Set<Link> getEgressLinks(ConnectPoint connectPoint) { + return null; + } + + @Override + public Set<Link> getIngressLinks(ConnectPoint connectPoint) { + return null; + } + + @Override + public Link getLink(ConnectPoint src, ConnectPoint dst) { + return null; + } + + @Override + public void addListener(LinkListener listener) { + } + + @Override + public void removeListener(LinkListener listener) { + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/DefaultMeterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/DefaultMeterTest.java new file mode 100644 index 00000000..b39d2efb --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/DefaultMeterTest.java @@ -0,0 +1,99 @@ +/* + * 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.net.meter; + +import com.google.common.testing.EqualsTester; +import org.junit.Before; +import org.junit.Test; + +import java.util.Collections; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onosproject.net.NetTestTools.APP_ID; +import static org.onosproject.net.NetTestTools.did; + + +/** + * DefaultMeter Tests. + */ +public class DefaultMeterTest { + + private Meter m1; + private Meter sameAsm1; + private Meter m2; + + @Before + public void setup() { + + Band band = DefaultBand.builder() + .ofType(Band.Type.DROP) + .withRate(500) + .build(); + + m1 = DefaultMeter.builder() + .forDevice(did("1")) + .fromApp(APP_ID) + .withId(MeterId.meterId(1)) + .withUnit(Meter.Unit.KB_PER_SEC) + .withBands(Collections.singletonList(band)) + .build(); + + sameAsm1 = DefaultMeter.builder() + .forDevice(did("1")) + .fromApp(APP_ID) + .withId(MeterId.meterId(1)) + .withUnit(Meter.Unit.KB_PER_SEC) + .withBands(Collections.singletonList(band)) + .build(); + + m2 = DefaultMeter.builder() + .forDevice(did("2")) + .fromApp(APP_ID) + .withId(MeterId.meterId(2)) + .withUnit(Meter.Unit.KB_PER_SEC) + .withBands(Collections.singletonList(band)) + .build(); + + } + + @Test + public void testEquality() { + new EqualsTester() + .addEqualityGroup(m1, sameAsm1) + .addEqualityGroup(m2).testEquals(); + } + + @Test + public void testConstruction() { + DefaultMeter m = (DefaultMeter) m1; + + assertThat(m.deviceId(), is(did("1"))); + assertThat(m.appId(), is(APP_ID)); + assertThat(m.id(), is(MeterId.meterId(1))); + assertThat(m.isBurst(), is(false)); + + assertThat(m.life(), is(0L)); + assertThat(m.bytesSeen(), is(0L)); + assertThat(m.packetsSeen(), is(0L)); + assertThat(m.referenceCount(), is(0L)); + + } + + + + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/MeterOperationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/MeterOperationTest.java new file mode 100644 index 00000000..ad53e3a3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/meter/MeterOperationTest.java @@ -0,0 +1,128 @@ +/* + * 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.net.meter; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.core.ApplicationId; +import org.onosproject.net.DeviceId; + +import java.util.Collection; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; + +/** + * Unit tests for the MeterOperationTest object. + */ +public class MeterOperationTest { + + + + /** + * Checks that the MeterOperation class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutableBaseClass(MeterOperation.class); + } + + @Test + public void testEquality() { + final Meter m1 = new TestMeter(); + final Meter m2 = new TestMeter(); + final MeterOperation op1 = new MeterOperation(m1, + MeterOperation.Type.ADD); + final MeterOperation sameAsOp1 = new MeterOperation(m1, + MeterOperation.Type.ADD); + final MeterOperation op2 = new MeterOperation(m2, + MeterOperation.Type.ADD); + + new EqualsTester() + .addEqualityGroup(op1, sameAsOp1) + .addEqualityGroup(op2) + .testEquals(); + } + + @Test + public void testConstruction() { + final Meter m1 = new TestMeter(); + + final MeterOperation op = new MeterOperation(m1, MeterOperation.Type.ADD); + + assertThat(op.meter(), is(m1)); + } + + private static final class TestMeter implements Meter { + + @Override + public DeviceId deviceId() { + return null; + } + + @Override + public MeterId id() { + return null; + } + + @Override + public ApplicationId appId() { + return null; + } + + @Override + public Unit unit() { + return null; + } + + @Override + public boolean isBurst() { + return false; + } + + @Override + public Collection<Band> bands() { + return null; + } + + @Override + public MeterState state() { + return null; + } + + @Override + public long life() { + return 0; + } + + @Override + public long referenceCount() { + return 0; + } + + @Override + public long packetsSeen() { + return 0; + } + + @Override + public long bytesSeen() { + return 0; + } + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourceAllocationTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourceAllocationTest.java new file mode 100644 index 00000000..a84927a0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourceAllocationTest.java @@ -0,0 +1,50 @@ +/* + * 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.net.newresource; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onlab.packet.VlanId; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.LinkKey; +import org.onosproject.net.PortNumber; +import org.onosproject.net.intent.IntentId; + +public class ResourceAllocationTest { + + private static final DeviceId D1 = DeviceId.deviceId("of:001"); + private static final DeviceId D2 = DeviceId.deviceId("of:002"); + private static final PortNumber P1 = PortNumber.portNumber(1); + private static final ConnectPoint CP1_1 = new ConnectPoint(D1, P1); + private static final ConnectPoint CP2_1 = new ConnectPoint(D2, P1); + private static final VlanId VLAN1 = VlanId.vlanId((short) 100); + private static final IntentId IID1 = IntentId.valueOf(30); + private static final LinkKey LK1 = LinkKey.linkKey(CP1_1, CP2_1); + private static final LinkKey LK2 = LinkKey.linkKey(CP2_1, CP1_1); + + @Test + public void testEquals() { + ResourceAllocation alloc1 = new ResourceAllocation(new ResourcePath(LK1, VLAN1), IID1); + ResourceAllocation sameAsAlloc1 = new ResourceAllocation(new ResourcePath(LK1, VLAN1), IID1); + ResourceAllocation alloc2 = new ResourceAllocation(new ResourcePath(LK2, VLAN1), IID1); + + new EqualsTester() + .addEqualityGroup(alloc1, sameAsAlloc1) + .addEqualityGroup(alloc2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourcePathTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourcePathTest.java new file mode 100644 index 00000000..4a8886a4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/newresource/ResourcePathTest.java @@ -0,0 +1,82 @@ +/* + * 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.net.newresource; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onlab.packet.VlanId; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.LinkKey; +import org.onosproject.net.PortNumber; + +import java.util.Optional; + +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +public class ResourcePathTest { + + private static final DeviceId D1 = DeviceId.deviceId("of:001"); + private static final DeviceId D2 = DeviceId.deviceId("of:002"); + private static final PortNumber P1 = PortNumber.portNumber(1); + private static final ConnectPoint CP1_1 = new ConnectPoint(D1, P1); + private static final ConnectPoint CP2_1 = new ConnectPoint(D2, P1); + private static final VlanId VLAN1 = VlanId.vlanId((short) 100); + + @Test + public void testEquals() { + ResourcePath resource1 = new ResourcePath(LinkKey.linkKey(CP1_1, CP2_1), VLAN1); + ResourcePath sameAsResource1 = new ResourcePath(LinkKey.linkKey(CP1_1, CP2_1), VLAN1); + ResourcePath resource2 = new ResourcePath(LinkKey.linkKey(CP2_1, CP1_1), VLAN1); + + new EqualsTester() + .addEqualityGroup(resource1, sameAsResource1) + .addEqualityGroup(resource2) + .testEquals(); + } + + @Test + public void testCreateWithZeroComponent() { + ResourcePath path = new ResourcePath(); + + assertThat(path, is(ResourcePath.ROOT)); + } + + @Test + public void testThereIsParent() { + ResourcePath path = new ResourcePath(LinkKey.linkKey(CP1_1, CP2_1), VLAN1); + ResourcePath parent = new ResourcePath(LinkKey.linkKey(CP1_1, CP2_1)); + + assertThat(path.parent(), is(Optional.of(parent))); + } + + @Test + public void testNoParent() { + ResourcePath path = new ResourcePath(LinkKey.linkKey(CP1_1, CP2_1)); + + assertThat(path.parent(), is(Optional.of(ResourcePath.ROOT))); + } + + @Test + public void testBase() { + LinkKey linkKey = LinkKey.linkKey(CP1_1, CP2_1); + ResourcePath path = new ResourcePath(linkKey); + + LinkKey child = (LinkKey) path.lastComponent(); + assertThat(child, is(linkKey)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultInboundPacketTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultInboundPacketTest.java new file mode 100644 index 00000000..eda68240 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultInboundPacketTest.java @@ -0,0 +1,81 @@ +/* + * 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.net.packet; + +import java.nio.ByteBuffer; + +import org.junit.Test; +import org.onlab.packet.Ethernet; +import org.onlab.packet.MacAddress; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.connectPoint; + +/** + * Unit tests for the DefaultInboundPacket class. + */ +public class DefaultInboundPacketTest { + + final Ethernet eth = new Ethernet() + .setDestinationMACAddress(MacAddress.BROADCAST) + .setSourceMACAddress(MacAddress.BROADCAST); + final ByteBuffer byteBuffer = ByteBuffer.wrap(eth.serialize()); + final DefaultInboundPacket packet1 = + new DefaultInboundPacket(connectPoint("d1", 1), + eth, + byteBuffer); + final DefaultInboundPacket sameAsPacket1 = + new DefaultInboundPacket(connectPoint("d1", 1), + eth, + byteBuffer); + final DefaultInboundPacket packet2 = + new DefaultInboundPacket(connectPoint("d2", 1), + eth, + byteBuffer); + /** + * Checks that the DefaultInboundPacket class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(DefaultInboundPacket.class); + } + + /** + * Tests the equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(packet1, sameAsPacket1) + .addEqualityGroup(packet2) + .testEquals(); + } + + /** + * Tests the object creation through the constructor. + */ + @Test + public void testConstruction() { + assertThat(packet1.receivedFrom(), equalTo(connectPoint("d1", 1))); + assertThat(packet1.parsed(), equalTo(eth)); + assertThat(packet1.unparsed(), notNullValue()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultOutboundPacketTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultOutboundPacketTest.java new file mode 100644 index 00000000..21f997d9 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultOutboundPacketTest.java @@ -0,0 +1,82 @@ +/* + * 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.net.packet; + +import java.nio.ByteBuffer; + +import org.junit.Test; +import org.onosproject.net.flow.TrafficTreatment; +import org.onosproject.net.intent.IntentTestsMocks; +import org.onlab.packet.Ethernet; +import org.onlab.packet.MacAddress; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.net.NetTestTools.did; + +/** + * Unit tests for the DefaultOutboundPacketTest class. + */ +public class DefaultOutboundPacketTest { + final Ethernet eth = new Ethernet() + .setDestinationMACAddress(MacAddress.BROADCAST) + .setSourceMACAddress(MacAddress.BROADCAST); + final ByteBuffer byteBuffer = ByteBuffer.wrap(eth.serialize()); + final TrafficTreatment treatment = new IntentTestsMocks.MockTreatment(); + final DefaultOutboundPacket packet1 = + new DefaultOutboundPacket(did("d1"), + treatment, + byteBuffer); + final DefaultOutboundPacket sameAsPacket1 = + new DefaultOutboundPacket(did("d1"), + treatment, + byteBuffer); + final DefaultOutboundPacket packet2 = + new DefaultOutboundPacket(did("d2"), + treatment, + byteBuffer); + /** + * Checks that the DefaultOutboundPacket class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(DefaultOutboundPacket.class); + } + + /** + * Tests the equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(packet1, sameAsPacket1) + .addEqualityGroup(packet2) + .testEquals(); + } + + /** + * Tests the object creation through the constructor. + */ + @Test + public void testConstruction() { + assertThat(packet1.sendThrough(), equalTo(did("d1"))); + assertThat(packet1.data(), equalTo(byteBuffer)); + assertThat(packet1.treatment(), equalTo(treatment)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultPacketContextTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultPacketContextTest.java new file mode 100644 index 00000000..ee7ae7e5 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/DefaultPacketContextTest.java @@ -0,0 +1,112 @@ +/* + * 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.net.packet; + +import java.nio.ByteBuffer; + +import org.junit.Test; +import org.onosproject.net.flow.TrafficTreatment; +import org.onosproject.net.intent.IntentTestsMocks; +import org.onlab.packet.Ethernet; +import org.onlab.packet.MacAddress; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutableBaseClass; +import static org.onosproject.net.NetTestTools.connectPoint; +import static org.onosproject.net.NetTestTools.did; + +/** + * Unit tests for the DefaultPacketContextTest. + */ +public class DefaultPacketContextTest { + final Ethernet eth = new Ethernet() + .setDestinationMACAddress(MacAddress.BROADCAST) + .setSourceMACAddress(MacAddress.BROADCAST); + final ByteBuffer byteBuffer = ByteBuffer.wrap(eth.serialize()); + final DefaultInboundPacket inPacket = + new DefaultInboundPacket(connectPoint("d1", 1), + eth, + byteBuffer); + final TrafficTreatment treatment = new IntentTestsMocks.MockTreatment(); + final DefaultOutboundPacket outPacket = + new DefaultOutboundPacket(did("d1"), + treatment, + byteBuffer); + + static class MockPacketContext extends DefaultPacketContext { + + protected MockPacketContext(long time, InboundPacket inPkt, + OutboundPacket outPkt, boolean block) { + super(time, inPkt, outPkt, block); + } + + @Override + public void send() { + + } + + @Override + public boolean block() { + return super.block(); + } + } + + final DefaultPacketContext context1 = + new MockPacketContext(123L, inPacket, outPacket, true); + final DefaultPacketContext sameAsContext1 = + new MockPacketContext(123L, inPacket, outPacket, true); + final DefaultPacketContext context2 = + new MockPacketContext(123123L, inPacket, outPacket, true); + + /** + * Checks that the DefaultOutboundPacket class is immutable but can be + * used as a base class. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutableBaseClass(DefaultPacketContext.class); + } + + /** + * Tests the equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + // No hashCode() or equals() defined, object comparison is used. + new EqualsTester() + .addEqualityGroup(context1) + .addEqualityGroup(sameAsContext1) + .addEqualityGroup(context2) + .testEquals(); + } + + /** + * Tests that objects are created properly. + */ + @Test + public void testConstruction() { + assertThat(context1.block(), is(true)); + assertThat(context1.inPacket(), is(inPacket)); + assertThat(context1.isHandled(), is(true)); + assertThat(context1.outPacket(), is(outPacket)); + assertThat(context1.time(), is(123L)); + assertThat(context1.treatmentBuilder(), is(notNullValue())); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/PacketServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/PacketServiceAdapter.java new file mode 100644 index 00000000..afe936b7 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/packet/PacketServiceAdapter.java @@ -0,0 +1,44 @@ +/* + * 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.net.packet; + +import org.onosproject.core.ApplicationId; +import org.onosproject.net.flow.TrafficSelector; + +/** + * Test adapter for packet service. + */ +public class PacketServiceAdapter implements PacketService { + @Override + public void addProcessor(PacketProcessor processor, int priority) { + } + + @Override + public void removeProcessor(PacketProcessor processor) { + } + + @Override + public void requestPackets(TrafficSelector selector, PacketPriority priority, ApplicationId appId) { + } + + @Override + public void cancelPackets(TrafficSelector selector, PacketPriority priority, ApplicationId appId) { + } + + @Override + public void emit(OutboundPacket packet) { + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderRegistryTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderRegistryTest.java new file mode 100644 index 00000000..f08d93bd --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderRegistryTest.java @@ -0,0 +1,108 @@ +/* + * 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.net.provider; + +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertEquals; + +/** + * Test of the base provider registry. + */ +public class AbstractProviderRegistryTest { + + private class TestProviderService extends AbstractProviderService<TestProvider> { + protected TestProviderService(TestProvider provider) { + super(provider); + } + } + + private class TestProviderRegistry extends AbstractProviderRegistry<TestProvider, TestProviderService> { + @Override + protected TestProviderService createProviderService(TestProvider provider) { + return new TestProviderService(provider); + } + } + + @Test + public void basics() { + TestProviderRegistry registry = new TestProviderRegistry(); + assertEquals("incorrect provider count", 0, registry.getProviders().size()); + + ProviderId fooId = new ProviderId("of", "foo"); + TestProvider pFoo = new TestProvider(fooId); + TestProviderService psFoo = registry.register(pFoo); + assertEquals("incorrect provider count", 1, registry.getProviders().size()); + assertThat("provider not found", registry.getProviders().contains(fooId)); + assertEquals("incorrect provider", psFoo.provider(), pFoo); + + ProviderId barId = new ProviderId("snmp", "bar"); + TestProvider pBar = new TestProvider(barId); + TestProviderService psBar = registry.register(pBar); + assertEquals("incorrect provider count", 2, registry.getProviders().size()); + assertThat("provider not found", registry.getProviders().contains(barId)); + assertEquals("incorrect provider", psBar.provider(), pBar); + + psFoo.checkValidity(); + registry.unregister(pFoo); + psBar.checkValidity(); + assertEquals("incorrect provider count", 1, registry.getProviders().size()); + assertThat("provider not found", registry.getProviders().contains(barId)); + } + + @Test + public void ancillaryProviders() { + TestProviderRegistry registry = new TestProviderRegistry(); + TestProvider pFoo = new TestProvider(new ProviderId("of", "foo")); + TestProvider pBar = new TestProvider(new ProviderId("of", "bar", true)); + registry.register(pFoo); + registry.register(pBar); + assertEquals("incorrect provider count", 2, registry.getProviders().size()); + } + + @Test(expected = IllegalStateException.class) + public void duplicateRegistration() { + TestProviderRegistry registry = new TestProviderRegistry(); + TestProvider pFoo = new TestProvider(new ProviderId("of", "foo")); + registry.register(pFoo); + registry.register(pFoo); + } + + @Test(expected = IllegalStateException.class) + public void duplicateSchemeRegistration() { + TestProviderRegistry registry = new TestProviderRegistry(); + TestProvider pFoo = new TestProvider(new ProviderId("of", "foo")); + TestProvider pBar = new TestProvider(new ProviderId("of", "bar")); + registry.register(pFoo); + registry.register(pBar); + } + + @Test + public void voidUnregistration() { + TestProviderRegistry registry = new TestProviderRegistry(); + registry.unregister(new TestProvider(new ProviderId("of", "foo"))); + } + + @Test(expected = IllegalStateException.class) + public void unregistration() { + TestProviderRegistry registry = new TestProviderRegistry(); + TestProvider pFoo = new TestProvider(new ProviderId("of", "foo")); + TestProviderService psFoo = registry.register(pFoo); + registry.unregister(pFoo); + psFoo.checkValidity(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderTest.java new file mode 100644 index 00000000..e9e06c76 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/AbstractProviderTest.java @@ -0,0 +1,33 @@ +/* + * 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.net.provider; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * Test of the base provider implementation. + */ +public class AbstractProviderTest { + + @Test + public void basics() { + ProviderId id = new ProviderId("of", "foo.bar"); + TestProvider provider = new TestProvider(id); + assertEquals("incorrect id", id, provider.id()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/ProviderIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/ProviderIdTest.java new file mode 100644 index 00000000..7e973991 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/ProviderIdTest.java @@ -0,0 +1,35 @@ +/* + * 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.net.provider; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +/** + * Test of the provider identifier. + */ +public class ProviderIdTest { + + @Test + public void basics() { + new EqualsTester() + .addEqualityGroup(new ProviderId("of", "foo"), new ProviderId("of", "foo")) + .addEqualityGroup(new ProviderId("snmp", "foo"), new ProviderId("snmp", "foo")) + .addEqualityGroup(new ProviderId("of", "bar")) + .testEquals(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/TestProvider.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/TestProvider.java new file mode 100644 index 00000000..2f521bbb --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/provider/TestProvider.java @@ -0,0 +1,32 @@ +/* + * 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.net.provider; + +/** + * Test provider fixture. + */ +public class TestProvider extends AbstractProvider { + + /** + * Creates a provider with the supplier identifier. + * + * @param id provider id + */ + protected TestProvider(ProviderId id) { + super(id); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/resource/MplsObjectsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/resource/MplsObjectsTest.java new file mode 100644 index 00000000..56f7a477 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/resource/MplsObjectsTest.java @@ -0,0 +1,89 @@ +/* + * 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.net.resource; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; +import org.onosproject.net.resource.link.MplsLabel; +import org.onosproject.net.resource.link.MplsLabelResourceAllocation; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * Unit tests for MPLS objects. + */ +public class MplsObjectsTest { + + MplsLabel label1 = MplsLabel.valueOf(1); + MplsLabel label2 = MplsLabel.valueOf(2); + MplsLabel sameAsLabel1 = MplsLabel.valueOf(1); + MplsLabel sameAsLabel2 = MplsLabel.valueOf(2); + MplsLabel label3 = MplsLabel.valueOf(3); + + /** + * Tests creation of MPLS label objects. + */ + @Test + public void checkLabelConstruction() { + assertThat(label1.label().toInt(), is(1)); + } + + /** + * Tests the operation of equals(), hashCode() and toString(). + */ + @Test + public void testLabelEqualsOperation() { + new EqualsTester() + .addEqualityGroup(label1, sameAsLabel1) + .addEqualityGroup(label2, sameAsLabel2) + .addEqualityGroup(label3) + .testEquals(); + } + + MplsLabelResourceAllocation labelAllocation1 = + new MplsLabelResourceAllocation(label1); + MplsLabelResourceAllocation sameAsLabelAllocation1 = + new MplsLabelResourceAllocation(label1); + MplsLabelResourceAllocation labelAllocation2 = + new MplsLabelResourceAllocation(label2); + MplsLabelResourceAllocation sameAsLabelAllocation2 = + new MplsLabelResourceAllocation(label2); + MplsLabelResourceAllocation labelAllocation3 = + new MplsLabelResourceAllocation(label3); + + /** + * Tests creation of MPLS label objects. + */ + @Test + public void checkLabelResourceAllocationConstruction() { + assertThat(labelAllocation1.mplsLabel().label().toInt(), is(1)); + assertThat(labelAllocation1.type(), is(ResourceType.MPLS_LABEL)); + } + + /** + * Tests the operation of equals(), hashCode() and toString(). + */ + @Test + public void testLabelResourceAllocationEqualsOperation() { + new EqualsTester() + .addEqualityGroup(labelAllocation1, sameAsLabelAllocation1) + .addEqualityGroup(labelAllocation2, sameAsLabelAllocation2) + .addEqualityGroup(labelAllocation3) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/DefaultLoadTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/DefaultLoadTest.java new file mode 100644 index 00000000..6b3ef93d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/DefaultLoadTest.java @@ -0,0 +1,92 @@ +/* + * 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.net.statistic; + +import org.junit.Before; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsNot.not; + +/** + * Unit tests for DefaultLoad class. + */ +public class DefaultLoadTest { + + @Before + public void reset() { + DefaultLoad.setPollInterval(10); + } + + /** + * Tests the default constructor. + */ + @Test + public void testDefaultConstructor() { + DefaultLoad load = new DefaultLoad(); + assertThat(load.isValid(), is(false)); + assertThat(load.latest(), is(-1L)); + assertThat(load.rate(), is(0L)); + assertThat(load.time(), is(not(0))); + } + + /** + * Tests the current-previous constructor. + */ + @Test + public void testCurrentPreviousConstructor() { + DefaultLoad load = new DefaultLoad(20, 10); + assertThat(load.isValid(), is(true)); + assertThat(load.latest(), is(20L)); + assertThat(load.rate(), is(1L)); + assertThat(load.time(), is(not(0))); + } + + /** + * Tests the current-previous-interval constructor. + */ + @Test + public void testCurrentPreviousIntervalConstructor() { + DefaultLoad load = new DefaultLoad(20, 10, 1); + assertThat(load.isValid(), is(true)); + assertThat(load.latest(), is(20L)); + assertThat(load.rate(), is(10L)); + assertThat(load.time(), is(not(0))); + } + + /** + * Tests the toString operation. + */ + @Test + public void testToString() { + DefaultLoad load = new DefaultLoad(20, 10); + + String s = load.toString(); + assertThat(s, containsString("Load{rate=1, latest=20}")); + } + + /** + * Tests setting the poll interval. + */ + @Test + public void testSettingPollInterval() { + DefaultLoad.setPollInterval(1); + DefaultLoad load = new DefaultLoad(40, 10); + assertThat(load.rate(), is(30L)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/StatisticServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/StatisticServiceAdapter.java new file mode 100644 index 00000000..cf8f36f8 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/statistic/StatisticServiceAdapter.java @@ -0,0 +1,61 @@ +/* + * 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.net.statistic; + +import org.onosproject.core.ApplicationId; +import org.onosproject.core.GroupId; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.Link; +import org.onosproject.net.Path; +import org.onosproject.net.flow.FlowRule; + +import java.util.Optional; + +/** + * Test adapter for statistics service. + */ +public class StatisticServiceAdapter implements StatisticService { + @Override + public Load load(Link link) { + return null; + } + + @Override + public Load load(ConnectPoint connectPoint) { + return null; + } + + @Override + public Link max(Path path) { + return null; + } + + @Override + public Link min(Path path) { + return null; + } + + @Override + public FlowRule highestHitter(ConnectPoint connectPoint) { + return null; + } + + @Override + public Load load(Link link, ApplicationId appId, Optional<GroupId> groupId) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/ClusterIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/ClusterIdTest.java new file mode 100644 index 00000000..1eb6331f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/ClusterIdTest.java @@ -0,0 +1,41 @@ +/* + * 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.net.topology; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.*; +import static org.onosproject.net.topology.ClusterId.clusterId; + +/** + * Test of the cluster ID. + */ +public class ClusterIdTest { + + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(clusterId(1), clusterId(1)) + .addEqualityGroup(clusterId(3), clusterId(3)).testEquals(); + } + + @Test + public void basics() { + assertEquals("incorrect index", 123, clusterId(123).index()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultGraphDescriptionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultGraphDescriptionTest.java new file mode 100644 index 00000000..8b0f8f05 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultGraphDescriptionTest.java @@ -0,0 +1,60 @@ +/* + * 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.net.topology; + +import com.google.common.collect.ImmutableSet; + +import org.junit.Test; +import org.onosproject.net.DefaultDevice; +import org.onosproject.net.Device; +import org.onosproject.net.DeviceId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.Device.Type.SWITCH; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.topology.DefaultTopologyEdgeTest.*; + +public class DefaultGraphDescriptionTest { + + static final DefaultTopologyEdge E1 = new DefaultTopologyEdge(V1, V2, L1); + static final DefaultTopologyEdge E2 = new DefaultTopologyEdge(V1, V2, L1); + + private static final DeviceId D3 = deviceId("3"); + + static final Device DEV1 = new DefaultDevice(PID, D1, SWITCH, "", "", "", "", null); + static final Device DEV2 = new DefaultDevice(PID, D2, SWITCH, "", "", "", "", null); + static final Device DEV3 = new DefaultDevice(PID, D3, SWITCH, "", "", "", "", null); + + @Test + public void basics() { + DefaultGraphDescription desc = + new DefaultGraphDescription(4321L, ImmutableSet.of(DEV1, DEV2, DEV3), + ImmutableSet.of(L1, L2)); + assertEquals("incorrect time", 4321L, desc.timestamp()); + assertEquals("incorrect vertex count", 3, desc.vertexes().size()); + assertEquals("incorrect edge count", 2, desc.edges().size()); + } + + @Test + public void missingVertex() { + GraphDescription desc = new DefaultGraphDescription(4321L, + ImmutableSet.of(DEV1, DEV3), + ImmutableSet.of(L1, L2)); + assertEquals("incorrect time", 4321L, desc.timestamp()); + assertEquals("incorrect vertex count", 2, desc.vertexes().size()); + assertEquals("incorrect edge count", 0, desc.edges().size()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyClusterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyClusterTest.java new file mode 100644 index 00000000..06ed8fde --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyClusterTest.java @@ -0,0 +1,54 @@ +/* + * 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.net.topology; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.topology.ClusterId.clusterId; + +/** + * Test of the default topology cluster implementation. + */ +public class DefaultTopologyClusterTest { + + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(cluster(3, 2, 1, "of:1"), cluster(3, 2, 1, "of:1")) + .addEqualityGroup(cluster(3, 2, 1, "of:2"), cluster(3, 2, 1, "of:2")) + .addEqualityGroup(cluster(0, 2, 1, "of:1"), cluster(0, 2, 1, "of:1")) + .addEqualityGroup(cluster(3, 3, 1, "of:1"), cluster(3, 3, 1, "of:1")) + .testEquals(); + } + + @Test + public void basics() { + TopologyCluster cluster = cluster(6, 5, 4, "of:111"); + assertEquals("incorrect id", clusterId(6), cluster.id()); + assertEquals("incorrect id", 5, cluster.deviceCount()); + assertEquals("incorrect id", 4, cluster.linkCount()); + assertEquals("incorrect id", deviceId("of:111"), cluster.root().deviceId()); + + } + + private TopologyCluster cluster(int id, int dc, int lc, String root) { + return new DefaultTopologyCluster(clusterId(id), dc, lc, + new DefaultTopologyVertex(deviceId(root))); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyEdgeTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyEdgeTest.java new file mode 100644 index 00000000..830e9b9f --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyEdgeTest.java @@ -0,0 +1,70 @@ +/* + * 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.net.topology; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DefaultLink; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; + +import static org.junit.Assert.assertEquals; +import static org.onosproject.net.DeviceId.deviceId; +import static org.onosproject.net.PortNumber.portNumber; + +/** + * Tests of the topology graph edge. + */ +public class DefaultTopologyEdgeTest { + + static final DeviceId D1 = deviceId("1"); + static final DeviceId D2 = deviceId("2"); + static final PortNumber P1 = portNumber(1); + static final PortNumber P2 = portNumber(2); + + static final ConnectPoint CP1 = new ConnectPoint(D1, P1); + static final ConnectPoint CP2 = new ConnectPoint(D2, P1); + static final ConnectPoint CP3 = new ConnectPoint(D2, P1); + static final ConnectPoint CP4 = new ConnectPoint(D1, P2); + + static final DefaultTopologyVertex V1 = new DefaultTopologyVertex(D1); + static final DefaultTopologyVertex V2 = new DefaultTopologyVertex(D2); + + static final ProviderId PID = new ProviderId("foo", "bar"); + + /** D1:P1 -> D2:P1. */ + static final Link L1 = new DefaultLink(PID, CP1, CP2, Link.Type.INDIRECT); + /** D2:P1 -> D1:P2. */ + static final Link L2 = new DefaultLink(PID, CP3, CP4, Link.Type.INDIRECT); + + @Test + public void basics() { + DefaultTopologyEdge e = new DefaultTopologyEdge(V1, V2, L1); + assertEquals("incorrect src", V1, e.src()); + assertEquals("incorrect dst", V2, e.dst()); + assertEquals("incorrect link", L1, e.link()); + + new EqualsTester() + .addEqualityGroup(new DefaultTopologyEdge(V1, V2, L1), + new DefaultTopologyEdge(V1, V2, L1)) + .addEqualityGroup(new DefaultTopologyEdge(V2, V1, L2), + new DefaultTopologyEdge(V2, V1, L2)) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyVertexTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyVertexTest.java new file mode 100644 index 00000000..aa01d261 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/DefaultTopologyVertexTest.java @@ -0,0 +1,44 @@ +/* + * 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.net.topology; + +import com.google.common.testing.EqualsTester; +import org.junit.Test; +import org.onosproject.net.DeviceId; + +import static org.junit.Assert.*; +import static org.onosproject.net.DeviceId.deviceId; + +/** + * Tests of the topology graph vertex. + */ +public class DefaultTopologyVertexTest { + + private static final DeviceId D1 = deviceId("1"); + private static final DeviceId D2 = deviceId("2"); + + @Test + public void basics() { + DefaultTopologyVertex v = new DefaultTopologyVertex(D1); + assertEquals("incorrect device id", D1, v.deviceId()); + + new EqualsTester() + .addEqualityGroup(new DefaultTopologyVertex(D1), + new DefaultTopologyVertex(D1)) + .addEqualityGroup(new DefaultTopologyVertex(D2), + new DefaultTopologyVertex(D2)).testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/TopologyServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/TopologyServiceAdapter.java new file mode 100644 index 00000000..07e67842 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/net/topology/TopologyServiceAdapter.java @@ -0,0 +1,92 @@ +/* + * 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.net.topology; + +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.Path; + +import java.util.Set; + +/** + * Test adapter for topology service. + */ +public class TopologyServiceAdapter implements TopologyService { + @Override + public Topology currentTopology() { + return null; + } + + @Override + public boolean isLatest(Topology topology) { + return false; + } + + @Override + public TopologyGraph getGraph(Topology topology) { + return null; + } + + @Override + public Set<TopologyCluster> getClusters(Topology topology) { + return null; + } + + @Override + public TopologyCluster getCluster(Topology topology, ClusterId clusterId) { + return null; + } + + @Override + public Set<DeviceId> getClusterDevices(Topology topology, TopologyCluster cluster) { + return null; + } + + @Override + public Set<Link> getClusterLinks(Topology topology, TopologyCluster cluster) { + return null; + } + + @Override + public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst) { + return null; + } + + @Override + public Set<Path> getPaths(Topology topology, DeviceId src, DeviceId dst, LinkWeight weight) { + return null; + } + + @Override + public boolean isInfrastructure(Topology topology, ConnectPoint connectPoint) { + return false; + } + + @Override + public boolean isBroadcastPoint(Topology topology, ConnectPoint connectPoint) { + return false; + } + + @Override + public void addListener(TopologyListener listener) { + } + + @Override + public void removeListener(TopologyListener listener) { + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterCommunicationServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterCommunicationServiceAdapter.java new file mode 100644 index 00000000..04f890c8 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterCommunicationServiceAdapter.java @@ -0,0 +1,88 @@ +/* + * 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.cluster.messaging; + +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; +import java.util.function.Function; + +import org.onosproject.cluster.NodeId; + +/** + * Testing adapter for the cluster communication service. + */ +public class ClusterCommunicationServiceAdapter + implements ClusterCommunicationService { + + @Override + public void addSubscriber(MessageSubject subject, + ClusterMessageHandler subscriber, + ExecutorService executor) { + } + + @Override + public void removeSubscriber(MessageSubject subject) {} + + @Override + public <M> void broadcast(M message, MessageSubject subject, + Function<M, byte[]> encoder) { + } + + @Override + public <M> void broadcastIncludeSelf(M message, + MessageSubject subject, Function<M, byte[]> encoder) { + } + + @Override + public <M> CompletableFuture<Void> unicast(M message, MessageSubject subject, + Function<M, byte[]> encoder, NodeId toNodeId) { + return null; + } + + @Override + public <M> void multicast(M message, MessageSubject subject, + Function<M, byte[]> encoder, Set<NodeId> nodes) { + } + + @Override + public <M, R> CompletableFuture<R> sendAndReceive(M message, + MessageSubject subject, Function<M, byte[]> encoder, + Function<byte[], R> decoder, NodeId toNodeId) { + return null; + } + + @Override + public <M, R> void addSubscriber(MessageSubject subject, + Function<byte[], M> decoder, Function<M, R> handler, + Function<R, byte[]> encoder, Executor executor) { + } + + @Override + public <M, R> void addSubscriber(MessageSubject subject, + Function<byte[], M> decoder, Function<M, CompletableFuture<R>> handler, + Function<R, byte[]> encoder) { + } + + @Override + public <M> void addSubscriber(MessageSubject subject, + Function<byte[], M> decoder, Consumer<M> handler, + Executor executor) { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterMessageTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterMessageTest.java new file mode 100644 index 00000000..22f841b4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/ClusterMessageTest.java @@ -0,0 +1,82 @@ +/* + * 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.cluster.messaging; + +import org.junit.Test; +import org.onosproject.cluster.NodeId; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * Units tests for ClusterMessage class. + */ +public class ClusterMessageTest { + private final MessageSubject subject1 = new MessageSubject("Message 1"); + private final MessageSubject subject2 = new MessageSubject("Message 2"); + + private final byte[] payload1 = {0, 1, 2, 3, 4, 5}; + private final byte[] payload2 = {0, 1, 2, 3, 4, 5, 6}; + + private final NodeId nodeId = new NodeId("node"); + + private final ClusterMessage message1 = + new ClusterMessage(nodeId, subject1, payload1); + private final ClusterMessage sameAsMessage1 = + new ClusterMessage(nodeId, subject1, payload1); + private final ClusterMessage message2 = + new ClusterMessage(nodeId, subject1, payload2); + private final ClusterMessage message3 = + new ClusterMessage(nodeId, subject2, payload1); + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(message1, sameAsMessage1) + .addEqualityGroup(message2) + .addEqualityGroup(message3) + .testEquals(); + } + + /** + * Checks the construction of a FlowId object. + */ + @Test + public void testConstruction() { + assertThat(message1.payload(), is(payload1)); + assertThat(message1.sender(), is(nodeId)); + assertThat(message1.subject(), is(subject1)); + + byte[] response = {2, 2, 2, 2, 2, 2, 2, 2}; + message1.respond(response); + assertThat(message1.response(), is(response)); + } + + /** + * Tests the toBytes and fromBytes methods. + */ + @Test + public void testByteMethods() { + byte[] fromBytes = message3.getBytes(); + ClusterMessage message = ClusterMessage.fromBytes(fromBytes); + assertThat(message, is(message3)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/EndpointTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/EndpointTest.java new file mode 100644 index 00000000..c88c711a --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/EndpointTest.java @@ -0,0 +1,68 @@ +/* + * 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.cluster.messaging; + + +import org.junit.Test; +import org.onlab.packet.IpAddress; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Unit tests for the Endpoint class. + */ +public class EndpointTest { + IpAddress host1 = IpAddress.valueOf("1.2.3.4"); + IpAddress host2 = IpAddress.valueOf("1.2.3.5"); + + private final Endpoint endpoint1 = new Endpoint(host1, 1); + private final Endpoint sameAsEndpoint1 = new Endpoint(host1, 1); + private final Endpoint endpoint2 = new Endpoint(host2, 1); + private final Endpoint endpoint3 = new Endpoint(host1, 2); + + /** + * Checks that the MessageSubject class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(Endpoint.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(endpoint1, sameAsEndpoint1) + .addEqualityGroup(endpoint2) + .addEqualityGroup(endpoint3) + .testEquals(); + } + + /** + * Checks the construction of a MessageSubject object. + */ + @Test + public void testConstruction() { + assertThat(endpoint2.host(), is(host2)); + assertThat(endpoint2.port(), is(1)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/MessageSubjectTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/MessageSubjectTest.java new file mode 100644 index 00000000..498edd33 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/cluster/messaging/MessageSubjectTest.java @@ -0,0 +1,64 @@ +/* + * 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.cluster.messaging; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; + +/** + * Unit tests for MessageSubject class. + */ +public class MessageSubjectTest { + private final MessageSubject subject1 = new MessageSubject("Message 1"); + private final MessageSubject sameAsSubject1 = new MessageSubject("Message 1"); + private final MessageSubject subject2 = new MessageSubject("Message 2"); + private final MessageSubject subject3 = new MessageSubject("Message 3"); + + /** + * Checks that the MessageSubject class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(MessageSubject.class); + } + + /** + * Checks the operation of equals(), hashCode() and toString() methods. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(subject1, sameAsSubject1) + .addEqualityGroup(subject2) + .addEqualityGroup(subject3) + .testEquals(); + } + + /** + * Checks the construction of a MessageSubject object. + */ + @Test + public void testConstruction() { + assertThat(subject3.value(), is("Message 3")); + MessageSubject serializerObject = new MessageSubject(); + assertThat(serializerObject.value(), is("")); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/AtomicValueEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/AtomicValueEventTest.java new file mode 100644 index 00000000..39481ca0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/AtomicValueEventTest.java @@ -0,0 +1,71 @@ +/* + * 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.service; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.store.service.AtomicValueEvent.Type.UPDATE; + +/** + * Unit tests for the AtomicValueEvent class. + */ +public class AtomicValueEventTest { + + AtomicValueEvent<String> event1 = + new AtomicValueEvent<>("map1", UPDATE, "e1"); + AtomicValueEvent<String> event2 = + new AtomicValueEvent<>("map1", UPDATE, "e2"); + AtomicValueEvent<String> sameAsEvent2 = + new AtomicValueEvent<>("map1", UPDATE, "e2"); + AtomicValueEvent<String> event3 = + new AtomicValueEvent<>("map2", UPDATE, "e2"); + + /** + * Checks that the SetEvent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(AtomicValueEvent.class); + } + + /** + * Checks the equals(), hashCode() and toString() operations. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(event1) + .addEqualityGroup(event2, sameAsEvent2) + .addEqualityGroup(event3) + .testEquals(); + } + + /** + * Checks that construction of the object is correct. + */ + @Test + public void testConstruction() { + assertThat(event1.type(), is(UPDATE)); + assertThat(event1.value(), is("e1")); + assertThat(event1.name(), is("map1")); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/ConsistentMapAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/ConsistentMapAdapter.java new file mode 100644 index 00000000..d0c1adf6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/ConsistentMapAdapter.java @@ -0,0 +1,149 @@ +/* + * 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.service; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Testing adapter for the consistent map. + */ +public class ConsistentMapAdapter<K, V> implements ConsistentMap<K, V> { + @Override + public int size() { + return 0; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public boolean containsKey(K key) { + return false; + } + + @Override + public boolean containsValue(V value) { + return false; + } + + @Override + public Versioned<V> get(K key) { + return null; + } + + @Override + public Versioned<V> computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { + return null; + } + + @Override + public Versioned<V> compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return null; + } + + @Override + public Versioned<V> computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return null; + } + + @Override + public Versioned<V> computeIf(K key, Predicate<? super V> condition, + BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return null; + } + + @Override + public Versioned<V> put(K key, V value) { + return null; + } + + @Override + public Versioned<V> putAndGet(K key, V value) { + return null; + } + + @Override + public Versioned<V> remove(K key) { + return null; + } + + @Override + public void clear() { + + } + + @Override + public Set<K> keySet() { + return null; + } + + @Override + public Collection<Versioned<V>> values() { + return null; + } + + @Override + public Set<Map.Entry<K, Versioned<V>>> entrySet() { + return null; + } + + @Override + public Versioned<V> putIfAbsent(K key, V value) { + return null; + } + + @Override + public boolean remove(K key, V value) { + return false; + } + + @Override + public boolean remove(K key, long version) { + return false; + } + + @Override + public boolean replace(K key, V oldValue, V newValue) { + return false; + } + + @Override + public boolean replace(K key, long oldVersion, V newValue) { + return false; + } + + @Override + public void addListener(MapEventListener<K, V> listener) { + + } + + @Override + public void removeListener(MapEventListener<K, V> listener) { + + } + + @Override + public Map<K, V> asJavaMap() { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/DatabaseUpdateTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/DatabaseUpdateTest.java new file mode 100644 index 00000000..b498c1c7 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/DatabaseUpdateTest.java @@ -0,0 +1,127 @@ +/* + * 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.service; + +import com.google.common.testing.EqualsTester; +import junit.framework.TestCase; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * Unit Tests for DatabseUpdate class. + */ + +public class DatabaseUpdateTest extends TestCase { + + private final DatabaseUpdate stats1 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.PUT) + .build(); + + private final DatabaseUpdate stats2 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.REMOVE) + .build(); + + private final DatabaseUpdate stats3 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.REMOVE_IF_VALUE_MATCH) + .build(); + + private final DatabaseUpdate stats4 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.REMOVE_IF_VERSION_MATCH) + .build(); + + private final DatabaseUpdate stats5 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.PUT_IF_VALUE_MATCH) + .build(); + + private final DatabaseUpdate stats6 = DatabaseUpdate.newBuilder() + .withCurrentValue("1".getBytes()) + .withValue("2".getBytes()) + .withCurrentVersion(3) + .withKey("4") + .withMapName("5") + .withType(DatabaseUpdate.Type.PUT_IF_VERSION_MATCH) + .build(); + + /** + * Tests the constructor for the class. + */ + @Test + public void testConstruction() { + assertThat(stats1.currentValue(), is("1".getBytes())); + assertThat(stats1.value(), is("2".getBytes())); + assertThat(stats1.currentVersion(), is(3L)); + assertThat(stats1.key(), is("4")); + assertThat(stats1.mapName(), is("5")); + assertThat(stats1.type(), is(DatabaseUpdate.Type.PUT)); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(stats1, stats1) + .addEqualityGroup(stats2) + .testEquals(); + + new EqualsTester() + .addEqualityGroup(stats3, stats3) + .addEqualityGroup(stats4) + .testEquals(); + + new EqualsTester() + .addEqualityGroup(stats5, stats5) + .addEqualityGroup(stats6) + .testEquals(); + } + + /** + * Tests if the toString method returns a consistent value for hashing. + */ + @Test + public void testToString() { + assertThat(stats1.toString(), is(stats1.toString())); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapAdapter.java new file mode 100644 index 00000000..07f5fb4d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapAdapter.java @@ -0,0 +1,111 @@ +/* + * 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.service; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; + +/** + * Testing adapter for EventuallyConsistentMap. + */ +public class EventuallyConsistentMapAdapter<K, V> implements EventuallyConsistentMap<K, V> { + @Override + public int size() { + return 0; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public boolean containsKey(K key) { + return false; + } + + @Override + public boolean containsValue(V value) { + return false; + } + + @Override + public V get(K key) { + return null; + } + + @Override + public void put(K key, V value) { + + } + + @Override + public V remove(K key) { + return null; + } + + @Override + public void remove(K key, V value) { + + } + + @Override + public V compute(K key, BiFunction<K, V, V> recomputeFunction) { + return null; + } + + @Override + public void putAll(Map<? extends K, ? extends V> m) { + + } + + @Override + public void clear() { + + } + + @Override + public Set<K> keySet() { + return null; + } + + @Override + public Collection<V> values() { + return null; + } + + @Override + public Set<Map.Entry<K, V>> entrySet() { + return null; + } + + @Override + public void addListener(EventuallyConsistentMapListener<K, V> listener) { + + } + + @Override + public void removeListener(EventuallyConsistentMapListener<K, V> listener) { + + } + + @Override + public void destroy() { + + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapEventTest.java new file mode 100644 index 00000000..a4163cb6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/EventuallyConsistentMapEventTest.java @@ -0,0 +1,82 @@ +/* + * 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.service; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.PUT; +import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.REMOVE; + +/** + * Unit tests for the EventuallyConsistentMapEvent class. + */ +public class EventuallyConsistentMapEventTest { + + EventuallyConsistentMapEvent<String, String> event1 = + new EventuallyConsistentMapEvent<>("map1", PUT, "k1", "v1"); + EventuallyConsistentMapEvent<String, String> event2 = + new EventuallyConsistentMapEvent<>("map1", REMOVE, "k1", "v1"); + EventuallyConsistentMapEvent<String, String> sameAsEvent2 = + new EventuallyConsistentMapEvent<>("map1", REMOVE, "k1", "v1"); + EventuallyConsistentMapEvent<String, String> event3 = + new EventuallyConsistentMapEvent<>("map1", PUT, "k2", "v1"); + EventuallyConsistentMapEvent<String, String> event4 = + new EventuallyConsistentMapEvent<>("map1", PUT, "k1", "v2"); + EventuallyConsistentMapEvent<String, String> event5 = + new EventuallyConsistentMapEvent<>("map2", REMOVE, "k1", "v2"); + EventuallyConsistentMapEvent<String, String> event6 = + new EventuallyConsistentMapEvent<>("map3", REMOVE, "k1", "v2"); + + + /** + * Checks the equals(), hashCode() and toString() operations. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(event1) + .addEqualityGroup(event2, sameAsEvent2) + .addEqualityGroup(event3) + .addEqualityGroup(event4) + .addEqualityGroup(event5) + .addEqualityGroup(event6) + .testEquals(); + } + + /** + * Checks that the EventuallyConsistentMapEvent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(EventuallyConsistentMapEvent.class); + } + + /** + * Checks that construction of the object is correct. + */ + @Test + public void testConstruction() { + assertThat(event1.type(), is(PUT)); + assertThat(event1.key(), is("k1")); + assertThat(event1.value(), is("v1")); + assertThat(event1.name(), is("map1")); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MapEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MapEventTest.java new file mode 100644 index 00000000..c241c0e0 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MapEventTest.java @@ -0,0 +1,61 @@ +/* + * 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.service; + +import com.google.common.testing.EqualsTester; +import junit.framework.TestCase; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * MapEvent unit tests. + */ +public class MapEventTest extends TestCase { + + private final Versioned<Integer> vStats = new Versioned<>(2, 1); + + private final MapEvent<String, Integer> stats1 = new MapEvent<>("a", MapEvent.Type.INSERT, "1", vStats); + + private final MapEvent<String, Integer> stats2 = new MapEvent<>("a", MapEvent.Type.REMOVE, "1", vStats); + + private final MapEvent<String, Integer> stats3 = new MapEvent<>("a", MapEvent.Type.UPDATE, "1", vStats); + + /** + * Tests the creation of the MapEvent object. + */ + @Test + public void testConstruction() { + assertThat(stats1.name(), is("a")); + assertThat(stats1.type(), is(MapEvent.Type.INSERT)); + assertThat(stats1.key(), is("1")); + assertThat(stats1.value(), is(vStats)); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(stats1, stats1) + .addEqualityGroup(stats2) + .addEqualityGroup(stats3) + .testEquals(); + } + +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MultiValuedTimestampTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MultiValuedTimestampTest.java new file mode 100644 index 00000000..5d991a26 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/MultiValuedTimestampTest.java @@ -0,0 +1,94 @@ +/* + * 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.service; + +import com.google.common.testing.EqualsTester; +import junit.framework.TestCase; + +import org.junit.Assert; +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.util.Arrays; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; + +/** + * MultiValuedTimestamp unit tests. + */ +public class MultiValuedTimestampTest extends TestCase { + + private final MultiValuedTimestamp<Integer, Integer> stats1 = new MultiValuedTimestamp<>(1, 3); + + private final MultiValuedTimestamp<Integer, Integer> stats2 = new MultiValuedTimestamp<>(1, 2); + + + /** + * Tests the creation of the MapEvent object. + */ + @Test + public void testConstruction() { + assertThat(stats1.value1(), is(1)); + assertThat(stats1.value2(), is(3)); + } + + /** + * Tests the toCompare function. + */ + @Test + public void testToCompare() { + assertThat(stats1.compareTo(stats2), is(1)); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(stats1, stats1) + .addEqualityGroup(stats2) + .testEquals(); + } + + /** + * Tests that the empty argument list constructor for serialization + * is present and creates a proper object. + */ + @Test + public void testSerializerConstructor() { + try { + Constructor[] constructors = MultiValuedTimestamp.class.getDeclaredConstructors(); + assertThat(constructors, notNullValue()); + Arrays.stream(constructors).filter(ctor -> + ctor.getParameterTypes().length == 0) + .forEach(noParamsCtor -> { + try { + noParamsCtor.setAccessible(true); + MultiValuedTimestamp stats = + (MultiValuedTimestamp) noParamsCtor.newInstance(); + assertThat(stats, notNullValue()); + } catch (Exception e) { + Assert.fail("Exception instantiating no parameters constructor"); + } + }); + } catch (Exception e) { + Assert.fail("Exception looking up constructors"); + } + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/SetEventTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/SetEventTest.java new file mode 100644 index 00000000..5cc89d85 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/SetEventTest.java @@ -0,0 +1,75 @@ +/* + * 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.service; + +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable; +import static org.onosproject.store.service.SetEvent.Type.ADD; +import static org.onosproject.store.service.SetEvent.Type.REMOVE; + +/** + * Unit tests for the SetEvent class. + */ +public class SetEventTest { + + SetEvent<String> event1 = + new SetEvent<>("map1", ADD, "e1"); + SetEvent<String> event2 = + new SetEvent<>("map1", REMOVE, "e1"); + SetEvent<String> sameAsEvent2 = + new SetEvent<>("map1", REMOVE, "e1"); + SetEvent<String> event3 = + new SetEvent<>("map1", ADD, "e2"); + SetEvent<String> event4 = + new SetEvent<>("map1", REMOVE, "e2"); + + /** + * Checks that the SetEvent class is immutable. + */ + @Test + public void testImmutability() { + assertThatClassIsImmutable(EventuallyConsistentMapEvent.class); + } + + /** + * Checks the equals(), hashCode() and toString() operations. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(event1) + .addEqualityGroup(event2, sameAsEvent2) + .addEqualityGroup(event3) + .addEqualityGroup(event4) + .testEquals(); + } + + /** + * Checks that construction of the object is correct. + */ + @Test + public void testConstruction() { + assertThat(event1.type(), is(ADD)); + assertThat(event1.entry(), is("e1")); + assertThat(event1.name(), is("map1")); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java new file mode 100644 index 00000000..ec04e331 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/StorageServiceAdapter.java @@ -0,0 +1,56 @@ +/* + * 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.service; + +/** + * Adapter for the storage service. + */ +public class StorageServiceAdapter implements StorageService { + @Override + public <K, V> EventuallyConsistentMapBuilder<K, V> eventuallyConsistentMapBuilder() { + return null; + } + + @Override + public <K, V> ConsistentMapBuilder<K, V> consistentMapBuilder() { + return null; + } + + @Override + public <E> DistributedSetBuilder<E> setBuilder() { + return null; + } + + @Override + public <E> DistributedQueueBuilder<E> queueBuilder() { + return null; + } + + @Override + public AtomicCounterBuilder atomicCounterBuilder() { + return null; + } + + @Override + public <V> AtomicValueBuilder<V> atomicValueBuilder() { + return null; + } + + @Override + public TransactionContextBuilder transactionContextBuilder() { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestAtomicCounter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestAtomicCounter.java new file mode 100644 index 00000000..01209be2 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestAtomicCounter.java @@ -0,0 +1,85 @@ +/* + * 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.service; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Test implementation of atomic counter. + */ +public final class TestAtomicCounter implements AtomicCounter { + final AtomicLong value; + + private TestAtomicCounter() { + value = new AtomicLong(); + } + + @Override + public long incrementAndGet() { + return value.incrementAndGet(); + } + + @Override + public long getAndIncrement() { + return value.getAndIncrement(); + } + + @Override + public long getAndAdd(long delta) { + return value.getAndAdd(delta); + } + + @Override + public long addAndGet(long delta) { + return value.addAndGet(delta); + } + + @Override + public long get() { + return value.get(); + } + + public static AtomicCounterBuilder builder() { + return new Builder(); + } + + public static class Builder implements AtomicCounterBuilder { + @Override + public AtomicCounterBuilder withName(String name) { + return this; + } + + @Override + public AtomicCounterBuilder withPartitionsDisabled() { + return this; + } + + @Override + public AtomicCounterBuilder withMeteringDisabled() { + return this; + } + + @Override + public AsyncAtomicCounter buildAsyncCounter() { + throw new UnsupportedOperationException("Async Counter is not supported"); + } + + @Override + public AtomicCounter build() { + return new TestAtomicCounter(); + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestConsistentMap.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestConsistentMap.java new file mode 100644 index 00000000..0136a94c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestConsistentMap.java @@ -0,0 +1,287 @@ +/* + * 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.service; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.onosproject.core.ApplicationId; +import static org.onosproject.store.service.MapEvent.Type; +import static org.onosproject.store.service.MapEvent.Type.*; + +/** + * Test implementation of the consistent map. + */ +public final class TestConsistentMap<K, V> extends ConsistentMapAdapter<K, V> { + + private final List<MapEventListener<K, V>> listeners; + private final HashMap<K, V> map; + private final String mapName; + private final AtomicLong counter = new AtomicLong(0); + + private TestConsistentMap(String mapName) { + map = new HashMap<>(); + listeners = new LinkedList<>(); + this.mapName = mapName; + } + + private Versioned<V> version(V v) { + return new Versioned<>(v, counter.incrementAndGet(), System.currentTimeMillis()); + } + + /** + * Notify all listeners of an event. + */ + private void notifyListeners(String mapName, Type type, + K key, Versioned<V> value) { + MapEvent<K, V> event = new MapEvent<>(mapName, type, key, value); + listeners.forEach( + listener -> listener.event(event) + ); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public boolean containsKey(K key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(V value) { + return map.containsValue(value); + } + + @Override + public Versioned<V> get(K key) { + V value = map.get(key); + if (value != null) { + return version(value); + } else { + return null; + } + } + + @Override + public Versioned<V> computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { + Versioned<V> result = version(map.computeIfAbsent(key, mappingFunction)); + notifyListeners(mapName, INSERT, key, result); + return result; + } + + @Override + public Versioned<V> compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return version(map.compute(key, remappingFunction)); + } + + @Override + public Versioned<V> computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return version(map.computeIfPresent(key, remappingFunction)); + } + + @Override + public Versioned<V> computeIf(K key, Predicate<? super V> condition, + BiFunction<? super K, ? super V, ? extends V> remappingFunction) { + return null; + } + + @Override + public Versioned<V> put(K key, V value) { + Versioned<V> result = version(value); + if (map.put(key, value) == null) { + notifyListeners(mapName, INSERT, key, result); + } else { + notifyListeners(mapName, UPDATE, key, result); + } + return result; + } + + @Override + public Versioned<V> putAndGet(K key, V value) { + Versioned<V> result = version(map.put(key, value)); + notifyListeners(mapName, UPDATE, key, result); + return result; + } + + @Override + public Versioned<V> remove(K key) { + Versioned<V> result = version(map.remove(key)); + notifyListeners(mapName, REMOVE, key, result); + return result; + } + + @Override + public void clear() { + map.clear(); + } + + @Override + public Set<K> keySet() { + return map.keySet(); + } + + @Override + public Collection<Versioned<V>> values() { + return map + .values() + .stream() + .map(this::version) + .collect(Collectors.toList()); + } + + @Override + public Set<Map.Entry<K, Versioned<V>>> entrySet() { + return super.entrySet(); + } + + @Override + public Versioned<V> putIfAbsent(K key, V value) { + Versioned<V> result = version(map.putIfAbsent(key, value)); + if (map.get(key).equals(value)) { + notifyListeners(mapName, INSERT, key, result); + } + return result; + } + + @Override + public boolean remove(K key, V value) { + boolean removed = map.remove(key, value); + if (removed) { + notifyListeners(mapName, REMOVE, key, null); + } + return removed; + } + + @Override + public boolean remove(K key, long version) { + boolean removed = map.remove(key, version); + if (removed) { + notifyListeners(mapName, REMOVE, key, null); + } + return removed; + } + + @Override + public boolean replace(K key, V oldValue, V newValue) { + boolean replaced = map.replace(key, oldValue, newValue); + if (replaced) { + notifyListeners(mapName, REMOVE, key, null); + } + return replaced; + } + + @Override + public boolean replace(K key, long oldVersion, V newValue) { + boolean replaced = map.replace(key, map.get(key), newValue); + if (replaced) { + notifyListeners(mapName, REMOVE, key, null); + } + return replaced; + } + + @Override + public void addListener(MapEventListener<K, V> listener) { + listeners.add(listener); + } + + @Override + public void removeListener(MapEventListener<K, V> listener) { + listeners.remove(listener); + } + + @Override + public Map<K, V> asJavaMap() { + return map; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder<K, V> implements ConsistentMapBuilder<K, V> { + String mapName = "map"; + + @Override + public ConsistentMapBuilder<K, V> withName(String mapName) { + this.mapName = mapName; + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withApplicationId(ApplicationId id) { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withSerializer(Serializer serializer) { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withPartitionsDisabled() { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withUpdatesDisabled() { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withPurgeOnUninstall() { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withRelaxedReadConsistency() { + return this; + } + + @Override + public ConsistentMapBuilder<K, V> withMeteringDisabled() { + return this; + } + + @Override + public ConsistentMap<K, V> build() { + return new TestConsistentMap<>(mapName); + } + + @Override + public AsyncConsistentMap<K, V> buildAsyncMap() { + return null; + } + + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestEventuallyConsistentMap.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestEventuallyConsistentMap.java new file mode 100644 index 00000000..4f612de2 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestEventuallyConsistentMap.java @@ -0,0 +1,238 @@ +/* + * 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.service; + +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; + +import org.onlab.util.KryoNamespace; +import org.onosproject.cluster.NodeId; +import org.onosproject.store.Timestamp; + +import static org.onosproject.store.service.EventuallyConsistentMapEvent.Type.*; + +/** + * Testing version of an Eventually Consistent Map. + */ + +public final class TestEventuallyConsistentMap<K, V> extends EventuallyConsistentMapAdapter<K, V> { + + private final HashMap<K, V> map; + private final String mapName; + private final List<EventuallyConsistentMapListener<K, V>> listeners; + private final BiFunction<K, V, Collection<NodeId>> peerUpdateFunction; + + private TestEventuallyConsistentMap(String mapName, + BiFunction<K, V, Collection<NodeId>> peerUpdateFunction) { + map = new HashMap<>(); + listeners = new LinkedList<>(); + this.mapName = mapName; + this.peerUpdateFunction = peerUpdateFunction; + } + + /** + * Notify all listeners of an event. + */ + private void notifyListeners(EventuallyConsistentMapEvent<K, V> event) { + listeners.forEach( + listener -> listener.event(event) + ); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public boolean containsKey(K key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(V value) { + return map.containsValue(value); + } + + @Override + public V get(K key) { + return map.get(key); + } + + @Override + public void put(K key, V value) { + map.put(key, value); + EventuallyConsistentMapEvent<K, V> addEvent = + new EventuallyConsistentMapEvent<>(mapName, PUT, key, value); + notifyListeners(addEvent); + if (peerUpdateFunction != null) { + peerUpdateFunction.apply(key, value); + } + } + + @Override + public V remove(K key) { + V result = map.remove(key); + if (result != null) { + EventuallyConsistentMapEvent<K, V> removeEvent = + new EventuallyConsistentMapEvent<>(mapName, REMOVE, + key, map.get(key)); + notifyListeners(removeEvent); + } + return result; + } + + @Override + public void remove(K key, V value) { + boolean removed = map.remove(key, value); + if (removed) { + EventuallyConsistentMapEvent<K, V> removeEvent = + new EventuallyConsistentMapEvent<>(mapName, REMOVE, key, value); + notifyListeners(removeEvent); + } + } + + @Override + public V compute(K key, BiFunction<K, V, V> recomputeFunction) { + return map.compute(key, recomputeFunction); + } + + @Override + public void putAll(Map<? extends K, ? extends V> m) { + map.putAll(m); + } + + @Override + public void clear() { + map.clear(); + } + + @Override + public Set<K> keySet() { + return map.keySet(); + } + + @Override + public Collection<V> values() { + return map.values(); + } + + @Override + public Set<Map.Entry<K, V>> entrySet() { + return map.entrySet(); + } + + public static <K, V> Builder<K, V> builder() { + return new Builder<>(); + } + + @Override + public void addListener(EventuallyConsistentMapListener<K, V> listener) { + listeners.add(listener); + } + + @Override + public void removeListener(EventuallyConsistentMapListener<K, V> listener) { + listeners.remove(listener); + } + + public static class Builder<K, V> implements EventuallyConsistentMapBuilder<K, V> { + private String name; + private BiFunction<K, V, Collection<NodeId>> peerUpdateFunction; + + @Override + public EventuallyConsistentMapBuilder<K, V> withName(String name) { + this.name = name; + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withSerializer(KryoNamespace.Builder serializerBuilder) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> + withTimestampProvider(BiFunction<K, V, Timestamp> timestampProvider) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withEventExecutor(ExecutorService executor) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withCommunicationExecutor(ExecutorService executor) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withBackgroundExecutor(ScheduledExecutorService executor) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> + withPeerUpdateFunction(BiFunction<K, V, Collection<NodeId>> peerUpdateFunction) { + this.peerUpdateFunction = peerUpdateFunction; + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withTombstonesDisabled() { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withAntiEntropyPeriod(long period, TimeUnit unit) { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withFasterConvergence() { + return this; + } + + @Override + public EventuallyConsistentMapBuilder<K, V> withPersistence() { + return this; + } + + @Override + public EventuallyConsistentMap<K, V> build() { + if (name == null) { + name = "test"; + } + return new TestEventuallyConsistentMap<>(name, peerUpdateFunction); + } + } + +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestStorageService.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestStorageService.java new file mode 100644 index 00000000..9b52a305 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/TestStorageService.java @@ -0,0 +1,55 @@ +/* + * 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.service; + +public class TestStorageService extends StorageServiceAdapter { + + + @Override + public <K, V> EventuallyConsistentMapBuilder<K, V> eventuallyConsistentMapBuilder() { + return TestEventuallyConsistentMap.builder(); + } + + @Override + public <K, V> ConsistentMapBuilder<K, V> consistentMapBuilder() { + return TestConsistentMap.builder(); + } + + @Override + public <E> DistributedSetBuilder<E> setBuilder() { + throw new UnsupportedOperationException("setBuilder"); + } + + @Override + public <E> DistributedQueueBuilder<E> queueBuilder() { + throw new UnsupportedOperationException("queueBuilder"); + } + + @Override + public AtomicCounterBuilder atomicCounterBuilder() { + return TestAtomicCounter.builder(); + } + + @Override + public <V> AtomicValueBuilder<V> atomicValueBuilder() { + throw new UnsupportedOperationException("atomicValueBuilder"); + } + + @Override + public TransactionContextBuilder transactionContextBuilder() { + throw new UnsupportedOperationException("transactionContextBuilder"); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/VersionedTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/VersionedTest.java new file mode 100644 index 00000000..8a401db2 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/VersionedTest.java @@ -0,0 +1,84 @@ +/* + * 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.service; + +import com.google.common.testing.EqualsTester; +import junit.framework.TestCase; +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +/** + * Versioned unit tests. + */ +public class VersionedTest extends TestCase { + + private final Versioned<Integer> stats1 = new Versioned<>(1, 2, 3); + + private final Versioned<Integer> stats2 = new Versioned<>(1, 2); + + /** + * Tests the creation of the MapEvent object. + */ + @Test + public void testConstruction() { + assertThat(stats1.value(), is(1)); + assertThat(stats1.version(), is(2L)); + assertThat(stats1.creationTime(), is(3L)); + } + + /** + * Maps an Integer to a String - Utility function to test the map function. + * @param a Actual Integer parameter. + * @return String Mapped valued. + */ + public static String transform(Integer a) { + return Integer.toString(a); + } + + /** + * Tests the map function. + */ + @Test + public void testMap() { + Versioned<String> tempObj = stats1.<String>map(VersionedTest::transform); + assertThat(tempObj.value(), is("1")); + } + + /** + * Tests the valueOrElse method. + */ + @Test + public void testOrElse() { + Versioned<String> vv = new Versioned<>("foo", 1); + Versioned<String> nullVV = null; + assertThat(Versioned.valueOrElse(vv, "bar"), is("foo")); + assertThat(Versioned.valueOrElse(nullVV, "bar"), is("bar")); + } + + /** + * Tests the equals, hashCode and toString methods using Guava EqualsTester. + */ + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(stats1, stats1) + .addEqualityGroup(stats2) + .testEquals(); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/WallClockTimestampTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/WallClockTimestampTest.java new file mode 100644 index 00000000..97f5a39b --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/store/service/WallClockTimestampTest.java @@ -0,0 +1,66 @@ +/* + * 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.service; + +import static org.junit.Assert.assertTrue; + +import java.nio.ByteBuffer; + +import org.junit.Test; +import org.onosproject.store.Timestamp; +import org.onlab.util.KryoNamespace; + +import com.google.common.testing.EqualsTester; + +/** + * Tests for {@link WallClockTimestamp}. + */ +public class WallClockTimestampTest { + + @Test + public final void testBasic() throws InterruptedException { + WallClockTimestamp ts1 = new WallClockTimestamp(); + Thread.sleep(50); + WallClockTimestamp ts2 = new WallClockTimestamp(); + long stamp = System.currentTimeMillis() + 10000; + WallClockTimestamp ts3 = new WallClockTimestamp(stamp); + + + assertTrue(ts1.compareTo(ts1) == 0); + assertTrue(ts2.compareTo(ts1) > 0); + assertTrue(ts1.compareTo(ts2) < 0); + assertTrue(ts3.unixTimestamp() == stamp); + } + + @Test + public final void testKryoSerializable() { + WallClockTimestamp ts1 = new WallClockTimestamp(); + WallClockTimestamp ts2 = new WallClockTimestamp(System.currentTimeMillis() + 10000); + final ByteBuffer buffer = ByteBuffer.allocate(1 * 1024 * 1024); + final KryoNamespace kryos = KryoNamespace.newBuilder() + .register(WallClockTimestamp.class) + .build(); + + kryos.serialize(ts1, buffer); + buffer.flip(); + Timestamp copy = kryos.deserialize(buffer); + + new EqualsTester() + .addEqualityGroup(ts1, copy) + .addEqualityGroup(ts2) + .testEquals(); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionServiceAdapter.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionServiceAdapter.java new file mode 100644 index 00000000..68d9264c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionServiceAdapter.java @@ -0,0 +1,41 @@ +/* + * 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.ui; + +import java.util.List; + +/** + * Adapter for testing against UI extension service. + */ +public class UiExtensionServiceAdapter implements UiExtensionService { + @Override + public void register(UiExtension extension) { + } + + @Override + public void unregister(UiExtension extension) { + } + + @Override + public List<UiExtension> getExtensions() { + return null; + } + + @Override + public UiExtension getViewExtension(String viewId) { + return null; + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionTest.java new file mode 100644 index 00000000..bd3d15f6 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/UiExtensionTest.java @@ -0,0 +1,140 @@ +/* + * 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.ui; + +import com.google.common.collect.ImmutableList; +import org.junit.Test; + +import java.io.IOException; +import java.util.List; + +import static com.google.common.io.ByteStreams.toByteArray; +import static org.junit.Assert.*; +import static org.onosproject.ui.UiView.Category.OTHER; + +/** + * Tests the default user interface extension descriptor. + */ +public class UiExtensionTest { + + private static final String FOO_ID = "foo"; + private static final String FOO_LABEL = "Foo View"; + private static final String BAR_ID = "bar"; + private static final String BAR_LABEL = "Bar View"; + private static final String CUSTOM = "custom"; + + + private static final UiView FOO_VIEW = new UiView(OTHER, FOO_ID, FOO_LABEL); + private static final UiView BAR_VIEW = new UiView(OTHER, BAR_ID, BAR_LABEL); + private static final UiView HIDDEN_VIEW = new UiViewHidden(FOO_ID); + + private static final UiMessageHandlerFactory MH_FACTORY = () -> null; + private static final UiTopoOverlayFactory TO_FACTORY = () -> null; + + private final ClassLoader cl = getClass().getClassLoader(); + + private List<UiView> viewList; + private UiExtension ext; + private String css; + private String js; + private UiView view; + + + + @Test + public void basics() throws IOException { + viewList = ImmutableList.of(FOO_VIEW); + ext = new UiExtension.Builder(cl, viewList).build(); + + css = new String(toByteArray(ext.css())); + assertTrue("incorrect css stream", css.contains("foo-css")); + js = new String(toByteArray(ext.js())); + assertTrue("incorrect js stream", js.contains("foo-js")); + + assertEquals("expected 1 view", 1, ext.views().size()); + view = ext.views().get(0); + assertEquals("wrong view category", OTHER, view.category()); + assertEquals("wrong view id", FOO_ID, view.id()); + assertEquals("wrong view label", FOO_LABEL, view.label()); + + assertNull("unexpected message handler factory", ext.messageHandlerFactory()); + assertNull("unexpected topo overlay factory", ext.topoOverlayFactory()); + } + + @Test + public void withPath() throws IOException { + viewList = ImmutableList.of(FOO_VIEW); + ext = new UiExtension.Builder(cl, viewList) + .resourcePath(CUSTOM) + .build(); + + css = new String(toByteArray(ext.css())); + assertTrue("incorrect css stream", css.contains("custom-css")); + js = new String(toByteArray(ext.js())); + assertTrue("incorrect js stream", js.contains("custom-js")); + + assertEquals("expected 1 view", 1, ext.views().size()); + view = ext.views().get(0); + assertEquals("wrong view category", OTHER, view.category()); + assertEquals("wrong view id", FOO_ID, view.id()); + assertEquals("wrong view label", FOO_LABEL, view.label()); + + assertNull("unexpected message handler factory", ext.messageHandlerFactory()); + assertNull("unexpected topo overlay factory", ext.topoOverlayFactory()); + } + + @Test + public void messageHandlerFactory() { + viewList = ImmutableList.of(FOO_VIEW); + ext = new UiExtension.Builder(cl, viewList) + .messageHandlerFactory(MH_FACTORY) + .build(); + + assertEquals("wrong message handler factory", MH_FACTORY, + ext.messageHandlerFactory()); + assertNull("unexpected topo overlay factory", ext.topoOverlayFactory()); + } + + @Test + public void topoOverlayFactory() { + viewList = ImmutableList.of(HIDDEN_VIEW); + ext = new UiExtension.Builder(cl, viewList) + .topoOverlayFactory(TO_FACTORY) + .build(); + + assertNull("unexpected message handler factory", ext.messageHandlerFactory()); + assertEquals("wrong topo overlay factory", TO_FACTORY, + ext.topoOverlayFactory()); + } + + @Test + public void twoViews() { + viewList = ImmutableList.of(FOO_VIEW, BAR_VIEW); + ext = new UiExtension.Builder(cl, viewList).build(); + + assertEquals("expected 2 views", 2, ext.views().size()); + + view = ext.views().get(0); + assertEquals("wrong view category", OTHER, view.category()); + assertEquals("wrong view id", FOO_ID, view.id()); + assertEquals("wrong view label", FOO_LABEL, view.label()); + + view = ext.views().get(1); + assertEquals("wrong view category", OTHER, view.category()); + assertEquals("wrong view id", BAR_ID, view.id()); + assertEquals("wrong view label", BAR_LABEL, view.label()); + } +}
\ No newline at end of file diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableModelTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableModelTest.java new file mode 100644 index 00000000..7524bcb3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableModelTest.java @@ -0,0 +1,338 @@ +/* + * 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.ui.table; + +import org.junit.Test; +import org.onosproject.ui.table.TableModel.SortDir; +import org.onosproject.ui.table.cell.DefaultCellFormatter; +import org.onosproject.ui.table.cell.HexFormatter; + +import static org.junit.Assert.*; + +/** + * Unit tests for {@link TableModel}. + */ +public class TableModelTest { + + private static final String UNEX_SORT = "unexpected sort: index "; + + private static final String FOO = "foo"; + private static final String BAR = "bar"; + private static final String ZOO = "zoo"; + + private enum StarWars { + LUKE_SKYWALKER, LEIA_ORGANA, HAN_SOLO, C3PO, R2D2, JABBA_THE_HUTT + } + + private static class ParenFormatter implements CellFormatter { + @Override + public String format(Object value) { + return "(" + value + ")"; + } + } + + private TableModel tm; + private TableModel.Row[] rows; + private TableModel.Row row; + private CellFormatter fmt; + + @Test(expected = NullPointerException.class) + public void guardAgainstNull() { + tm = new TableModel(null); + } + + @Test(expected = IllegalArgumentException.class) + public void guardAgainstEmpty() { + tm = new TableModel(); + } + + @Test(expected = IllegalArgumentException.class) + public void guardAgainstDuplicateCols() { + tm = new TableModel(FOO, BAR, FOO); + } + + @Test + public void basic() { + tm = new TableModel(FOO, BAR); + assertEquals("column count", 2, tm.columnCount()); + assertEquals("row count", 0, tm.rowCount()); + } + + @Test + public void defaultFormatter() { + tm = new TableModel(FOO); + fmt = tm.getFormatter(FOO); + assertTrue("Wrong formatter", fmt instanceof DefaultCellFormatter); + } + + @Test(expected = IllegalArgumentException.class) + public void formatterBadColumn() { + tm = new TableModel(FOO); + fmt = tm.getFormatter(BAR); + } + + @Test + public void altFormatter() { + tm = new TableModel(FOO, BAR); + tm.setFormatter(BAR, new ParenFormatter()); + + fmt = tm.getFormatter(FOO); + assertTrue("Wrong formatter", fmt instanceof DefaultCellFormatter); + assertEquals("Wrong result", "2", fmt.format(2)); + + fmt = tm.getFormatter(BAR); + assertTrue("Wrong formatter", fmt instanceof ParenFormatter); + assertEquals("Wrong result", "(2)", fmt.format(2)); + } + + @Test + public void emptyRow() { + tm = new TableModel(FOO, BAR); + tm.addRow(); + assertEquals("bad row count", 1, tm.rowCount()); + } + + @Test(expected = IllegalArgumentException.class) + public void rowBadColumn() { + tm = new TableModel(FOO, BAR); + tm.addRow().cell(ZOO, 2); + } + + @Test + public void simpleRow() { + tm = new TableModel(FOO, BAR); + tm.addRow().cell(FOO, 3).cell(BAR, true); + assertEquals("bad row count", 1, tm.rowCount()); + row = tm.getRows()[0]; + assertEquals("bad cell", 3, row.get(FOO)); + assertEquals("bad cell", true, row.get(BAR)); + } + + + private static final String ONE = "one"; + private static final String TWO = "two"; + private static final String THREE = "three"; + private static final String FOUR = "four"; + private static final String ELEVEN = "eleven"; + private static final String TWELVE = "twelve"; + private static final String TWENTY = "twenty"; + private static final String THIRTY = "thirty"; + + private static final String[] NAMES = { + FOUR, + THREE, + TWO, + ONE, + ELEVEN, + TWELVE, + THIRTY, + TWENTY, + }; + private static final String[] SORTED_NAMES = { + ELEVEN, + FOUR, + ONE, + THIRTY, + THREE, + TWELVE, + TWENTY, + TWO, + }; + + private static final int[] NUMBERS = { + 4, 3, 2, 1, 11, 12, 30, 20 + }; + + private static final int[] SORTED_NUMBERS = { + 1, 2, 3, 4, 11, 12, 20, 30 + }; + + private static final String[] SORTED_HEX = { + "0x1", "0x2", "0x3", "0x4", "0xb", "0xc", "0x14", "0x1e" + }; + + @Test + public void verifyTestData() { + // not a unit test per se, but will fail if we don't keep + // the three test arrays in sync + int nalen = NAMES.length; + int snlen = SORTED_NAMES.length; + int nulen = NUMBERS.length; + + if (nalen != snlen || nalen != nulen) { + fail("test data array size discrepancy"); + } + } + + private void initUnsortedTable() { + tm = new TableModel(FOO, BAR); + for (int i = 0; i < NAMES.length; i++) { + tm.addRow().cell(FOO, NAMES[i]).cell(BAR, NUMBERS[i]); + } + } + + @Test + public void tableStringSort() { + initUnsortedTable(); + + // sort by name + tm.sort(FOO, SortDir.ASC); + + // verify results + rows = tm.getRows(); + int nr = rows.length; + assertEquals("row count", NAMES.length, nr); + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, SORTED_NAMES[i], rows[i].get(FOO)); + } + + // now the other way + tm.sort(FOO, SortDir.DESC); + + // verify results + rows = tm.getRows(); + nr = rows.length; + assertEquals("row count", NAMES.length, nr); + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, + SORTED_NAMES[nr - 1 - i], rows[i].get(FOO)); + } + } + + @Test + public void tableNumberSort() { + initUnsortedTable(); + + // sort by number + tm.sort(BAR, SortDir.ASC); + + // verify results + rows = tm.getRows(); + int nr = rows.length; + assertEquals("row count", NUMBERS.length, nr); + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, SORTED_NUMBERS[i], rows[i].get(BAR)); + } + + // now the other way + tm.sort(BAR, SortDir.DESC); + + // verify results + rows = tm.getRows(); + nr = rows.length; + assertEquals("row count", NUMBERS.length, nr); + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, + SORTED_NUMBERS[nr - 1 - i], rows[i].get(BAR)); + } + } + + @Test + public void sortAndFormat() { + initUnsortedTable(); + + // set hex formatter + tm.setFormatter(BAR, HexFormatter.INSTANCE); + + // sort by number + tm.sort(BAR, SortDir.ASC); + + // verify results + rows = tm.getRows(); + int nr = rows.length; + assertEquals("row count", SORTED_HEX.length, nr); + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, SORTED_HEX[i], rows[i].getAsString(BAR)); + } + } + + private static final String[][] SORTED_NAMES_AND_HEX = { + {ELEVEN, "0xb"}, + {FOUR, "0x4"}, + {ONE, "0x1"}, + {THIRTY, "0x1e"}, + {THREE, "0x3"}, + {TWELVE, "0xc"}, + {TWENTY, "0x14"}, + {TWO, "0x2"}, + }; + + @Test + public void sortAndFormatTwo() { + initUnsortedTable(); + tm.setFormatter(BAR, HexFormatter.INSTANCE); + tm.sort(FOO, SortDir.ASC); + rows = tm.getRows(); + int nr = rows.length; + for (int i = 0; i < nr; i++) { + String[] exp = SORTED_NAMES_AND_HEX[i]; + String[] act = rows[i].getAsFormattedStrings(); + assertArrayEquals(UNEX_SORT + i, exp, act); + } + } + + private static final String[] FBZ = {FOO, BAR, ZOO}; + + @Test + public void getColumnIds() { + tm = new TableModel(FOO, BAR, ZOO); + assertArrayEquals("col IDs", FBZ, tm.getColumnIds()); + } + + @Test + public void sortDirAsc() { + assertEquals("asc sort dir", SortDir.ASC, TableModel.sortDir("asc")); + } + + @Test + public void sortDirDesc() { + assertEquals("desc sort dir", SortDir.DESC, TableModel.sortDir("desc")); + } + + @Test + public void sortDirOther() { + assertEquals("other sort dir", SortDir.ASC, TableModel.sortDir("other")); + } + + @Test + public void sortDirNull() { + assertEquals("null sort dir", SortDir.ASC, TableModel.sortDir(null)); + } + + + @Test + public void enumSort() { + tm = new TableModel(FOO); + tm.addRow().cell(FOO, StarWars.HAN_SOLO); + tm.addRow().cell(FOO, StarWars.C3PO); + tm.addRow().cell(FOO, StarWars.JABBA_THE_HUTT); + tm.addRow().cell(FOO, StarWars.LEIA_ORGANA); + tm.addRow().cell(FOO, StarWars.R2D2); + tm.addRow().cell(FOO, StarWars.LUKE_SKYWALKER); + + tm.sort(FOO, SortDir.ASC); + + // verify expected results + StarWars[] ordered = StarWars.values(); + TableModel.Row[] rows = tm.getRows(); + assertEquals("wrong length?", ordered.length, rows.length); + int nr = rows.length; + for (int i = 0; i < nr; i++) { + assertEquals(UNEX_SORT + i, ordered[i], rows[i].get(FOO)); + } + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableUtilsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableUtilsTest.java new file mode 100644 index 00000000..7c2f2d73 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/TableUtilsTest.java @@ -0,0 +1,45 @@ +/* + * 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.ui.table; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import org.junit.Assert; +import org.junit.Test; + +/** + * Unit tests for {@link TableUtils}. + */ +public class TableUtilsTest { + + private static final String FOO = "foo"; + private static final String BAR = "bar"; + + private static final String ARRAY_AS_STRING = + "[{\"foo\":\"1\",\"bar\":\"2\"},{\"foo\":\"3\",\"bar\":\"4\"}]"; + + @Test + public void basic() { + TableModel tm = new TableModel(FOO, BAR); + tm.addRow().cell(FOO, 1).cell(BAR, 2); + tm.addRow().cell(FOO, 3).cell(BAR, 4); + + ArrayNode array = TableUtils.generateArrayNode(tm); + Assert.assertEquals("wrong results", ARRAY_AS_STRING, array.toString()); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellComparatorTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellComparatorTest.java new file mode 100644 index 00000000..0b9af23d --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellComparatorTest.java @@ -0,0 +1,59 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellComparator; + +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link AbstractCellComparator}. + */ +public class AbstractCellComparatorTest { + + private static class Concrete extends AbstractCellComparator { + @Override + protected int nonNullCompare(Object o1, Object o2) { + return 42; + } + } + + private CellComparator cmp = new Concrete(); + + @Test + public void twoNullArgs() { + assertTrue("two nulls", cmp.compare(null, null) == 0); + } + + @Test + public void nullArgOne() { + assertTrue("null one", cmp.compare(null, 1) < 0); + } + + @Test + public void nullArgTwo() { + assertTrue("null two", cmp.compare(1, null) > 0); + } + + // mock output, but check that our method was invoked... + @Test + public void noNulls() { + assertTrue("no Nulls", cmp.compare(1, 2) == 42); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellFormatterTest.java new file mode 100644 index 00000000..7a3c34bc --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellFormatterTest.java @@ -0,0 +1,52 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link AbstractCellFormatter}. + */ +public class AbstractCellFormatterTest { + + private static final String MOCK_OUTPUT = "Mock!!"; + + private static class Concrete extends AbstractCellFormatter { + @Override + protected String nonNullFormat(Object value) { + return MOCK_OUTPUT; + } + } + + private CellFormatter frm = new Concrete(); + + @Test + public void nullInput() { + assertEquals("wrong result", "", frm.format(null)); + } + + // mock output, but check that our method was invoked... + @Test + public void nonNullInput() { + assertEquals("what?", MOCK_OUTPUT, frm.format(1)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AppIdFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AppIdFormatterTest.java new file mode 100644 index 00000000..e74fb47c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/AppIdFormatterTest.java @@ -0,0 +1,50 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.core.ApplicationId; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link AppIdFormatter}. + */ +public class AppIdFormatterTest { + + private static final ApplicationId APP_ID = new ApplicationId() { + @Override + public short id() { + return 25; + } + + @Override + public String name() { + return "some app"; + } + }; + + private CellFormatter fmt = AppIdFormatter.INSTANCE; + + @Test + public void basic() { + assertEquals("wrong format", "25 : some app", fmt.format(APP_ID)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/ConnectPointFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/ConnectPointFormatterTest.java new file mode 100644 index 00000000..65fd7843 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/ConnectPointFormatterTest.java @@ -0,0 +1,45 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.PortNumber; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link ConnectPointFormatter}. + */ +public class ConnectPointFormatterTest { + + private static final DeviceId DEVID = DeviceId.deviceId("foobar"); + private static final PortNumber PORT = PortNumber.portNumber(42); + + private static final ConnectPoint CP = new ConnectPoint(DEVID, PORT); + + private CellFormatter fmt = ConnectPointFormatter.INSTANCE; + + @Test + public void basic() { + assertEquals("wrong format", "foobar/42", fmt.format(CP)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellComparatorTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellComparatorTest.java new file mode 100644 index 00000000..87c95288 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellComparatorTest.java @@ -0,0 +1,147 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellComparator; + +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link DefaultCellComparator}. + */ +public class DefaultCellComparatorTest { + + private static final String SOME = "SoMeStRiNg"; + private static final String OTHER = "OtherSTRING"; + + private CellComparator cmp = DefaultCellComparator.INSTANCE; + + // default comparator should detect Comparable<T> impls and use that + + @Test + public void sameString() { + assertTrue("same string", cmp.compare(SOME, SOME) == 0); + } + + @Test + public void someVsOther() { + assertTrue("some vs other", cmp.compare(SOME, OTHER) > 0); + } + + @Test + public void otherVsSome() { + assertTrue("other vs some", cmp.compare(OTHER, SOME) < 0); + } + + @Test + public void someVsNull() { + assertTrue("some vs null", cmp.compare(SOME, null) > 0); + } + + @Test + public void nullVsSome() { + assertTrue("null vs some", cmp.compare(null, SOME) < 0); + } + + @Test(expected = ClassCastException.class) + public void mismatch() { + cmp.compare(42, SOME); + } + + + @Test + public void strElevenTwo() { + assertTrue("str 11 vs 2", cmp.compare("11", "2") < 0); + } + + @Test + public void intElevenTwo() { + assertTrue("int 11 vs 2", cmp.compare(11, 2) > 0); + } + + + @Test + public void intSmallBig() { + assertTrue("int 2 vs 4", cmp.compare(2, 4) < 0); + } + + @Test + public void intBigSmall() { + assertTrue("int 4 vs 2", cmp.compare(4, 2) > 0); + } + + @Test + public void intEqual() { + assertTrue("int 4 vs 4", cmp.compare(4, 4) == 0); + } + + @Test + public void longSmallBig() { + assertTrue("long 2 vs 4", cmp.compare(2L, 4L) < 0); + } + + @Test + public void longBigSmall() { + assertTrue("long 4 vs 2", cmp.compare(4L, 2L) > 0); + } + + @Test + public void longEqual() { + assertTrue("long 4 vs 4", cmp.compare(4L, 4L) == 0); + } + + + private enum SmallStarWars { C3PO, R2D2, LUKE } + + @Test + public void swEpisodeI() { + assertTrue("c3po r2d2", + cmp.compare(SmallStarWars.C3PO, SmallStarWars.R2D2) < 0); + } + + @Test + public void swEpisodeII() { + assertTrue("r2d2 c3po", + cmp.compare(SmallStarWars.R2D2, SmallStarWars.C3PO) > 0); + } + + @Test + public void swEpisodeIII() { + assertTrue("luke c3po", + cmp.compare(SmallStarWars.LUKE, SmallStarWars.C3PO) > 0); + } + + @Test + public void swEpisodeIV() { + assertTrue("c3po luke", + cmp.compare(SmallStarWars.C3PO, SmallStarWars.LUKE) < 0); + } + + @Test + public void swEpisodeV() { + assertTrue("luke r2d2", + cmp.compare(SmallStarWars.LUKE, SmallStarWars.R2D2) > 0); + } + + @Test + public void swEpisodeVI() { + assertTrue("r2d2 luke", + cmp.compare(SmallStarWars.R2D2, SmallStarWars.LUKE) < 0); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellFormatterTest.java new file mode 100644 index 00000000..6351a1f4 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/DefaultCellFormatterTest.java @@ -0,0 +1,71 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link DefaultCellFormatter}. + */ +public class DefaultCellFormatterTest { + + private static final String UNEX = "Unexpected result"; + private static final String SOME_STRING = "SoMeStRiNg"; + + private static class TestClass { + @Override + public String toString() { + return SOME_STRING; + } + } + + private CellFormatter fmt = DefaultCellFormatter.INSTANCE; + + @Test + public void formatNull() { + assertEquals(UNEX, "", fmt.format(null)); + } + + @Test + public void formatInteger() { + assertEquals(UNEX, "3", fmt.format(3)); + } + + @Test + public void formatTrue() { + assertEquals(UNEX, "true", fmt.format(true)); + } + + @Test + public void formatFalse() { + assertEquals(UNEX, "false", fmt.format(false)); + } + + @Test + public void formatString() { + assertEquals(UNEX, "FOO", fmt.format("FOO")); + } + + @Test + public void formatObject() { + assertEquals(UNEX, SOME_STRING, fmt.format(new TestClass())); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/EnumFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/EnumFormatterTest.java new file mode 100644 index 00000000..68833c90 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/EnumFormatterTest.java @@ -0,0 +1,60 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link EnumFormatter}. + */ +public class EnumFormatterTest { + + enum TestEnum { + ADDED, + PENDING_ADD, + WAITING_AUDIT_COMPLETE + } + + private CellFormatter fmt = EnumFormatter.INSTANCE; + + @Test + public void nullValue() { + assertEquals("null value", "", fmt.format(null)); + } + + @Test + public void noUnderscores() { + assertEquals("All caps", "Added", fmt.format(TestEnum.ADDED)); + } + + @Test + public void underscores() { + assertEquals("All caps with underscores", + "Pending Add", fmt.format(TestEnum.PENDING_ADD)); + } + + @Test + public void multiUnderscores() { + assertEquals("All caps with underscores", + "Waiting Audit Complete", + fmt.format(TestEnum.WAITING_AUDIT_COMPLETE)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HexFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HexFormatterTest.java new file mode 100644 index 00000000..ad23b02c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HexFormatterTest.java @@ -0,0 +1,57 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link HexFormatter}. + */ +public class HexFormatterTest { + + private CellFormatter fmt = HexFormatter.INSTANCE; + + @Test + public void nullValue() { + assertEquals("null value", "", fmt.format(null)); + } + + @Test + public void zero() { + assertEquals("zero", "0x0", fmt.format(0)); + } + + @Test + public void one() { + assertEquals("one", "0x1", fmt.format(1)); + } + + @Test + public void ten() { + assertEquals("ten", "0xa", fmt.format(10)); + } + + @Test + public void twenty() { + assertEquals("twenty", "0x14", fmt.format(20)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HostLocationFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HostLocationFormatterTest.java new file mode 100644 index 00000000..bfbe4541 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/HostLocationFormatterTest.java @@ -0,0 +1,46 @@ +/* + * 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.ui.table.cell; + +import org.junit.Test; +import org.onosproject.net.DeviceId; +import org.onosproject.net.HostLocation; +import org.onosproject.net.PortNumber; +import org.onosproject.ui.table.CellFormatter; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link HostLocationFormatter}. + */ +public class HostLocationFormatterTest { + + private static final DeviceId DEVID = DeviceId.deviceId("foobar"); + private static final PortNumber PORT = PortNumber.portNumber(42); + private static final long TIME = 12345; + + private static final HostLocation LOC = new HostLocation(DEVID, PORT, TIME); + + private CellFormatter fmt = HostLocationFormatter.INSTANCE; + + @Test + public void basic() { + assertEquals("wrong format", "foobar/42", fmt.format(LOC)); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/TimeFormatterTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/TimeFormatterTest.java new file mode 100644 index 00000000..f41d82b3 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/table/cell/TimeFormatterTest.java @@ -0,0 +1,52 @@ +/* + * 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.ui.table.cell; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.junit.Test; +import org.onosproject.ui.table.CellFormatter; + +import java.util.Locale; + +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link TimeFormatter}. + */ +public class TimeFormatterTest { + + private static final Locale LOCALE = Locale.ENGLISH; + private static final DateTimeZone ZONE = DateTimeZone.UTC; + + private static final DateTime TIME = new DateTime(2015, 5, 4, 15, 30, ZONE); + private static final String EXP_ZONE_NAME = "3:30:00 PM UTC"; + private static final String EXP_ZONE_OFFSET = "3:30:00 PM +00:00"; + + // Have to use explicit Locale and TimeZone for the unit test, so that + // irrespective of which locale and time zone the test is run in, it + // always produces the same result... + private CellFormatter fmt = + new TimeFormatter().withLocale(LOCALE).withZone(ZONE); + + @Test + public void basic() { + assertTrue("wrong format", (EXP_ZONE_NAME.equals(fmt.format(TIME)) || + EXP_ZONE_OFFSET.equals(fmt.format(TIME)))); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkMapTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkMapTest.java new file mode 100644 index 00000000..17fcc229 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkMapTest.java @@ -0,0 +1,76 @@ +/* + * 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.ui.topo; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link BiLinkMap}. + */ +public class BiLinkMapTest extends BiLinkTestBase { + + + private ConcreteLink clink; + private ConcreteLinkMap linkMap; + + @Before + public void setUp() { + linkMap = new ConcreteLinkMap(); + } + + @Test + public void basic() { + assertEquals("wrong map size", 0, linkMap.size()); + assertTrue("unexpected links", linkMap.biLinks().isEmpty()); + } + + @Test + public void addSameLinkTwice() { + linkMap.add(LINK_AB); + assertEquals("wrong map size", 1, linkMap.size()); + clink = linkMap.biLinks().iterator().next(); + assertEquals("wrong link one", LINK_AB, clink.one()); + assertNull("unexpected link two", clink.two()); + + linkMap.add(LINK_AB); + assertEquals("wrong map size", 1, linkMap.size()); + clink = linkMap.biLinks().iterator().next(); + assertEquals("wrong link one", LINK_AB, clink.one()); + assertNull("unexpected link two", clink.two()); + } + + @Test + public void addPairOfLinks() { + linkMap.add(LINK_AB); + assertEquals("wrong map size", 1, linkMap.size()); + clink = linkMap.biLinks().iterator().next(); + assertEquals("wrong link one", LINK_AB, clink.one()); + assertNull("unexpected link two", clink.two()); + + linkMap.add(LINK_BA); + assertEquals("wrong map size", 1, linkMap.size()); + clink = linkMap.biLinks().iterator().next(); + assertEquals("wrong link one", LINK_AB, clink.one()); + assertEquals("wrong link two", LINK_BA, clink.two()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTest.java new file mode 100644 index 00000000..1acc06fa --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTest.java @@ -0,0 +1,62 @@ +/* + * 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.ui.topo; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +/** + * Unit tests for {@link BiLink}. + */ +public class BiLinkTest extends BiLinkTestBase { + + private static final String EXP_ID_AB = "device-a/1-device-b/2"; + + private BiLink blink; + + @Test + public void basic() { + blink = new ConcreteLink(KEY_AB, LINK_AB); + assertEquals("wrong id", EXP_ID_AB, blink.linkId()); + assertEquals("wrong key", KEY_AB, blink.key()); + assertEquals("wrong link one", LINK_AB, blink.one()); + assertNull("what?", blink.two()); + + blink.setOther(LINK_BA); + assertEquals("wrong link two", LINK_BA, blink.two()); + } + + @Test(expected = NullPointerException.class) + public void nullKey() { + new ConcreteLink(null, LINK_AB); + } + + @Test(expected = NullPointerException.class) + public void nullLink() { + new ConcreteLink(KEY_AB, null); + } + + @Test(expected = NullPointerException.class) + public void nullOther() { + blink = new ConcreteLink(KEY_AB, LINK_AB); + blink.setOther(null); + } +} + diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTestBase.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTestBase.java new file mode 100644 index 00000000..b5bd41ef --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/BiLinkTestBase.java @@ -0,0 +1,98 @@ +/* + * 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.ui.topo; + +import org.onosproject.net.Annotations; +import org.onosproject.net.ConnectPoint; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Link; +import org.onosproject.net.LinkKey; +import org.onosproject.net.PortNumber; +import org.onosproject.net.provider.ProviderId; + +/** + * Base class for unit tests of {@link BiLink} and {@link BiLinkMap}. + */ +public abstract class BiLinkTestBase { + + protected static class FakeLink implements Link { + private final ConnectPoint src; + private final ConnectPoint dst; + + FakeLink(ConnectPoint src, ConnectPoint dst) { + this.src = src; + this.dst = dst; + } + + @Override public ConnectPoint src() { + return src; + } + @Override public ConnectPoint dst() { + return dst; + } + + @Override public Type type() { + return null; + } + @Override public State state() { + return null; + } + @Override public boolean isDurable() { + return false; + } + @Override public Annotations annotations() { + return null; + } + @Override public ProviderId providerId() { + return null; + } + } + + protected static final DeviceId DEV_A_ID = DeviceId.deviceId("device-A"); + protected static final DeviceId DEV_B_ID = DeviceId.deviceId("device-B"); + protected static final PortNumber PORT_1 = PortNumber.portNumber(1); + protected static final PortNumber PORT_2 = PortNumber.portNumber(2); + + protected static final ConnectPoint CP_A1 = new ConnectPoint(DEV_A_ID, PORT_1); + protected static final ConnectPoint CP_B2 = new ConnectPoint(DEV_B_ID, PORT_2); + + protected static final LinkKey KEY_AB = LinkKey.linkKey(CP_A1, CP_B2); + protected static final LinkKey KEY_BA = LinkKey.linkKey(CP_B2, CP_A1); + + protected static final Link LINK_AB = new FakeLink(CP_A1, CP_B2); + protected static final Link LINK_BA = new FakeLink(CP_B2, CP_A1); + + protected static class ConcreteLink extends BiLink { + public ConcreteLink(LinkKey key, Link link) { + super(key, link); + } + @Override + public LinkHighlight highlight(Enum<?> type) { + return null; + } + } + + protected static class ConcreteLinkMap extends BiLinkMap<ConcreteLink> { + @Override + public ConcreteLink create(LinkKey key, Link link) { + return new ConcreteLink(key, link); + } + } + + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ButtonIdTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ButtonIdTest.java new file mode 100644 index 00000000..04c6dc18 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ButtonIdTest.java @@ -0,0 +1,56 @@ +/* + * 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.ui.topo; + +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link ButtonId}. + */ +public class ButtonIdTest { + + private static final String ID1 = "id-1"; + private static final String ID2 = "id-2"; + + private ButtonId b1, b2; + + + @Test + public void basic() { + b1 = new ButtonId(ID1); + } + + @Test + public void same() { + b1 = new ButtonId(ID1); + b2 = new ButtonId(ID1); + assertFalse("same ref?", b1 == b2); + assertTrue("not equal?", b1.equals(b2)); + } + + @Test + public void notSame() { + b1 = new ButtonId(ID1); + b2 = new ButtonId(ID2); + assertFalse("same ref?", b1 == b2); + assertFalse("equal?", b1.equals(b2)); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/HighlightsTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/HighlightsTest.java new file mode 100644 index 00000000..7d6dfe67 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/HighlightsTest.java @@ -0,0 +1,91 @@ +/* + * 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.ui.topo; + +import org.junit.Before; +import org.junit.Test; +import org.onosproject.ui.topo.Highlights.Amount; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Unit tests for {@link Highlights}. + */ +public class HighlightsTest { + + private static final String DEV_1 = "dev-1"; + private static final String DEV_2 = "dev-2"; + private static final String HOST_A = "Host...A"; + + private Highlights highlights; + private DeviceHighlight dh1; + private DeviceHighlight dh2; + private HostHighlight hha; + + @Before + public void setUp() { + highlights = new Highlights(); + } + + @Test + public void basic() { + assertEquals("devices", 0, highlights.devices().size()); + assertEquals("hosts", 0, highlights.hosts().size()); + assertEquals("links", 0, highlights.links().size()); + assertEquals("sudue", Amount.ZERO, highlights.subdueLevel()); + } + + @Test + public void coupleOfDevices() { + dh1 = new DeviceHighlight(DEV_1); + dh2 = new DeviceHighlight(DEV_2); + + highlights.add(dh1); + highlights.add(dh2); + assertTrue("missing dh1", highlights.devices().contains(dh1)); + assertTrue("missing dh2", highlights.devices().contains(dh2)); + } + + @Test + public void alternateSubdue() { + highlights.subdueAllElse(Amount.MINIMALLY); + assertEquals("wrong level", Amount.MINIMALLY, highlights.subdueLevel()); + } + + @Test + public void highlightRetrieval() { + dh1 = new DeviceHighlight(DEV_1); + hha = new HostHighlight(HOST_A); + highlights.add(dh1) + .add(hha); + + assertNull("dev as host", highlights.getHost(DEV_1)); + assertNull("host as dev", highlights.getDevice(HOST_A)); + + assertEquals("missed dev as dev", dh1, highlights.getDevice(DEV_1)); + assertEquals("missed dev as node", dh1, highlights.getNode(DEV_1)); + + assertEquals("missed host as host", hha, highlights.getHost(HOST_A)); + assertEquals("missed host as node", hha, highlights.getNode(HOST_A)); + } + + // NOTE: further unit tests involving the Highlights class are done + // in TopoJsonTest. +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/LinkHighlightTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/LinkHighlightTest.java new file mode 100644 index 00000000..205f08ce --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/LinkHighlightTest.java @@ -0,0 +1,116 @@ +/* + * 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.ui.topo; + +import org.junit.Test; + +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onosproject.ui.topo.LinkHighlight.Flavor.*; + +/** + * Unit tests for {@link LinkHighlight}. + */ +public class LinkHighlightTest { + + private static final String LINK_ID = "link-id-for-testing"; + private static final String LABEL = "some label"; + private static final String EMPTY = ""; + private static final String CUSTOM = "custom"; + private static final String ANIMATED = "animated"; + private static final String OPTICAL = "optical"; + + private LinkHighlight lh; + + @Test + public void basic() { + lh = new LinkHighlight(LINK_ID, NO_HIGHLIGHT); + + assertEquals("wrong flavor", NO_HIGHLIGHT, lh.flavor()); + assertTrue("unexpected mods", lh.mods().isEmpty()); + assertEquals("wrong css", "plain", lh.cssClasses()); + assertEquals("wrong label", EMPTY, lh.label()); + } + + @Test + public void primaryOptical() { + lh = new LinkHighlight(LINK_ID, PRIMARY_HIGHLIGHT) + .addMod(LinkHighlight.MOD_OPTICAL); + + assertEquals("wrong flavor", PRIMARY_HIGHLIGHT, lh.flavor()); + assertEquals("missing mod", 1, lh.mods().size()); + Mod m = lh.mods().iterator().next(); + assertEquals("wrong mod", LinkHighlight.MOD_OPTICAL, m); + assertEquals("wrong css", "primary optical", lh.cssClasses()); + assertEquals("wrong label", EMPTY, lh.label()); + } + + @Test + public void secondaryAnimatedWithLabel() { + lh = new LinkHighlight(LINK_ID, SECONDARY_HIGHLIGHT) + .addMod(LinkHighlight.MOD_ANIMATED) + .setLabel(LABEL); + + assertEquals("wrong flavor", SECONDARY_HIGHLIGHT, lh.flavor()); + assertEquals("missing mod", 1, lh.mods().size()); + Mod m = lh.mods().iterator().next(); + assertEquals("wrong mod", LinkHighlight.MOD_ANIMATED, m); + assertEquals("wrong css", "secondary animated", lh.cssClasses()); + assertEquals("wrong label", LABEL, lh.label()); + } + + @Test + public void customMod() { + lh = new LinkHighlight(LINK_ID, PRIMARY_HIGHLIGHT) + .addMod(new Mod(CUSTOM)); + + assertEquals("missing mod", 1, lh.mods().size()); + Mod m = lh.mods().iterator().next(); + assertEquals("wrong mod", CUSTOM, m.toString()); + assertEquals("wrong css", "primary custom", lh.cssClasses()); + } + + @Test + public void severalMods() { + lh = new LinkHighlight(LINK_ID, SECONDARY_HIGHLIGHT) + .addMod(LinkHighlight.MOD_OPTICAL) + .addMod(LinkHighlight.MOD_ANIMATED) + .addMod(new Mod(CUSTOM)); + + assertEquals("missing mods", 3, lh.mods().size()); + Iterator<Mod> iter = lh.mods().iterator(); + // NOTE: we know we are using TreeSet as backing => sorted order + assertEquals("wrong mod", ANIMATED, iter.next().toString()); + assertEquals("wrong mod", CUSTOM, iter.next().toString()); + assertEquals("wrong mod", OPTICAL, iter.next().toString()); + assertEquals("wrong css", "secondary animated custom optical", lh.cssClasses()); + } + + @Test(expected = NullPointerException.class) + public void noFlavor() { + new LinkHighlight(LINK_ID, null); + } + + @Test(expected = NullPointerException.class) + public void noIdentity() { + new LinkHighlight(null, PRIMARY_HIGHLIGHT); + } + +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ModTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ModTest.java new file mode 100644 index 00000000..bb40279c --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/ModTest.java @@ -0,0 +1,62 @@ +/* + * 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.ui.topo; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * Unit tests for {@link Mod}. + */ +public class ModTest { + + private static final String AAA = "aaa"; + private static final String BBB = "bbb"; + + private Mod mod1; + private Mod mod2; + + @Test(expected = NullPointerException.class) + public void nullId() { + new Mod(null); + } + + @Test + public void basic() { + mod1 = new Mod(AAA); + assertEquals("wrong id", AAA, mod1.toString()); + } + + @Test + public void equivalence() { + mod1 = new Mod(AAA); + mod2 = new Mod(AAA); + assertNotSame("oops", mod1, mod2); + assertEquals("not equivalent", mod1, mod2); + } + + @Test + public void comparable() { + mod1 = new Mod(AAA); + mod2 = new Mod(BBB); + assertNotEquals("what?", mod1, mod2); + assertTrue(mod1.compareTo(mod2) < 0); + assertTrue(mod2.compareTo(mod1) > 0); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/NodeSelectionTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/NodeSelectionTest.java new file mode 100644 index 00000000..60cada45 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/NodeSelectionTest.java @@ -0,0 +1,349 @@ +/* + * 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.ui.topo; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.Test; +import org.onlab.packet.ChassisId; +import org.onlab.packet.IpAddress; +import org.onlab.packet.MacAddress; +import org.onlab.packet.VlanId; +import org.onosproject.net.Annotations; +import org.onosproject.net.Device; +import org.onosproject.net.DeviceId; +import org.onosproject.net.Host; +import org.onosproject.net.HostId; +import org.onosproject.net.HostLocation; +import org.onosproject.net.device.DeviceService; +import org.onosproject.net.device.DeviceServiceAdapter; +import org.onosproject.net.host.HostService; +import org.onosproject.net.host.HostServiceAdapter; +import org.onosproject.net.provider.ProviderId; + +import java.util.Set; + +import static org.junit.Assert.*; + +/** + * Unit tests for {@link NodeSelection}. + */ +public class NodeSelectionTest { + + private static class FakeDevice implements Device { + + private final DeviceId id; + + FakeDevice(DeviceId id) { + this.id = id; + } + + @Override + public DeviceId id() { + return id; + } + + @Override + public Type type() { + return null; + } + + @Override + public String manufacturer() { + return null; + } + + @Override + public String hwVersion() { + return null; + } + + @Override + public String swVersion() { + return null; + } + + @Override + public String serialNumber() { + return null; + } + + @Override + public ChassisId chassisId() { + return null; + } + + @Override + public Annotations annotations() { + return null; + } + + @Override + public ProviderId providerId() { + return null; + } + } + + private static class FakeHost implements Host { + + private final HostId id; + + FakeHost(HostId id) { + this.id = id; + } + + @Override + public HostId id() { + return id; + } + + @Override + public MacAddress mac() { + return null; + } + + @Override + public VlanId vlan() { + return null; + } + + @Override + public Set<IpAddress> ipAddresses() { + return null; + } + + @Override + public HostLocation location() { + return null; + } + + @Override + public Annotations annotations() { + return null; + } + + @Override + public ProviderId providerId() { + return null; + } + } + + + + private final ObjectMapper mapper = new ObjectMapper(); + + private static final String IDS = "ids"; + private static final String HOVER = "hover"; + + private static final DeviceId DEVICE_1_ID = DeviceId.deviceId("Device-1"); + private static final DeviceId DEVICE_2_ID = DeviceId.deviceId("Device-2"); + private static final HostId HOST_A_ID = HostId.hostId("aa:aa:aa:aa:aa:aa/1"); + private static final HostId HOST_B_ID = HostId.hostId("bb:bb:bb:bb:bb:bb/2"); + + private static final Device DEVICE_1 = new FakeDevice(DEVICE_1_ID); + private static final Device DEVICE_2 = new FakeDevice(DEVICE_2_ID); + private static final Host HOST_A = new FakeHost(HOST_A_ID); + private static final Host HOST_B = new FakeHost(HOST_B_ID); + + // ================== + // == FAKE SERVICES + private static class FakeDevices extends DeviceServiceAdapter { + @Override + public Device getDevice(DeviceId deviceId) { + if (DEVICE_1_ID.equals(deviceId)) { + return DEVICE_1; + } + if (DEVICE_2_ID.equals(deviceId)) { + return DEVICE_2; + } + return null; + } + } + + private static class FakeHosts extends HostServiceAdapter { + @Override + public Host getHost(HostId hostId) { + if (HOST_A_ID.equals(hostId)) { + return HOST_A; + } + if (HOST_B_ID.equals(hostId)) { + return HOST_B; + } + return null; + } + } + + private DeviceService deviceService = new FakeDevices(); + private HostService hostService = new FakeHosts(); + + private NodeSelection ns; + + private ObjectNode objectNode() { + return mapper.createObjectNode(); + } + + private ArrayNode arrayNode() { + return mapper.createArrayNode(); + } + + private NodeSelection createNodeSelection(ObjectNode payload) { + return new NodeSelection(payload, deviceService, hostService); + } + + // selection JSON payload creation methods + private ObjectNode emptySelection() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + return payload; + } + + private ObjectNode oneDeviceSelected() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + ids.add(DEVICE_1_ID.toString()); + return payload; + } + + private ObjectNode oneHostSelected() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + ids.add(HOST_A_ID.toString()); + return payload; + } + + private ObjectNode twoHostsOneDeviceSelected() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + ids.add(HOST_A_ID.toString()); + ids.add(DEVICE_1_ID.toString()); + ids.add(HOST_B_ID.toString()); + return payload; + } + + private ObjectNode oneHostAndHoveringDeviceSelected() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + ids.add(HOST_A_ID.toString()); + payload.put(HOVER, DEVICE_2_ID.toString()); + return payload; + } + + private ObjectNode twoDevicesOneHostAndHoveringHostSelected() { + ObjectNode payload = objectNode(); + ArrayNode ids = arrayNode(); + payload.set(IDS, ids); + ids.add(HOST_A_ID.toString()); + ids.add(DEVICE_1_ID.toString()); + ids.add(DEVICE_2_ID.toString()); + payload.put(HOVER, HOST_B_ID.toString()); + return payload; + } + + + @Test + public void basic() { + ns = createNodeSelection(emptySelection()); + assertEquals("unexpected devices", 0, ns.devices().size()); + assertEquals("unexpected devices w/hover", 0, ns.devicesWithHover().size()); + assertEquals("unexpected hosts", 0, ns.hosts().size()); + assertEquals("unexpected hosts w/hover", 0, ns.hostsWithHover().size()); + assertTrue("unexpected selection", ns.none()); + assertNull("hover?", ns.hovered()); + } + + @Test + public void oneDevice() { + ns = createNodeSelection(oneDeviceSelected()); + assertEquals("missing device", 1, ns.devices().size()); + assertTrue("missing device 1", ns.devices().contains(DEVICE_1)); + assertEquals("missing device w/hover", 1, ns.devicesWithHover().size()); + assertTrue("missing device 1 w/hover", ns.devicesWithHover().contains(DEVICE_1)); + assertEquals("unexpected hosts", 0, ns.hosts().size()); + assertEquals("unexpected hosts w/hover", 0, ns.hostsWithHover().size()); + assertFalse("unexpected selection", ns.none()); + assertNull("hover?", ns.hovered()); + } + + @Test + public void oneHost() { + ns = createNodeSelection(oneHostSelected()); + assertEquals("unexpected devices", 0, ns.devices().size()); + assertEquals("unexpected devices w/hover", 0, ns.devicesWithHover().size()); + assertEquals("missing host", 1, ns.hosts().size()); + assertTrue("missing host A", ns.hosts().contains(HOST_A)); + assertEquals("missing host w/hover", 1, ns.hostsWithHover().size()); + assertTrue("missing host A w/hover", ns.hostsWithHover().contains(HOST_A)); + assertFalse("unexpected selection", ns.none()); + assertNull("hover?", ns.hovered()); + } + + @Test + public void twoHostsOneDevice() { + ns = createNodeSelection(twoHostsOneDeviceSelected()); + assertEquals("missing device", 1, ns.devices().size()); + assertTrue("missing device 1", ns.devices().contains(DEVICE_1)); + assertEquals("missing device w/hover", 1, ns.devicesWithHover().size()); + assertTrue("missing device 1 w/hover", ns.devicesWithHover().contains(DEVICE_1)); + assertEquals("unexpected hosts", 2, ns.hosts().size()); + assertTrue("missing host A", ns.hosts().contains(HOST_A)); + assertTrue("missing host B", ns.hosts().contains(HOST_B)); + assertEquals("unexpected hosts w/hover", 2, ns.hostsWithHover().size()); + assertTrue("missing host A w/hover", ns.hostsWithHover().contains(HOST_A)); + assertTrue("missing host B w/hover", ns.hostsWithHover().contains(HOST_B)); + assertFalse("unexpected selection", ns.none()); + assertNull("hover?", ns.hovered()); + } + + @Test + public void oneHostAndHoveringDevice() { + ns = createNodeSelection(oneHostAndHoveringDeviceSelected()); + assertEquals("unexpected devices", 0, ns.devices().size()); + assertEquals("unexpected devices w/hover", 1, ns.devicesWithHover().size()); + assertTrue("missing device 2 w/hover", ns.devicesWithHover().contains(DEVICE_2)); + assertEquals("missing host", 1, ns.hosts().size()); + assertTrue("missing host A", ns.hosts().contains(HOST_A)); + assertEquals("missing host w/hover", 1, ns.hostsWithHover().size()); + assertTrue("missing host A w/hover", ns.hostsWithHover().contains(HOST_A)); + assertFalse("unexpected selection", ns.none()); + assertEquals("missing hover device 2", DEVICE_2, ns.hovered()); + } + + @Test + public void twoDevicesOneHostAndHoveringHost() { + ns = createNodeSelection(twoDevicesOneHostAndHoveringHostSelected()); + assertEquals("missing devices", 2, ns.devices().size()); + assertTrue("missing device 1", ns.devices().contains(DEVICE_1)); + assertTrue("missing device 2", ns.devices().contains(DEVICE_2)); + assertEquals("missing devices w/hover", 2, ns.devicesWithHover().size()); + assertTrue("missing device 1 w/hover", ns.devicesWithHover().contains(DEVICE_1)); + assertTrue("missing device 2 w/hover", ns.devicesWithHover().contains(DEVICE_2)); + assertEquals("missing host", 1, ns.hosts().size()); + assertTrue("missing host A", ns.hosts().contains(HOST_A)); + assertEquals("missing host w/hover", 2, ns.hostsWithHover().size()); + assertTrue("missing host A w/hover", ns.hostsWithHover().contains(HOST_A)); + assertTrue("missing host B w/hover", ns.hostsWithHover().contains(HOST_B)); + assertFalse("unexpected selection", ns.none()); + assertEquals("missing hover host B", HOST_B, ns.hovered()); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/PropertyPanelTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/PropertyPanelTest.java new file mode 100644 index 00000000..b08ee4dc --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/PropertyPanelTest.java @@ -0,0 +1,238 @@ +/* + * 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.ui.topo; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onosproject.ui.topo.PropertyPanel.Prop; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import static org.junit.Assert.*; + +/** + * Unit tests for {@link PropertyPanel}. + */ +public class PropertyPanelTest { + + private static final String TITLE_ORIG = "Original Title"; + private static final String TYPE_ORIG = "Original type ID"; + private static final String TITLE_NEW = "New Title"; + private static final String TYPE_NEW = "New type"; + private static final String SOME_IDENTIFICATION = "It's Me!"; + + private static final String KEY_A = "A"; + private static final String KEY_B = "B"; + private static final String KEY_C = "C"; + private static final String SEP = "-"; + private static final String KEY_Z = "Z"; + private static final String VALUE_A = "Hay"; + private static final String VALUE_B = "Bee"; + private static final String VALUE_C = "Sea"; + private static final String VALUE_Z = "Zed"; + + private static final Map<String, Prop> PROP_MAP = new HashMap<>(); + + private static class FooClass { + private final String s; + FooClass(String s) { + this.s = s; + } + + @Override + public String toString() { + return ">" + s + "<"; + } + } + + private PropertyPanel pp; + + + + @BeforeClass + public static void setUpClass() { + PROP_MAP.put(KEY_A, new Prop(KEY_A, VALUE_A)); + PROP_MAP.put(KEY_B, new Prop(KEY_B, VALUE_B)); + PROP_MAP.put(KEY_C, new Prop(KEY_C, VALUE_C)); + PROP_MAP.put(KEY_Z, new Prop(KEY_Z, VALUE_Z)); + PROP_MAP.put(SEP, new PropertyPanel.Separator()); + } + + @Test + public void basic() { + pp = new PropertyPanel(TITLE_ORIG, TYPE_ORIG); + assertEquals("wrong title", TITLE_ORIG, pp.title()); + assertEquals("wrong type", TYPE_ORIG, pp.typeId()); + assertNull("id?", pp.id()); + assertEquals("unexpected props", 0, pp.properties().size()); + assertEquals("unexpected buttons", 0, pp.buttons().size()); + } + + @Test + public void changeTitle() { + basic(); + pp.title(TITLE_NEW); + assertEquals("wrong title", TITLE_NEW, pp.title()); + } + + @Test + public void changeType() { + basic(); + pp.typeId(TYPE_NEW); + assertEquals("wrong type", TYPE_NEW, pp.typeId()); + } + + @Test + public void setId() { + basic(); + pp.id(SOME_IDENTIFICATION); + assertEquals("wrong id", SOME_IDENTIFICATION, pp.id()); + } + + private void validateProps(String... keys) { + Iterator<Prop> iter = pp.properties().iterator(); + for (String k: keys) { + Prop exp = PROP_MAP.get(k); + Prop act = iter.next(); + assertEquals("Bad prop sequence", exp, act); + } + } + + private void validateProp(String key, String expValue) { + Iterator<Prop> iter = pp.properties().iterator(); + Prop prop = null; + while (iter.hasNext()) { + Prop p = iter.next(); + if (p.key().equals(key)) { + prop = p; + break; + } + } + if (prop == null) { + fail("no prop found with key: " + key); + } + assertEquals("Wrong prop value", expValue, prop.value()); + } + + @Test + public void props() { + basic(); + pp.addProp(KEY_A, VALUE_A) + .addProp(KEY_B, VALUE_B) + .addProp(KEY_C, VALUE_C); + assertEquals("bad props", 3, pp.properties().size()); + validateProps(KEY_A, KEY_B, KEY_C); + } + + @Test + public void separator() { + props(); + pp.addSeparator() + .addProp(KEY_Z, VALUE_Z); + + assertEquals("bad props", 5, pp.properties().size()); + validateProps(KEY_A, KEY_B, KEY_C, SEP, KEY_Z); + } + + @Test + public void removeAllProps() { + props(); + assertEquals("wrong props", 3, pp.properties().size()); + pp.removeAllProps(); + assertEquals("unexpected props", 0, pp.properties().size()); + } + + @Test + public void adjustProps() { + props(); + pp.removeProps(KEY_B, KEY_A); + pp.addProp(KEY_Z, VALUE_Z); + validateProps(KEY_C, KEY_Z); + } + + @Test + public void intValues() { + basic(); + pp.addProp(KEY_A, 200) + .addProp(KEY_B, 2000) + .addProp(KEY_C, 1234567); + + validateProp(KEY_A, "200"); + validateProp(KEY_B, "2,000"); + validateProp(KEY_C, "1,234,567"); + } + + @Test + public void longValues() { + basic(); + pp.addProp(KEY_A, 200L) + .addProp(KEY_B, 2000L) + .addProp(KEY_C, 1234567L) + .addProp(KEY_Z, Long.MAX_VALUE); + + validateProp(KEY_A, "200"); + validateProp(KEY_B, "2,000"); + validateProp(KEY_C, "1,234,567"); + validateProp(KEY_Z, "9,223,372,036,854,775,807"); + } + + @Test + public void objectValue() { + basic(); + pp.addProp(KEY_A, new FooClass("a")) + .addProp(KEY_B, new FooClass("bxyyzy"), "[xz]"); + + validateProp(KEY_A, ">a<"); + validateProp(KEY_B, ">byyy<"); + } + + private static final ButtonId BD_A = new ButtonId(KEY_A); + private static final ButtonId BD_B = new ButtonId(KEY_B); + private static final ButtonId BD_C = new ButtonId(KEY_C); + private static final ButtonId BD_Z = new ButtonId(KEY_Z); + + private void verifyButtons(String... keys) { + Iterator<ButtonId> iter = pp.buttons().iterator(); + for (String k: keys) { + assertEquals("wrong button", k, iter.next().id()); + } + assertFalse("too many buttons", iter.hasNext()); + } + + @Test + public void buttons() { + basic(); + pp.addButton(BD_A) + .addButton(BD_B); + assertEquals("wrong buttons", 2, pp.buttons().size()); + verifyButtons(KEY_A, KEY_B); + + pp.removeButtons(BD_B) + .addButton(BD_C) + .addButton(BD_Z); + assertEquals("wrong buttons", 3, pp.buttons().size()); + verifyButtons(KEY_A, KEY_C, KEY_Z); + + pp.removeAllButtons() + .addButton(BD_B); + assertEquals("wrong buttons", 1, pp.buttons().size()); + verifyButtons(KEY_B); + } +} diff --git a/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/TopoJsonTest.java b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/TopoJsonTest.java new file mode 100644 index 00000000..6a3bfa43 --- /dev/null +++ b/framework/src/onos/core/api/src/test/java/org/onosproject/ui/topo/TopoJsonTest.java @@ -0,0 +1,72 @@ +/* + * 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.ui.topo; + +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.Test; +import org.onosproject.ui.JsonUtils; +import org.onosproject.ui.topo.Highlights.Amount; + +import static org.junit.Assert.assertEquals; + +/** + * Unit tests for {@link TopoJson}. + */ +public class TopoJsonTest { + + private ObjectNode payload; + + private void checkArrayLength(String key, int expLen) { + ArrayNode a = (ArrayNode) payload.get(key); + assertEquals("wrong size: " + key, expLen, a.size()); + } + + private void checkEmptyArrays() { + checkArrayLength(TopoJson.DEVICES, 0); + checkArrayLength(TopoJson.HOSTS, 0); + checkArrayLength(TopoJson.LINKS, 0); + } + + @Test + public void basicHighlights() { + Highlights h = new Highlights(); + payload = TopoJson.json(h); + checkEmptyArrays(); + String subdue = JsonUtils.string(payload, TopoJson.SUBDUE); + assertEquals("subdue", "", subdue); + } + + @Test + public void subdueMinimalHighlights() { + Highlights h = new Highlights().subdueAllElse(Amount.MINIMALLY); + payload = TopoJson.json(h); + checkEmptyArrays(); + String subdue = JsonUtils.string(payload, TopoJson.SUBDUE); + assertEquals("not min", "min", subdue); + } + + @Test + public void subdueMaximalHighlights() { + Highlights h = new Highlights().subdueAllElse(Amount.MAXIMALLY); + payload = TopoJson.json(h); + checkEmptyArrays(); + String subdue = JsonUtils.string(payload, TopoJson.SUBDUE); + assertEquals("not max", "max", subdue); + } +} |