BUG-4592: RR message operation impl
[bgpcep.git] / bgp / rib-impl / src / test / java / org / opendaylight / protocol / bgp / rib / impl / BGPSessionImplTest.java
index 286bae6b3b10af5fcdf795629f4cae2f45965838..f41f1ded7615c6a81bb903edb09d5999fe6ee3db 100644 (file)
@@ -10,36 +10,24 @@ package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
 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 com.google.common.collect.Lists;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelHandler;
-import io.netty.channel.ChannelPipeline;
-import io.netty.channel.EventLoop;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.GenericFutureListener;
-import io.netty.util.concurrent.GlobalEventExecutor;
-import java.net.InetAddress;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelOutboundHandlerAdapter;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.embedded.EmbeddedChannel;
 import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.TimeUnit;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 import org.opendaylight.controller.config.yang.bgp.rib.impl.BgpSessionState;
 import org.opendaylight.protocol.bgp.parser.BGPError;
+import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
 import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
+import org.opendaylight.protocol.bgp.parser.spi.pojo.ServiceLoaderBGPExtensionProviderContext;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.AsNumber;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.KeepaliveBuilder;
@@ -50,15 +38,18 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.mess
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.ProtocolVersion;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.Update;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.UpdateBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParameters;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.BgpParametersBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilities;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.OptionalCapabilitiesBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.As4BytesCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.as4.bytes._case.As4BytesCapabilityBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParameters;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.BgpParametersBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilities;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.OptionalCapabilitiesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.CParametersBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev130919.open.message.bgp.parameters.optional.capabilities.c.parameters.As4BytesCapabilityBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.BgpTableType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCaseBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.multiprotocol._case.MultiprotocolCapabilityBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.CParameters1Builder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.RouteRefreshBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.GracefulRestartCapabilityBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev130919.open.bgp.parameters.optional.capabilities.c.parameters.MultiprotocolCapabilityBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.Ipv4AddressFamily;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.UnicastSubsequentAddressFamily;
 import org.opendaylight.yangtools.yang.binding.Notification;
@@ -71,75 +62,51 @@ public class BGPSessionImplTest {
     private static final String LOCAL_IP = "1.1.1.4";
     private static final int LOCAL_PORT = 12345;
 
-    @Mock
-    private EventLoop eventLoop;
-
-    @Mock
-    private Channel speakerListener;
-
-    @Mock
-    private ChannelPipeline pipeline;
-
     private final BgpTableType ipv4tt = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
 
-    private final List<Notification> receivedMsgs = Lists.newArrayList();
-
     private Open classicOpen;
 
     private BGPSessionImpl bgpSession;
 
     private SimpleSessionListener listener;
 
+    private EmbeddedChannel embeddedChannel;
+
+    private MessageCollector collector;
+
     @Before
     public void setUp() throws UnknownHostException {
-        MockitoAnnotations.initMocks(this);
-        final List<BgpParameters> tlvs = Lists.newArrayList();
-        this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER).setVersion(new ProtocolVersion((short) 4)).setBgpParameters(
-                tlvs).setBgpIdentifier(BGP_ID).build();
+        this.collector = new MessageCollector();
+        this.embeddedChannel = Mockito.spy(new EmbeddedChannel());
+        final BGPHandlerFactory hf = new BGPHandlerFactory(ServiceLoaderBGPExtensionProviderContext.getSingletonInstance().getMessageRegistry());
+        this.embeddedChannel.pipeline().addLast(hf.getDecoders());
+        this.embeddedChannel.pipeline().addLast(this.collector);
+        Mockito.doReturn(new InetSocketAddress(BGP_ID.getValue(), LOCAL_PORT)).when(this.embeddedChannel).remoteAddress();
+        Mockito.doReturn(new InetSocketAddress(LOCAL_IP, LOCAL_PORT)).when(this.embeddedChannel).localAddress();
 
+        final List<BgpParameters> tlvs = Lists.newArrayList();
         final List<OptionalCapabilities> capa = Lists.newArrayList();
+        capa.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(CParameters1.class,
+            new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
+                .setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build()).build());
+        capa.add(new OptionalCapabilitiesBuilder().setCParameters(
+                new CParametersBuilder().addAugmentation(
+                        CParameters1.class, new CParameters1Builder().setGracefulRestartCapability(
+                                new GracefulRestartCapabilityBuilder().build()).build()).build()).build());
+        capa.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
         capa.add(new OptionalCapabilitiesBuilder().setCParameters(
-            new MultiprotocolCaseBuilder().setMultiprotocolCapability(
-                new MultiprotocolCapabilityBuilder().setAfi(this.ipv4tt.getAfi()).setSafi(this.ipv4tt.getSafi()).build()).build()).build());
-        capa.add(new OptionalCapabilitiesBuilder().setCParameters(new As4BytesCaseBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(
-            AS_NUMBER).build()).build()).build());
+                new CParametersBuilder().setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(AS_NUMBER).build()).build()).build());
         tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capa).build());
+        this.classicOpen = new OpenBuilder().setMyAsNumber(AS_NUMBER.getValue().intValue()).setHoldTimer(HOLD_TIMER)
+                .setVersion(new ProtocolVersion((short) 4)).setBgpParameters(tlvs).setBgpIdentifier(BGP_ID).build();
 
-        final ChannelFuture f = mock(ChannelFuture.class);
-        doReturn(null).when(f).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
-
-        doAnswer(new Answer<Object>() {
-            @Override
-            public Object answer(final InvocationOnMock invocation) {
-                final Object[] args = invocation.getArguments();
-                BGPSessionImplTest.this.receivedMsgs.add((Notification) args[0]);
-                return f;
-            }
-        }).when(this.speakerListener).writeAndFlush(any(Notification.class));
-        doReturn(this.eventLoop).when(this.speakerListener).eventLoop();
-        doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable command = (Runnable) invocation.getArguments()[0];
-                final long delay = (long) invocation.getArguments()[1];
-                final TimeUnit unit = (TimeUnit) invocation.getArguments()[2];
-                GlobalEventExecutor.INSTANCE.schedule(command, delay, unit);
-                return null;
-            }
-        }).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
-        doReturn("TestingChannel").when(this.speakerListener).toString();
-        doReturn(new InetSocketAddress(InetAddress.getByName(BGP_ID.getValue()), 179)).when(this.speakerListener).remoteAddress();
-        doReturn(new InetSocketAddress(InetAddress.getByName(LOCAL_IP), LOCAL_PORT)).when(this.speakerListener).localAddress();
-        doReturn(this.pipeline).when(this.speakerListener).pipeline();
-        doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
-        doReturn(mock(ChannelFuture.class)).when(this.speakerListener).close();
         this.listener = new SimpleSessionListener();
-        this.bgpSession = new BGPSessionImpl(this.listener, this.speakerListener, this.classicOpen, this.classicOpen.getHoldTimer());
+        this.bgpSession = new BGPSessionImpl(this.listener, this.embeddedChannel, this.classicOpen, this.classicOpen.getHoldTimer(), null);
+        this.embeddedChannel.pipeline().addFirst(this.bgpSession);
     }
 
     @Test
     public void testBGPSession() {
-        this.bgpSession.sessionUp();
         assertEquals(BGPSessionImpl.State.UP, this.bgpSession.getState());
         assertEquals(AS_NUMBER, this.bgpSession.getAsNumber());
         assertEquals(BGP_ID, this.bgpSession.getBgpId());
@@ -152,10 +119,13 @@ public class BGPSessionImplTest {
         assertEquals(BGPSessionImpl.State.UP.name(), state.getSessionState());
         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getAddress());
         assertEquals(AS_NUMBER.getValue(), state.getPeerPreferences().getAs());
+        assertTrue(state.getPeerPreferences().getBgpExtendedMessageCapability());
         assertEquals(BGP_ID.getValue(), state.getPeerPreferences().getBgpId());
         assertEquals(1, state.getPeerPreferences().getAdvertizedTableTypes().size());
         assertEquals(HOLD_TIMER, state.getPeerPreferences().getHoldtime().intValue());
-        assertTrue(state.getPeerPreferences().getFourOctetAsCapability());
+        assertTrue(state.getPeerPreferences().getFourOctetAsCapability().booleanValue());
+        assertTrue(state.getPeerPreferences().getBgpExtendedMessageCapability().booleanValue());
+        assertTrue(state.getPeerPreferences().getGrCapability());
         assertEquals(LOCAL_IP, state.getSpeakerPreferences().getAddress());
         assertEquals(LOCAL_PORT, state.getSpeakerPreferences().getPort().intValue());
         assertEquals(0, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
@@ -168,21 +138,26 @@ public class BGPSessionImplTest {
         assertEquals(1, state.getMessagesStats().getUpdateMsgs().getReceived().getCount().longValue());
         assertEquals(0, state.getMessagesStats().getUpdateMsgs().getSent().getCount().longValue());
 
+        this.bgpSession.handleMessage(new RouteRefreshBuilder().build());
+        assertEquals(2, this.listener.getListMsg().size());
+        assertEquals(1, state.getMessagesStats().getRouteRefreshMsgs().getReceived().getCount().longValue());
+        assertEquals(0, state.getMessagesStats().getRouteRefreshMsgs().getSent().getCount().longValue());
+
         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
         this.bgpSession.handleMessage(new KeepaliveBuilder().build());
-        assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
+        assertEquals(4, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
         assertEquals(2, state.getMessagesStats().getKeepAliveMsgs().getReceived().getCount().longValue());
         assertEquals(0, state.getMessagesStats().getKeepAliveMsgs().getSent().getCount().longValue());
 
         this.bgpSession.close();
         assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
-        assertEquals(1, this.receivedMsgs.size());
-        assertTrue(this.receivedMsgs.get(0) instanceof Notify);
-        final Notify error = (Notify) this.receivedMsgs.get(0);
+        assertEquals(1, this.collector.receivedMsgs.size());
+        assertTrue(this.collector.receivedMsgs.get(0) instanceof Notify);
+        final Notify error = (Notify) this.collector.receivedMsgs.get(0);
         assertEquals(BGPError.CEASE.getCode(), error.getErrorCode().shortValue());
         assertEquals(BGPError.CEASE.getSubcode(), error.getErrorSubcode().shortValue());
-        Mockito.verify(this.speakerListener).close();
-        assertEquals(3, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
+        Mockito.verify(this.embeddedChannel).close();
+        assertEquals(4, state.getMessagesStats().getTotalMsgs().getReceived().getCount().longValue());
         assertEquals(1, state.getMessagesStats().getTotalMsgs().getSent().getCount().longValue());
         assertEquals(1, state.getMessagesStats().getErrorMsgs().getErrorSent().getCount().longValue());
         assertEquals(BGPError.CEASE.getCode(), state.getMessagesStats().getErrorMsgs().getErrorSent().getCode().shortValue());
@@ -198,12 +173,12 @@ public class BGPSessionImplTest {
     public void testHandleOpenMsg() {
         this.bgpSession.handleMessage(this.classicOpen);
         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
-        Assert.assertEquals(1, this.receivedMsgs.size());
-        Assert.assertTrue(this.receivedMsgs.get(0) instanceof Notify);
-        final Notify error = (Notify) this.receivedMsgs.get(0);
+        Assert.assertEquals(1, this.collector.receivedMsgs.size());
+        Assert.assertTrue(this.collector.receivedMsgs.get(0) instanceof Notify);
+        final Notify error = (Notify) this.collector.receivedMsgs.get(0);
         Assert.assertEquals(BGPError.FSM_ERROR.getCode(), error.getErrorCode().shortValue());
         Assert.assertEquals(BGPError.FSM_ERROR.getSubcode(), error.getErrorSubcode().shortValue());
-        Mockito.verify(this.speakerListener).close();
+        Mockito.verify(this.embeddedChannel).close();
     }
 
     @Test
@@ -213,12 +188,11 @@ public class BGPSessionImplTest {
         assertEquals(BGPError.BAD_BGP_ID.getCode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getCode().shortValue());
         assertEquals(BGPError.BAD_BGP_ID.getSubcode(), this.bgpSession.getBgpSesionState().getMessagesStats().getErrorMsgs().getErrorReceived().getSubCode().shortValue());
         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
-        Mockito.verify(this.speakerListener).close();
+        Mockito.verify(this.embeddedChannel).close();
     }
 
     @Test
     public void testEndOfInput() {
-        this.bgpSession.sessionUp();
         Assert.assertFalse(this.listener.down);
         this.bgpSession.endOfInput();
         Assert.assertTrue(this.listener.down);
@@ -226,14 +200,25 @@ public class BGPSessionImplTest {
 
     @Test
     public void testHoldTimerExpire() throws InterruptedException {
-        this.bgpSession.sessionUp();
-        Thread.sleep(3500);
+        while (this.embeddedChannel.runScheduledPendingTasks() != -1) {
+        }
         Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
-        Assert.assertEquals(3, this.receivedMsgs.size());
-        Assert.assertTrue(this.receivedMsgs.get(2) instanceof Notify);
-        final Notify error = (Notify) this.receivedMsgs.get(2);
+        Assert.assertEquals(3, this.collector.receivedMsgs.size());
+        Assert.assertTrue(this.collector.receivedMsgs.get(2) instanceof Notify);
+        final Notify error = (Notify) this.collector.receivedMsgs.get(2);
         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getCode(), error.getErrorCode().shortValue());
         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getSubcode(), error.getErrorSubcode().shortValue());
-        Mockito.verify(this.speakerListener).close();
+        Mockito.verify(this.embeddedChannel).close();
+    }
+
+    private static final class MessageCollector extends ChannelOutboundHandlerAdapter {
+
+        private final List<Notification> receivedMsgs = new ArrayList<>();
+
+        @Override
+        public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception {
+            this.receivedMsgs.add((Notification) msg);
+            super.write(ctx, msg, promise);
+        }
     }
 }