diff options
author | Maros Marsalek <mmarsale@cisco.com> | 2016-07-29 16:27:12 +0200 |
---|---|---|
committer | Maros Marsalek <mmarsale@cisco.com> | 2016-07-29 16:32:17 +0200 |
commit | e3c31cee916480b2d9d169c1f5afb1c42efaabe1 (patch) | |
tree | c88b0ca3e7296dd7e68628db6d5f33ffd1e1b55e /v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate | |
parent | 0578156b721fa01c8c645b8f9625ecebdb6449e4 (diff) |
HONEYCOMB-130: Rename infra packages(remove vpp/v3po)
Change-Id: Ic5b90e397e3743623d01b206bc60bc5c7df6b981
Signed-off-by: Maros Marsalek <mmarsale@cisco.com>
Diffstat (limited to 'v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate')
39 files changed, 6465 insertions, 0 deletions
diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/InterfacesInitializerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/InterfacesInitializerTest.java new file mode 100644 index 000000000..3dc74a3e5 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/InterfacesInitializerTest.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.initializers; + +import static org.junit.Assert.assertEquals; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.Arrays; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.EthernetCsmacd; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesStateBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; + +public class InterfacesInitializerTest { + + @Mock + private DataBroker bindingDataBroker; + + private InterfacesInitializer interfacesInitializer; + + @Before + public void setUp() { + initMocks(this); + interfacesInitializer = new InterfacesInitializer(bindingDataBroker); + } + + @Test + public void testConvert() throws Exception { + final InterfacesState operationalData = operationalData(); + final Interfaces expectedConfigData = expectedConfigData(); + + final Interfaces configData = interfacesInitializer.convert(operationalData); + assertEquals(expectedConfigData, configData); + } + + private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface operInterface( + String name, Class<? extends InterfaceType> inerfaceType, Interface.AdminStatus adminStatus) { + final org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder + iface = + new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder(); + iface.setKey( + new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey( + name)); + iface.setName(name); + iface.setType(inerfaceType); + iface.setAdminStatus(adminStatus); + return iface.build(); + } + + private InterfacesState operationalData() { + final InterfacesStateBuilder builder = new InterfacesStateBuilder(); + builder.setInterface( + Arrays.asList( + operInterface("eth1", EthernetCsmacd.class, Interface.AdminStatus.Up), + operInterface("eth2", EthernetCsmacd.class, Interface.AdminStatus.Down) + )); + return builder.build(); + } + + private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface configInterface( + String name, Class<? extends InterfaceType> inerfaceType, boolean isEnabled) { + final org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder + iface = + new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder(); + iface.setKey( + new org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey( + name)); + iface.setName(name); + iface.setType(inerfaceType); + iface.setEnabled(isEnabled); + return iface.build(); + } + + private Interfaces expectedConfigData() { + final InterfacesBuilder builder = new InterfacesBuilder(); + + builder.setInterface( + Arrays.asList( + configInterface("eth1", EthernetCsmacd.class, true), + configInterface("eth2", EthernetCsmacd.class, false) + )); + return builder.build(); + } + +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/VppInitializerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/VppInitializerTest.java new file mode 100644 index 000000000..48a35c371 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/initializers/VppInitializerTest.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.initializers; + +import static org.junit.Assert.assertEquals; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.util.Arrays; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.opendaylight.controller.md.sal.binding.api.DataBroker; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.Vpp; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppStateBuilder; + +public class VppInitializerTest { + + @Mock + private DataBroker bindingDataBroker; + + private VppInitializer vppInitializer; + + @Before + public void setUp() throws Exception { + initMocks(this); + vppInitializer = new VppInitializer(bindingDataBroker); + } + + @Test + public void testConvert() throws Exception { + final VppState operationalData = operationalData(); + final Vpp expectedConfigData = expectedConfigData(); + final Vpp configData = vppInitializer.convert(operationalData); + assertEquals(expectedConfigData, configData); + } + + private org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomain + operBd(String name, boolean learn, boolean unknownUnicastFlood, boolean arpTermination, boolean flood, + boolean forward) { + final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainBuilder + bd = + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainBuilder(); + bd.setName(name); + bd.setKey( + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainKey( + name)); + bd.setLearn(learn); + bd.setUnknownUnicastFlood(unknownUnicastFlood); + bd.setArpTermination(arpTermination); + bd.setFlood(flood); + bd.setForward(forward); + return bd.build(); + } + + private VppState operationalData() { + final VppStateBuilder builder = new VppStateBuilder(); + + final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomainsBuilder + bdBuilder = + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomainsBuilder(); + bdBuilder.setBridgeDomain(Arrays.asList( + operBd("b1", true, true, true, true, true), + operBd("b2", false, false, false, false, false) + )); + builder.setBridgeDomains(bdBuilder.build()); + return builder.build(); + } + + private org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomain + configBd(String name, boolean learn, boolean unknownUnicastFlood, boolean arpTermination, boolean flood, + boolean forward) { + final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainBuilder + bd = + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainBuilder(); + bd.setName(name); + bd.setKey( + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainKey( + name)); + bd.setLearn(learn); + bd.setUnknownUnicastFlood(unknownUnicastFlood); + bd.setArpTermination(arpTermination); + bd.setFlood(flood); + bd.setForward(forward); + return bd.build(); + } + + private Vpp expectedConfigData() { + final VppBuilder builder = new VppBuilder(); + + final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.BridgeDomainsBuilder + bdBuilder = + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.BridgeDomainsBuilder(); + bdBuilder.setBridgeDomain(Arrays.asList( + configBd("b1", true, true, true, true, true), + configBd("b2", false, false, false, false, false) + )); + builder.setBridgeDomains(bdBuilder.build()); + return builder.build(); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/AclCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/AclCustomizerTest.java new file mode 100644 index 000000000..af9799a99 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/AclCustomizerTest.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMapping; +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMappingIid; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.acl.base.attributes.L2Acl; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.acl.base.attributes.L2AclBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.Acl; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.AclBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.InputAclSetInterface; +import org.openvpp.jvpp.dto.InputAclSetInterfaceReply; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewriteReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class AclCustomizerTest { + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext interfaceContext; + private NamingContext classifyTableContext; + private AclCustomizer customizer; + + private static final String IFC_TEST_INSTANCE = "ifc-test-instance"; + private static final String CT_TEST_INSTANCE = "ct-test-instance"; + private static final String IF_NAME = "local0"; + private static final int IF_INDEX = 1; + + private static final int ACL_TABLE_INDEX = 0; + private static final String ACL_TABLE_NAME = "table0"; + + @Before + public void setUp() throws Exception { + initMocks(this); + interfaceContext = new NamingContext("generatedInterfaceName", IFC_TEST_INSTANCE); + classifyTableContext = new NamingContext("generatedClassifyTable", CT_TEST_INSTANCE); + doReturn(mappingContext).when(writeContext).getMappingContext(); + customizer = new AclCustomizer(api, interfaceContext, classifyTableContext); + + final KeyedInstanceIdentifier<Mapping, MappingKey> ifcMappingKey = getMappingIid(IF_NAME, IFC_TEST_INSTANCE); + final Optional<Mapping> ifcMapping = getMapping(IF_NAME, IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(ifcMappingKey); + + final KeyedInstanceIdentifier<Mapping, MappingKey> ctMappingKey = + getMappingIid(ACL_TABLE_NAME, CT_TEST_INSTANCE); + final Optional<Mapping> ctMapping = getMapping(ACL_TABLE_NAME, ACL_TABLE_INDEX); + doReturn(ctMapping).when(mappingContext).read(ctMappingKey); + + final List<Mapping> allCtMappings = Lists.newArrayList(ctMapping.get()); + final Mappings allCtMappingsBaObject = new MappingsBuilder().setMapping(allCtMappings).build(); + doReturn(Optional.of(allCtMappingsBaObject)).when(mappingContext) + .read(ctMappingKey.firstIdentifierOf(Mappings.class)); + } + + + private InstanceIdentifier<Acl> getAclId(final String name) { + return InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(name)).augmentation( + VppInterfaceAugmentation.class).child(Acl.class); + } + + private Acl generateAcl(final String tableName) { + final AclBuilder builder = new AclBuilder(); + final L2Acl l2Acl = new L2AclBuilder().setClassifyTable(tableName).build(); + builder.setL2Acl(l2Acl); + return builder.build(); + } + + private void whenInputAclSetInterfaceThenSuccess() throws ExecutionException, InterruptedException { + final CompletableFuture<InputAclSetInterfaceReply> replyFuture = new CompletableFuture<>(); + final InputAclSetInterfaceReply reply = new InputAclSetInterfaceReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).inputAclSetInterface(any(InputAclSetInterface.class)); + } + + private void whenInputAclSetInterfaceThenFailure() throws ExecutionException, InterruptedException { + doReturn(TestHelperUtils.<L2InterfaceVlanTagRewriteReply>createFutureException()).when(api) + .inputAclSetInterface(any(InputAclSetInterface.class)); + } + + private void verifyInputAclSetInterfaceWasInvoked(final InputAclSetInterface expected) { + final ArgumentCaptor<InputAclSetInterface> argumentCaptor = ArgumentCaptor.forClass(InputAclSetInterface.class); + verify(api).inputAclSetInterface(argumentCaptor.capture()); + final InputAclSetInterface actual = argumentCaptor.getValue(); + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.l2TableIndex, actual.l2TableIndex); + assertEquals(expected.ip4TableIndex, actual.ip4TableIndex); + assertEquals(expected.ip6TableIndex, actual.ip6TableIndex); + assertEquals(expected.isAdd, actual.isAdd); + } + + private void verifyInputAclSetInterfaceDisableWasInvoked(final InputAclSetInterface expected) { + final ArgumentCaptor<InputAclSetInterface> argumentCaptor = ArgumentCaptor.forClass(InputAclSetInterface.class); + verify(api).inputAclSetInterface(argumentCaptor.capture()); + final InputAclSetInterface actual = argumentCaptor.getValue(); + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.l2TableIndex, actual.l2TableIndex); + assertEquals(0, actual.isAdd); + } + + private static InputAclSetInterface generateInputAclSetInterface(final byte isAdd, final int ifIndex, + final int l2TableIndex) { + final InputAclSetInterface request = new InputAclSetInterface(); + request.isAdd = isAdd; + request.l2TableIndex = l2TableIndex; + request.ip4TableIndex = ~0; + request.ip6TableIndex = ~0; + request.swIfIndex = ifIndex; + return request; + } + + @Test + public void testCreate() throws Exception { + final Acl acl = generateAcl(ACL_TABLE_NAME); + final InstanceIdentifier<Acl> id = getAclId(IF_NAME); + + whenInputAclSetInterfaceThenSuccess(); + + customizer.writeCurrentAttributes(id, acl, writeContext); + + verifyInputAclSetInterfaceWasInvoked(generateInputAclSetInterface((byte) 1, IF_INDEX, ACL_TABLE_INDEX)); + } + + @Test + public void testCreateFailed() throws Exception { + final Acl acl = generateAcl(ACL_TABLE_NAME); + final InstanceIdentifier<Acl> id = getAclId(IF_NAME); + + whenInputAclSetInterfaceThenFailure(); + + try { + customizer.writeCurrentAttributes(id, acl, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyInputAclSetInterfaceWasInvoked(generateInputAclSetInterface((byte) 1, IF_INDEX, ACL_TABLE_INDEX)); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testDelete() throws Exception { + final Acl acl = generateAcl(ACL_TABLE_NAME); + final InstanceIdentifier<Acl> id = getAclId(IF_NAME); + + whenInputAclSetInterfaceThenSuccess(); + + customizer.deleteCurrentAttributes(id, acl, writeContext); + + verifyInputAclSetInterfaceDisableWasInvoked(generateInputAclSetInterface((byte) 0, IF_INDEX, ACL_TABLE_INDEX)); + } + + @Test + public void testDeleteFailed() throws Exception { + final Acl acl = generateAcl(ACL_TABLE_NAME); + final InstanceIdentifier<Acl> id = getAclId(IF_NAME); + + whenInputAclSetInterfaceThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, acl, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyInputAclSetInterfaceDisableWasInvoked( + generateInputAclSetInterface((byte) 0, IF_INDEX, ACL_TABLE_INDEX)); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/InterfaceTypeTestUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/InterfaceTypeTestUtils.java new file mode 100644 index 000000000..0dabe1468 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/InterfaceTypeTestUtils.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static org.mockito.Mockito.doReturn; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.ModificationCache; +import org.mockito.Matchers; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfaceType; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +final class InterfaceTypeTestUtils { + + private InterfaceTypeTestUtils() {} + + static void setupWriteContext(final WriteContext writeContext, final Class<? extends InterfaceType> ifcType) { + doReturn(new ModificationCache()).when(writeContext).getModificationCache(); + doReturn(Optional.of(new InterfaceBuilder() + .setType(ifcType) + .build())).when(writeContext).readAfter(Matchers.any(InstanceIdentifier.class)); + } + +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/RewriteCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/RewriteCustomizerTest.java new file mode 100644 index 000000000..1b35dfed2 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/RewriteCustomizerTest.java @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.v3po.util.TagRewriteOperation; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.SubinterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527._802dot1q; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.SubInterfaces; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.sub.interfaces.SubInterface; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.sub.interfaces.SubInterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.l2.Rewrite; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.l2.RewriteBuilder; +import org.opendaylight.yangtools.yang.binding.ChildOf; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewrite; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewriteReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class RewriteCustomizerTest { + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext namingContext; + private RewriteCustomizer customizer; + + public static final String VLAN_IF_NAME = "local0.1"; + public static final int VLAN_IF_ID = 1; + public static final int VLAN_IF_INDEX = 11; + + @Before + public void setUp() throws Exception { + initMocks(this); + namingContext = new NamingContext("generatedSubInterfaceName", "test-instance"); + doReturn(mappingContext).when(writeContext).getMappingContext(); + customizer = new RewriteCustomizer(api, namingContext); + + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(VLAN_IF_NAME, VLAN_IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + } + + private InstanceIdentifier<Rewrite> getVlanTagRewriteId(final String name, final long index) { + final Class<ChildOf<? super SubInterface>> child = (Class)Rewrite.class; + final InstanceIdentifier id = + InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(name)).augmentation( + SubinterfaceAugmentation.class).child(SubInterfaces.class) + .child(SubInterface.class, new SubInterfaceKey(index)) + .child(child); + return id; + } + + private Rewrite generateRewrite(final TagRewriteOperation op) { + final RewriteBuilder builder = new RewriteBuilder(); + builder.setPopTags((short) op.getPopTags()); + builder.setVlanType(_802dot1q.class); + return builder.build(); + } + + private L2InterfaceVlanTagRewrite generateL2InterfaceVlanTagRewrite(final int swIfIndex, + final TagRewriteOperation op) { + final L2InterfaceVlanTagRewrite request = new L2InterfaceVlanTagRewrite(); + request.swIfIndex = swIfIndex; + request.vtrOp = op.ordinal(); + request.pushDot1Q = 1; + return request; + } + + /** + * Positive response + */ + private void whenL2InterfaceVlanTagRewriteThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException { + final CompletableFuture<L2InterfaceVlanTagRewriteReply> replyFuture = new CompletableFuture<>(); + final L2InterfaceVlanTagRewriteReply reply = new L2InterfaceVlanTagRewriteReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).l2InterfaceVlanTagRewrite(any(L2InterfaceVlanTagRewrite.class)); + } + + /** + * Failure response send + */ + private void whenL2InterfaceVlanTagRewriteThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<L2InterfaceVlanTagRewriteReply>createFutureException()).when(api) + .l2InterfaceVlanTagRewrite(any(L2InterfaceVlanTagRewrite.class)); + } + + private void verifyL2InterfaceVlanTagRewriteWasInvoked(final L2InterfaceVlanTagRewrite expected) + throws VppInvocationException { + ArgumentCaptor<L2InterfaceVlanTagRewrite> argumentCaptor = + ArgumentCaptor.forClass(L2InterfaceVlanTagRewrite.class); + verify(api).l2InterfaceVlanTagRewrite(argumentCaptor.capture()); + final L2InterfaceVlanTagRewrite actual = argumentCaptor.getValue(); + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.vtrOp, actual.vtrOp); + assertEquals(expected.pushDot1Q, actual.pushDot1Q); + assertEquals(expected.tag1, actual.tag1); + assertEquals(expected.tag2, actual.tag2); + } + + private void verifyL2InterfaceVlanTagRewriteDeleteWasInvoked() throws VppInvocationException { + final L2InterfaceVlanTagRewrite request = new L2InterfaceVlanTagRewrite(); + request.swIfIndex = VLAN_IF_INDEX; + verifyL2InterfaceVlanTagRewriteWasInvoked(request); + } + + @Test + public void testCreate() throws Exception { + final TagRewriteOperation op = TagRewriteOperation.pop_2; + final Rewrite vlanTagRewrite = generateRewrite(op); + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID); + + whenL2InterfaceVlanTagRewriteThenSuccess(); + + customizer.writeCurrentAttributes(id, vlanTagRewrite, writeContext); + + verifyL2InterfaceVlanTagRewriteWasInvoked(generateL2InterfaceVlanTagRewrite(VLAN_IF_INDEX, op)); + } + + @Test + public void testCreateFailed() throws Exception { + final TagRewriteOperation op = TagRewriteOperation.pop_2; + final Rewrite vlanTagRewrite = generateRewrite(op); + final String subIfaceName = "local0.11"; + final int subifIndex = 1; + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(subIfaceName, subifIndex); + + whenL2InterfaceVlanTagRewriteThenFailure(); + + try { + customizer.writeCurrentAttributes(id, vlanTagRewrite, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyL2InterfaceVlanTagRewriteWasInvoked(generateL2InterfaceVlanTagRewrite(VLAN_IF_INDEX, op)); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testUpdate() throws Exception { + final Rewrite before = generateRewrite(TagRewriteOperation.pop_2); + final Rewrite after = generateRewrite(TagRewriteOperation.pop_1); + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID); + + whenL2InterfaceVlanTagRewriteThenSuccess(); + + customizer.updateCurrentAttributes(id, before, after, writeContext); + + verifyL2InterfaceVlanTagRewriteWasInvoked( + generateL2InterfaceVlanTagRewrite(VLAN_IF_INDEX, TagRewriteOperation.pop_1)); + } + + @Test + public void testUpdateFailed() throws Exception { + final Rewrite before = generateRewrite(TagRewriteOperation.pop_2); + final Rewrite after = generateRewrite(TagRewriteOperation.pop_1); + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID); + + whenL2InterfaceVlanTagRewriteThenFailure(); + + try { + customizer.updateCurrentAttributes(id, before, after, writeContext); + } catch (WriteFailedException.UpdateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyL2InterfaceVlanTagRewriteWasInvoked(generateL2InterfaceVlanTagRewrite(VLAN_IF_INDEX, + TagRewriteOperation.pop_1)); + return; + } + fail("WriteFailedException.UpdateFailedException was expected"); + } + + @Test + public void testDelete() throws Exception { + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID); + + whenL2InterfaceVlanTagRewriteThenSuccess(); + + customizer.deleteCurrentAttributes(id, null, writeContext); + + verifyL2InterfaceVlanTagRewriteDeleteWasInvoked(); + } + + @Test + public void testDeleteFailed() throws Exception { + final InstanceIdentifier<Rewrite> id = getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID); + + whenL2InterfaceVlanTagRewriteThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, null, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + Assert.assertTrue(e.getCause() instanceof VppBaseCallException); + verifyL2InterfaceVlanTagRewriteDeleteWasInvoked(); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/SubInterfaceCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/SubInterfaceCustomizerTest.java new file mode 100644 index 000000000..deecc6c83 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/SubInterfaceCustomizerTest.java @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.CVlan; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.Dot1qTagVlanType; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.Dot1qVlanId; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.SVlan; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.dot1q.tag.or.any.Dot1qTag; +import org.opendaylight.yang.gen.v1.urn.ieee.params.xml.ns.yang.dot1q.types.rev150626.dot1q.tag.or.any.Dot1qTagBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.SubinterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527._802dot1ad; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.SubInterfaces; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.sub.interfaces.SubInterface; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.sub.interfaces.SubInterfaceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces._interface.sub.interfaces.SubInterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.match.attributes.match.type.vlan.tagged.VlanTaggedBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.Match; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.MatchBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.TagsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.tags.Tag; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.tags.TagBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.tags.TagKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.CreateSubif; +import org.openvpp.jvpp.dto.CreateSubifReply; +import org.openvpp.jvpp.dto.SwInterfaceSetFlags; +import org.openvpp.jvpp.dto.SwInterfaceSetFlagsReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class SubInterfaceCustomizerTest { + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext namingContext; + private SubInterfaceCustomizer customizer; + + public static final String SUPER_IF_NAME = "local0"; + public static final int SUPER_IF_ID = 1; + private static final String SUB_IFACE_NAME = "local0.11"; + private static final int SUBIF_INDEX = 11; + + private static final short STAG_ID = 100; + private static final short CTAG_ID = 200; + private static final short CTAG_ANY_ID = 0; // only the *IdAny flag is set + + private final Tag STAG_100; + private final Tag CTAG_200; + private final Tag CTAG_ANY; + + public SubInterfaceCustomizerTest() { + STAG_100 = generateTag((short) 0, SVlan.class, new Dot1qTag.VlanId(new Dot1qVlanId((int) STAG_ID))); + CTAG_200 = generateTag((short) 1, CVlan.class, new Dot1qTag.VlanId(new Dot1qVlanId(200))); + CTAG_ANY = generateTag((short) 1, CVlan.class, new Dot1qTag.VlanId(Dot1qTag.VlanId.Enumeration.Any)); + } + + @Before + public void setUp() throws Exception { + initMocks(this); + namingContext = new NamingContext("generatedSubInterfaceName", "test-instance"); + doReturn(mappingContext).when(writeContext).getMappingContext(); + // TODO create base class for tests using vppApi + customizer = new SubInterfaceCustomizer(api, namingContext); + doReturn(ContextTestUtils.getMapping(SUPER_IF_NAME, SUPER_IF_ID)).when(mappingContext) + .read(ContextTestUtils.getMappingIid(SUPER_IF_NAME, "test-instance")); + } + + private SubInterface generateSubInterface(final boolean enabled, final List<Tag> tagList) { + SubInterfaceBuilder builder = new SubInterfaceBuilder(); + builder.setVlanType(_802dot1ad.class); + builder.setIdentifier(11L); + final TagsBuilder tags = new TagsBuilder(); + + tags.setTag(tagList); + + builder.setTags(tags.build()); + + builder.setMatch(generateMatch()); + builder.setEnabled(enabled); + return builder.build(); + } + + private static Tag generateTag(final short index, final Class<? extends Dot1qTagVlanType> tagType, + final Dot1qTag.VlanId vlanId) { + TagBuilder tag = new TagBuilder(); + tag.setIndex(index); + tag.setKey(new TagKey(index)); + final Dot1qTagBuilder dtag = new Dot1qTagBuilder(); + dtag.setTagType(tagType); + dtag.setVlanId(vlanId); + tag.setDot1qTag(dtag.build()); + return tag.build(); + } + + private static Match generateMatch() { + final MatchBuilder match = new MatchBuilder(); + final VlanTaggedBuilder tagged = new VlanTaggedBuilder(); + tagged.setMatchExactTags(true); + match.setMatchType( + new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.match.attributes.match.type.VlanTaggedBuilder() + .setVlanTagged(tagged.build()).build()); + return match.build(); + } + + private CreateSubif generateSubInterfaceRequest(final int superIfId, final short innerVlanId, + final boolean isInnerAny) { + CreateSubif request = new CreateSubif(); + request.subId = 11; + request.swIfIndex = superIfId; + request.twoTags = 1; + request.innerVlanId = innerVlanId; + request.innerVlanIdAny = (byte) (isInnerAny + ? 1 + : 0); + request.dot1Ad = 1; + request.outerVlanId = STAG_ID; + return request; + } + + private SwInterfaceSetFlags generateSwInterfaceEnableRequest(final int swIfIndex) { + SwInterfaceSetFlags request = new SwInterfaceSetFlags(); + request.swIfIndex = swIfIndex; + request.adminUpDown = 1; + return request; + } + + private InstanceIdentifier<SubInterface> getSubInterfaceId(final String name, final long index) { + return InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(name)).augmentation( + SubinterfaceAugmentation.class).child(SubInterfaces.class) + .child(SubInterface.class, new SubInterfaceKey(index)); + } + + private void whenCreateSubifThenSuccess() throws ExecutionException, InterruptedException, VppBaseCallException { + final CompletableFuture<CreateSubifReply> replyFuture = new CompletableFuture<>(); + final CreateSubifReply reply = new CreateSubifReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).createSubif(any(CreateSubif.class)); + } + + /** + * Failure response send + */ + private void whenCreateSubifThenFailure() throws ExecutionException, InterruptedException, VppBaseCallException { + doReturn(TestHelperUtils.<CreateSubifReply>createFutureException()).when(api) + .createSubif(any(CreateSubif.class)); + } + + private void whenSwInterfaceSetFlagsThenSuccess() + throws ExecutionException, InterruptedException, VppBaseCallException { + final CompletableFuture<SwInterfaceSetFlagsReply> replyFuture = new CompletableFuture<>(); + final SwInterfaceSetFlagsReply reply = new SwInterfaceSetFlagsReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).swInterfaceSetFlags(any(SwInterfaceSetFlags.class)); + } + + private CreateSubif verifyCreateSubifWasInvoked(final CreateSubif expected) throws VppBaseCallException { + ArgumentCaptor<CreateSubif> argumentCaptor = ArgumentCaptor.forClass(CreateSubif.class); + verify(api).createSubif(argumentCaptor.capture()); + final CreateSubif actual = argumentCaptor.getValue(); + + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.subId, actual.subId); + assertEquals(expected.noTags, actual.noTags); + assertEquals(expected.oneTag, actual.oneTag); + assertEquals(expected.twoTags, actual.twoTags); + assertEquals(expected.dot1Ad, actual.dot1Ad); + assertEquals(expected.exactMatch, actual.exactMatch); + assertEquals(expected.defaultSub, actual.defaultSub); + assertEquals(expected.outerVlanIdAny, actual.outerVlanIdAny); + assertEquals(expected.innerVlanIdAny, actual.innerVlanIdAny); + assertEquals(expected.outerVlanId, actual.outerVlanId); + assertEquals(expected.innerVlanId, actual.innerVlanId); + return actual; + } + + private SwInterfaceSetFlags verifySwInterfaceSetFlagsWasInvoked(final SwInterfaceSetFlags expected) + throws VppBaseCallException { + ArgumentCaptor<SwInterfaceSetFlags> argumentCaptor = ArgumentCaptor.forClass(SwInterfaceSetFlags.class); + verify(api).swInterfaceSetFlags(argumentCaptor.capture()); + final SwInterfaceSetFlags actual = argumentCaptor.getValue(); + + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.adminUpDown, actual.adminUpDown); + return actual; + } + + @Test + public void testCreateTwoTags() throws Exception { + final SubInterface subInterface = generateSubInterface(false, Arrays.asList(STAG_100, CTAG_200)); + final InstanceIdentifier<SubInterface> id = getSubInterfaceId(SUPER_IF_NAME, SUBIF_INDEX); + + whenCreateSubifThenSuccess(); + whenSwInterfaceSetFlagsThenSuccess(); + + customizer.writeCurrentAttributes(id, subInterface, writeContext); + + verifyCreateSubifWasInvoked(generateSubInterfaceRequest(SUPER_IF_ID, CTAG_ID, false)); + verify(mappingContext) + .put(eq(ContextTestUtils.getMappingIid(SUB_IFACE_NAME, "test-instance")), eq( + ContextTestUtils.getMapping(SUB_IFACE_NAME, 0).get())); + } + + @Test + public void testCreateDot1qAnyTag() throws Exception { + final SubInterface subInterface = generateSubInterface(false, Arrays.asList(STAG_100, CTAG_ANY)); + final InstanceIdentifier<SubInterface> id = getSubInterfaceId(SUPER_IF_NAME, SUBIF_INDEX); + + whenCreateSubifThenSuccess(); + whenSwInterfaceSetFlagsThenSuccess(); + + customizer.writeCurrentAttributes(id, subInterface, writeContext); + + verifyCreateSubifWasInvoked(generateSubInterfaceRequest(SUPER_IF_ID, CTAG_ANY_ID, true)); + verify(mappingContext) + .put(eq(ContextTestUtils.getMappingIid(SUB_IFACE_NAME, "test-instance")), eq( + ContextTestUtils.getMapping(SUB_IFACE_NAME, 0).get())); + } + + @Test + public void testCreateFailed() throws Exception { + final SubInterface subInterface = generateSubInterface(false, Arrays.asList(STAG_100, CTAG_200)); + final InstanceIdentifier<SubInterface> id = getSubInterfaceId(SUPER_IF_NAME, SUBIF_INDEX); + + whenCreateSubifThenFailure(); + + try { + customizer.writeCurrentAttributes(id, subInterface, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyCreateSubifWasInvoked(generateSubInterfaceRequest(SUPER_IF_ID, CTAG_ID, false)); + verify(mappingContext, times(0)).put( + eq(ContextTestUtils.getMappingIid(SUPER_IF_NAME, "test-instance")), + eq(ContextTestUtils.getMapping(SUPER_IF_NAME, 0).get())); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testUpdate() throws Exception { + final List<Tag> tags = Arrays.asList(STAG_100, CTAG_200); + final SubInterface before = generateSubInterface(false, tags); + final SubInterface after = generateSubInterface(true, tags); + final InstanceIdentifier<SubInterface> id = getSubInterfaceId(SUPER_IF_NAME, SUBIF_INDEX); + + whenSwInterfaceSetFlagsThenSuccess(); + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(SUPER_IF_NAME, SUBIF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + + customizer.updateCurrentAttributes(id, before, after, writeContext); + + verifySwInterfaceSetFlagsWasInvoked(generateSwInterfaceEnableRequest(SUBIF_INDEX)); + } + + @Test + public void testUpdateNoStateChange() throws Exception { + final List<Tag> tags = Arrays.asList(STAG_100, CTAG_200); + final SubInterface before = generateSubInterface(false, tags); + final SubInterface after = generateSubInterface(false, tags); + customizer.updateCurrentAttributes(null, before, after, writeContext); + + verify(api, never()).swInterfaceSetFlags(any()); + } + + @Test(expected = UnsupportedOperationException.class) + public void testDelete() throws Exception { + final SubInterface subInterface = generateSubInterface(false, Arrays.asList(STAG_100, CTAG_200)); + customizer.deleteCurrentAttributes(null, subInterface, writeContext); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/TapCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/TapCustomizerTest.java new file mode 100644 index 000000000..43e210073 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/TapCustomizerTest.java @@ -0,0 +1,161 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.Tap; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.TapBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.TapConnect; +import org.openvpp.jvpp.dto.TapConnectReply; +import org.openvpp.jvpp.dto.TapDelete; +import org.openvpp.jvpp.dto.TapDeleteReply; +import org.openvpp.jvpp.dto.TapModify; +import org.openvpp.jvpp.dto.TapModifyReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class TapCustomizerTest { + + @Mock + private FutureJVpp vppApi; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private TapCustomizer tapCustomizer; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + InterfaceTypeTestUtils.setupWriteContext(writeContext, + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.Tap.class); + final NamingContext ctx = new NamingContext("ifcintest", "test-instance"); + final ModificationCache toBeReturned = new ModificationCache(); + doReturn(toBeReturned).when(writeContext).getModificationCache(); + doReturn(mappingContext).when(writeContext).getMappingContext(); + + tapCustomizer = new TapCustomizer(vppApi, ctx); + } + + @Test + public void testCreate() throws Exception { + doAnswer(new Answer() { + + int idx = 0; + + @Override + public Object answer(final InvocationOnMock invocation) throws Throwable { + final CompletableFuture<Object> reply = new CompletableFuture<>(); + final TapConnectReply t = new TapConnectReply(); + t.swIfIndex = idx++; + reply.complete(t); + return reply; + } + }).when(vppApi).tapConnect(any(TapConnect.class)); + + tapCustomizer.writeCurrentAttributes(getTapId("tap"), getTapData("tap", "ff:ff:ff:ff:ff:ff"), writeContext); + tapCustomizer.writeCurrentAttributes(getTapId("tap2"), getTapData("tap2", "ff:ff:ff:ff:ff:ff"), writeContext); + + verify(vppApi, times(2)).tapConnect(any(TapConnect.class)); + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid("tap", "test-instance")), eq( + ContextTestUtils.getMapping("tap", 0).get())); + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid("tap2", "test-instance")), eq( + ContextTestUtils.getMapping("tap2", 1).get())); + } + + @Test + public void testModify() throws Exception { + final CompletableFuture<TapConnectReply> reply = new CompletableFuture<>(); + final TapConnectReply t = new TapConnectReply(); + t.swIfIndex = 0; + reply.complete(t); + doReturn(reply).when(vppApi).tapConnect(any(TapConnect.class)); + + final CompletableFuture<TapModifyReply> replyModif = new CompletableFuture<>(); + final TapModifyReply tmodif = new TapModifyReply(); + tmodif.swIfIndex = 0; + replyModif.complete(tmodif); + doReturn(replyModif).when(vppApi).tapModify(any(TapModify.class)); + + tapCustomizer.writeCurrentAttributes(getTapId("tap"), getTapData("tap", "ff:ff:ff:ff:ff:ff"), writeContext); + doReturn(ContextTestUtils.getMapping("tap", 1)).when(mappingContext).read( + ContextTestUtils.getMappingIid("tap", "test-instance")); + tapCustomizer.updateCurrentAttributes(getTapId("tap"), getTapData("tap", "ff:ff:ff:ff:ff:ff"), getTapData("tap", "ff:ff:ff:ff:ff:f1"), writeContext); + + verify(vppApi).tapConnect(any(TapConnect.class)); + verify(vppApi).tapModify(any(TapModify.class)); + + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid("tap", "test-instance")), eq( + ContextTestUtils.getMapping("tap", 0).get())); + } + + @Test + public void testDelete() throws Exception { + final CompletableFuture<TapConnectReply> reply = new CompletableFuture<>(); + final TapConnectReply t = new TapConnectReply(); + t.swIfIndex = 0; + reply.complete(t); + doReturn(reply).when(vppApi).tapConnect(any(TapConnect.class)); + + final CompletableFuture<TapDeleteReply> replyDelete = new CompletableFuture<>(); + final TapDeleteReply tmodif = new TapDeleteReply(); + replyDelete.complete(tmodif); + doReturn(replyDelete).when(vppApi).tapDelete(any(TapDelete.class)); + + tapCustomizer.writeCurrentAttributes(getTapId("tap"), getTapData("tap", "ff:ff:ff:ff:ff:ff"), writeContext); + doReturn(ContextTestUtils.getMapping("tap", 1)).when(mappingContext).read( + ContextTestUtils.getMappingIid("tap", "test-instance")); + tapCustomizer.deleteCurrentAttributes(getTapId("tap"), getTapData("tap", "ff:ff:ff:ff:ff:ff"), writeContext); + + verify(vppApi).tapConnect(any(TapConnect.class)); + verify(vppApi).tapDelete(any(TapDelete.class)); + verify(mappingContext).delete(eq(ContextTestUtils.getMappingIid("tap", "test-instance"))); + } + + private InstanceIdentifier<Tap> getTapId(final String tap) { + return InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(tap)).augmentation( + VppInterfaceAugmentation.class).child(Tap.class); + } + + private Tap getTapData(final String tap, final String mac) { + return new TapBuilder().setTapName(tap).setMac(new PhysAddress(mac)).build(); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VhostUserCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VhostUserCustomizerTest.java new file mode 100644 index 000000000..f7165aa3c --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VhostUserCustomizerTest.java @@ -0,0 +1,294 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.v3po.util.TranslateUtils; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VhostUserRole; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.VhostUser; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.VhostUserBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.CreateVhostUserIf; +import org.openvpp.jvpp.dto.CreateVhostUserIfReply; +import org.openvpp.jvpp.dto.DeleteVhostUserIf; +import org.openvpp.jvpp.dto.DeleteVhostUserIfReply; +import org.openvpp.jvpp.dto.ModifyVhostUserIf; +import org.openvpp.jvpp.dto.ModifyVhostUserIfReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class VhostUserCustomizerTest { + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private VhostUserCustomizer customizer; + private static final int IFACE_ID = 1; + private static final String IFACE_NAME = "eth0"; + private static final InstanceIdentifier<VhostUser> ID = + InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(IFACE_NAME)) + .augmentation(VppInterfaceAugmentation.class).child(VhostUser.class); + + @Before + public void setUp() throws Exception { + initMocks(this); + InterfaceTypeTestUtils.setupWriteContext(writeContext, + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VhostUser.class); + final NamingContext namingContext = new NamingContext("generatedInterfaceName", "test-instance"); + final ModificationCache toBeReturned = new ModificationCache(); + doReturn(toBeReturned).when(writeContext).getModificationCache(); + doReturn(mappingContext).when(writeContext).getMappingContext(); + + // TODO create base class for tests using vppApi + customizer = new VhostUserCustomizer(api, namingContext); + } + + private void whenCreateVhostUserIfThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException, TimeoutException { + final CompletionStage<CreateVhostUserIfReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<CreateVhostUserIfReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final CreateVhostUserIfReply reply = new CreateVhostUserIfReply(); + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.createVhostUserIf(any(CreateVhostUserIf.class))).thenReturn(replyCS); + } + + /** + * Failure response send + */ + private void whenCreateVhostUserIfThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<CreateVhostUserIfReply>createFutureException()).when(api) + .createVhostUserIf(any(CreateVhostUserIf.class)); + } + + private void whenModifyVhostUserIfThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException, TimeoutException { + final CompletionStage<ModifyVhostUserIfReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<ModifyVhostUserIfReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final ModifyVhostUserIfReply reply = new ModifyVhostUserIfReply(); + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.modifyVhostUserIf(any(ModifyVhostUserIf.class))).thenReturn(replyCS); + } + + /** + * Failure response send + */ + private void whenModifyVhostUserIfThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<ModifyVhostUserIfReply>createFutureException()).when(api) + .modifyVhostUserIf(any(ModifyVhostUserIf.class)); + } + + private void whenDeleteVhostUserIfThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException, TimeoutException { + final CompletionStage<DeleteVhostUserIfReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<DeleteVhostUserIfReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final DeleteVhostUserIfReply reply = new DeleteVhostUserIfReply(); + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.deleteVhostUserIf(any(DeleteVhostUserIf.class))).thenReturn(replyCS); + } + + /** + * Failure response send + */ + private void whenDeleteVhostUserIfThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<DeleteVhostUserIfReply>createFutureException()).when(api) + .deleteVhostUserIf(any(DeleteVhostUserIf.class)); + } + + private CreateVhostUserIf verifyCreateVhostUserIfWasInvoked(final VhostUser vhostUser) throws VppInvocationException { + ArgumentCaptor<CreateVhostUserIf> argumentCaptor = ArgumentCaptor.forClass(CreateVhostUserIf.class); + verify(api).createVhostUserIf(argumentCaptor.capture()); + final CreateVhostUserIf actual = argumentCaptor.getValue(); + assertEquals(0, actual.customDevInstance); + + assertEquals(TranslateUtils.booleanToByte(VhostUserRole.Server.equals(vhostUser.getRole())), actual.isServer); + assertEquals(0, actual.renumber); + assertEquals(0, actual.useCustomMac); + assertArrayEquals(vhostUser.getSocket().getBytes(), actual.sockFilename); + assertNotNull(actual.macAddress); + return actual; + } + + private ModifyVhostUserIf verifyModifyVhostUserIfWasInvoked(final VhostUser vhostUser, final int swIfIndex) + throws VppInvocationException { + ArgumentCaptor<ModifyVhostUserIf> argumentCaptor = ArgumentCaptor.forClass(ModifyVhostUserIf.class); + verify(api).modifyVhostUserIf(argumentCaptor.capture()); + final ModifyVhostUserIf actual = argumentCaptor.getValue(); + assertEquals(0, actual.customDevInstance); + + assertEquals(TranslateUtils.booleanToByte(VhostUserRole.Server.equals(vhostUser.getRole())), actual.isServer); + assertEquals(0, actual.renumber); + assertEquals(swIfIndex, actual.swIfIndex); + assertArrayEquals(vhostUser.getSocket().getBytes(), actual.sockFilename); + return actual; + } + + private DeleteVhostUserIf verifyDeleteVhostUserIfWasInvoked(final int swIfIndex) throws VppInvocationException { + ArgumentCaptor<DeleteVhostUserIf> argumentCaptor = ArgumentCaptor.forClass(DeleteVhostUserIf.class); + verify(api).deleteVhostUserIf(argumentCaptor.capture()); + final DeleteVhostUserIf actual = argumentCaptor.getValue(); + assertEquals(swIfIndex, actual.swIfIndex); + return actual; + } + + private static VhostUser generateVhostUser(final VhostUserRole role, final String socketName) { + VhostUserBuilder builder = new VhostUserBuilder(); + builder.setRole(role); + builder.setSocket(socketName); + return builder.build(); + } + + @Test + public void testWriteCurrentAttributes() throws Exception { + final VhostUser vhostUser = generateVhostUser(VhostUserRole.Server, "socketName"); + + whenCreateVhostUserIfThenSuccess(); + + customizer.writeCurrentAttributes(ID, vhostUser, writeContext); + verifyCreateVhostUserIfWasInvoked(vhostUser); + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance")), eq( + ContextTestUtils.getMapping(IFACE_NAME, 0).get())); + } + + @Test + public void testWriteCurrentAttributesFailed() throws Exception { + final VhostUser vhostUser = generateVhostUser(VhostUserRole.Client, "socketName"); + + whenCreateVhostUserIfThenFailure(); + + try { + customizer.writeCurrentAttributes(ID, vhostUser, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyCreateVhostUserIfWasInvoked(vhostUser); + verifyZeroInteractions(mappingContext); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testUpdateCurrentAttributes() throws Exception { + final VhostUser vhostUserBefore = generateVhostUser(VhostUserRole.Client, "socketName0"); + final VhostUser vhostUserAfter = generateVhostUser(VhostUserRole.Server, "socketName1"); + doReturn(ContextTestUtils.getMapping(IFACE_NAME, IFACE_ID)).when(mappingContext).read( + ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance")); + + whenModifyVhostUserIfThenSuccess(); + + customizer.updateCurrentAttributes(ID, vhostUserBefore, vhostUserAfter, writeContext); + verifyModifyVhostUserIfWasInvoked(vhostUserAfter, IFACE_ID); + } + + @Test + public void testUpdateCurrentAttributesFailed() throws Exception { + final VhostUser vhostUserBefore = generateVhostUser(VhostUserRole.Client, "socketName0"); + final VhostUser vhostUserAfter = generateVhostUser(VhostUserRole.Server, "socketName1"); + doReturn(ContextTestUtils.getMapping(IFACE_NAME, IFACE_ID)).when(mappingContext).read( + ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance")); + + whenModifyVhostUserIfThenFailure(); + + try { + customizer.updateCurrentAttributes(ID, vhostUserBefore, vhostUserAfter, writeContext); + } catch (WriteFailedException.UpdateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyModifyVhostUserIfWasInvoked(vhostUserAfter, IFACE_ID); + return; + } + fail("WriteFailedException.UpdateFailedException was expected"); + } + + @Test + public void testDeleteCurrentAttributes() throws Exception { + final VhostUser vhostUser = generateVhostUser(VhostUserRole.Client, "socketName"); + doReturn(ContextTestUtils.getMapping(IFACE_NAME, IFACE_ID)).when(mappingContext).read( + ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance")); + + whenDeleteVhostUserIfThenSuccess(); + + customizer.deleteCurrentAttributes(ID, vhostUser, writeContext); + verifyDeleteVhostUserIfWasInvoked(IFACE_ID); + verify(mappingContext).delete(eq(ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance"))); + } + + @Test + public void testDeleteCurrentAttributesFailed() throws Exception { + final VhostUser vhostUser = generateVhostUser(VhostUserRole.Client, "socketName"); + doReturn(ContextTestUtils.getMapping(IFACE_NAME, IFACE_ID)).when(mappingContext).read( + ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance")); + + whenDeleteVhostUserIfThenFailure(); + + try { + customizer.deleteCurrentAttributes(ID, vhostUser, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyDeleteVhostUserIfWasInvoked(IFACE_ID); + // Delete from context not invoked if delete from VPP failed + verify(mappingContext, times(0)).delete(eq(ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance"))); + verify(mappingContext).read(eq(ContextTestUtils.getMappingIid(IFACE_NAME, "test-instance"))); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanCustomizerTest.java new file mode 100644 index 000000000..b2b9aebba --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanCustomizerTest.java @@ -0,0 +1,253 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMapping; +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMappingIid; +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import com.google.common.net.InetAddresses; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanVni; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.Vxlan; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.VxlanBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.VxlanAddDelTunnel; +import org.openvpp.jvpp.dto.VxlanAddDelTunnelReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class VxlanCustomizerTest { + + private static final byte ADD_VXLAN = 1; + private static final byte DEL_VXLAN = 0; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private VxlanCustomizer customizer; + private String ifaceName; + private InstanceIdentifier<Vxlan> id; + + @Before + public void setUp() throws Exception { + initMocks(this); + InterfaceTypeTestUtils.setupWriteContext(writeContext, + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanTunnel.class); + // TODO create base class for tests using vppApi + NamingContext namingContext = new NamingContext("generateInterfaceNAme", "test-instance"); + final ModificationCache toBeReturned = new ModificationCache(); + doReturn(toBeReturned).when(writeContext).getModificationCache(); + doReturn(mappingContext).when(writeContext).getMappingContext(); + + customizer = new VxlanCustomizer(api, namingContext); + + ifaceName = "eth0"; + id = InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(ifaceName)) + .augmentation(VppInterfaceAugmentation.class).child(Vxlan.class); + } + + private void whenVxlanAddDelTunnelThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException, TimeoutException { + final CompletionStage<VxlanAddDelTunnelReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<VxlanAddDelTunnelReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final VxlanAddDelTunnelReply reply = new VxlanAddDelTunnelReply(); + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.vxlanAddDelTunnel(any(VxlanAddDelTunnel.class))).thenReturn(replyCS); + } + + /** + * Failure response send + */ + private void whenVxlanAddDelTunnelThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<VxlanAddDelTunnelReply>createFutureException()).when(api) + .vxlanAddDelTunnel(any(VxlanAddDelTunnel.class)); + } + + private VxlanAddDelTunnel verifyVxlanAddDelTunnelWasInvoked(final Vxlan vxlan) throws VppInvocationException { + ArgumentCaptor<VxlanAddDelTunnel> argumentCaptor = ArgumentCaptor.forClass(VxlanAddDelTunnel.class); + verify(api).vxlanAddDelTunnel(argumentCaptor.capture()); + final VxlanAddDelTunnel actual = argumentCaptor.getValue(); + assertEquals(0, actual.isIpv6); + assertEquals(-1, actual.decapNextIndex); + assertArrayEquals(InetAddresses.forString(vxlan.getSrc().getIpv4Address().getValue()).getAddress(), + actual.srcAddress); + assertArrayEquals(InetAddresses.forString(vxlan.getDst().getIpv4Address().getValue()).getAddress(), + actual.dstAddress); + assertEquals(vxlan.getEncapVrfId().intValue(), actual.encapVrfId); + assertEquals(vxlan.getVni().getValue().intValue(), actual.vni); + return actual; + } + + private void verifyVxlanAddWasInvoked(final Vxlan vxlan) throws VppInvocationException { + final VxlanAddDelTunnel actual = verifyVxlanAddDelTunnelWasInvoked(vxlan); + assertEquals(ADD_VXLAN, actual.isAdd); + } + + private void verifyVxlanDeleteWasInvoked(final Vxlan vxlan) throws VppInvocationException { + final VxlanAddDelTunnel actual = verifyVxlanAddDelTunnelWasInvoked(vxlan); + assertEquals(DEL_VXLAN, actual.isAdd); + } + + private static Vxlan generateVxlan(long vni) { + final VxlanBuilder builder = new VxlanBuilder(); + builder.setSrc(new IpAddress(new Ipv4Address("192.168.20.10"))); + builder.setDst(new IpAddress(new Ipv4Address("192.168.20.11"))); + builder.setEncapVrfId(Long.valueOf(123)); + builder.setVni(new VxlanVni(Long.valueOf(vni))); + return builder.build(); + } + + private static Vxlan generateVxlan() { + return generateVxlan(Long.valueOf(11)); + } + + @Test + public void testWriteCurrentAttributes() throws Exception { + final Vxlan vxlan = generateVxlan(); + + whenVxlanAddDelTunnelThenSuccess(); + + doReturn(Optional.absent()) + .when(mappingContext).read(getMappingIid(ifaceName, "test-instance").firstIdentifierOf(Mappings.class)); + + customizer.writeCurrentAttributes(id, vxlan, writeContext); + verifyVxlanAddWasInvoked(vxlan); + verify(mappingContext).put(eq(getMappingIid(ifaceName, "test-instance")), eq(getMapping(ifaceName, 0).get())); + } + + @Test + public void testWriteCurrentAttributesMappingAlreadyPresent() throws Exception { + final Vxlan vxlan = generateVxlan(); + + whenVxlanAddDelTunnelThenSuccess(); + final Optional<Mapping> ifcMapping = getMapping(ifaceName, 0); + + doReturn(Optional.of(new MappingsBuilder().setMapping(singletonList(ifcMapping.get())).build())) + .when(mappingContext).read(getMappingIid(ifaceName, "test-instance").firstIdentifierOf(Mappings.class)); + + customizer.writeCurrentAttributes(id, vxlan, writeContext); + verifyVxlanAddWasInvoked(vxlan); + + // Remove the first mapping before putting in the new one + verify(mappingContext).delete(eq(getMappingIid(ifaceName, "test-instance"))); + verify(mappingContext).put(eq(getMappingIid(ifaceName, "test-instance")), eq(ifcMapping.get())); + } + + @Test + public void testWriteCurrentAttributesFailed() throws Exception { + final Vxlan vxlan = generateVxlan(); + + whenVxlanAddDelTunnelThenFailure(); + + try { + customizer.writeCurrentAttributes(id, vxlan, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyVxlanAddWasInvoked(vxlan); + // Mapping not stored due to failure + verify(mappingContext, times(0)).put(eq(getMappingIid(ifaceName, "test-instance")), eq(getMapping(ifaceName, 0).get())); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testUpdateCurrentAttributes() throws Exception { + try { + customizer.updateCurrentAttributes(id, generateVxlan(10), generateVxlan(11), writeContext); + } catch (WriteFailedException.UpdateFailedException e) { + assertEquals(UnsupportedOperationException.class, e.getCause().getClass()); + return; + } + fail("WriteFailedException.UpdateFailedException was expected"); + } + + @Test + public void testDeleteCurrentAttributes() throws Exception { + final Vxlan vxlan = generateVxlan(); + + whenVxlanAddDelTunnelThenSuccess(); + doReturn(getMapping(ifaceName, 1)).when(mappingContext).read(getMappingIid(ifaceName, "test-instance")); + + customizer.deleteCurrentAttributes(id, vxlan, writeContext); + verifyVxlanDeleteWasInvoked(vxlan); + verify(mappingContext).delete(eq(getMappingIid(ifaceName, "test-instance"))); + } + + @Test + public void testDeleteCurrentAttributesaFailed() throws Exception { + final Vxlan vxlan = generateVxlan(); + + whenVxlanAddDelTunnelThenFailure(); + doReturn(getMapping(ifaceName, 1)).when(mappingContext).read(getMappingIid(ifaceName, "test-instance")); + + try { + customizer.deleteCurrentAttributes(id, vxlan, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyVxlanDeleteWasInvoked(vxlan); + verify(mappingContext, times(0)).delete(eq(getMappingIid(ifaceName, "test-instance"))); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanGpeCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanGpeCustomizerTest.java new file mode 100644 index 000000000..bec33cbbd --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/VxlanGpeCustomizerTest.java @@ -0,0 +1,262 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces; + +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import com.google.common.net.InetAddresses; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import io.fd.honeycomb.translate.MappingContext; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanGpeNextProtocol; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanGpeVni; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.VxlanGpe; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces._interface.VxlanGpeBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.VxlanAddDelTunnelReply; +import org.openvpp.jvpp.dto.VxlanGpeAddDelTunnel; +import org.openvpp.jvpp.dto.VxlanGpeAddDelTunnelReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class VxlanGpeCustomizerTest { + + private static final byte ADD_VXLAN_GPE = 1; + private static final byte DEL_VXLAN_GPE = 0; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private VxlanGpeCustomizer customizer; + private String ifaceName; + private InstanceIdentifier<VxlanGpe> id; + + @Before + public void setUp() throws Exception { + initMocks(this); + InterfaceTypeTestUtils.setupWriteContext(writeContext, + org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanGpeTunnel.class); + // TODO create base class for tests using vppApi + NamingContext namingContext = new NamingContext("generateInterfaceNAme", "test-instance"); + final ModificationCache toBeReturned = new ModificationCache(); + doReturn(toBeReturned).when(writeContext).getModificationCache(); + doReturn(mappingContext).when(writeContext).getMappingContext(); + + customizer = new VxlanGpeCustomizer(api, namingContext); + + ifaceName = "eth0"; + id = InstanceIdentifier.create(Interfaces.class).child(Interface.class, new InterfaceKey(ifaceName)) + .augmentation(VppInterfaceAugmentation.class).child(VxlanGpe.class); + } + + private void whenVxlanGpeAddDelTunnelThenSuccess() + throws ExecutionException, InterruptedException, VppBaseCallException, TimeoutException { + final CompletionStage<VxlanGpeAddDelTunnelReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<VxlanGpeAddDelTunnelReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final VxlanGpeAddDelTunnelReply reply = new VxlanGpeAddDelTunnelReply(); + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.vxlanGpeAddDelTunnel(any(VxlanGpeAddDelTunnel.class))).thenReturn(replyCS); + } + + /** + * Failure response send + */ + private void whenVxlanGpeAddDelTunnelThenFailure() + throws ExecutionException, InterruptedException, VppBaseCallException { + doReturn(TestHelperUtils.<VxlanAddDelTunnelReply>createFutureException()).when(api) + .vxlanGpeAddDelTunnel(any(VxlanGpeAddDelTunnel.class)); + } + + private VxlanGpeAddDelTunnel verifyVxlanGpeAddDelTunnelWasInvoked(final VxlanGpe vxlanGpe) + throws VppBaseCallException { + ArgumentCaptor<VxlanGpeAddDelTunnel> argumentCaptor = ArgumentCaptor.forClass(VxlanGpeAddDelTunnel.class); + verify(api).vxlanGpeAddDelTunnel(argumentCaptor.capture()); + final VxlanGpeAddDelTunnel actual = argumentCaptor.getValue(); + assertEquals(0, actual.isIpv6); + assertArrayEquals(InetAddresses.forString(vxlanGpe.getLocal().getIpv4Address().getValue()).getAddress(), + actual.local); + assertArrayEquals(InetAddresses.forString(vxlanGpe.getRemote().getIpv4Address().getValue()).getAddress(), + actual.remote); + assertEquals(vxlanGpe.getVni().getValue().intValue(), actual.vni); + assertEquals(vxlanGpe.getNextProtocol().getIntValue(), actual.protocol); + assertEquals(vxlanGpe.getEncapVrfId().intValue(), actual.encapVrfId); + assertEquals(vxlanGpe.getDecapVrfId().intValue(), actual.decapVrfId); + return actual; + } + + private void verifyVxlanGpeAddWasInvoked(final VxlanGpe vxlanGpe) throws VppBaseCallException { + final VxlanGpeAddDelTunnel actual = verifyVxlanGpeAddDelTunnelWasInvoked(vxlanGpe); + assertEquals(ADD_VXLAN_GPE, actual.isAdd); + } + + private void verifyVxlanGpeDeleteWasInvoked(final VxlanGpe vxlanGpe) throws VppBaseCallException{ + final VxlanGpeAddDelTunnel actual = verifyVxlanGpeAddDelTunnelWasInvoked(vxlanGpe); + assertEquals(DEL_VXLAN_GPE, actual.isAdd); + } + + private static VxlanGpe generateVxlanGpe(long vni) { + final VxlanGpeBuilder builder = new VxlanGpeBuilder(); + builder.setLocal(new IpAddress(new Ipv4Address("192.168.20.10"))); + builder.setRemote(new IpAddress(new Ipv4Address("192.168.20.11"))); + builder.setVni(new VxlanGpeVni(Long.valueOf(vni))); + builder.setNextProtocol(VxlanGpeNextProtocol.forValue(1)); + builder.setEncapVrfId(Long.valueOf(123)); + builder.setDecapVrfId(Long.valueOf(456)); + return builder.build(); + } + + private static VxlanGpe generateVxlanGpe() { + return generateVxlanGpe(Long.valueOf(11)); + } + + @Test + public void testWriteCurrentAttributes() throws Exception { + final VxlanGpe vxlanGpe = generateVxlanGpe(); + + whenVxlanGpeAddDelTunnelThenSuccess(); + + doReturn(Optional.absent()) + .when(mappingContext).read(ContextTestUtils.getMappingIid(ifaceName, "test-instance").firstIdentifierOf(Mappings.class)); + + customizer.writeCurrentAttributes(id, vxlanGpe, writeContext); + verifyVxlanGpeAddWasInvoked(vxlanGpe); + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance")), eq( + ContextTestUtils.getMapping(ifaceName, 0).get())); + } + + @Test + public void testWriteCurrentAttributesMappingAlreadyPresent() throws Exception { + final VxlanGpe vxlanGpe = generateVxlanGpe(); + + whenVxlanGpeAddDelTunnelThenSuccess(); + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(ifaceName, 0); + + doReturn(Optional.of(new MappingsBuilder().setMapping(singletonList(ifcMapping.get())).build())) + .when(mappingContext).read(ContextTestUtils.getMappingIid(ifaceName, "test-instance").firstIdentifierOf(Mappings.class)); + + customizer.writeCurrentAttributes(id, vxlanGpe, writeContext); + verifyVxlanGpeAddWasInvoked(vxlanGpe); + + // Remove the first mapping before putting in the new one + verify(mappingContext).delete(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance"))); + verify(mappingContext).put(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance")), eq(ifcMapping.get())); + } + + @Test + public void testWriteCurrentAttributesFailed() throws Exception { + final VxlanGpe vxlanGpe = generateVxlanGpe(); + + whenVxlanGpeAddDelTunnelThenFailure(); + + try { + customizer.writeCurrentAttributes(id, vxlanGpe, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyVxlanGpeAddWasInvoked(vxlanGpe); + // Mapping not stored due to failure + verify(mappingContext, times(0)) + .put(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance")), eq( + ContextTestUtils.getMapping(ifaceName, 0).get())); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testUpdateCurrentAttributes() throws Exception { + try { + customizer.updateCurrentAttributes(id, generateVxlanGpe(10), generateVxlanGpe(11), writeContext); + } catch (WriteFailedException.UpdateFailedException e) { + assertEquals(UnsupportedOperationException.class, e.getCause().getClass()); + return; + } + fail("WriteFailedException.UpdateFailedException was expected"); + } + + @Test + public void testDeleteCurrentAttributes() throws Exception { + final VxlanGpe vxlanGpe = generateVxlanGpe(); + + whenVxlanGpeAddDelTunnelThenSuccess(); + doReturn(ContextTestUtils.getMapping(ifaceName, 1)).when(mappingContext).read( + ContextTestUtils.getMappingIid(ifaceName, "test-instance")); + + customizer.deleteCurrentAttributes(id, vxlanGpe, writeContext); + verifyVxlanGpeDeleteWasInvoked(vxlanGpe); + verify(mappingContext).delete(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance"))); + } + + @Test + public void testDeleteCurrentAttributesaFailed() throws Exception { + final VxlanGpe vxlanGpe = generateVxlanGpe(); + + whenVxlanGpeAddDelTunnelThenFailure(); + doReturn(ContextTestUtils.getMapping(ifaceName, 1)).when(mappingContext).read( + ContextTestUtils.getMappingIid(ifaceName, "test-instance")); + + try { + customizer.deleteCurrentAttributes(id, vxlanGpe, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyVxlanGpeDeleteWasInvoked(vxlanGpe); + verify(mappingContext, times(0)).delete(eq(ContextTestUtils.getMappingIid(ifaceName, "test-instance"))); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4AddressCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4AddressCustomizerTest.java new file mode 100644 index 000000000..8f3c9ad8d --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4AddressCustomizerTest.java @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces.ip; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.Interface1; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.Ipv4; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.AddressBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.address.subnet.Netmask; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.address.subnet.NetmaskBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.address.subnet.PrefixLength; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.address.subnet.PrefixLengthBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DottedQuad; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.SwInterfaceAddDelAddress; +import org.openvpp.jvpp.dto.SwInterfaceAddDelAddressReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class Ipv4AddressCustomizerTest { + + private static final String IFC_CTX_NAME = "ifc-test-instance"; + private static final String IFACE_NAME = "eth0"; + private static final int IFACE_ID = 123; + + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + @Mock + private FutureJVpp api; + + private NamingContext interfaceContext; + private Ipv4AddressCustomizer customizer; + + @Before + public void setUp() throws Exception { + initMocks(this); + doReturn(mappingContext).when(writeContext).getMappingContext(); + interfaceContext = new NamingContext("generatedlIfaceName", IFC_CTX_NAME); + + customizer = new Ipv4AddressCustomizer(api, interfaceContext); + } + + private static InstanceIdentifier<Address> getAddressId(final String ifaceName) { + return InstanceIdentifier.builder(Interfaces.class) + .child(Interface.class, new InterfaceKey(ifaceName)) + .augmentation(Interface1.class) + .child(Ipv4.class) + .child(Address.class) + .build(); + } + + private void whenSwInterfaceAddDelAddressThenSuccess() { + final CompletableFuture<SwInterfaceAddDelAddressReply> replyFuture = new CompletableFuture<>(); + final SwInterfaceAddDelAddressReply reply = new SwInterfaceAddDelAddressReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).swInterfaceAddDelAddress(any(SwInterfaceAddDelAddress.class)); + } + + private void whenSwInterfaceAddDelAddressThenFailure() { + doReturn(TestHelperUtils.createFutureException()).when(api) + .swInterfaceAddDelAddress(any(SwInterfaceAddDelAddress.class)); + } + + private void verifySwInterfaceAddDelAddressWasInvoked(final SwInterfaceAddDelAddress expected) throws + VppInvocationException { + ArgumentCaptor<SwInterfaceAddDelAddress> argumentCaptor = + ArgumentCaptor.forClass(SwInterfaceAddDelAddress.class); + verify(api).swInterfaceAddDelAddress(argumentCaptor.capture()); + verifySwInterfaceAddDelAddressWasInvoked(expected, argumentCaptor.getValue()); + } + + private void verifySwInterfaceAddDelAddressWasInvoked(final SwInterfaceAddDelAddress expected, + final SwInterfaceAddDelAddress actual) throws + VppInvocationException { + assertArrayEquals(expected.address, actual.address); + assertEquals(expected.addressLength, actual.addressLength); + assertEquals(expected.delAll, actual.delAll); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(expected.isIpv6, actual.isIpv6); + assertEquals(expected.swIfIndex, actual.swIfIndex); + } + + @Test + public void testAddPrefixLengthIpv4Address() throws Exception { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PrefixLength length = new PrefixLengthBuilder().setPrefixLength(new Integer(24).shortValue()).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(length).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + whenSwInterfaceAddDelAddressThenSuccess(); + + customizer.writeCurrentAttributes(id, data, writeContext); + + verifySwInterfaceAddDelAddressWasInvoked(generateSwInterfaceAddDelAddressRequest(new byte[] {-64, -88, 2, 1}, + (byte) 1, (byte) 24)); + } + + @Test + public void testAddPrefixLengthIpv4AddressFailed() throws Exception { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PrefixLength length = new PrefixLengthBuilder().setPrefixLength(new Integer(24).shortValue()).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(length).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + whenSwInterfaceAddDelAddressThenFailure(); + + try { + customizer.writeCurrentAttributes(id, data, writeContext); + } catch (WriteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifySwInterfaceAddDelAddressWasInvoked( + generateSwInterfaceAddDelAddressRequest(new byte[] {-64, -88, 2, 1}, + (byte) 1, (byte) 24)); + return; + } + fail("WriteFailedException was expected"); + } + + private SwInterfaceAddDelAddress generateSwInterfaceAddDelAddressRequest(final byte[] address, final byte isAdd, + final byte prefixLength) { + final SwInterfaceAddDelAddress request = new SwInterfaceAddDelAddress(); + request.swIfIndex = IFACE_ID; + request.isAdd = isAdd; + request.isIpv6 = 0; + request.delAll = 0; + request.addressLength = prefixLength; + request.address = address; + return request; + } + + @Test + public void testDeletePrefixLengthIpv4Address() throws Exception { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PrefixLength length = new PrefixLengthBuilder().setPrefixLength(new Integer(24).shortValue()).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(length).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + whenSwInterfaceAddDelAddressThenSuccess(); + + customizer.deleteCurrentAttributes(id, data, writeContext); + + verifySwInterfaceAddDelAddressWasInvoked(generateSwInterfaceAddDelAddressRequest(new byte[] {-64, -88, 2, 1}, + (byte) 0, (byte) 24)); + } + + @Test + public void testDeletePrefixLengthIpv4AddressFailed() throws Exception { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PrefixLength length = new PrefixLengthBuilder().setPrefixLength(new Integer(24).shortValue()).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(length).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + whenSwInterfaceAddDelAddressThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, data, writeContext); + } catch (WriteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifySwInterfaceAddDelAddressWasInvoked( + generateSwInterfaceAddDelAddressRequest(new byte[] {-64, -88, 2, 1}, + (byte) 0, (byte) 24)); + return; + } + fail("WriteFailedException was expec16ted"); + } + + private void testSingleNetmask(final int expectedPrefixLength, final String stringMask) throws Exception { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + Netmask subnet = new NetmaskBuilder().setNetmask(new DottedQuad(stringMask)).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(subnet).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + final CompletableFuture<SwInterfaceAddDelAddressReply> replyFuture = new CompletableFuture<>(); + replyFuture.complete(new SwInterfaceAddDelAddressReply()); + ArgumentCaptor<SwInterfaceAddDelAddress> argumentCaptor = + ArgumentCaptor.forClass(SwInterfaceAddDelAddress.class); + doReturn(replyFuture).when(api).swInterfaceAddDelAddress(argumentCaptor.capture()); + + customizer.writeCurrentAttributes(id, data, writeContext); + + verifySwInterfaceAddDelAddressWasInvoked(generateSwInterfaceAddDelAddressRequest(new byte[] {-64, -88, 2, 1}, + (byte) 1, (byte) expectedPrefixLength), argumentCaptor.getValue()); + } + + private void testSingleIllegalNetmask(final String stringMask) throws Exception { + try { + final InstanceIdentifier<Address> id = getAddressId(IFACE_NAME); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + Netmask subnet = new NetmaskBuilder().setNetmask(new DottedQuad(stringMask)).build(); + Address data = new AddressBuilder().setIp(noZoneIp).setSubnet(subnet).build(); + + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + final CompletableFuture<SwInterfaceAddDelAddressReply> replyFuture = new CompletableFuture<>(); + replyFuture.complete(new SwInterfaceAddDelAddressReply()); + ArgumentCaptor<SwInterfaceAddDelAddress> argumentCaptor = + ArgumentCaptor.forClass(SwInterfaceAddDelAddress.class); + doReturn(replyFuture).when(api).swInterfaceAddDelAddress(argumentCaptor.capture()); + + customizer.writeCurrentAttributes(id, data, writeContext); + } catch (IllegalArgumentException e) { + return; + } + fail("IllegalArgumentException expected"); + + } + + /** + * Test contiguous netmask length from QuadDotted notation + */ + @Test + public void testNetmaskLength() throws Exception { + testSingleNetmask(1, "128.0.0.0"); + testSingleNetmask(2, "192.0.0.0"); + testSingleNetmask(8, "255.0.0.0"); + testSingleNetmask(9, "255.128.0.0"); + testSingleNetmask(16, "255.255.0.0"); + testSingleNetmask(24, "255.255.255.0"); + } + + @Test + public void testNetmaskIllegal() throws Exception { + testSingleIllegalNetmask(""); + testSingleIllegalNetmask("."); + testSingleIllegalNetmask(".255"); + testSingleIllegalNetmask("255"); + testSingleIllegalNetmask("255."); + testSingleIllegalNetmask("255.255"); + testSingleIllegalNetmask("255.255.0"); + testSingleIllegalNetmask("255.255.255."); + testSingleIllegalNetmask("255.255.255.256"); + testSingleIllegalNetmask("0.0.0.0"); + testSingleIllegalNetmask("10.10.10.10"); + testSingleIllegalNetmask("255.1.255.0"); + testSingleIllegalNetmask("255.255.255.255"); + } + +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4NeighbourCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4NeighbourCustomizerTest.java new file mode 100644 index 000000000..27ab352cf --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfaces/ip/Ipv4NeighbourCustomizerTest.java @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfaces.ip; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Optional; +import com.google.common.io.BaseEncoding; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.v3po.util.TranslateUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.Interfaces; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.Interface1; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.Ipv4; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.Neighbor; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces._interface.ipv4.NeighborBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.IpNeighborAddDel; +import org.openvpp.jvpp.dto.IpNeighborAddDelReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class Ipv4NeighbourCustomizerTest { + + @Mock + private FutureJVpp jvpp; + + @Mock + private WriteContext context; + + @Mock + private MappingContext mappingContext; + + @Mock + private Mapping mapping; + + private ArgumentCaptor<IpNeighborAddDel> requestCaptor; + private Ipv4NeighbourCustomizer customizer; + private NamingContext namingContext; + + + @Before + public void init() { + MockitoAnnotations.initMocks(this); + + namingContext = new NamingContext("prefix", "instance"); + namingContext.addName(5, "parent", mappingContext); + + customizer = new Ipv4NeighbourCustomizer(jvpp,namingContext); + + requestCaptor = ArgumentCaptor.forClass(IpNeighborAddDel.class); + + CompletableFuture<IpNeighborAddDelReply> future = new CompletableFuture<>(); + future.complete(new IpNeighborAddDelReply()); + + when(context.getMappingContext()).thenReturn(mappingContext); + when(mapping.getIndex()).thenReturn(5); + when(mapping.getName()).thenReturn("parent"); + when(mappingContext.read(Mockito.any())).thenReturn(Optional.fromNullable(mapping)); + when(jvpp.ipNeighborAddDel(Mockito.any(IpNeighborAddDel.class))).thenReturn(future); + } + + @Test + public void testWriteCurrentAttributes() throws WriteFailedException { + + InterfaceKey intfKey = new InterfaceKey("parent"); + + InstanceIdentifier<Neighbor> id = InstanceIdentifier.builder(Interfaces.class).child(Interface.class, intfKey) + .augmentation(Interface1.class).child(Ipv4.class).child(Neighbor.class).build(); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PhysAddress mac = new PhysAddress("aa:bb:cc:ee:11:22"); + + Neighbor data = new NeighborBuilder().setIp(noZoneIp).setLinkLayerAddress(mac).build(); + + customizer.writeCurrentAttributes(id, data, context); + + verify(jvpp, times(1)).ipNeighborAddDel(requestCaptor.capture()); + + IpNeighborAddDel request = requestCaptor.getValue(); + + assertEquals(0, request.isIpv6); + assertEquals(1, request.isAdd); + assertEquals(1, request.isStatic); + assertEquals("1.2.168.192", TranslateUtils.arrayToIpv4AddressNoZone(request.dstAddress).getValue()); + assertEquals("aabbccee1122", BaseEncoding.base16().lowerCase().encode(request.macAddress)); + assertEquals(5, request.swIfIndex); + } + + @Test + public void testDeleteCurrentAttributes() throws WriteFailedException { + InterfaceKey intfKey = new InterfaceKey("parent"); + + InstanceIdentifier<Neighbor> id = InstanceIdentifier.builder(Interfaces.class).child(Interface.class, intfKey) + .augmentation(Interface1.class).child(Ipv4.class).child(Neighbor.class).build(); + + Ipv4AddressNoZone noZoneIp = new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")); + PhysAddress mac = new PhysAddress("aa:bb:cc:ee:11:22"); + + Neighbor data = new NeighborBuilder().setIp(noZoneIp).setLinkLayerAddress(mac).build(); + + customizer.deleteCurrentAttributes(id, data, context); + + verify(jvpp, times(1)).ipNeighborAddDel(requestCaptor.capture()); + + IpNeighborAddDel request = requestCaptor.getValue(); + + assertEquals(0, request.isIpv6); + assertEquals(0, request.isAdd); + assertEquals(1, request.isStatic); + assertEquals("1.2.168.192", TranslateUtils.arrayToIpv4AddressNoZone(request.dstAddress).getValue()); + assertEquals("aabbccee1122", BaseEncoding.base16().lowerCase().encode(request.macAddress)); + assertEquals(5, request.swIfIndex); + } + +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/AclCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/AclCustomizerTest.java new file mode 100644 index 000000000..f36e49727 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/AclCustomizerTest.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentationBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.acl.base.attributes.L2AclBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.Acl; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.AclBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.dto.ClassifyTableByInterface; +import org.openvpp.jvpp.dto.ClassifyTableByInterfaceReply; + +public class AclCustomizerTest extends ReaderCustomizerTest<Acl, AclBuilder> { + + private static final String IF_NAME = "local0"; + private static final int IF_INDEX = 1; + private static final int TABLE_INDEX = 123; + private static final String TABLE_NAME = "table123"; + + private static final String IFC_TEST_INSTANCE = "ifc-test-instance"; + private static final String CT_TEST_INSTANCE = "ct-test-instance"; + + private NamingContext interfaceContext; + private NamingContext classifyTableContext; + + public AclCustomizerTest() { + super(Acl.class); + } + + @Override + public void setUpBefore() { + interfaceContext = new NamingContext("generatedIfaceName", IFC_TEST_INSTANCE); + classifyTableContext = new NamingContext("generatedTableContext", CT_TEST_INSTANCE); + + final KeyedInstanceIdentifier<Mapping, MappingKey> ifcMappingKey = ContextTestUtils + .getMappingIid(IF_NAME, IFC_TEST_INSTANCE); + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(IF_NAME, IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(ifcMappingKey); + + final KeyedInstanceIdentifier<Mapping, MappingKey> ctMappingKey = ContextTestUtils + .getMappingIid(TABLE_NAME, CT_TEST_INSTANCE); + final Optional<Mapping> ctMapping = ContextTestUtils.getMapping(TABLE_NAME, TABLE_INDEX); + doReturn(ctMapping).when(mappingContext).read(ctMappingKey); + + final List<Mapping> allCtMappings = Lists.newArrayList(ctMapping.get()); + final Mappings allCtMappingsBaObject = new MappingsBuilder().setMapping(allCtMappings).build(); + doReturn(Optional.of(allCtMappingsBaObject)).when(mappingContext) + .read(ctMappingKey.firstIdentifierOf(Mappings.class)); + + final List<Mapping> allIfcMappings = Lists.newArrayList(ifcMapping.get()); + final Mappings allIfcMappingsBaObject = new MappingsBuilder().setMapping(allIfcMappings).build(); + doReturn(Optional.of(allIfcMappingsBaObject)).when(mappingContext) + .read(ifcMappingKey.firstIdentifierOf(Mappings.class)); + } + + @Override + protected ReaderCustomizer<Acl, AclBuilder> initCustomizer() { + return new AclCustomizer(api, interfaceContext, classifyTableContext); + } + + @Test + public void testMerge() { + final VppInterfaceStateAugmentationBuilder builder = mock(VppInterfaceStateAugmentationBuilder.class); + final Acl value = mock(Acl.class); + getCustomizer().merge(builder, value); + verify(builder).setAcl(value); + } + + private InstanceIdentifier<Acl> getAclId(final String name) { + return InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey(name)) + .augmentation( + VppInterfaceStateAugmentation.class).child(Acl.class); + } + + @Test + public void testRead() throws Exception { + final InstanceIdentifier<Acl> id = getAclId(IF_NAME); + final AclBuilder builder = mock(AclBuilder.class); + + final CompletableFuture<ClassifyTableByInterfaceReply> replyFuture = new CompletableFuture<>(); + final ClassifyTableByInterfaceReply reply = new ClassifyTableByInterfaceReply(); + reply.l2TableId = TABLE_INDEX; + reply.ip4TableId = ~0; + reply.ip6TableId = ~0; + replyFuture.complete(reply); + doReturn(replyFuture).when(api).classifyTableByInterface(any(ClassifyTableByInterface.class)); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + + verify(builder).setL2Acl(new L2AclBuilder().setClassifyTable(TABLE_NAME).build()); + verify(builder).setIp4Acl(null); + verify(builder).setIp6Acl(null); + } + +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceCustomizerTest.java new file mode 100644 index 000000000..8bde1ac32 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceCustomizerTest.java @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.InterfaceTestUtils; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesStateBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.SwInterfaceDetails; +import org.openvpp.jvpp.dto.SwInterfaceDump; + +public class InterfaceCustomizerTest extends + ListReaderCustomizerTest<Interface, InterfaceKey, InterfaceBuilder> { + + private NamingContext interfacesContext; + + public InterfaceCustomizerTest() { + super(Interface.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("generatedIfaceName", "test-instance"); + } + + @Override + protected ReaderCustomizer<Interface, InterfaceBuilder> initCustomizer() { + final KeyedInstanceIdentifier<Mapping, MappingKey> eth0Id = ContextTestUtils + .getMappingIid("eth0", "test-instance"); + final KeyedInstanceIdentifier<Mapping, MappingKey> eth1Id = ContextTestUtils + .getMappingIid("eth1", "test-instance"); + final KeyedInstanceIdentifier<Mapping, MappingKey> subEth1Id = ContextTestUtils + .getMappingIid("eth1.1", "test-instance"); + final Optional<Mapping> eth0 = ContextTestUtils.getMapping("eth0", 0); + final Optional<Mapping> eth1 = ContextTestUtils.getMapping("eth1", 1); + final Optional<Mapping> subEth1 = ContextTestUtils.getMapping("eth1.1", 2); + + final List<Mapping> allMappings = + Lists.newArrayList(ContextTestUtils.getMapping("eth0", 0).get(), ContextTestUtils.getMapping("eth1", 1).get(), ContextTestUtils + .getMapping("eth1.1", 2).get()); + final Mappings allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(eth0Id.firstIdentifierOf(Mappings.class)); + + doReturn(eth0).when(mappingContext).read(eth0Id); + doReturn(eth1).when(mappingContext).read(eth1Id); + doReturn(subEth1).when(mappingContext).read(subEth1Id); + + return new InterfaceCustomizer(api, interfacesContext); + } + + // TODO use reflexion and move to ListReaderCustomizerTest + @Test + public void testMerge() throws Exception { + final InterfacesStateBuilder builder = mock(InterfacesStateBuilder.class); + final List<Interface> value = Collections.emptyList(); + getCustomizer().merge(builder, value); + verify(builder).setInterface(value); + } + + private void verifySwInterfaceDumpWasInvoked(final int nameFilterValid, final String ifaceName, + final int dumpIfcsInvocationCount) + throws VppInvocationException { + // TODO adding equals methods for jvpp DTOs would make ArgumentCaptor usage obsolete + ArgumentCaptor<SwInterfaceDump> argumentCaptor = ArgumentCaptor.forClass(SwInterfaceDump.class); + verify(api, times(dumpIfcsInvocationCount)).swInterfaceDump(argumentCaptor.capture()); + final SwInterfaceDump actual = argumentCaptor.getValue(); + assertEquals(nameFilterValid, actual.nameFilterValid); + assertArrayEquals(ifaceName.getBytes(), actual.nameFilter); + } + + private static void assertIfacesAreEqual(final Interface iface, final SwInterfaceDetails details) { + assertEquals(iface.getName(), new String(details.interfaceName)); + Assert.assertEquals(InterfaceUtils.yangIfIndexToVpp(iface.getIfIndex().intValue()), details.swIfIndex); + assertEquals(iface.getPhysAddress().getValue(), InterfaceUtils.vppPhysAddrToYang(details.l2Address)); + } + + @Test + public void testReadCurrentAttributes() throws Exception { + final String ifaceName = "eth0"; + final InstanceIdentifier<Interface> id = InstanceIdentifier.create(InterfacesState.class) + .child(Interface.class, new InterfaceKey(ifaceName)); + final InterfaceBuilder builder = getCustomizer().getBuilder(id); + + final SwInterfaceDetails iface = new SwInterfaceDetails(); + iface.interfaceName = ifaceName.getBytes(); + iface.swIfIndex = 0; + iface.linkSpeed = 1; + iface.l2AddressLength = 6; + iface.l2Address = new byte[iface.l2AddressLength]; + final List<SwInterfaceDetails> interfaceList = Collections.singletonList(iface); + InterfaceTestUtils.whenSwInterfaceDumpThenReturn(api, interfaceList); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + + verifySwInterfaceDumpWasInvoked(1, ifaceName, 1); + assertIfacesAreEqual(builder.build(), iface); + } + + @Test + public void testReadCurrentAttributesFailed() throws Exception { + final String ifaceName = "eth0"; + final InstanceIdentifier<Interface> id = InstanceIdentifier.create(InterfacesState.class) + .child(Interface.class, new InterfaceKey(ifaceName)); + final InterfaceBuilder builder = getCustomizer().getBuilder(id); + + InterfaceTestUtils.whenSwInterfaceDumpThenReturn(api, Collections.emptyList()); + + try { + getCustomizer().readCurrentAttributes(id, builder, ctx); + } catch (IllegalArgumentException e) { + verifySwInterfaceDumpWasInvoked(0, ifaceName, 2); + return; + } + + fail("ReadFailedException was expected"); + } + + @Test + public void testReadSubInterface() throws Exception { + final String ifaceName = "eth1.1"; + final InstanceIdentifier<Interface> id = InstanceIdentifier.create(InterfacesState.class) + .child(Interface.class, new InterfaceKey(ifaceName)); + final InterfaceBuilder builder = mock(InterfaceBuilder.class); + + final SwInterfaceDetails iface = new SwInterfaceDetails(); + iface.interfaceName = ifaceName.getBytes(); + iface.swIfIndex = 2; + iface.supSwIfIndex = 1; + iface.subId = 1; + final List<SwInterfaceDetails> interfaceList = Collections.singletonList(iface); + InterfaceTestUtils.whenSwInterfaceDumpThenReturn(api, interfaceList); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + + verifySwInterfaceDumpWasInvoked(1, ifaceName, 1); + verifyZeroInteractions(builder); + } + + @Test + public void testGetAllIds() throws Exception { + final InstanceIdentifier<Interface> id = InstanceIdentifier.create(InterfacesState.class) + .child(Interface.class); + + final String swIf0Name = "eth0"; + final SwInterfaceDetails swIf0 = new SwInterfaceDetails(); + swIf0.swIfIndex = 0; + swIf0.interfaceName = swIf0Name.getBytes(); + final String swIf1Name = "eth1"; + final SwInterfaceDetails swIf1 = new SwInterfaceDetails(); + swIf1.swIfIndex = 1; + swIf1.interfaceName = swIf1Name.getBytes(); + final String swSubIf1Name = "eth1.1"; + final SwInterfaceDetails swSubIf1 = new SwInterfaceDetails(); + swSubIf1.swIfIndex = 2; + swSubIf1.subId = 1; + swSubIf1.supSwIfIndex = 1; + swSubIf1.interfaceName = swSubIf1Name.getBytes(); + InterfaceTestUtils.whenSwInterfaceDumpThenReturn(api, Arrays.asList(swIf0, swIf1, swSubIf1)); + + final List<InterfaceKey> expectedIds = Arrays.asList(new InterfaceKey(swIf0Name), new InterfaceKey(swIf1Name)); + final List<InterfaceKey> actualIds = getCustomizer().getAllIds(id, ctx); + + verifySwInterfaceDumpWasInvoked(0, "", 1); + + // sub-interface should not be on the list + assertEquals(expectedIds, actualIds); + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceUtilsTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceUtilsTest.java new file mode 100644 index 000000000..c74e1ccfb --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/InterfaceUtilsTest.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.iana._if.type.rev140508.EthernetCsmacd; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.Tap; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VhostUser; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanGpeTunnel; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VxlanTunnel; + +public class InterfaceUtilsTest { + + @Test + public void testVppPhysAddrToYang() throws Exception { + assertEquals("01:02:03:04:05:06", InterfaceUtils.vppPhysAddrToYang(new byte[]{1, 2, 3, 4, 5, 6})); + assertEquals("0a:0b:0c:0d:0e:0f", InterfaceUtils.vppPhysAddrToYang(new byte[]{0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0})); + } + + @Test(expected = NullPointerException.class) + public void testVppPhysAddrToYangFailNullArgument() throws Exception { + InterfaceUtils.vppPhysAddrToYang(null); + } + + @Test(expected = IllegalArgumentException.class) + public void testVppPhysAddrToYangInvalidByteArrayLength() throws Exception { + InterfaceUtils.vppPhysAddrToYang(new byte[]{1, 2, 3, 4, 5}); + } + + @Test + public void testGetInterfaceType() { + assertEquals(Tap.class, InterfaceUtils.getInterfaceType("tap0")); + assertEquals(VxlanTunnel.class, InterfaceUtils.getInterfaceType("vxlan0")); + assertEquals(VxlanGpeTunnel.class, InterfaceUtils.getInterfaceType("vxlan_gpe0")); + assertEquals(VhostUser.class, InterfaceUtils.getInterfaceType("VirtualEthernet0/0/0")); + assertEquals(EthernetCsmacd.class, InterfaceUtils.getInterfaceType("eth0.0")); + assertEquals(EthernetCsmacd.class, InterfaceUtils.getInterfaceType("local0")); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/L2CustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/L2CustomizerTest.java new file mode 100644 index 000000000..ecd32c6d1 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/L2CustomizerTest.java @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentationBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.L2; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.L2Builder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.base.attributes.Interconnection; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.base.attributes.interconnection.BridgeBasedBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.BridgeDomainDetails; +import org.openvpp.jvpp.dto.BridgeDomainDetailsReplyDump; +import org.openvpp.jvpp.dto.BridgeDomainDump; +import org.openvpp.jvpp.dto.BridgeDomainSwIfDetails; +import org.openvpp.jvpp.dto.SwInterfaceDetails; + +public class L2CustomizerTest extends ReaderCustomizerTest<L2, L2Builder> { + + private NamingContext interfaceContext; + private NamingContext bridgeDomainContext; + + public L2CustomizerTest() { + super(L2.class); + } + + @Override + public void setUpBefore() { + interfaceContext = new NamingContext("generatedIfaceName", "ifc-test-instance"); + bridgeDomainContext = new NamingContext("generatedBDName", "bd-test-instance"); + } + + @Override + protected ReaderCustomizer<L2, L2Builder> initCustomizer() { + return new L2Customizer(api, interfaceContext, bridgeDomainContext); + } + + @Test + public void testMerge() { + final VppInterfaceStateAugmentationBuilder builder = mock(VppInterfaceStateAugmentationBuilder.class); + final L2 value = mock(L2.class); + getCustomizer().merge(builder, value); + verify(builder).setL2(value); + } + + private InstanceIdentifier<L2> getL2Id(final String name) { + return InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey(name)) + .augmentation( + VppInterfaceStateAugmentation.class).child(L2.class); + } + + private void whenBridgeDomainSwIfDumpThenReturn(final List<BridgeDomainSwIfDetails> bdSwIfList, + final List<BridgeDomainDetails> bridgeDomainDetailses) + throws ExecutionException, InterruptedException, VppInvocationException { + final BridgeDomainDetailsReplyDump reply = new BridgeDomainDetailsReplyDump(); + reply.bridgeDomainSwIfDetails = bdSwIfList; + reply.bridgeDomainDetails = bridgeDomainDetailses; + + final CompletableFuture<BridgeDomainDetailsReplyDump> replyFuture = new CompletableFuture<>(); + replyFuture.complete(reply); + when(api.bridgeDomainSwIfDump(any(BridgeDomainDump.class))).thenReturn(replyFuture); + } + + + private BridgeDomainSwIfDetails generateBdSwIfDetails(final int ifId, final int bdId) { + final BridgeDomainSwIfDetails bdSwIfDetails = new BridgeDomainSwIfDetails(); + bdSwIfDetails.swIfIndex = ifId; + bdSwIfDetails.shg = 1; + bdSwIfDetails.bdId = bdId; + return bdSwIfDetails; + } + + private Interconnection generateInterconnection(final int ifId, final String bdName, final Boolean bvi) { + final BridgeBasedBuilder bbBuilder = new BridgeBasedBuilder(); + bbBuilder.setBridgeDomain(bdName); + bbBuilder.setSplitHorizonGroup((short) 1); + if (bvi != null) { + bbBuilder.setBridgedVirtualInterface(bvi); + } else { + bbBuilder.setBridgedVirtualInterface(false); // false is default + } + return bbBuilder.build(); + } + + @Test + public void testRead() throws Exception { + final Map<Integer, SwInterfaceDetails> cachedInterfaceDump = new HashMap<>(); + final int ifId = 1; + final int bdId = 1; + final String bdName = "bd001"; + final String ifName = "eth0.sub0"; + final KeyedInstanceIdentifier<Mapping, MappingKey> ifcIid = ContextTestUtils + .getMappingIid(ifName, "ifc-test-instance"); + doReturn(ContextTestUtils.getMapping(ifName, ifId)).when(mappingContext).read(ifcIid); + final KeyedInstanceIdentifier<Mapping, MappingKey> bdIid = ContextTestUtils + .getMappingIid(bdName, "bd-test-instance"); + doReturn(ContextTestUtils.getMapping(bdName, bdId)).when(mappingContext).read(bdIid); + + List<Mapping> allMappings = Lists.newArrayList(ContextTestUtils.getMapping(ifName, ifId).get()); + Mappings allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(ifcIid.firstIdentifierOf(Mappings.class)); + + allMappings = Lists.newArrayList(ContextTestUtils.getMapping(bdName, bdId).get()); + allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(bdIid.firstIdentifierOf(Mappings.class)); + + final SwInterfaceDetails ifaceDetails = new SwInterfaceDetails(); + ifaceDetails.subId = ifId; + cachedInterfaceDump.put(ifId, ifaceDetails); + cache.put(InterfaceCustomizer.DUMPED_IFCS_CONTEXT_KEY, cachedInterfaceDump); + + // BVI + whenBridgeDomainSwIfDumpThenReturn(Collections.singletonList(generateBdSwIfDetails(ifId, bdId)), + Collections.singletonList(generateBdDetails(ifId, bdId))); + + L2Builder builder = mock(L2Builder.class); + getCustomizer().readCurrentAttributes(getL2Id(ifName), builder, ctx); + + verify(builder).setInterconnection(generateInterconnection(ifId, bdName, true)); + + // Not BVI + whenBridgeDomainSwIfDumpThenReturn(Collections.singletonList(generateBdSwIfDetails(ifId, bdId)), + Collections.singletonList(generateBdDetails(99 /* Different ifc is marked as BVI in bd details */, bdId))); + + builder = mock(L2Builder.class); + getCustomizer().readCurrentAttributes(getL2Id(ifName), builder, ctx); + + verify(builder).setInterconnection(generateInterconnection(ifId, bdName, null)); + } + + private BridgeDomainDetails generateBdDetails(final int ifId, final int bdId) { + final BridgeDomainDetails bridgeDomainDetails = new BridgeDomainDetails(); + bridgeDomainDetails.bviSwIfIndex = ifId; + bridgeDomainDetails.bdId = bdId; + return bridgeDomainDetails; + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/RewriteCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/RewriteCustomizerTest.java new file mode 100644 index 000000000..ec0851d9c --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/RewriteCustomizerTest.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.v3po.util.TagRewriteOperation; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.SubinterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527._802dot1q; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.SubInterfaces; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.sub.interfaces.SubInterface; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.sub.interfaces.SubInterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.L2Builder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.l2.Rewrite; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.l2.RewriteBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.tag.rewrite.PushTags; +import org.opendaylight.yangtools.yang.binding.ChildOf; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.SwInterfaceDetails; + +public class RewriteCustomizerTest extends ReaderCustomizerTest<Rewrite, RewriteBuilder> { + + public static final String VLAN_IF_NAME = "local0.1"; + public static final int VLAN_IF_ID = 1; + public static final int VLAN_IF_INDEX = 11; + + private NamingContext interfacesContext; + + @Captor + private ArgumentCaptor<List<PushTags>> captor; + + public RewriteCustomizerTest() { + super(Rewrite.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("generatedIfaceName", "test-instance"); + + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(VLAN_IF_NAME, VLAN_IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + } + + @Override + protected ReaderCustomizer<Rewrite, RewriteBuilder> initCustomizer() { + return new RewriteCustomizer(api, interfacesContext); + } + + @Test + public void testMerge() { + final L2Builder builder = mock(L2Builder.class); + final Rewrite value = mock(Rewrite.class); + getCustomizer().merge(builder, value); + verify(builder).setRewrite(value); + } + + private InstanceIdentifier<Rewrite> getVlanTagRewriteId(final String name, final long index) { + final Class<ChildOf<? super SubInterface>> child = (Class)Rewrite.class; + final InstanceIdentifier id = + InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey(name)).augmentation( + SubinterfaceStateAugmentation.class).child(SubInterfaces.class) + .child(SubInterface.class, new SubInterfaceKey(index)) + .child(child); + return id; + } + + @Test + public void testRead() throws ReadFailedException { + final Map<Integer, SwInterfaceDetails> cachedInterfaceDump = new HashMap<>(); + + final SwInterfaceDetails ifaceDetails = new SwInterfaceDetails(); + ifaceDetails.subId = VLAN_IF_ID; + ifaceDetails.interfaceName = VLAN_IF_NAME.getBytes(); + ifaceDetails.vtrOp = TagRewriteOperation.translate_2_to_2.ordinal(); + ifaceDetails.subNumberOfTags = 2; + ifaceDetails.vtrTag1 = 123; + ifaceDetails.vtrTag2 = 321; + ifaceDetails.vtrPushDot1Q = 1; + cachedInterfaceDump.put(VLAN_IF_INDEX, ifaceDetails); + cache.put(InterfaceCustomizer.DUMPED_IFCS_CONTEXT_KEY, cachedInterfaceDump); + + final RewriteBuilder builder = mock(RewriteBuilder.class); + + getCustomizer().readCurrentAttributes(getVlanTagRewriteId(VLAN_IF_NAME, VLAN_IF_ID), builder, ctx); + + verify(builder).setVlanType(_802dot1q.class); + verify(builder).setPopTags((short) 2); + + verify(builder).setPushTags(captor.capture()); + final List<PushTags> tags = captor.getValue(); + assertEquals(ifaceDetails.subNumberOfTags, tags.size()); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/SubInterfaceCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/SubInterfaceCustomizerTest.java new file mode 100644 index 000000000..b93c9f42a --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/SubInterfaceCustomizerTest.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.InterfaceTestUtils; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.SubinterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.SubInterfaces; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.SubInterfacesBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.sub.interfaces.SubInterface; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.sub.interfaces.SubInterfaceBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.interfaces.state._interface.sub.interfaces.SubInterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.match.attributes.match.type.VlanTagged; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.Match; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.vlan.rev150527.sub._interface.base.attributes.Tags; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.SwInterfaceDetails; + +public class SubInterfaceCustomizerTest extends + ListReaderCustomizerTest<SubInterface, SubInterfaceKey, SubInterfaceBuilder> { + + public static final String SUPER_IF_NAME = "local0"; + public static final int SUPER_IF_INDEX = 1; + public static final String VLAN_IF_NAME = "local0.1"; + public static final int VLAN_IF_ID = 1; + public static final int VLAN_IF_INDEX = 11; + + private NamingContext interfacesContext; + + public SubInterfaceCustomizerTest() { + super(SubInterface.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("generatedIfaceName", "test-instance"); + } + + @Override + protected ReaderCustomizer<SubInterface, SubInterfaceBuilder> initCustomizer() { + return new SubInterfaceCustomizer(api, interfacesContext); + } + + private InstanceIdentifier<SubInterface> getSubInterfaceId(final String name, final long id) { + return InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey(name)).augmentation( + SubinterfaceStateAugmentation.class).child( + SubInterfaces.class).child(SubInterface.class, new SubInterfaceKey(id)); + } + + @Test + public void testMerge() { + final SubInterfacesBuilder builder = mock(SubInterfacesBuilder.class); + final List<SubInterface> value = mock(List.class); + getCustomizer().merge(builder, value); + verify(builder).setSubInterface(value); + } + + @Test + public void testRead() throws ReadFailedException { + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(VLAN_IF_NAME, VLAN_IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + + final Map<Integer, SwInterfaceDetails> cachedInterfaceDump = new HashMap<>(); + + final SwInterfaceDetails ifaceDetails = new SwInterfaceDetails(); + ifaceDetails.subId = VLAN_IF_ID; + ifaceDetails.interfaceName = VLAN_IF_NAME.getBytes(); + ifaceDetails.subDot1Ad = 1; + ifaceDetails.subNumberOfTags = 2; + ifaceDetails.subOuterVlanIdAny = 1; + ifaceDetails.subInnerVlanIdAny = 1; + ifaceDetails.subExactMatch = 1; + cachedInterfaceDump.put(VLAN_IF_INDEX, ifaceDetails); + cache.put(InterfaceCustomizer.DUMPED_IFCS_CONTEXT_KEY, cachedInterfaceDump); + + final SubInterfaceBuilder builder = mock(SubInterfaceBuilder.class); + getCustomizer().readCurrentAttributes(getSubInterfaceId(VLAN_IF_NAME, VLAN_IF_ID), builder, ctx); + + verify(builder).setIdentifier((long) VLAN_IF_ID); + + ArgumentCaptor<Tags> tagCaptor = ArgumentCaptor.forClass(Tags.class); + verify(builder).setTags(tagCaptor.capture()); + assertEquals(ifaceDetails.subNumberOfTags, tagCaptor.getValue().getTag().size()); + + ArgumentCaptor<Match> matchCaptor = ArgumentCaptor.forClass(Match.class); + verify(builder).setMatch(matchCaptor.capture()); + final VlanTagged matchType = (VlanTagged)matchCaptor.getValue().getMatchType(); + assertTrue(matchType.getVlanTagged().isMatchExactTags()); + } + + @Test + public void testGetAllIds() throws Exception { + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(SUPER_IF_NAME, SUPER_IF_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + + final SwInterfaceDetails iface = new SwInterfaceDetails(); + iface.interfaceName = VLAN_IF_NAME.getBytes(); + iface.swIfIndex = VLAN_IF_INDEX; + iface.subId = VLAN_IF_ID; + iface.supSwIfIndex = SUPER_IF_INDEX; + final List<SwInterfaceDetails> ifaces = Collections.singletonList(iface); + InterfaceTestUtils.whenSwInterfaceDumpThenReturn(api, ifaces); + + final List<SubInterfaceKey> allIds = + getCustomizer().getAllIds(getSubInterfaceId(VLAN_IF_NAME, VLAN_IF_ID), ctx); + + assertEquals(ifaces.size(), allIds.size()); + + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanCustomizerTest.java new file mode 100644 index 000000000..a5c1d3465 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanCustomizerTest.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.Vxlan; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.VxlanBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.SwInterfaceDetails; +import org.openvpp.jvpp.dto.VxlanTunnelDetails; +import org.openvpp.jvpp.dto.VxlanTunnelDetailsReplyDump; +import org.openvpp.jvpp.dto.VxlanTunnelDump; + +public class VxlanCustomizerTest extends ReaderCustomizerTest<Vxlan, VxlanBuilder> { + + private NamingContext interfacesContext; + static final InstanceIdentifier<Vxlan> IID = + InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey("ifc1")) + .augmentation(VppInterfaceStateAugmentation.class).child(Vxlan.class); + + public VxlanCustomizerTest() { + super(Vxlan.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("vxlan-tunnel", "test-instance"); + doReturn(ContextTestUtils.getMapping("ifc1", 0)).when(mappingContext).read( + ContextTestUtils.getMappingIid("ifc1", "test-instance")); + + final SwInterfaceDetails v = new SwInterfaceDetails(); + v.interfaceName = "vxlan-tunnel4".getBytes(); + final Map<Integer, SwInterfaceDetails> map = new HashMap<>(); + map.put(0, v); + cache.put(InterfaceCustomizer.DUMPED_IFCS_CONTEXT_KEY, map); + } + + @Override + protected void setUpAfter() throws UnknownHostException, VppInvocationException { + final CompletableFuture<VxlanTunnelDetailsReplyDump> vxlanTunnelDetailsReplyDumpCompletionStage = + new CompletableFuture<>(); + + final VxlanTunnelDetailsReplyDump value = new VxlanTunnelDetailsReplyDump(); + final VxlanTunnelDetails vxlanTunnelDetails = new VxlanTunnelDetails(); + vxlanTunnelDetails.isIpv6 = 0; + vxlanTunnelDetails.decapNextIndex = 1; + vxlanTunnelDetails.dstAddress = InetAddress.getByName("1.2.3.4").getAddress(); + vxlanTunnelDetails.srcAddress = InetAddress.getByName("1.2.3.5").getAddress(); + vxlanTunnelDetails.encapVrfId = 55; + vxlanTunnelDetails.swIfIndex = 0; + vxlanTunnelDetails.vni = 9; + + value.vxlanTunnelDetails = Lists.newArrayList(vxlanTunnelDetails); + vxlanTunnelDetailsReplyDumpCompletionStage.complete(value); + + doReturn(vxlanTunnelDetailsReplyDumpCompletionStage).when(api).vxlanTunnelDump(any(VxlanTunnelDump.class)); + } + + @Test + public void testReadCurrentAttributes() throws Exception { + final VxlanBuilder builder = getCustomizer().getBuilder(IID); + getCustomizer().readCurrentAttributes(IID, builder, ctx); + + assertEquals(9, builder.getVni().getValue().intValue()); + assertEquals(55, builder.getEncapVrfId().intValue()); + + assertNull(builder.getSrc().getIpv6Address()); + assertNotNull(builder.getSrc().getIpv4Address()); + assertEquals("1.2.3.5", builder.getSrc().getIpv4Address().getValue()); + + assertNull(builder.getDst().getIpv6Address()); + assertNotNull(builder.getDst().getIpv4Address()); + assertEquals("1.2.3.4", builder.getDst().getIpv4Address().getValue()); + + verify(api).vxlanTunnelDump(any(VxlanTunnelDump.class)); + } + + @Test(expected = NullPointerException.class) + public void testReadCurrentAttributesVppNameNotCached() throws Exception { + InterfaceCustomizer.getCachedInterfaceDump(cache).remove(0); + + final VxlanBuilder builder = getCustomizer().getBuilder(IID); + getCustomizer().readCurrentAttributes(IID, builder, ctx); + } + + @Test + public void testReadCurrentAttributesWrongType() throws Exception { + final SwInterfaceDetails v = new SwInterfaceDetails(); + v.interfaceName = "tap-2".getBytes(); + InterfaceCustomizer.getCachedInterfaceDump(cache).put(0, v); + + final VxlanBuilder builder = getCustomizer().getBuilder(IID); + getCustomizer().readCurrentAttributes(IID, builder, ctx); + + // Should be ignored + verifyZeroInteractions(api); + } + + @Override + protected ReaderCustomizer<Vxlan, VxlanBuilder> initCustomizer() { + return new VxlanCustomizer(api, interfacesContext); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanGpeCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanGpeCustomizerTest.java new file mode 100644 index 000000000..2569d8ae0 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/VxlanGpeCustomizerTest.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; + +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppInterfaceStateAugmentation; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.VxlanGpe; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.interfaces.state._interface.VxlanGpeBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.SwInterfaceDetails; +import org.openvpp.jvpp.dto.VxlanGpeTunnelDetails; +import org.openvpp.jvpp.dto.VxlanGpeTunnelDetailsReplyDump; +import org.openvpp.jvpp.dto.VxlanGpeTunnelDump; + +public class VxlanGpeCustomizerTest extends ReaderCustomizerTest<VxlanGpe, VxlanGpeBuilder> { + + private NamingContext interfacesContext; + static final InstanceIdentifier<VxlanGpe> VXLAN_GPE_ID = + InstanceIdentifier.create(InterfacesState.class).child(Interface.class, new InterfaceKey("ifc2")) + .augmentation(VppInterfaceStateAugmentation.class).child(VxlanGpe.class); + + public VxlanGpeCustomizerTest() { + super(VxlanGpe.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("vxlan_gpe_inf", "test-instance"); + doReturn(ContextTestUtils.getMapping("ifc2", 0)).when(mappingContext).read( + ContextTestUtils.getMappingIid("ifc2", "test-instance")); + + final SwInterfaceDetails v = new SwInterfaceDetails(); + v.interfaceName = "vxlan_gpe_inf2".getBytes(); + final Map<Integer, SwInterfaceDetails> map = new HashMap<>(); + map.put(0, v); + cache.put(InterfaceCustomizer.DUMPED_IFCS_CONTEXT_KEY, map); + } + + @Override + protected void setUpAfter() throws UnknownHostException, VppBaseCallException { + final CompletableFuture<VxlanGpeTunnelDetailsReplyDump> vxlanGpeTunnelDetailsReplyDumpCompletionStage = + new CompletableFuture<>(); + + final VxlanGpeTunnelDetailsReplyDump value = new VxlanGpeTunnelDetailsReplyDump(); + final VxlanGpeTunnelDetails vxlanGpeTunnelDetails = new VxlanGpeTunnelDetails(); + vxlanGpeTunnelDetails.isIpv6 = 0; + vxlanGpeTunnelDetails.local = InetAddress.getByName("1.2.3.4").getAddress(); + vxlanGpeTunnelDetails.remote = InetAddress.getByName("1.2.3.5").getAddress(); + vxlanGpeTunnelDetails.vni = 9; + vxlanGpeTunnelDetails.protocol = 1; + vxlanGpeTunnelDetails.encapVrfId = 55; + vxlanGpeTunnelDetails.decapVrfId = 66; + vxlanGpeTunnelDetails.swIfIndex = 0; + + value.vxlanGpeTunnelDetails = Lists.newArrayList(vxlanGpeTunnelDetails); + vxlanGpeTunnelDetailsReplyDumpCompletionStage.complete(value); + + doReturn(vxlanGpeTunnelDetailsReplyDumpCompletionStage).when(api).vxlanGpeTunnelDump(any(VxlanGpeTunnelDump.class)); + } + + @Test + public void testReadCurrentAttributes() throws Exception { + final VxlanGpeBuilder builder = getCustomizer().getBuilder(VXLAN_GPE_ID); + getCustomizer().readCurrentAttributes(VXLAN_GPE_ID, builder, ctx); + + assertNull(builder.getLocal().getIpv6Address()); + assertNotNull(builder.getLocal().getIpv4Address()); + assertEquals("1.2.3.4", builder.getLocal().getIpv4Address().getValue()); + + assertNull(builder.getRemote().getIpv6Address()); + assertNotNull(builder.getRemote().getIpv4Address()); + assertEquals("1.2.3.5", builder.getRemote().getIpv4Address().getValue()); + + assertEquals(9, builder.getVni().getValue().intValue()); + assertEquals(1, builder.getNextProtocol().getIntValue()); + assertEquals(55, builder.getEncapVrfId().intValue()); + assertEquals(66, builder.getDecapVrfId().intValue()); + + verify(api).vxlanGpeTunnelDump(any(VxlanGpeTunnelDump.class)); + } + + @Test(expected = NullPointerException.class) + public void testReadCurrentAttributesVppNameNotCached() throws Exception { + InterfaceCustomizer.getCachedInterfaceDump(cache).remove(0); + + final VxlanGpeBuilder builder = getCustomizer().getBuilder(VXLAN_GPE_ID); + getCustomizer().readCurrentAttributes(VXLAN_GPE_ID, builder, ctx); + } + + @Test + public void testReadCurrentAttributesWrongType() throws Exception { + final SwInterfaceDetails v = new SwInterfaceDetails(); + v.interfaceName = "tap-3".getBytes(); + InterfaceCustomizer.getCachedInterfaceDump(cache).put(0, v); + + final VxlanGpeBuilder builder = getCustomizer().getBuilder(VXLAN_GPE_ID); + getCustomizer().readCurrentAttributes(VXLAN_GPE_ID, builder, ctx); + + // Should be ignored + verifyZeroInteractions(api); + } + + @Override + protected ReaderCustomizer<VxlanGpe, VxlanGpeBuilder> initCustomizer() { + return new VxlanGpeCustomizer(api, interfacesContext); + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/ip/Ipv4AddressCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/ip/Ipv4AddressCustomizerTest.java new file mode 100644 index 000000000..e4814296d --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/interfacesstate/ip/Ipv4AddressCustomizerTest.java @@ -0,0 +1,297 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.interfacesstate.ip; + +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMapping; +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMappingIid; +import static io.fd.honeycomb.translate.v3po.util.TranslateUtils.reverseBytes; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.v3po.util.TranslateUtils; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; +import org.hamcrest.CoreMatchers; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4AddressNoZone; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.InterfacesState; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.Interface; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.interfaces.rev140508.interfaces.state.InterfaceKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.Interface2; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces.state._interface.Ipv4; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces.state._interface.Ipv4Builder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces.state._interface.ipv4.Address; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces.state._interface.ipv4.AddressBuilder; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.ip.rev140616.interfaces.state._interface.ipv4.AddressKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.dto.IpAddressDetails; +import org.openvpp.jvpp.dto.IpAddressDetailsReplyDump; +import org.openvpp.jvpp.dto.IpAddressDump; + +public class Ipv4AddressCustomizerTest extends ListReaderCustomizerTest<Address, AddressKey, AddressBuilder> { + + private static final String IFACE_NAME = "eth0"; + private static final String IFACE_2_NAME = "eth1"; + private static final int IFACE_ID = 1; + private static final int IFACE_2_ID = 2; + + private NamingContext interfacesContext; + + public Ipv4AddressCustomizerTest() { + super(Address.class); + } + + @Override + public void setUpBefore() { + interfacesContext = new NamingContext("generatedIfaceName", "test-instance"); + } + + @Override + protected ReaderCustomizer<Address, AddressBuilder> initCustomizer() { + final KeyedInstanceIdentifier<Mapping, MappingKey> eth0Id = getMappingIid(IFACE_NAME, "test-instance"); + final KeyedInstanceIdentifier<Mapping, MappingKey> eth1Id = getMappingIid(IFACE_2_NAME, "test-instance"); + final Optional<Mapping> eth0 = getMapping(IFACE_NAME, IFACE_ID); + final Optional<Mapping> eth1 = getMapping(IFACE_2_NAME, IFACE_2_ID); + + final List<Mapping> allMappings = Lists.newArrayList(eth0.get(), eth1.get()); + final Mappings allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(eth0Id.firstIdentifierOf(Mappings.class)); + + doReturn(eth0).when(mappingContext).read(eth0Id); + doReturn(eth1).when(mappingContext).read(eth1Id); + + return new Ipv4AddressCustomizer(api, interfacesContext); + } + + private static InstanceIdentifier<Address> getId(final String address, final String ifaceName) { + return InstanceIdentifier.builder(InterfacesState.class) + .child(Interface.class, new InterfaceKey(ifaceName)) + .augmentation(Interface2.class) + .child(Ipv4.class) + .child(Address.class, new AddressKey(new Ipv4AddressNoZone(new Ipv4Address(address)))) + .build(); + } + + @Test + public void testReadCurrentAttributesFromCache() throws ReadFailedException { + ModificationCache cache = new ModificationCache(); + + IpAddressDetails detail1 = new IpAddressDetails(); + IpAddressDetails detail2 = new IpAddressDetails(); + IpAddressDetails detail3 = new IpAddressDetails(); + + detail1.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")))); + detail2.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.2")))); + detail3.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.3")))); + + IpAddressDetailsReplyDump reply = new IpAddressDetailsReplyDump(); + reply.ipAddressDetails = ImmutableList.of(detail1, detail2, detail3); + + cache.put(Ipv4ReadUtils.CACHE_KEY + IFACE_NAME, reply); + when(ctx.getModificationCache()).thenReturn(cache); + + final AddressBuilder builder = new AddressBuilder(); + final InstanceIdentifier<Address> id = getId("192.168.2.1", IFACE_NAME); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + + assertEquals("192.168.2.1", builder.getIp().getValue()); + } + + @Test + public void testReadCurrentAttributesFor2Ifcs() throws ReadFailedException { + ModificationCache cache = new ModificationCache(); + + IpAddressDetails detail1 = new IpAddressDetails(); + IpAddressDetails detail2 = new IpAddressDetails(); + + detail1.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")))); + detail2.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.2")))); + + IpAddressDetailsReplyDump reply = new IpAddressDetailsReplyDump(); + reply.ipAddressDetails = ImmutableList.of(detail1); + IpAddressDetailsReplyDump reply2 = new IpAddressDetailsReplyDump(); + reply2.ipAddressDetails = ImmutableList.of(detail2); + + CompletableFuture<IpAddressDetailsReplyDump> future = new CompletableFuture<>(); + future.complete(reply); + CompletableFuture<IpAddressDetailsReplyDump> future2 = new CompletableFuture<>(); + future2.complete(reply2); + + when(api.ipAddressDump(Mockito.any(IpAddressDump.class))).thenReturn(future).thenReturn(future2); + when(ctx.getModificationCache()).thenReturn(cache); + + final InstanceIdentifier<Address> id = getId("192.168.2.1", IFACE_NAME); + final InstanceIdentifier<Address> id2 = getId("192.168.2.2", IFACE_2_NAME); + + final List<AddressKey> ifc1Ids = getCustomizer().getAllIds(id, ctx); + assertThat(ifc1Ids.size(), is(1)); + assertThat(ifc1Ids, CoreMatchers.hasItem(new AddressKey(new Ipv4AddressNoZone("192.168.2.1")))); + final List<AddressKey> ifc2Ids = getCustomizer().getAllIds(id2, ctx); + assertThat(ifc2Ids.size(), is(1)); + assertThat(ifc2Ids, CoreMatchers.hasItem(new AddressKey(new Ipv4AddressNoZone("192.168.2.2")))); + + AddressBuilder builder = new AddressBuilder(); + getCustomizer().readCurrentAttributes(id, builder, ctx); + assertEquals(builder.getIp().getValue(), "192.168.2.1"); + builder = new AddressBuilder(); + getCustomizer().readCurrentAttributes(id2, builder, ctx); + assertEquals(builder.getIp().getValue(), "192.168.2.2"); + } + + @Test + public void testReadCurrentAttributesFromOperationalData() throws ReadFailedException { + ModificationCache cache = new ModificationCache(); + + IpAddressDetails detail1 = new IpAddressDetails(); + IpAddressDetails detail2 = new IpAddressDetails(); + IpAddressDetails detail3 = new IpAddressDetails(); + + detail1.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")))); + detail2.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.2")))); + detail3.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.3")))); + + IpAddressDetailsReplyDump reply = new IpAddressDetailsReplyDump(); + reply.ipAddressDetails = ImmutableList.of(detail1, detail2, detail3); + + CompletableFuture<IpAddressDetailsReplyDump> future = new CompletableFuture<>(); + future.complete(reply); + + when(api.ipAddressDump(Mockito.any(IpAddressDump.class))).thenReturn(future); + when(ctx.getModificationCache()).thenReturn(cache); + + + final AddressBuilder builder = new AddressBuilder(); + final InstanceIdentifier<Address> id = getId("192.168.2.1", IFACE_NAME); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + + assertEquals("192.168.2.1", builder.getIp().getValue()); + } + + @Test + public void testGetAllIdsFromCache() throws ReadFailedException { + ModificationCache cache = new ModificationCache(); + + IpAddressDetails detail1 = new IpAddressDetails(); + IpAddressDetails detail2 = new IpAddressDetails(); + IpAddressDetails detail3 = new IpAddressDetails(); + + detail1.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")))); + detail2.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.2")))); + detail3.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.3")))); + + IpAddressDetailsReplyDump reply = new IpAddressDetailsReplyDump(); + reply.ipAddressDetails = ImmutableList.of(detail1, detail2, detail3); + + cache.put(Ipv4ReadUtils.CACHE_KEY + IFACE_NAME, reply); + when(ctx.getModificationCache()).thenReturn(cache); + + final InstanceIdentifier<Address> id = getId("192.168.2.1", IFACE_NAME); + + List<Ipv4AddressNoZone> ids = getCustomizer().getAllIds(id, ctx).stream() + .map(key -> key.getIp()) + .collect(Collectors.toList()); + + verify(api, times(0)).ipAddressDump(Mockito.any(IpAddressDump.class)); + assertEquals(3, ids.size()); + assertEquals(true, "192.168.2.1".equals(ids.get(0).getValue())); + assertEquals(true, "192.168.2.2".equals(ids.get(1).getValue())); + assertEquals(true, "192.168.2.3".equals(ids.get(2).getValue())); + } + + @Test + public void testGetAllIdsFromOperationalData() throws ReadFailedException { + ModificationCache cache = new ModificationCache(); + + IpAddressDetails detail1 = new IpAddressDetails(); + IpAddressDetails detail2 = new IpAddressDetails(); + IpAddressDetails detail3 = new IpAddressDetails(); + + detail1.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.1")))); + detail2.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.2")))); + detail3.ip = reverseBytes( + TranslateUtils.ipv4AddressNoZoneToArray(new Ipv4AddressNoZone(new Ipv4Address("192.168.2.3")))); + + IpAddressDetailsReplyDump reply = new IpAddressDetailsReplyDump(); + reply.ipAddressDetails = ImmutableList.of(detail1, detail2, detail3); + + CompletableFuture<IpAddressDetailsReplyDump> future = new CompletableFuture<>(); + future.complete(reply); + + when(api.ipAddressDump(Mockito.any(IpAddressDump.class))).thenReturn(future); + when(ctx.getModificationCache()).thenReturn(cache); + + final InstanceIdentifier<Address> id = getId("192.168.2.1", IFACE_NAME); + + List<Ipv4AddressNoZone> ids = getCustomizer().getAllIds(id, ctx).stream() + .map(key -> key.getIp()) + .collect(Collectors.toList()); + + assertEquals(3, ids.size()); + assertEquals(true, "192.168.2.1".equals(ids.get(0).getValue())); + assertEquals(true, "192.168.2.2".equals(ids.get(1).getValue())); + assertEquals(true, "192.168.2.3".equals(ids.get(2).getValue())); + } + + @Test + public void testMerge() { + + Address address = new AddressBuilder().build(); + Ipv4Builder ipv4Builder = new Ipv4Builder(); + getCustomizer().merge(ipv4Builder, Arrays.asList(address)); + + assertEquals(1, ipv4Builder.getAddress().size()); + assertEquals(true, ipv4Builder.getAddress().contains(address)); + } + +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/notification/InterfaceChangeNotificationProducerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/notification/InterfaceChangeNotificationProducerTest.java new file mode 100644 index 000000000..14b01193f --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/notification/InterfaceChangeNotificationProducerTest.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.notification; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.notification.NotificationCollector; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.MappingContext; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceStateChange; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.InterfaceStatus; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.callback.SwInterfaceSetFlagsNotificationCallback; +import org.openvpp.jvpp.dto.SwInterfaceSetFlagsNotification; +import org.openvpp.jvpp.dto.WantInterfaceEvents; +import org.openvpp.jvpp.dto.WantInterfaceEventsReply; +import org.openvpp.jvpp.future.FutureJVpp; +import org.openvpp.jvpp.notification.NotificationRegistry; + +public class InterfaceChangeNotificationProducerTest { + + @Mock + private FutureJVpp jVpp; + private NamingContext namingContext = new NamingContext("test", "test-instance"); + @Mock + private MappingContext mappingContext; + @Mock + private NotificationCollector collector; + @Mock + private NotificationRegistry notificationRegistry; + @Mock + private AutoCloseable notificationListenerReg; + + private ArgumentCaptor<SwInterfaceSetFlagsNotificationCallback> callbackArgumentCaptor; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + doReturn(notificationRegistry).when(jVpp).getNotificationRegistry(); + callbackArgumentCaptor = ArgumentCaptor.forClass(SwInterfaceSetFlagsNotificationCallback.class); + doReturn(notificationListenerReg).when(notificationRegistry).registerSwInterfaceSetFlagsNotificationCallback( + callbackArgumentCaptor.capture()); + + final KeyedInstanceIdentifier<Mapping, MappingKey> eth0Id = ContextTestUtils + .getMappingIid("eth0", "test-instance"); + final Optional<Mapping> eth0 = ContextTestUtils.getMapping("eth0", 0); + + final List<Mapping> allMappings = Lists.newArrayList(ContextTestUtils.getMapping("eth0", 0).get()); + final Mappings allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(eth0Id.firstIdentifierOf(Mappings.class)); + + doReturn(eth0).when(mappingContext).read(eth0Id); + } + + @Test + public void testStart() throws Exception { + final CompletableFuture<WantInterfaceEventsReply> response = new CompletableFuture<>(); + response.complete(new WantInterfaceEventsReply()); + doReturn(response).when(jVpp).wantInterfaceEvents(any(WantInterfaceEvents.class)); + final InterfaceChangeNotificationProducer interfaceChangeNotificationProducer = + new InterfaceChangeNotificationProducer(jVpp, namingContext, mappingContext); + + interfaceChangeNotificationProducer.start(collector); + verify(jVpp).wantInterfaceEvents(any(WantInterfaceEvents.class)); + verify(jVpp).getNotificationRegistry(); + verify(notificationRegistry).registerSwInterfaceSetFlagsNotificationCallback(any( + SwInterfaceSetFlagsNotificationCallback.class)); + + interfaceChangeNotificationProducer.stop(); + verify(jVpp, times(2)).wantInterfaceEvents(any(WantInterfaceEvents.class)); + verify(notificationListenerReg).close(); + } + + @Test + public void testNotification() throws Exception { + final CompletableFuture<WantInterfaceEventsReply> response = new CompletableFuture<>(); + response.complete(new WantInterfaceEventsReply()); + doReturn(response).when(jVpp).wantInterfaceEvents(any(WantInterfaceEvents.class)); + final InterfaceChangeNotificationProducer interfaceChangeNotificationProducer = + new InterfaceChangeNotificationProducer(jVpp, namingContext, mappingContext); + + interfaceChangeNotificationProducer.start(collector); + + final SwInterfaceSetFlagsNotification swInterfaceSetFlagsNotification = new SwInterfaceSetFlagsNotification(); + swInterfaceSetFlagsNotification.deleted = 0; + swInterfaceSetFlagsNotification.swIfIndex = 0; + swInterfaceSetFlagsNotification.adminUpDown = 1; + swInterfaceSetFlagsNotification.linkUpDown = 1; + + callbackArgumentCaptor.getValue().onSwInterfaceSetFlagsNotification(swInterfaceSetFlagsNotification); + final ArgumentCaptor<InterfaceStateChange> notificationCaptor = + ArgumentCaptor.forClass(InterfaceStateChange.class); + verify(collector).onNotification(notificationCaptor.capture()); + + assertEquals("eth0", notificationCaptor.getValue().getName().getString()); + assertEquals(InterfaceStatus.Up, notificationCaptor.getValue().getAdminStatus()); + assertEquals(InterfaceStatus.Up, notificationCaptor.getValue().getOperStatus()); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ContextTestUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ContextTestUtils.java new file mode 100644 index 000000000..3b637a44c --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ContextTestUtils.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.test; + +import static org.mockito.Mockito.doReturn; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.MappingContext; +import java.util.List; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.Contexts; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.NamingContextKey; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; + +public class ContextTestUtils { + + public static Optional<Mapping> getMapping(final String name, final int index) { + return Optional.of(new MappingBuilder().setName(name).setIndex(index).build()); + } + + public static KeyedInstanceIdentifier<Mapping, MappingKey> getMappingIid(final String name, + final String namingContextName) { + return InstanceIdentifier.create(Contexts.class).child( + org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.NamingContext.class, + new NamingContextKey(namingContextName)).child(Mappings.class).child(Mapping.class, new MappingKey(name)); + } + + public static void mockMapping(final MappingContext mappingContext, final String name, final int id, + final String namingContextName) { + final InstanceIdentifier<Mappings> mappingsIid = + getMappingIid(name, namingContextName).firstIdentifierOf(Mappings.class); + + final Optional<Mapping> singleMapping = getMapping(name, id); + final Optional<Mappings> previousMappings = mappingContext.read(mappingsIid); + + final MappingsBuilder mappingsBuilder; + if (previousMappings != null && previousMappings.isPresent()) { + mappingsBuilder = new MappingsBuilder(previousMappings.get()); + } else { + mappingsBuilder = new MappingsBuilder(); + mappingsBuilder.setMapping(Lists.newArrayList()); + } + + final List<Mapping> mappingList = mappingsBuilder.getMapping(); + mappingList.add(singleMapping.get()); + doReturn(Optional.of(mappingsBuilder.setMapping(mappingList).build())) + .when(mappingContext).read(mappingsIid); + doReturn(singleMapping).when(mappingContext).read(getMappingIid(name, namingContextName)); + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/InterfaceTestUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/InterfaceTestUtils.java new file mode 100644 index 000000000..08898bfed --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/InterfaceTestUtils.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.test; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.SwInterfaceDetails; +import org.openvpp.jvpp.dto.SwInterfaceDetailsReplyDump; +import org.openvpp.jvpp.dto.SwInterfaceDump; +import org.openvpp.jvpp.future.FutureJVpp; + +public final class InterfaceTestUtils { + private InterfaceTestUtils() { + throw new UnsupportedOperationException("Utility class cannot be instantiated"); + } + + public static void whenSwInterfaceDumpThenReturn(final FutureJVpp api, final List<SwInterfaceDetails> interfaceList) + throws ExecutionException, InterruptedException, VppBaseCallException, TimeoutException { + final CompletionStage<SwInterfaceDetailsReplyDump> replyCS = mock(CompletionStage.class); + final CompletableFuture<SwInterfaceDetailsReplyDump> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final SwInterfaceDetailsReplyDump reply = new SwInterfaceDetailsReplyDump(); + reply.swInterfaceDetails = interfaceList; + when(replyFuture.get(anyLong(), eq(TimeUnit.SECONDS))).thenReturn(reply); + when(api.swInterfaceDump(any(SwInterfaceDump.class))).thenReturn(replyCS); + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ListReaderCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ListReaderCustomizerTest.java new file mode 100644 index 000000000..936e82c16 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ListReaderCustomizerTest.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.test; + +import static org.junit.Assert.assertNotNull; + +import io.fd.honeycomb.translate.spi.read.ListReaderCustomizer; +import org.junit.Test; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.Identifiable; +import org.opendaylight.yangtools.yang.binding.Identifier; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; + +/** + * Generic test for classes implementing {@link ListReaderCustomizer} interface. + * + * @param <D> Specific DataObject derived type (Identifiable), that is handled by this customizer + * @param <K> Specific Identifier for handled type (D) + * @param <B> Specific Builder for handled type (D) + */ +public abstract class ListReaderCustomizerTest<D extends DataObject & Identifiable<K>, K extends Identifier<D>, B extends Builder<D>> extends + ReaderCustomizerTest<D, B> { + + + protected ListReaderCustomizerTest(Class<D> dataObjectClass) { + super(dataObjectClass); + } + + @Override + protected ListReaderCustomizer<D, K, B> getCustomizer() { + return ListReaderCustomizer.class.cast(super.getCustomizer()); + } + + @Test + public void testGetBuilder() throws Exception { + assertNotNull(getCustomizer().getBuilder(InstanceIdentifier.create(dataObjectClass))); + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ReaderCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ReaderCustomizerTest.java new file mode 100644 index 000000000..170e53bfe --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/ReaderCustomizerTest.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.test; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.MockitoAnnotations.initMocks; + +import io.fd.honeycomb.translate.read.ReadContext; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.ModificationCache; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.opendaylight.yangtools.concepts.Builder; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.future.FutureJVpp; + +/** + * Generic test for classes implementing {@link ReaderCustomizer} interface. + * + * @param <D> Specific DataObject derived type (Identifiable), that is handled by this customizer + * @param <B> Specific Builder for handled type (D) + */ +public abstract class ReaderCustomizerTest<D extends DataObject, B extends Builder<D>> { + + @Mock + protected FutureJVpp api; + protected ModificationCache cache; + @Mock + protected ReadContext ctx; + @Mock + protected MappingContext mappingContext; + + protected final Class<D> dataObjectClass; + private ReaderCustomizer<D, B> customizer; + + protected ReaderCustomizerTest(Class<D> dataObjectClass) { + this.dataObjectClass = dataObjectClass; + } + + @Before + public void setUpParent() throws Exception { + initMocks(this); + cache = new ModificationCache(); + doReturn(cache).when(ctx).getModificationCache(); + doReturn(mappingContext).when(ctx).getMappingContext(); + + setUpBefore(); + customizer = initCustomizer(); + setUpAfter(); + } + + /** + * Optional setup for subclasses. Invoked before customizer is initialized. + */ + protected void setUpBefore() { + + } + + /** + * Optional setup for subclasses. Invoked after customizer is initialized. + */ + protected void setUpAfter() throws Exception { + + } + + protected abstract ReaderCustomizer<D, B> initCustomizer(); + + protected ReaderCustomizer<D, B> getCustomizer() { + return customizer; + } + + @Test + public void testGetBuilder() throws Exception { + assertNotNull(customizer.getBuilder(InstanceIdentifier.create(dataObjectClass))); + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/TestHelperUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/TestHelperUtils.java new file mode 100644 index 000000000..4cf3a9b77 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/test/TestHelperUtils.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.test; + +import org.openvpp.jvpp.VppCallbackException; +import org.openvpp.jvpp.dto.JVppReply; + +import java.util.concurrent.CompletableFuture; + +public class TestHelperUtils { + private final static int ERROR_RETVAL = -1; + + /** + * Static helper method for creation of Exception failure state in CompletableFuture object + * with retval = -1 + * @return CompletableFuture with VppCallbackException as a cause + */ + public static CompletableFuture<? extends JVppReply> createFutureException() { + final CompletableFuture<? extends JVppReply> replyFuture = new CompletableFuture<>(); + replyFuture.completeExceptionally(new VppCallbackException("test-call", 1, ERROR_RETVAL)); + return replyFuture; + } +} diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainCustomizerTest.java new file mode 100644 index 000000000..e64a440ac --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainCustomizerTest.java @@ -0,0 +1,327 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vpp; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import io.fd.honeycomb.translate.MappingContext; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainBuilder; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.BridgeDomainAddDel; +import org.openvpp.jvpp.dto.BridgeDomainAddDelReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class BridgeDomainCustomizerTest { + + private static final byte ADD_OR_UPDATE_BD = (byte) 1; + private static final byte ZERO = 0; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext ctx; + @Mock + private MappingContext mappingContext; + + private BridgeDomainCustomizer customizer; + + @Before + public void setUp() throws Exception { + initMocks(this); + // TODO create base class for tests using vppApi + NamingContext namingContext = new NamingContext("generatedBDName", "test-instance"); + final ModificationCache toBeReturned = new ModificationCache(); + doReturn(toBeReturned).when(ctx).getModificationCache(); + doReturn(mappingContext).when(ctx).getMappingContext(); + + customizer = new BridgeDomainCustomizer(api, namingContext); + } + + private BridgeDomain generateBridgeDomain(final String bdName) { + final byte arpTerm = 0; + final byte flood = 1; + final byte forward = 0; + final byte learn = 1; + final byte uuf = 0; + return generateBridgeDomain(bdName, arpTerm, flood, forward, learn, uuf); + } + + private BridgeDomain generateBridgeDomain(final String bdName, final int arpTerm, final int flood, + final int forward, final int learn, final int uuf) { + return new BridgeDomainBuilder() + .setName(bdName) + .setArpTermination(BridgeDomainTestUtils.intToBoolean(arpTerm)) + .setFlood(BridgeDomainTestUtils.intToBoolean(flood)) + .setForward(BridgeDomainTestUtils.intToBoolean(forward)) + .setLearn(BridgeDomainTestUtils.intToBoolean(learn)) + .setUnknownUnicastFlood(BridgeDomainTestUtils.intToBoolean(uuf)) + .build(); + } + + private void verifyBridgeDomainAddOrUpdateWasInvoked(final BridgeDomain bd, final int bdId) + throws VppInvocationException { + final byte arpTerm = BridgeDomainTestUtils.booleanToByte(bd.isArpTermination()); + final byte flood = BridgeDomainTestUtils.booleanToByte(bd.isFlood()); + final byte forward = BridgeDomainTestUtils.booleanToByte(bd.isForward()); + final byte learn = BridgeDomainTestUtils.booleanToByte(bd.isLearn()); + final byte uuf = BridgeDomainTestUtils.booleanToByte(bd.isUnknownUnicastFlood()); + + // TODO adding equals methods for jvpp DTOs would make ArgumentCaptor usage obsolete + ArgumentCaptor<BridgeDomainAddDel> argumentCaptor = ArgumentCaptor.forClass(BridgeDomainAddDel.class); + verify(api).bridgeDomainAddDel(argumentCaptor.capture()); + final BridgeDomainAddDel actual = argumentCaptor.getValue(); + assertEquals(arpTerm, actual.arpTerm); + assertEquals(flood, actual.flood); + assertEquals(forward, actual.forward); + assertEquals(learn, actual.learn); + assertEquals(uuf, actual.uuFlood); + assertEquals(ADD_OR_UPDATE_BD, actual.isAdd); + assertEquals(bdId, actual.bdId); + } + + private void verifyBridgeDomainDeleteWasInvoked(final int bdId) throws VppInvocationException { + ArgumentCaptor<BridgeDomainAddDel> argumentCaptor = ArgumentCaptor.forClass(BridgeDomainAddDel.class); + verify(api).bridgeDomainAddDel(argumentCaptor.capture()); + final BridgeDomainAddDel actual = argumentCaptor.getValue(); + assertEquals(bdId, actual.bdId); + assertEquals(ZERO, actual.arpTerm); + assertEquals(ZERO, actual.flood); + assertEquals(ZERO, actual.forward); + assertEquals(ZERO, actual.learn); + assertEquals(ZERO, actual.uuFlood); + assertEquals(ZERO, actual.isAdd); + } + + private void whenBridgeDomainAddDelThenSuccess() + throws ExecutionException, InterruptedException, VppInvocationException { + final CompletionStage<BridgeDomainAddDelReply> replyCS = mock(CompletionStage.class); + final CompletableFuture<BridgeDomainAddDelReply> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final BridgeDomainAddDelReply reply = new BridgeDomainAddDelReply(); + when(replyFuture.get()).thenReturn(reply); + when(api.bridgeDomainAddDel(any(BridgeDomainAddDel.class))).thenReturn(replyCS); + } + + private void whenBridgeDomainAddDelThenFailure() + throws ExecutionException, InterruptedException, VppInvocationException { + doReturn(TestHelperUtils.<BridgeDomainAddDelReply>createFutureException()).when(api) + .bridgeDomainAddDel(any(BridgeDomainAddDel.class)); + } + + @Test + public void testAddBridgeDomain() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain(bdName); + // Make bdContext.containsName() return false + doReturn(Optional.absent()).when(mappingContext) + .read(ContextTestUtils.getMappingIid(bdName, "test-instance").firstIdentifierOf(Mappings.class)); + // Make bdContext.containsIndex() return false + doReturn(Optional.absent()).when(mappingContext) + .read(ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenSuccess(); + + customizer.writeCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + + verifyBridgeDomainAddOrUpdateWasInvoked(bd, bdId); + verify(mappingContext).put( + ContextTestUtils.getMappingIid(bdName, "test-instance"), ContextTestUtils.getMapping(bdName, bdId).get()); + } + + @Test + public void testAddBridgeDomainPresentInBdContext() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain(bdName); + // Make bdContext.containsIndex() return true + doReturn(Optional.of(new MappingBuilder().setIndex(bdId).build())).when(mappingContext) + .read(ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenSuccess(); + + customizer.writeCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + + verifyBridgeDomainAddOrUpdateWasInvoked(bd, bdId); + verify(mappingContext).put( + ContextTestUtils.getMappingIid(bdName, "test-instance"), ContextTestUtils.getMapping(bdName, bdId).get()); + } + + @Test + public void testAddBridgeDomainFailed() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain(bdName); + + // Returning no Mappings for "test-instance" makes bdContext.containsName() return false + doReturn(Optional.absent()).when(mappingContext) + .read(ContextTestUtils.getMappingIid(bdName, "test-instance").firstIdentifierOf(Mappings.class)); + // Make bdContext.containsIndex() return false + doReturn(Optional.absent()).when(mappingContext) + .read(ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenFailure(); + + try { + customizer.writeCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + } catch (WriteFailedException.CreateFailedException e) { + verifyBridgeDomainAddOrUpdateWasInvoked(bd, bdId); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testDeleteBridgeDomain() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain(bdName); + doReturn(ContextTestUtils.getMapping(bdName, bdId)).when(mappingContext).read( + ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenSuccess(); + + customizer.deleteCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + + verifyBridgeDomainDeleteWasInvoked(bdId); + } + + @Test + public void testDeleteUnknownBridgeDomain() throws Exception { + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain("bd1"); + doReturn(Optional.absent()).when(mappingContext).read(ContextTestUtils.getMappingIid(bdName, "test-instance")); + + try { + customizer.deleteCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + } catch (IllegalArgumentException e) { + verify(api, never()).bridgeDomainAddDel(any(BridgeDomainAddDel.class)); + return; + } + fail("IllegalArgumentException was expected"); + } + + @Test + public void testDeleteBridgeDomainFailed() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bd = generateBridgeDomain(bdName); + doReturn(ContextTestUtils.getMapping(bdName, bdId)).when(mappingContext).read( + ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenFailure(); + + try { + customizer.deleteCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bd, ctx); + } catch (WriteFailedException.DeleteFailedException e) { + verifyBridgeDomainDeleteWasInvoked(bdId); + return; + } + + fail("WriteFailedException.DeleteFailedException was expected"); + } + + @Test + public void testUpdateBridgeDomain() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + doReturn(ContextTestUtils.getMapping(bdName, bdId)).when(mappingContext).read( + ContextTestUtils.getMappingIid(bdName, "test-instance")); + + final byte arpTermBefore = 1; + final byte floodBefore = 1; + final byte forwardBefore = 0; + final byte learnBefore = 1; + final byte uufBefore = 0; + + final BridgeDomain dataBefore = + generateBridgeDomain(bdName, arpTermBefore, floodBefore, forwardBefore, learnBefore, uufBefore); + final BridgeDomain dataAfter = + generateBridgeDomain(bdName, arpTermBefore ^ 1, floodBefore ^ 1, forwardBefore ^ 1, learnBefore ^ 1, + uufBefore ^ 1); + + whenBridgeDomainAddDelThenSuccess(); + + customizer + .updateCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), dataBefore, dataAfter, ctx); + verifyBridgeDomainAddOrUpdateWasInvoked(dataAfter, bdId); + } + + @Test + public void testUpdateUnknownBridgeDomain() throws Exception { + final String bdName = "bd1"; + final BridgeDomain bdBefore = generateBridgeDomain(bdName, 0, 1, 0, 1, 0); + final BridgeDomain bdAfter = generateBridgeDomain(bdName, 1, 1, 0, 1, 0); + doReturn(Optional.absent()).when(mappingContext).read(ContextTestUtils.getMappingIid(bdName, "test-instance")); + + try { + customizer + .updateCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bdBefore, bdAfter, ctx); + } catch (IllegalArgumentException e) { + verify(api, never()).bridgeDomainAddDel(any(BridgeDomainAddDel.class)); + return; + } + fail("IllegalArgumentException was expected"); + } + + @Test + public void testUpdateBridgeDomainFailed() throws Exception { + final int bdId = 1; + final String bdName = "bd1"; + final BridgeDomain bdBefore = generateBridgeDomain(bdName, 0, 1, 0, 1, 0); + final BridgeDomain bdAfter = generateBridgeDomain(bdName, 1, 1, 0, 1, 0); + doReturn(ContextTestUtils.getMapping(bdName, bdId)).when(mappingContext).read( + ContextTestUtils.getMappingIid(bdName, "test-instance")); + + whenBridgeDomainAddDelThenFailure(); + + try { + customizer + .updateCurrentAttributes(BridgeDomainTestUtils.bdIdentifierForName(bdName), bdBefore, bdAfter, ctx); + } catch (WriteFailedException.UpdateFailedException e) { + verifyBridgeDomainAddOrUpdateWasInvoked(bdAfter, bdId); + return; + } + fail("IllegalStateException was expected"); + } + +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainTestUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainTestUtils.java new file mode 100644 index 000000000..9ffc4edaa --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/BridgeDomainTestUtils.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vpp; + +import javax.annotation.Nullable; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.BridgeDomains; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; + +final class BridgeDomainTestUtils { + + private BridgeDomainTestUtils() { + throw new UnsupportedOperationException("Utility class cannot be instantiated."); + } + + public static byte booleanToByte(@Nullable final Boolean value) { + return value != null && value ? (byte) 1 : (byte) 0; + } + + @Nullable + public static Boolean intToBoolean(final int value) { + if (value == 0) { + return Boolean.FALSE; + } + if (value == 1) { + return Boolean.TRUE; + } + return null; + } + + public static int bdNameToID(String bName) { + return Integer.parseInt(((Character)bName.charAt(bName.length() - 1)).toString()); + } + + public static KeyedInstanceIdentifier<BridgeDomain, BridgeDomainKey> bdIdentifierForName( + final String bdName) { + return InstanceIdentifier.create(BridgeDomains.class).child(BridgeDomain.class, new BridgeDomainKey(bdName)); + } + + public static final Answer<Integer> BD_NAME_TO_ID_ANSWER = new Answer<Integer>() { + @Override + public Integer answer(final InvocationOnMock invocationOnMock) throws Throwable { + return bdNameToID((String) invocationOnMock.getArguments()[0]); + } + }; +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/L2FibEntryCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/L2FibEntryCustomizerTest.java new file mode 100644 index 000000000..b351699c9 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vpp/L2FibEntryCustomizerTest.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vpp; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.L2FibFilter; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.L2FibTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntry; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntryBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntryKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.BridgeDomains; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.bridge.domains.BridgeDomainKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.L2FibAddDel; +import org.openvpp.jvpp.dto.L2FibAddDelReply; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewriteReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class L2FibEntryCustomizerTest { + private static final String BD_CTX_NAME = "bd-test-instance"; + private static final String IFC_CTX_NAME = "ifc-test-instance"; + + private static final String BD_NAME = "testBD0"; + private static final int BD_ID = 111; + private static final String IFACE_NAME = "eth0"; + private static final int IFACE_ID = 123; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext bdContext; + private NamingContext interfaceContext; + + private L2FibEntryCustomizer customizer; + + @Before + public void setUp() throws Exception { + initMocks(this); + doReturn(mappingContext).when(writeContext).getMappingContext(); + bdContext = new NamingContext("generatedBdName", BD_CTX_NAME); + interfaceContext = new NamingContext("generatedIfaceName", IFC_CTX_NAME); + + customizer = new L2FibEntryCustomizer(api, bdContext, interfaceContext); + } + + private static InstanceIdentifier<L2FibEntry> getL2FibEntryId(final PhysAddress address) { + return InstanceIdentifier.create(BridgeDomains.class).child(BridgeDomain.class, new BridgeDomainKey(BD_NAME)) + .child(L2FibTable.class).child(L2FibEntry.class, new L2FibEntryKey(address)); + } + + private void whenL2FibAddDelThenSuccess() { + final CompletableFuture<L2FibAddDelReply> replyFuture = new CompletableFuture<>(); + final L2FibAddDelReply reply = new L2FibAddDelReply(); + replyFuture.complete(reply); + doReturn(replyFuture).when(api).l2FibAddDel(any(L2FibAddDel.class)); + } + + private void whenL2FibAddDelThenFailure() { + doReturn(TestHelperUtils.<L2InterfaceVlanTagRewriteReply>createFutureException()).when(api) + .l2FibAddDel(any(L2FibAddDel.class)); + } + + private L2FibAddDel generateL2FibAddDelRequest(final long mac, final byte isAdd) { + final L2FibAddDel request = new L2FibAddDel(); + request.mac = mac; + request.bdId = BD_ID; + request.swIfIndex = IFACE_ID; + request.isAdd = isAdd; + if (isAdd == 1) { + request.staticMac = 1; + request.filterMac = 1; + } + return request; + } + + private L2FibEntry generateL2FibEntry(final PhysAddress address) { + final L2FibEntryBuilder entry = new L2FibEntryBuilder(); + entry.setKey(new L2FibEntryKey(address)); + entry.setPhysAddress(address); + entry.setStaticConfig(true); + entry.setBridgedVirtualInterface(false); + entry.setAction(L2FibFilter.class); + entry.setOutgoingInterface(IFACE_NAME); + return entry.build(); + } + + private void verifyL2FibAddDelWasInvoked(final L2FibAddDel expected) throws + VppInvocationException { + ArgumentCaptor<L2FibAddDel> argumentCaptor = ArgumentCaptor.forClass(L2FibAddDel.class); + verify(api).l2FibAddDel(argumentCaptor.capture()); + final L2FibAddDel actual = argumentCaptor.getValue(); + assertEquals(expected.mac, actual.mac); + assertEquals(expected.bdId, actual.bdId); + assertEquals(expected.swIfIndex, actual.swIfIndex); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(expected.staticMac, actual.staticMac); + assertEquals(expected.filterMac, actual.filterMac); + } + + @Test + public void testCreate() throws Exception { + final long address_vpp = 0x0102030405060000L; + final PhysAddress address = new PhysAddress("01:02:03:04:05:06"); + final L2FibEntry entry = generateL2FibEntry(address); + final InstanceIdentifier<L2FibEntry> id = getL2FibEntryId(address); + + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + whenL2FibAddDelThenSuccess(); + + customizer.writeCurrentAttributes(id, entry, writeContext); + + verifyL2FibAddDelWasInvoked(generateL2FibAddDelRequest(address_vpp, (byte) 1)); + } + + @Test + public void testCreateFailed() throws Exception { + final long address_vpp = 0x1122334455660000L; + final PhysAddress address = new PhysAddress("11:22:33:44:55:66"); + final L2FibEntry entry = generateL2FibEntry(address); + final InstanceIdentifier<L2FibEntry> id = getL2FibEntryId(address); + + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + whenL2FibAddDelThenFailure(); + + try { + customizer.writeCurrentAttributes(id, entry, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyL2FibAddDelWasInvoked(generateL2FibAddDelRequest(address_vpp, (byte) 1)); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUpdate() throws Exception { + customizer.updateCurrentAttributes(InstanceIdentifier.create(L2FibEntry.class), mock(L2FibEntry.class), + mock(L2FibEntry.class), writeContext); + } + + @Test + public void testDelete() throws Exception { + final long address_vpp = 0x1122334455660000L; + final PhysAddress address = new PhysAddress("11:22:33:44:55:66"); + final L2FibEntry entry = generateL2FibEntry(address); + final InstanceIdentifier<L2FibEntry> id = getL2FibEntryId(address); + + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + whenL2FibAddDelThenSuccess(); + + customizer.deleteCurrentAttributes(id, entry, writeContext); + + verifyL2FibAddDelWasInvoked(generateL2FibAddDelRequest(address_vpp, (byte) 0)); + } + + @Test + public void testDeleteFailed() throws Exception { + final long address_vpp = 0x0102030405060000L; + final PhysAddress address = new PhysAddress("01:02:03:04:05:06"); + final L2FibEntry entry = generateL2FibEntry(address); + final InstanceIdentifier<L2FibEntry> id = getL2FibEntryId(address); + + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + whenL2FibAddDelThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, entry, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyL2FibAddDelWasInvoked(generateL2FibAddDelRequest(address_vpp, (byte) 0)); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionReaderTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionReaderTest.java new file mode 100644 index 000000000..895c20e87 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionReaderTest.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppclassifier; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.HexString; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppClassifierState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySession; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.ClassifySessionDetails; +import org.openvpp.jvpp.dto.ClassifySessionDetailsReplyDump; +import org.openvpp.jvpp.dto.ClassifySessionDump; + +public class ClassifySessionReaderTest extends + ListReaderCustomizerTest<ClassifySession, ClassifySessionKey, ClassifySessionBuilder> { + + private static final String MATCH_1 = "00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00"; + private static final String MATCH_2 = "00:00:00:00:00:00:01:02:03:04:05:07:00:00:00:00"; + + private static final int TABLE_INDEX = 1; + private static final String TABLE_NAME = "table1"; + + private NamingContext classifyTableContext; + + public ClassifySessionReaderTest() { + super(ClassifySession.class); + } + + @Override + public void setUpBefore() { + classifyTableContext = new NamingContext("classifyTableContext", "test-instance"); + + final Optional<Mapping> ifcMapping = ContextTestUtils.getMapping(TABLE_NAME, TABLE_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + } + + @Override + protected ReaderCustomizer<ClassifySession, ClassifySessionBuilder> initCustomizer() { + return new ClassifySessionReader(api, classifyTableContext); + } + + private static InstanceIdentifier<ClassifySession> getClassifySessionId(final String tableName, + final String match) { + return InstanceIdentifier.create(VppClassifierState.class) + .child(ClassifyTable.class, new ClassifyTableKey(tableName)) + .child(ClassifySession.class, new ClassifySessionKey(new HexString(match))); + } + + @Test + public void testMerge() { + final ClassifyTableBuilder builder = mock(ClassifyTableBuilder.class); + final List<ClassifySession> value = mock(List.class); + getCustomizer().merge(builder, value); + verify(builder).setClassifySession(value); + } + + @Test + public void testReadWithCache() throws ReadFailedException { + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, MATCH_1); + final ClassifySessionBuilder builder = mock(ClassifySessionBuilder.class); + final ModificationCache cache = new ModificationCache(); + final ClassifySessionDetailsReplyDump dump = new ClassifySessionDetailsReplyDump(); + final ClassifySessionDetails details = new ClassifySessionDetails(); + details.match = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x06, 0x00, 0x00, 0x00, 0x00}; + dump.classifySessionDetails = Collections.singletonList(details); + cache.put(ClassifySessionReader.CACHE_KEY + id.firstKeyOf(ClassifyTable.class), dump); + when(ctx.getModificationCache()).thenReturn(cache); + + getCustomizer().readCurrentAttributes(id, builder, ctx); + } + + @Test + public void testGetAllIds() throws ReadFailedException { + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, MATCH_1); + final ClassifySessionDetailsReplyDump dump = new ClassifySessionDetailsReplyDump(); + final ClassifySessionDetails details1 = new ClassifySessionDetails(); + details1.match = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x06, 0x00, 0x00, 0x00, 0x00}; + final ClassifySessionDetails details2 = new ClassifySessionDetails(); + details2.match = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x07, 0x00, 0x00, 0x00, 0x00}; + dump.classifySessionDetails = Arrays.asList(details1, details2); + + final CompletableFuture<ClassifySessionDetailsReplyDump> replyFuture = new CompletableFuture<>(); + replyFuture.complete(dump); + doReturn(replyFuture).when(api).classifySessionDump(any(ClassifySessionDump.class)); + + final List<ClassifySessionKey> allIds = getCustomizer().getAllIds(id, ctx); + assertEquals(2, allIds.size()); + assertEquals(MATCH_1, allIds.get(0).getMatch().getValue()); + assertEquals(MATCH_2, allIds.get(1).getMatch().getValue()); + } + +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionWriterTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionWriterTest.java new file mode 100644 index 000000000..25c7ffbb0 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifySessionWriterTest.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppclassifier; + +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMapping; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.HexString; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.OpaqueIndex; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.PacketHandlingAction; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppClassifier; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySession; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.classify.table.base.attributes.ClassifySessionKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.ClassifyTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.ClassifyTableKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.ClassifyAddDelSession; +import org.openvpp.jvpp.dto.ClassifyAddDelSessionReply; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewriteReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class ClassifySessionWriterTest { + + private static final int TABLE_INDEX = 123; + private static final String TABLE_NAME = "table123"; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext classifyTableContext; + private ClassifySessionWriter customizer; + private static final int SESSION_INDEX = 456; + + @Before + public void setUp() throws Exception { + initMocks(this); + classifyTableContext = new NamingContext("generatedClassifyTableName", "test-instance"); + doReturn(mappingContext).when(writeContext).getMappingContext(); + customizer = new ClassifySessionWriter(api, classifyTableContext); + + final Optional<Mapping> ifcMapping = getMapping(TABLE_NAME, TABLE_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + } + + private static ClassifySession generateClassifySession(final long opaqueIndex, final String match) { + final ClassifySessionBuilder builder = new ClassifySessionBuilder(); + builder.setOpaqueIndex(new OpaqueIndex(opaqueIndex)); + builder.setHitNext(new VppNode(PacketHandlingAction.Deny)); + builder.setAdvance(123); + builder.setMatch(new HexString(match)); + return builder.build(); + } + + private static InstanceIdentifier<ClassifySession> getClassifySessionId(final String tableName, + final String match) { + return InstanceIdentifier.create(VppClassifier.class) + .child(ClassifyTable.class, new ClassifyTableKey(tableName)) + .child(ClassifySession.class, new ClassifySessionKey(new HexString(match))); + } + + private void whenClassifyAddDelSessionThenSuccess() throws ExecutionException, InterruptedException { + final CompletableFuture<ClassifyAddDelSessionReply> replyFuture = new CompletableFuture<>(); + replyFuture.complete(new ClassifyAddDelSessionReply()); + doReturn(replyFuture).when(api).classifyAddDelSession(any(ClassifyAddDelSession.class)); + } + + private void whenClassifyAddDelSessionThenFailure() throws ExecutionException, InterruptedException { + doReturn(TestHelperUtils.<L2InterfaceVlanTagRewriteReply>createFutureException()).when(api) + .classifyAddDelSession(any(ClassifyAddDelSession.class)); + } + + private void verifyClassifyAddDelSessionWasInvoked(final ClassifyAddDelSession expected) { + ArgumentCaptor<ClassifyAddDelSession> argumentCaptor = ArgumentCaptor.forClass(ClassifyAddDelSession.class); + verify(api).classifyAddDelSession(argumentCaptor.capture()); + final ClassifyAddDelSession actual = argumentCaptor.getValue(); + assertEquals(expected.opaqueIndex, actual.opaqueIndex); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(expected.tableIndex, actual.tableIndex); + assertEquals(expected.hitNextIndex, actual.hitNextIndex); + assertArrayEquals(expected.match, actual.match); + assertEquals(expected.advance, actual.advance); + } + + private void verifyClassifyAddDelSessionDeleteWasInvoked(final ClassifyAddDelSession expected) { + ArgumentCaptor<ClassifyAddDelSession> argumentCaptor = ArgumentCaptor.forClass(ClassifyAddDelSession.class); + verify(api).classifyAddDelSession(argumentCaptor.capture()); + final ClassifyAddDelSession actual = argumentCaptor.getValue(); + assertEquals(expected.opaqueIndex, actual.opaqueIndex); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(expected.tableIndex, actual.tableIndex); + } + + private static ClassifyAddDelSession generateClassifyAddDelSession(final byte isAdd, final int tableIndex, + final int sessionIndex) { + final ClassifyAddDelSession request = new ClassifyAddDelSession(); + request.isAdd = isAdd; + request.tableIndex = tableIndex; + request.opaqueIndex = sessionIndex; + request.hitNextIndex = 0; + request.advance = 123; + request.match = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x06, 0x00, 0x00, 0x00, 0x00}; + return request; + } + + @Test + public void testCreate() throws Exception { + final String match = "00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00"; + final ClassifySession classifySession = generateClassifySession(SESSION_INDEX, match); + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, match); + + whenClassifyAddDelSessionThenSuccess(); + + customizer.writeCurrentAttributes(id, classifySession, writeContext); + + verifyClassifyAddDelSessionWasInvoked(generateClassifyAddDelSession((byte) 1, TABLE_INDEX, SESSION_INDEX)); + } + + @Test + public void testCreateFailed() throws Exception { + final String match = "00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00"; + final ClassifySession classifySession = generateClassifySession(SESSION_INDEX, match); + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, match); + + whenClassifyAddDelSessionThenFailure(); + + try { + customizer.writeCurrentAttributes(id, classifySession, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyClassifyAddDelSessionWasInvoked(generateClassifyAddDelSession((byte) 1, TABLE_INDEX, SESSION_INDEX)); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUpdate() throws Exception { + customizer.updateCurrentAttributes(null, null, null, writeContext); + } + + @Test + public void testDelete() throws Exception { + final String match = "00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00"; + final ClassifySession classifySession = generateClassifySession(SESSION_INDEX, match); + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, match); + + whenClassifyAddDelSessionThenSuccess(); + + customizer.deleteCurrentAttributes(id, classifySession, writeContext); + + verifyClassifyAddDelSessionDeleteWasInvoked( + generateClassifyAddDelSession((byte) 0, TABLE_INDEX, SESSION_INDEX)); + } + + @Test + public void testDeleteFailed() throws Exception { + final String match = "00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00"; + final ClassifySession classifySession = generateClassifySession(SESSION_INDEX, match); + final InstanceIdentifier<ClassifySession> id = getClassifySessionId(TABLE_NAME, match); + + whenClassifyAddDelSessionThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, classifySession, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyClassifyAddDelSessionDeleteWasInvoked( + generateClassifyAddDelSession((byte) 0, TABLE_INDEX, SESSION_INDEX)); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + + customizer.deleteCurrentAttributes(id, classifySession, writeContext); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableReaderTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableReaderTest.java new file mode 100644 index 000000000..e334da3b4 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableReaderTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppclassifier; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.google.common.base.Optional; +import com.google.common.collect.Lists; +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.read.ReadFailedException; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.Mappings; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.MappingsBuilder; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.MappingKey; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.HexString; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.PacketHandlingAction; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppClassifierState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppClassifierStateBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.state.ClassifyTableKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier; +import org.openvpp.jvpp.dto.ClassifyTableIds; +import org.openvpp.jvpp.dto.ClassifyTableIdsReply; +import org.openvpp.jvpp.dto.ClassifyTableInfo; +import org.openvpp.jvpp.dto.ClassifyTableInfoReply; + +public class ClassifyTableReaderTest extends + ListReaderCustomizerTest<ClassifyTable, ClassifyTableKey, ClassifyTableBuilder> { + + private static final int TABLE_INDEX_1 = 1; + private static final String TABLE_NAME_1 = "table1"; + private static final int TABLE_INDEX_2 = 2; + private static final String TABLE_NAME_2 = "table2"; + + private NamingContext classifyTableContext; + + public ClassifyTableReaderTest() { + super(ClassifyTable.class); + } + + @Override + public void setUpBefore() { + classifyTableContext = new NamingContext("classifyTableContext", "test-instance"); + + final KeyedInstanceIdentifier<Mapping, MappingKey> t0Id = ContextTestUtils + .getMappingIid(TABLE_NAME_1, "test-instance"); + final KeyedInstanceIdentifier<Mapping, MappingKey> t1Id = ContextTestUtils + .getMappingIid(TABLE_NAME_2, "test-instance"); + final Optional<Mapping> t0 = ContextTestUtils.getMapping(TABLE_NAME_1, TABLE_INDEX_1); + final Optional<Mapping> t1 = ContextTestUtils.getMapping(TABLE_NAME_2, TABLE_INDEX_2); + final List<Mapping> allMappings = Lists.newArrayList(t0.get(), t1.get()); + final Mappings allMappingsBaObject = new MappingsBuilder().setMapping(allMappings).build(); + doReturn(Optional.of(allMappingsBaObject)).when(mappingContext).read(t0Id.firstIdentifierOf(Mappings.class)); + doReturn(t0).when(mappingContext).read(t0Id); + doReturn(t1).when(mappingContext).read(t1Id); + } + + @Override + protected ReaderCustomizer<ClassifyTable, ClassifyTableBuilder> initCustomizer() { + return new ClassifyTableReader(api, classifyTableContext); + } + + private static InstanceIdentifier<ClassifyTable> getClassifyTableId(final String name) { + return InstanceIdentifier.create(VppClassifierState.class) + .child(ClassifyTable.class, new ClassifyTableKey(name)); + } + + private static ClassifyTableInfoReply generateClassifyTableInfoReply() { + final ClassifyTableInfoReply reply = new ClassifyTableInfoReply(); + reply.tableId = TABLE_INDEX_1; + reply.nbuckets = 2; + reply.skipNVectors = 0; + reply.matchNVectors = 1; + reply.nextTableIndex = ~0; + reply.missNextIndex = ~0; + reply.mask = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x06, 0x00, 0x00, 0x00, 0x00}; + return reply; + } + + private void verifyClasifyTableRead(final ClassifyTableBuilder builder) { + verify(builder).setName(TABLE_NAME_1); + verify(builder).setNbuckets(2L); + verify(builder, times(0)).setNextTable(anyString()); + verify(builder).setMissNext(new VppNode(PacketHandlingAction.Permit)); + verify(builder).setMask(new HexString("00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00")); + verify(builder).setActiveSessions(0L); + } + + @Test + public void testMerge() { + final VppClassifierStateBuilder builder = mock(VppClassifierStateBuilder.class); + final List<ClassifyTable> value = mock(List.class); + getCustomizer().merge(builder, value); + verify(builder).setClassifyTable(value); + } + + @Test + public void testRead() throws ReadFailedException { + final CompletableFuture<ClassifyTableInfoReply> replyFuture = new CompletableFuture<>(); + replyFuture.complete(generateClassifyTableInfoReply()); + doReturn(replyFuture).when(api).classifyTableInfo(any(ClassifyTableInfo.class)); + + final ClassifyTableBuilder builder = mock(ClassifyTableBuilder.class); + getCustomizer().readCurrentAttributes(getClassifyTableId(TABLE_NAME_1), builder, ctx); + + verifyClasifyTableRead(builder); + } + + @Test + public void testGetAllIds() throws ReadFailedException { + final CompletableFuture<ClassifyTableIdsReply> replyFuture = new CompletableFuture<>(); + final ClassifyTableIdsReply reply = new ClassifyTableIdsReply(); + reply.ids = new int[] {1, 2}; + replyFuture.complete(reply); + doReturn(replyFuture).when(api).classifyTableIds(any(ClassifyTableIds.class)); + + final List<ClassifyTableKey> allIds = getCustomizer().getAllIds(getClassifyTableId(TABLE_NAME_1), ctx); + + assertEquals(reply.ids.length, allIds.size()); + assertEquals(TABLE_NAME_1, allIds.get(0).getName()); + assertEquals(TABLE_NAME_2, allIds.get(1).getName()); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableWriterTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableWriterTest.java new file mode 100644 index 000000000..7724116fd --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppclassifier/ClassifyTableWriterTest.java @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppclassifier; + +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMapping; +import static io.fd.honeycomb.translate.v3po.test.ContextTestUtils.getMappingIid; +import static junit.framework.TestCase.assertTrue; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.v3po.test.TestHelperUtils; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import io.fd.honeycomb.translate.write.WriteContext; +import io.fd.honeycomb.translate.write.WriteFailedException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.honeycomb.params.xml.ns.yang.naming.context.rev160513.contexts.naming.context.mappings.Mapping; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.HexString; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.PacketHandlingAction; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppClassifier; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.VppNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.ClassifyTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.ClassifyTableBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.vpp.classifier.rev150603.vpp.classifier.ClassifyTableKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppBaseCallException; +import org.openvpp.jvpp.dto.ClassifyAddDelTable; +import org.openvpp.jvpp.dto.ClassifyAddDelTableReply; +import org.openvpp.jvpp.dto.L2InterfaceVlanTagRewriteReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class ClassifyTableWriterTest { + + private static final int TABLE_INDEX = 123; + private static final String TABLE_NAME = "table123"; + + @Mock + private FutureJVpp api; + @Mock + private WriteContext writeContext; + @Mock + private MappingContext mappingContext; + + private NamingContext classifyTableContext; + private ClassifyTableWriter customizer; + + @Before + public void setUp() throws Exception { + initMocks(this); + classifyTableContext = new NamingContext("generatedClassifyTableName", "test-instance"); + doReturn(mappingContext).when(writeContext).getMappingContext(); + customizer = new ClassifyTableWriter(api, classifyTableContext); + } + + private static ClassifyTable generateClassifyTable(final String name) { + final ClassifyTableBuilder builder = new ClassifyTableBuilder(); + builder.setName(name); + builder.setKey(new ClassifyTableKey(name)); + builder.setSkipNVectors(0L); + builder.setNbuckets(2L); + builder.setMemorySize(2L << 20); + builder.setMissNext(new VppNode(PacketHandlingAction.Permit)); + builder.setMask(new HexString("00:00:00:00:00:00:01:02:03:04:05:06:00:00:00:00")); + return builder.build(); + } + + private static InstanceIdentifier<ClassifyTable> getClassifyTableId(final String name) { + return InstanceIdentifier.create(VppClassifier.class) + .child(ClassifyTable.class, new ClassifyTableKey(name)); + } + + private void whenClassifyAddDelTableThenSuccess() throws ExecutionException, InterruptedException { + final CompletableFuture<ClassifyAddDelTableReply> replyFuture = new CompletableFuture<>(); + final ClassifyAddDelTableReply reply = new ClassifyAddDelTableReply(); + reply.newTableIndex = TABLE_INDEX; + replyFuture.complete(reply); + doReturn(replyFuture).when(api).classifyAddDelTable(any(ClassifyAddDelTable.class)); + } + + private void whenClassifyAddDelTableThenFailure() throws ExecutionException, InterruptedException { + doReturn(TestHelperUtils.<L2InterfaceVlanTagRewriteReply>createFutureException()).when(api) + .classifyAddDelTable(any(ClassifyAddDelTable.class)); + } + + private void verifyClassifyAddDelTableAddWasInvoked(final ClassifyAddDelTable expected) { + ArgumentCaptor<ClassifyAddDelTable> argumentCaptor = ArgumentCaptor.forClass(ClassifyAddDelTable.class); + verify(api).classifyAddDelTable(argumentCaptor.capture()); + final ClassifyAddDelTable actual = argumentCaptor.getValue(); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(~0, actual.tableIndex); + assertEquals(expected.nbuckets, actual.nbuckets); + assertEquals(expected.memorySize, actual.memorySize); + assertEquals(expected.skipNVectors, actual.skipNVectors); + assertEquals(expected.matchNVectors, actual.matchNVectors); + assertEquals(expected.nextTableIndex, actual.nextTableIndex); + assertEquals(expected.missNextIndex, actual.missNextIndex); + assertArrayEquals(expected.mask, actual.mask); + } + + private void verifyClassifyAddDelTableDeleteWasInvoked(final ClassifyAddDelTable expected) { + ArgumentCaptor<ClassifyAddDelTable> argumentCaptor = ArgumentCaptor.forClass(ClassifyAddDelTable.class); + verify(api).classifyAddDelTable(argumentCaptor.capture()); + final ClassifyAddDelTable actual = argumentCaptor.getValue(); + assertEquals(expected.isAdd, actual.isAdd); + assertEquals(expected.tableIndex, actual.tableIndex); + } + + private static ClassifyAddDelTable generateClassifyAddDelTable(final byte isAdd, final int tableIndex) { + final ClassifyAddDelTable request = new ClassifyAddDelTable(); + request.isAdd = isAdd; + request.tableIndex = tableIndex; + request.nbuckets = 2; + request.memorySize = 2 << 20; + request.skipNVectors = 0; + request.matchNVectors = 1; + request.nextTableIndex = ~0; + request.missNextIndex = ~0; + request.mask = + new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte) 0x01, (byte) 0x02, (byte) 0x03, (byte) 0x04, + (byte) 0x05, (byte) 0x06, 0x00, 0x00, 0x00, 0x00}; + return request; + } + + @Test + public void testCreate() throws Exception { + final ClassifyTable classifyTable = generateClassifyTable(TABLE_NAME); + final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); + + whenClassifyAddDelTableThenSuccess(); + + customizer.writeCurrentAttributes(id, classifyTable, writeContext); + + verifyClassifyAddDelTableAddWasInvoked(generateClassifyAddDelTable((byte) 1, TABLE_INDEX)); + verify(mappingContext) + .put(eq(getMappingIid(TABLE_NAME, "test-instance")), eq(getMapping(TABLE_NAME, TABLE_INDEX).get())); + } + + @Test + public void testCreateFailed() throws Exception { + final ClassifyTable classifyTable = generateClassifyTable(TABLE_NAME); + final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); + + whenClassifyAddDelTableThenFailure(); + + try { + customizer.writeCurrentAttributes(id, classifyTable, writeContext); + } catch (WriteFailedException.CreateFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyClassifyAddDelTableAddWasInvoked(generateClassifyAddDelTable((byte) 1, TABLE_INDEX)); + verify(mappingContext, times(0)).put( + eq(getMappingIid(TABLE_NAME, "test-instance")), + eq(getMapping(TABLE_NAME, TABLE_INDEX).get())); + return; + } + fail("WriteFailedException.CreateFailedException was expected"); + } + + @Test + public void testDelete() throws Exception { + final ClassifyTable classifyTable = generateClassifyTable(TABLE_NAME); + final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); + + final Optional<Mapping> ifcMapping = getMapping(TABLE_NAME, TABLE_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + + whenClassifyAddDelTableThenSuccess(); + + customizer.deleteCurrentAttributes(id, classifyTable, writeContext); + + verifyClassifyAddDelTableDeleteWasInvoked(generateClassifyAddDelTable((byte) 0, TABLE_INDEX)); + } + + @Test + public void testDeleteFailed() throws Exception { + final ClassifyTable classifyTable = generateClassifyTable(TABLE_NAME); + final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); + + final Optional<Mapping> ifcMapping = getMapping(TABLE_NAME, TABLE_INDEX); + doReturn(ifcMapping).when(mappingContext).read(any()); + + whenClassifyAddDelTableThenFailure(); + + try { + customizer.deleteCurrentAttributes(id, classifyTable, writeContext); + } catch (WriteFailedException.DeleteFailedException e) { + assertTrue(e.getCause() instanceof VppBaseCallException); + verifyClassifyAddDelTableDeleteWasInvoked(generateClassifyAddDelTable((byte) 0, TABLE_INDEX)); + return; + } + fail("WriteFailedException.DeleteFailedException was expected"); + + customizer.deleteCurrentAttributes(id, classifyTable, writeContext); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUpdate() throws Exception { + final ClassifyTable classifyTableBefore = generateClassifyTable(TABLE_NAME); + final InstanceIdentifier<ClassifyTable> id = getClassifyTableId(TABLE_NAME); + customizer.updateCurrentAttributes(id, classifyTableBefore, new ClassifyTableBuilder().build(), writeContext); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/BridgeDomainCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/BridgeDomainCustomizerTest.java new file mode 100644 index 000000000..bcd6a36f6 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/BridgeDomainCustomizerTest.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppstate; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomainsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainKey; + +public class BridgeDomainCustomizerTest + extends ListReaderCustomizerTest<BridgeDomain, BridgeDomainKey, BridgeDomainBuilder> { + + private NamingContext bdContext; + private NamingContext interfacesContext; + + public BridgeDomainCustomizerTest() { + super(BridgeDomain.class); + } + + @Override + public void setUpBefore() { + bdContext = new NamingContext("generatedBdName", "bd-test-instance"); + interfacesContext = new NamingContext("generatedIfaceName", "ifc-test-instance"); + } + + @Test + public void testMerge() throws Exception { + final BridgeDomainsBuilder builder = mock(BridgeDomainsBuilder.class); + final List<BridgeDomain> value = Collections.emptyList(); + getCustomizer().merge(builder, value); + verify(builder).setBridgeDomain(value); + } + + @Override + protected ReaderCustomizer<BridgeDomain, BridgeDomainBuilder> initCustomizer() { + return new BridgeDomainCustomizer(api, bdContext); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/L2FibEntryCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/L2FibEntryCustomizerTest.java new file mode 100644 index 000000000..f9eb2d6c6 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/L2FibEntryCustomizerTest.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppstate; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.v3po.test.ListReaderCustomizerTest; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.L2FibForward; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.L2FibTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.L2FibTableBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntry; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntryBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntryKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomains; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.L2FibTableDump; +import org.openvpp.jvpp.dto.L2FibTableEntry; +import org.openvpp.jvpp.dto.L2FibTableEntryReplyDump; + +public class L2FibEntryCustomizerTest extends ListReaderCustomizerTest<L2FibEntry, L2FibEntryKey, L2FibEntryBuilder> { + + private static final String BD_NAME = "testBD0"; + private static final int BD_ID = 111; + private static final String IFACE_NAME = "eth0"; + private static final int IFACE_ID = 123; + private static final String BD_CTX_NAME = "bd-test-instance"; + private static final String IFC_CTX_NAME = "ifc-test-instance"; + private NamingContext bdContext; + private NamingContext interfacesContext; + + public L2FibEntryCustomizerTest() { + super(L2FibEntry.class); + } + + @Override + public void setUpBefore() { + bdContext = new NamingContext("generatedBdName", BD_CTX_NAME); + interfacesContext = new NamingContext("generatedIfaceName", IFC_CTX_NAME); + } + + @Override + protected ReaderCustomizer<L2FibEntry, L2FibEntryBuilder> initCustomizer() { + return new L2FibEntryCustomizer(api, bdContext, interfacesContext); + } + + @Test + public void testMerge() throws Exception { + final L2FibTableBuilder builder = mock(L2FibTableBuilder.class); + final List<L2FibEntry> value = Collections.emptyList(); + getCustomizer().merge(builder, value); + verify(builder).setL2FibEntry(value); + } + + private static InstanceIdentifier<L2FibEntry> getL2FibEntryId(final String bdName, final PhysAddress address) { + return InstanceIdentifier.create(BridgeDomains.class).child(BridgeDomain.class, new BridgeDomainKey(bdName)) + .child(L2FibTable.class).child(L2FibEntry.class, new L2FibEntryKey(address)); + } + + private void whenL2FibTableDumpThenReturn(final List<L2FibTableEntry> l2FibTableEntryList) + throws ExecutionException, InterruptedException, VppInvocationException { + final L2FibTableEntryReplyDump reply = new L2FibTableEntryReplyDump(); + reply.l2FibTableEntry = l2FibTableEntryList; + + final CompletableFuture<L2FibTableEntryReplyDump> replyFuture = new CompletableFuture<>(); + replyFuture.complete(reply); + when(api.l2FibTableDump(any(L2FibTableDump.class))).thenReturn(replyFuture); + } + + @Test + public void testRead() throws Exception { + final long address_vpp = 0x0000010203040506L; + final PhysAddress address = new PhysAddress("01:02:03:04:05:06"); + + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + ContextTestUtils.mockMapping(mappingContext, IFACE_NAME, IFACE_ID, IFC_CTX_NAME); + + whenL2FibTableDumpThenReturn(Collections.singletonList(generateL2FibEntry(address_vpp))); + + final L2FibEntryBuilder builder = mock(L2FibEntryBuilder.class); + getCustomizer().readCurrentAttributes(getL2FibEntryId(BD_NAME, address), builder, ctx); + + verify(builder).setAction(L2FibForward.class); + verify(builder).setBridgedVirtualInterface(false); + verify(builder).setOutgoingInterface(IFACE_NAME); + verify(builder).setStaticConfig(false); + verify(builder).setPhysAddress(address); + verify(builder).setKey(new L2FibEntryKey(address)); + } + + private L2FibTableEntry generateL2FibEntry(final long mac) { + final L2FibTableEntry entry = new L2FibTableEntry(); + entry.mac = mac; + entry.swIfIndex = IFACE_ID; + return entry; + } + + @Test + public void testGetAllIds() throws Exception { + final long address_vpp = 0x0000112233445566L; + final PhysAddress address = new PhysAddress("11:22:33:44:55:66"); + ContextTestUtils.mockMapping(mappingContext, BD_NAME, BD_ID, BD_CTX_NAME); + + whenL2FibTableDumpThenReturn(Collections.singletonList(generateL2FibEntry(address_vpp))); + + final List<L2FibEntryKey> ids = getCustomizer().getAllIds(getL2FibEntryId(BD_NAME, address), ctx); + assertEquals(1, ids.size()); + assertEquals(address, ids.get(0).getPhysAddress()); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VersionCustomizerTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VersionCustomizerTest.java new file mode 100644 index 000000000..b220b32da --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VersionCustomizerTest.java @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppstate; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.fd.honeycomb.translate.spi.read.ReaderCustomizer; +import io.fd.honeycomb.translate.v3po.test.ReaderCustomizerTest; +import java.util.concurrent.CompletableFuture; +import org.junit.Test; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppStateBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.Version; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.VersionBuilder; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.dto.ShowVersion; +import org.openvpp.jvpp.dto.ShowVersionReply; + +public class VersionCustomizerTest extends ReaderCustomizerTest<Version, VersionBuilder> { + + public VersionCustomizerTest() { + super(Version.class); + } + + @Override + protected ReaderCustomizer<Version, VersionBuilder> initCustomizer() { + return new VersionCustomizer(api); + } + + @Test + public void testMerge() { + final VppStateBuilder builder = mock(VppStateBuilder.class); + final Version value = mock(Version.class); + getCustomizer().merge(builder, value); + verify(builder).setVersion(value); + } + + @Test + public void testReadCurrentAttributes() throws Exception { + final CompletableFuture<ShowVersionReply> replyFuture = new CompletableFuture<>(); + final ShowVersionReply reply = new ShowVersionReply(); + reply.version = new byte[]{}; + reply.program = new byte[]{}; + reply.buildDate = new byte[]{}; + reply.buildDirectory = new byte[]{}; + replyFuture.complete(reply); + + when(api.showVersion(any(ShowVersion.class))).thenReturn(replyFuture); + getCustomizer().readCurrentAttributes(InstanceIdentifier.create(Version.class), new VersionBuilder(), ctx); + verify(api).showVersion(any(ShowVersion.class)); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTest.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTest.java new file mode 100644 index 000000000..7287c2859 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTest.java @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppstate; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.common.base.Optional; +import com.google.common.collect.Iterables; +import com.google.common.collect.Multimap; +import io.fd.honeycomb.translate.ModificationCache; +import io.fd.honeycomb.translate.impl.read.GenericListReader; +import io.fd.honeycomb.translate.read.ReadContext; +import io.fd.honeycomb.translate.v3po.test.ContextTestUtils; +import io.fd.honeycomb.translate.MappingContext; +import io.fd.honeycomb.translate.read.registry.ReaderRegistry; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; +import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.PhysAddress; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.L2FibTable; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntry; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.l2.fib.attributes.l2.fib.table.L2FibEntryKey; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomains; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.Version; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.VersionBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainKey; +import org.opendaylight.yangtools.yang.binding.DataObject; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.VppInvocationException; +import org.openvpp.jvpp.dto.BridgeDomainDetails; +import org.openvpp.jvpp.dto.BridgeDomainDetailsReplyDump; +import org.openvpp.jvpp.dto.BridgeDomainDump; +import org.openvpp.jvpp.dto.L2FibTableDump; +import org.openvpp.jvpp.dto.L2FibTableEntry; +import org.openvpp.jvpp.dto.L2FibTableEntryReplyDump; +import org.openvpp.jvpp.dto.ShowVersion; +import org.openvpp.jvpp.dto.ShowVersionReply; +import org.openvpp.jvpp.future.FutureJVpp; + +public class VppStateTest { + + @Mock + private FutureJVpp api; + @Mock + private ReadContext ctx; + @Mock + private MappingContext mappingContext; + + private NamingContext bdContext; + private NamingContext interfaceContext; + + private ReaderRegistry readerRegistry; + + @Before + public void setUp() throws Exception { + initMocks(this); + final ModificationCache cache = new ModificationCache(); + doReturn(cache).when(ctx).getModificationCache(); + doReturn(mappingContext).when(ctx).getMappingContext(); + + bdContext = new NamingContext("generatedBdName", "bd-test-instance"); + interfaceContext = new NamingContext("generatedIfaceName", "ifc-test-instance"); + readerRegistry = VppStateTestUtils.getVppStateReader(api, bdContext); + } + + private static Version getVersion() { + return new VersionBuilder() + .setName("test") + .setBuildDirectory("1") + .setBranch("2") + .setBuildDate("3") + .build(); + } + + private void whenShowVersionThenReturn(int retval, Version version) + throws ExecutionException, InterruptedException, VppInvocationException { + final CompletableFuture<ShowVersionReply> replyFuture = new CompletableFuture<>(); + final ShowVersionReply reply = new ShowVersionReply(); + reply.buildDate = version.getBuildDate().getBytes(); + reply.program = version.getName().getBytes(); + reply.version = version.getBranch().getBytes(); + reply.buildDirectory = version.getBuildDirectory().getBytes(); + + replyFuture.complete(reply); + when(api.showVersion(any(ShowVersion.class))).thenReturn(replyFuture); + } + + private void whenL2FibTableDumpThenReturn(final List<L2FibTableEntry> entryList) + throws ExecutionException, InterruptedException, VppInvocationException { + final CompletionStage<L2FibTableEntryReplyDump> replyCS = mock(CompletionStage.class); + final CompletableFuture<L2FibTableEntryReplyDump> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final L2FibTableEntryReplyDump reply = new L2FibTableEntryReplyDump(); + reply.l2FibTableEntry = entryList; + when(replyFuture.get()).thenReturn(reply); + when(api.l2FibTableDump(any(L2FibTableDump.class))).thenReturn(replyCS); + } + + private void whenBridgeDomainDumpThenReturn(final List<BridgeDomainDetails> bdList) + throws ExecutionException, InterruptedException, VppInvocationException { + final CompletionStage<BridgeDomainDetailsReplyDump> replyCS = mock(CompletionStage.class); + final CompletableFuture<BridgeDomainDetailsReplyDump> replyFuture = mock(CompletableFuture.class); + when(replyCS.toCompletableFuture()).thenReturn(replyFuture); + final BridgeDomainDetailsReplyDump reply = new BridgeDomainDetailsReplyDump(); + reply.bridgeDomainDetails = bdList; + when(replyFuture.get()).thenReturn(reply); + + doAnswer(invocation -> { + BridgeDomainDump request = (BridgeDomainDump) invocation.getArguments()[0]; + if (request.bdId == -1) { + reply.bridgeDomainDetails = bdList; + } else { + reply.bridgeDomainDetails = Collections.singletonList(bdList.get(request.bdId)); + } + return replyCS; + }).when(api).bridgeDomainDump(any(BridgeDomainDump.class)); + } + + @Test + public void testReadAll() throws Exception { + final Version version = getVersion(); + whenShowVersionThenReturn(0, version); + + final BridgeDomainDetails bridgeDomainDetails = new BridgeDomainDetails(); + final BridgeDomainDetails bridgeDomainDetails2 = new BridgeDomainDetails(); + bridgeDomainDetails2.bdId = 1; + + final List<BridgeDomainDetails> bdList = Arrays.asList(bridgeDomainDetails, bridgeDomainDetails2); + mockBdMapping(bridgeDomainDetails, "bd1"); + mockBdMapping(bridgeDomainDetails2, "bd2"); + + whenBridgeDomainDumpThenReturn(bdList); + + final Multimap<InstanceIdentifier<? extends DataObject>, ? extends DataObject> dataObjects = + readerRegistry.readAll(ctx); + assertEquals(dataObjects.size(), 1); + final VppState dataObject = + (VppState) Iterables.getOnlyElement(dataObjects.get(Iterables.getOnlyElement(dataObjects.keySet()))); + assertEquals(version, dataObject.getVersion()); + assertEquals(2, dataObject.getBridgeDomains().getBridgeDomain().size()); + } + + @Test + public void testReadSpecific() throws Exception { + final Version version = getVersion(); + whenShowVersionThenReturn(0, version); + whenBridgeDomainDumpThenReturn(Collections.emptyList()); + + final Optional<? extends DataObject> read = readerRegistry.read(InstanceIdentifier.create(VppState.class), ctx); + assertTrue(read.isPresent()); + assertEquals(version, ((VppState) read.get()).getVersion()); + } + + @Test + public void testReadBridgeDomains() throws Exception { + final Version version = getVersion(); + whenShowVersionThenReturn(0, version); + final BridgeDomainDetails details = new BridgeDomainDetails(); + whenBridgeDomainDumpThenReturn(Collections.singletonList(details)); + + mockBdMapping(details, "bdn1"); + VppState readRoot = (VppState) readerRegistry.read(InstanceIdentifier.create(VppState.class), ctx).get(); + + Optional<? extends DataObject> read = + readerRegistry.read(InstanceIdentifier.create(VppState.class).child(BridgeDomains.class), ctx); + assertTrue(read.isPresent()); + assertEquals(readRoot.getBridgeDomains(), read.get()); + } + + /** + * L2fib does not have a dedicated reader, relying on auto filtering + */ + @Test + @Ignore("L2 FIB was moved to dedicated customizer. TODO: add infra test that covers such case") + @SuppressWarnings("unchecked") + public void testReadL2Fib() throws Exception { + final BridgeDomainDetails bd = new BridgeDomainDetails(); + bd.bdId = 0; + final String bdName = "bdn1"; + mockBdMapping(bd, bdName); + ContextTestUtils.mockMapping(mappingContext, "eth1", 0, "ifc-test-instance"); + + whenBridgeDomainDumpThenReturn(Collections.singletonList(bd)); + final L2FibTableEntry l2FibEntry = new L2FibTableEntry(); + l2FibEntry.bdId = 0; + l2FibEntry.mac = 0x0605040302010000L; + whenL2FibTableDumpThenReturn(Collections.singletonList(l2FibEntry)); + + // Deep child without a dedicated reader with specific l2fib key + final InstanceIdentifier<? extends DataObject> idExisting = + InstanceIdentifier.create(VppState.class).child(BridgeDomains.class).child( + BridgeDomain.class, new BridgeDomainKey("bdn1")).child(L2FibTable.class) + .child(L2FibEntry.class, new L2FibEntryKey(new PhysAddress("01:02:03:04:05:06"))); + Optional<? extends DataObject> read = + readerRegistry.read(idExisting, ctx); + assertTrue(read.isPresent()); + + // non existing l2fib + final InstanceIdentifier<? extends DataObject> idNonExisting = + InstanceIdentifier.create(VppState.class).child(BridgeDomains.class).child( + BridgeDomain.class, new BridgeDomainKey("bdn1")).child(L2FibTable.class) + .child(L2FibEntry.class, new L2FibEntryKey(new PhysAddress("FF:FF:FF:04:05:06"))); + read = readerRegistry.read(idNonExisting, ctx); + assertFalse(read.isPresent()); + } + + private void mockBdMapping(final BridgeDomainDetails bd, final String bdName) { + ContextTestUtils.mockMapping(mappingContext, bdName, bd.bdId, "bd-test-instance"); + } + + @Test + public void testReadBridgeDomainAll() throws Exception { + final Version version = getVersion(); + whenShowVersionThenReturn(0, version); + final BridgeDomainDetails details = new BridgeDomainDetails(); + whenBridgeDomainDumpThenReturn(Collections.singletonList(details)); + mockBdMapping(details, "bd2"); + + VppState readRoot = (VppState) readerRegistry.read(InstanceIdentifier.create(VppState.class), ctx).get(); + + final GenericListReader<BridgeDomain, BridgeDomainKey, BridgeDomainBuilder> bridgeDomainReader = + VppStateTestUtils.getBridgeDomainReader(api, bdContext); + + final List<BridgeDomain> read = + bridgeDomainReader.readList(InstanceIdentifier.create(VppState.class).child(BridgeDomains.class).child( + BridgeDomain.class), ctx); + + assertEquals(readRoot.getBridgeDomains().getBridgeDomain(), read); + } + + @Test + public void testReadBridgeDomain() throws Exception { + final BridgeDomainDetails bd = new BridgeDomainDetails(); + bd.bdId = 0; + final String bdName = "bdn1"; + mockBdMapping(bd, bdName); + + whenBridgeDomainDumpThenReturn(Collections.singletonList(bd)); + whenShowVersionThenReturn(0, getVersion()); + + VppState readRoot = (VppState) readerRegistry.read(InstanceIdentifier.create(VppState.class), ctx).get(); + + final Optional<? extends DataObject> read = + readerRegistry.read(InstanceIdentifier.create(VppState.class).child(BridgeDomains.class).child( + BridgeDomain.class, new BridgeDomainKey(bdName)), ctx); + + assertTrue(read.isPresent()); + assertEquals(readRoot.getBridgeDomains().getBridgeDomain().stream().filter( + input -> input.getKey().getName().equals(bdName)).findFirst().get(), + read.get()); + } + + @Test(expected = IllegalArgumentException.class) + public void testReadBridgeDomainNotExisting() throws Exception { + doReturn(Optional.absent()).when(mappingContext).read( + ContextTestUtils.getMappingIid("NOT EXISTING", "bd-test-instance")); + + final Optional<? extends DataObject> read = + readerRegistry.read(InstanceIdentifier.create(VppState.class).child(BridgeDomains.class).child( + BridgeDomain.class, new BridgeDomainKey("NOT EXISTING")), ctx); + assertFalse(read.isPresent()); + } + + @Test + public void testReadVersion() throws Exception { + whenShowVersionThenReturn(0, getVersion()); + whenBridgeDomainDumpThenReturn(Collections.emptyList()); + VppState readRoot = (VppState) readerRegistry.read(InstanceIdentifier.create(VppState.class), ctx).get(); + + Optional<? extends DataObject> read = + readerRegistry.read(InstanceIdentifier.create(VppState.class).child(Version.class), ctx); + assertTrue(read.isPresent()); + assertEquals(readRoot.getVersion(), read.get()); + } +}
\ No newline at end of file diff --git a/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTestUtils.java b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTestUtils.java new file mode 100644 index 000000000..b0f8e78d3 --- /dev/null +++ b/v3po/v3po2vpp/src/test/java/io/fd/honeycomb/translate/v3po/vppstate/VppStateTestUtils.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2016 Cisco and/or its affiliates. + * + * 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 io.fd.honeycomb.translate.v3po.vppstate; + +import io.fd.honeycomb.translate.impl.read.GenericListReader; +import io.fd.honeycomb.translate.impl.read.GenericReader; +import io.fd.honeycomb.translate.read.registry.ReaderRegistry; +import io.fd.honeycomb.translate.util.read.registry.CompositeReaderRegistryBuilder; +import io.fd.honeycomb.translate.v3po.util.NamingContext; +import javax.annotation.Nonnull; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppState; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.VppStateBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomains; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.BridgeDomainsBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.Version; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomain; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.v3po.rev150105.vpp.state.bridge.domains.BridgeDomainKey; +import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; +import org.openvpp.jvpp.future.FutureJVpp; + +final class VppStateTestUtils { + + private static InstanceIdentifier<BridgeDomains> bridgeDomainsId; + + public VppStateTestUtils() { + } + + /** + * Create root VppState reader with all its children wired. + */ + static ReaderRegistry getVppStateReader(@Nonnull final FutureJVpp jVpp, + @Nonnull final NamingContext bdContext) { + final CompositeReaderRegistryBuilder registry = new CompositeReaderRegistryBuilder(); + + // VppState(Structural) + final InstanceIdentifier<VppState> vppStateId = InstanceIdentifier.create(VppState.class); + registry.addStructuralReader(vppStateId, VppStateBuilder.class); + // Version + // Wrap with keepalive reader to detect connection issues + // TODO keepalive reader wrapper relies on VersionReaderCustomizer (to perform timeout on reads) + // Once readers+customizers are asynchronous, pull the timeout to keepalive executor so that keepalive wrapper + // is truly generic + registry.add(new GenericReader<>(vppStateId.child(Version.class), new VersionCustomizer(jVpp))); + // BridgeDomains(Structural) + bridgeDomainsId = vppStateId.child(BridgeDomains.class); + registry.addStructuralReader(bridgeDomainsId, BridgeDomainsBuilder.class); + // BridgeDomain + registry.add(getBridgeDomainReader(jVpp, bdContext)); + return registry.build(); + } + + static GenericListReader<BridgeDomain, BridgeDomainKey, BridgeDomainBuilder> getBridgeDomainReader( + final @Nonnull FutureJVpp jVpp, final @Nonnull NamingContext bdContext) { + final InstanceIdentifier<BridgeDomain> bridgeDomainId = bridgeDomainsId.child(BridgeDomain.class); + return new GenericListReader<>(bridgeDomainId, new BridgeDomainCustomizer(jVpp, bdContext)); + } +} |