BUG-6120: Fix intermitent test fail 88/42288/2
authorClaudio <cgaspari@cisco.com>
Fri, 22 Jul 2016 07:24:50 +0000 (09:24 +0200)
committerMilos Fabian <milfabia@cisco.com>
Fri, 22 Jul 2016 15:07:55 +0000 (15:07 +0000)
Improve test to wait for at least 10 seconds

Change-Id: I50cde477f374069e577ee930ca3193ca16840a75
Signed-off-by: Claudio <cgaspari@cisco.com>
18 files changed:
bgp/bmp-mock/src/main/java/org/opendaylight/protocol/bmp/mock/BmpMockDispatcher.java
bgp/bmp-mock/src/test/java/org/opendaylight/protocol/bmp/mock/BmpMockDispatcherTest.java
bgp/bmp-mock/src/test/java/org/opendaylight/protocol/bmp/mock/BmpMockTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/BGPDispatcherImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/BGPSessionImplTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/FSMTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SimpleSessionListener.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/PCEPDispatcherImplTest.java
pcep/pcc-mock/src/main/java/org/opendaylight/protocol/pcep/pcc/mock/protocol/PCCDispatcherImpl.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCDispatcherImplTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCIncrementalSyncTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCMockCommon.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCSyncAvoidanceProcedureTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCTriggeredFullDBResyncTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCTriggeredLspResyncTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCTriggeredSyncTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/TestingSessionListener.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/WaitForFutureSucces.java [new file with mode: 0644]

index 9d60873f3b35f5046e09e1888a23d673d70d5b9a..b7c2e30133bf8fb1e09b7e94b44e07b888e2e175 100644 (file)
@@ -42,6 +42,7 @@ public final class BmpMockDispatcher {
         b.channel(NioSocketChannel.class);
         b.option(ChannelOption.SO_KEEPALIVE, true);
         b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 2000);
+        b.option(ChannelOption.SO_REUSEADDR, true);
         b.group(workergroup);
 
         b.handler(new ChannelInitializer<NioSocketChannel>() {
index 5c88113f401477ae0b787fb8eb1a3e2af5870544..79b831e21cb3a2cdaed4c66fdebfb076a141a713 100644 (file)
@@ -8,6 +8,8 @@
 
 package org.opendaylight.protocol.bmp.mock;
 
+import static org.opendaylight.protocol.bmp.mock.BmpMockTest.waitFutureSuccess;
+
 import com.google.common.base.Optional;
 import com.google.common.net.InetAddresses;
 import io.netty.channel.Channel;
@@ -39,6 +41,7 @@ public class BmpMockDispatcherTest {
 
         final ChannelFuture channelFuture = dispatcher.createClient(new InetSocketAddress(InetAddresses.forString("127.0.0.2"), 0),
                 new InetSocketAddress(InetAddresses.forString("127.0.0.3"), port));
+        waitFutureSuccess(channelFuture);
         final Channel channel = channelFuture.sync().channel();
 
         Assert.assertTrue(channel.isActive());
index 53b2e887e92a7daf2c96ee67c3183bc207a8cb5a..4b77c4e8b7f72f31617ee04a9f5c0577bed8b3fb 100644 (file)
@@ -9,9 +9,15 @@
 package org.opendaylight.protocol.bmp.mock;
 
 import com.google.common.base.Optional;
+import com.google.common.util.concurrent.Uninterruptibles;
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
 import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
 import java.net.InetSocketAddress;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -39,13 +45,13 @@ public class BmpMockTest {
     private BmpDispatcher bmpDispatcher;
 
     @Before
-    public void setUp() {
+    public void setUp() throws InterruptedException {
         final BmpExtensionProviderContext ctx = new SimpleBmpExtensionProviderContext();
         this.bmpActivator = new BmpActivator(
-                ServiceLoaderBGPExtensionProviderContext.getSingletonInstance());
+            ServiceLoaderBGPExtensionProviderContext.getSingletonInstance());
         this.bmpActivator.start(ctx);
         this.bmpDispatcher = new BmpDispatcherImpl(new NioEventLoopGroup(), new NioEventLoopGroup(), ctx.getBmpMessageRegistry(),
-                new DefaultBmpSessionFactory());
+            new DefaultBmpSessionFactory());
         final BmpSessionListenerFactory bmpSessionListenerFactory = new BmpSessionListenerFactory() {
             @Override
             public BmpSessionListener getSessionListener() {
@@ -53,8 +59,10 @@ public class BmpMockTest {
             }
         };
         this.serverPort = BmpMockDispatcherTest.getRandomPort();
-        this.serverChannel = this.bmpDispatcher.createServer(new InetSocketAddress("127.0.0.1", this.serverPort),
-                bmpSessionListenerFactory, Optional.<KeyMapping>absent()).channel();
+        final ChannelFuture futureServer = this.bmpDispatcher.createServer(new InetSocketAddress("127.0.0.1", this.serverPort),
+            bmpSessionListenerFactory, Optional.<KeyMapping>absent());
+        waitFutureSuccess(futureServer);
+        this.serverChannel = futureServer.channel();
     }
 
     @After
@@ -66,11 +74,21 @@ public class BmpMockTest {
 
     @Test
     public void testMain() throws Exception {
-        BmpMock.main(new String[] {"--remote_address", "127.0.0.1:" + serverPort, "--peers_count", "3", "--pre_policy_routes", "3"});
+        BmpMock.main(new String[]{"--remote_address", "127.0.0.1:" + serverPort, "--peers_count", "3", "--pre_policy_routes", "3"});
         Thread.sleep(1000);
         Mockito.verify(this.sessionListener).onSessionUp(Mockito.any(BmpSession.class));
         //1 * Initiate message + 3 * PeerUp Notification + 9 * Route Monitoring message
         Mockito.verify(this.sessionListener, Mockito.times(13)).onMessage(Mockito.any(BmpSession.class), Mockito.any(Notification.class));
     }
 
+    static void waitFutureSuccess(final ChannelFuture future) throws InterruptedException {
+        final CountDownLatch latch = new CountDownLatch(1);
+        future.addListener(new GenericFutureListener<Future<? super Void>>() {
+            @Override
+            public void operationComplete(final Future<? super Void> future) throws Exception {
+                latch.countDown();
+            }
+        });
+        Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS);
+    }
 }
index d00914fb64a88c3e555267505edb4f6807de4646..14e29638145a49f8db03180a73242fc8d4d9f211 100644 (file)
@@ -11,16 +11,20 @@ package org.opendaylight.protocol.bgp.rib.impl;
 import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.Uninterruptibles;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.FutureListener;
 import io.netty.util.concurrent.GenericFutureListener;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import java.net.InetSocketAddress;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -68,7 +72,7 @@ public class BGPDispatcherImplTest {
     private Channel channel;
 
     @Before
-    public void setUp() throws BGPDocumentedException {
+    public void setUp() throws BGPDocumentedException, InterruptedException {
         final EventLoopGroup group = new NioEventLoopGroup();
         this.registry = new StrictBGPPeerRegistry();
         this.registry.addPeer(new IpAddress(new Ipv4Address(CLIENT_ADDRESS.getAddress().getHostAddress())),
@@ -80,6 +84,7 @@ public class BGPDispatcherImplTest {
                 CLIENT_ADDRESS);
 
         final ChannelFuture future = this.dispatcher.createServer(this.registry, ADDRESS);
+        waitFutureSuccess(future);
         future.addListener(new GenericFutureListener<Future<Void>>() {
             @Override
             public void operationComplete(final Future<Void> future) {
@@ -91,10 +96,23 @@ public class BGPDispatcherImplTest {
         this.channel = future.channel();
     }
 
+    private static <T extends Future> void waitFutureSuccess(final T future) throws InterruptedException {
+        final CountDownLatch latch = new CountDownLatch(1);
+        future.addListener(new FutureListener<T>() {
+            @Override
+            public void operationComplete(final Future<T> future) throws Exception {
+                latch.countDown();
+            }
+        });
+        Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS);
+    }
+
     @Test
     public void testCreateClient() throws InterruptedException, ExecutionException {
-        final BGPSessionImpl session = this.clientDispatcher.createClient(ADDRESS, this.registry,
-                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, TIMEOUT), Optional.<InetSocketAddress>absent()).get();
+        final Future<BGPSessionImpl> futureClient = this.clientDispatcher.createClient(ADDRESS, this.registry,
+                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, TIMEOUT), Optional.<InetSocketAddress>absent());
+        waitFutureSuccess(futureClient);
+        final BGPSessionImpl session =   futureClient.get();
         Assert.assertEquals(BGPSessionImpl.State.UP, session.getState());
         Assert.assertEquals(AS_NUMBER, session.getAsNumber());
         Assert.assertEquals(Sets.newHashSet(this.ipv4tt), session.getAdvertisedTableTypes());
@@ -114,9 +132,10 @@ public class BGPDispatcherImplTest {
         this.registry.addPeer(new IpAddress(new Ipv4Address(CLIENT_ADDRESS2.getAddress().getHostAddress())), listener, createPreferences(CLIENT_ADDRESS2));
         final Future<Void> cf = this.clientDispatcher.createReconnectingClient(CLIENT_ADDRESS2, this.registry,
                 new ReconnectStrategyFctImpl(), Optional.<InetSocketAddress>absent());
-        final Channel channel2 = this.dispatcher.createServer(this.registry, CLIENT_ADDRESS2).channel();
-        Thread.sleep(1000);
-        Assert.assertTrue(listener.up);
+        final ChannelFuture future = this.dispatcher.createServer(this.registry, CLIENT_ADDRESS2);
+        waitFutureSuccess(future);
+        final Channel channel2 = future.channel();
+        Assert.assertTrue(listener.isUp());
         Assert.assertTrue(channel2.isActive());
         cf.cancel(true);
         listener.releaseConnection();
index 06fdec89142d8aeab18d4f5b48642295741de703..549239e15aacb001891e78d31bb2e80db8fed86b 100644 (file)
@@ -15,7 +15,9 @@ import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
+import com.google.common.base.Stopwatch;
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Uninterruptibles;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelHandler;
@@ -233,8 +235,7 @@ public class BGPSessionImplTest {
     @Test
     public void testHoldTimerExpire() throws InterruptedException {
         this.bgpSession.sessionUp();
-        Thread.sleep(3500);
-        Assert.assertEquals(BGPSessionImpl.State.IDLE, this.bgpSession.getState());
+        checkIdleState(this.bgpSession);
         Assert.assertEquals(3, this.receivedMsgs.size());
         Assert.assertTrue(this.receivedMsgs.get(2) instanceof Notify);
         final Notify error = (Notify) this.receivedMsgs.get(2);
@@ -242,4 +243,16 @@ public class BGPSessionImplTest {
         Assert.assertEquals(BGPError.HOLD_TIMER_EXPIRED.getSubcode(), error.getErrorSubcode().shortValue());
         Mockito.verify(this.speakerListener).close();
     }
+
+    static void checkIdleState (final BGPSessionImpl session){
+        final Stopwatch sw = Stopwatch.createStarted();
+        while(sw.elapsed(TimeUnit.SECONDS) <= 10) {
+            if (BGPSessionImpl.State.IDLE != session.getState()){
+                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+            } else {
+                return;
+            }
+        }
+        Assert.fail();
+    }
 }
index 8158ad1a19937d8ea586f46a4d31fc7a993d768e..d44ca64b8cb114ce7f885c914f777ccffafbba5b 100644 (file)
@@ -160,8 +160,6 @@ public class FSMTest {
         assertTrue(this.receivedMsgs.get(1) instanceof Keepalive);
         this.clientSession.handleMessage(new KeepaliveBuilder().build());
         assertEquals(this.clientSession.getState(), BGPClientSessionNegotiator.State.FINISHED);
-        Thread.sleep(1000);
-        Thread.sleep(100);
     }
 
     @Test
index c7e3d3aaca2c454a82bb39d4622b212244dd4020..ad73d2244caef7d8b406d02f0158b9aa1fef346e 100644 (file)
@@ -7,8 +7,13 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
+import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Uninterruptibles;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.junit.Assert;
 import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
 import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
 import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
@@ -38,6 +43,7 @@ public class SimpleSessionListener implements BGPSessionListener {
     public List<Notification> getListMsg() {
         return this.listMsg;
     }
+    private final CountDownLatch sessionLatch = new CountDownLatch(1);
 
     @Override
     public void onMessage(final BGPSession session, final Notification message) {
@@ -50,6 +56,7 @@ public class SimpleSessionListener implements BGPSessionListener {
         LOG.debug("Session Up");
         this.session = session;
         this.up = true;
+        sessionLatch.countDown();
     }
 
     @Override
@@ -85,4 +92,13 @@ public class SimpleSessionListener implements BGPSessionListener {
     public void markUptodate(final TablesKey tablesKey) {
         LOG.debug("Table marked as up-to-date {}", tablesKey);
     }
+
+    public boolean isUp() {
+        Preconditions.checkNotNull(getSession());
+        return up;
+    }
+    public BGPSessionImpl getSession() {
+        Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(sessionLatch, 10, TimeUnit.SECONDS));
+        return (BGPSessionImpl) this.session;
+    }
 }
index 1879bd21551a53ead6981649f14640e0afc629c5..b541098728093db4c2786772edce9ed1d751791b 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.protocol.pcep.impl;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.Uninterruptibles;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelInitializer;
@@ -21,13 +22,16 @@ import io.netty.channel.socket.nio.NioSocketChannel;
 import io.netty.util.concurrent.DefaultPromise;
 import io.netty.util.concurrent.EventExecutor;
 import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.FutureListener;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import io.netty.util.concurrent.Promise;
 import java.net.InetSocketAddress;
 import java.nio.channels.Channel;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -98,23 +102,28 @@ public class PCEPDispatcherImplTest {
                         return new SimpleSessionListener();
                     }
                 }, null);
-        final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(CLIENT1_ADDRESS,
-                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
-                new PCEPSessionListenerFactory() {
-                    @Override
-                    public PCEPSessionListener getSessionListener() {
-                        return new SimpleSessionListener();
-                    }
-                }).get();
+        waitFutureSuccess(futureChannel);
+        final Future<PCEPSession> client1 = this.pccMock.createClient(CLIENT1_ADDRESS,
+            new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
+            new PCEPSessionListenerFactory() {
+                @Override
+                public PCEPSessionListener getSessionListener() {
+                    return new SimpleSessionListener();
+                }
+            });
+        waitFutureSuccess(client1);
+        final PCEPSessionImpl session1 = (PCEPSessionImpl) client1.get();
 
-        final PCEPSessionImpl session2 = (PCEPSessionImpl) this.pccMock.createClient(CLIENT2_ADDRESS,
-                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
-                new PCEPSessionListenerFactory() {
-                    @Override
-                    public PCEPSessionListener getSessionListener() {
-                        return new SimpleSessionListener();
-                    }
-                }).get();
+        final Future<PCEPSession> client2 = this.pccMock.createClient(CLIENT2_ADDRESS,
+            new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
+            new PCEPSessionListenerFactory() {
+                @Override
+                public PCEPSessionListener getSessionListener() {
+                    return new SimpleSessionListener();
+                }
+            });
+        waitFutureSuccess(client2);
+        final PCEPSessionImpl session2 = (PCEPSessionImpl) client2.get();
 
         Assert.assertTrue(futureChannel.channel().isActive());
         Assert.assertEquals(CLIENT1_ADDRESS.getAddress().getHostAddress(), session1.getPeerPref().getIpAddress());
@@ -130,23 +139,37 @@ public class PCEPDispatcherImplTest {
         Assert.assertTrue(futureChannel.channel().isActive());
     }
 
+    static <T extends Future> void waitFutureSuccess(final T future) throws InterruptedException {
+        final CountDownLatch latch = new CountDownLatch(1);
+        future.addListener(new FutureListener() {
+            @Override
+            public void operationComplete(final Future future) throws Exception {
+                latch.countDown();
+            }
+        });
+        Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS);
+    }
+
     @Test
     public void testCreateDuplicateClient() throws InterruptedException, ExecutionException {
-        this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", PORT),
-                new PCEPSessionListenerFactory() {
-                    @Override
-                    public PCEPSessionListener getSessionListener() {
-                        return new SimpleSessionListener();
-                    }
-                }, null);
-        final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(CLIENT1_ADDRESS,
+        final ChannelFuture futureServer = this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", PORT),
+            new PCEPSessionListenerFactory() {
+                @Override
+                public PCEPSessionListener getSessionListener() {
+                    return new SimpleSessionListener();
+                }
+            }, null);
+        waitFutureSuccess(futureServer);
+        final Future<PCEPSession> futureClient = this.pccMock.createClient(CLIENT1_ADDRESS,
             new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
             new PCEPSessionListenerFactory() {
                 @Override
                 public PCEPSessionListener getSessionListener() {
                     return new SimpleSessionListener();
                 }
-            }).get();
+            });
+        waitFutureSuccess(futureClient);
+        final PCEPSessionImpl session1 = (PCEPSessionImpl) futureClient.get();
 
         try {
             this.pccMock.createClient(CLIENT1_ADDRESS,
@@ -167,21 +190,25 @@ public class PCEPDispatcherImplTest {
 
     @Test
     public void testReconectClient() throws InterruptedException, ExecutionException {
-        this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", PORT),
-                new PCEPSessionListenerFactory() {
-                    @Override
-                    public PCEPSessionListener getSessionListener() {
-                        return new SimpleSessionListener();
-                    }
-                }, null);
-        final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(CLIENT1_ADDRESS,
-                new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
-                new PCEPSessionListenerFactory() {
-                    @Override
-                    public PCEPSessionListener getSessionListener() {
-                        return new SimpleSessionListener();
-                    }
-                }).get();
+        final ChannelFuture futureServer = this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", PORT),
+            new PCEPSessionListenerFactory() {
+                @Override
+                public PCEPSessionListener getSessionListener() {
+                    return new SimpleSessionListener();
+                }
+            }, null);
+        waitFutureSuccess(futureServer);
+
+        final Future<PCEPSession> client = this.pccMock.createClient(CLIENT1_ADDRESS,
+            new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 500),
+            new PCEPSessionListenerFactory() {
+                @Override
+                public PCEPSessionListener getSessionListener() {
+                    return new SimpleSessionListener();
+                }
+            });
+        waitFutureSuccess(client);
+        final PCEPSessionImpl session1 =  (PCEPSessionImpl)  client.get();
 
         Assert.assertEquals(CLIENT1_ADDRESS.getAddress(), session1.getRemoteAddress());
         Assert.assertEquals(DEAD_TIMER, session1.getDeadTimerValue().shortValue());
@@ -205,7 +232,7 @@ public class PCEPDispatcherImplTest {
     }
 
     @Test
-    public void testCustomizeBootstrap() {
+    public void testCustomizeBootstrap() throws InterruptedException {
         final KeyMapping keys = new KeyMapping();
         keys.put(CLIENT1_ADDRESS.getAddress(), new String("CLIENT1_ADDRESS").getBytes() );
         keys.put(CLIENT2_ADDRESS.getAddress(), new String("CLIENT2_ADDRESS").getBytes() );
@@ -217,6 +244,7 @@ public class PCEPDispatcherImplTest {
                     return new SimpleSessionListener();
                 }
             }, null);
+        waitFutureSuccess(futureChannel);
         Mockito.verify(this.disp2Spy).createServerBootstrap(Mockito.any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
     }
 
index a2737832504e5f72679025822b39f6d35954b511..b82ebd7ca6245e897923011fb792268a8a95a8fb 100644 (file)
@@ -103,6 +103,7 @@ public final class PCCDispatcherImpl implements PCCDispatcher, AutoCloseable {
         setChannelFactory(b, keys);
         b.option(ChannelOption.SO_KEEPALIVE, true);
         b.option(ChannelOption.MAX_MESSAGES_PER_READ, 1);
+        b.option(ChannelOption.SO_REUSEADDR, true);
         final ReconnectStrategyFactory reconnectStrategy = reconnectTime == -1 ? getNeverReconnectStrategyFactory() : getTimedReconnectStrategyFactory(reconnectTime);
         final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, reconnectStrategy, b);
         final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
index 6036d542bb27e67879f8e896fa09b4f1661d6986..3435501162893e7b7b0afc73eeadc0f72870b8d9 100644 (file)
@@ -8,7 +8,11 @@
 
 package org.opendaylight.protocol.pcep.pcc.mock;
 
+import static org.opendaylight.protocol.pcep.pcc.mock.PCCMockCommon.checkSessionListenerNotNull;
+import static org.opendaylight.protocol.pcep.pcc.mock.WaitForFutureSucces.waitFutureSuccess;
+
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.util.concurrent.Future;
@@ -35,13 +39,12 @@ public class PCCDispatcherImplTest {
 
     private static final List<PCEPCapability> CAPS = new ArrayList<>();
     private static final PCEPSessionProposalFactory PROPOSAL = new BasePCEPSessionProposalFactory(30, 120, CAPS);
-
-    private PCCDispatcherImpl dispatcher;
     private final DefaultPCEPSessionNegotiatorFactory nf = new DefaultPCEPSessionNegotiatorFactory(PROPOSAL, 0);
+    private final Random random = new Random();
+    private PCCDispatcherImpl dispatcher;
     private PCEPDispatcher pcepDispatcher;
     private InetSocketAddress serverAddress;
     private InetSocketAddress clientAddress;
-    private final Random random = new Random();
     private EventLoopGroup workerGroup;
     private EventLoopGroup bossGroup;
 
@@ -51,7 +54,7 @@ public class PCCDispatcherImplTest {
         this.bossGroup = new NioEventLoopGroup();
         this.dispatcher = new PCCDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry());
         this.pcepDispatcher = new PCEPDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry(),
-                this.nf, this.bossGroup, this.workerGroup);
+            this.nf, this.bossGroup, this.workerGroup);
         this.serverAddress = new InetSocketAddress("127.0.5.0", getRandomPort());
         this.clientAddress = new InetSocketAddress("127.0.4.0", getRandomPort());
     }
@@ -66,13 +69,17 @@ public class PCCDispatcherImplTest {
     @Test
     public void testClientReconnect() throws Exception {
         final Future<PCEPSession> futureSession = this.dispatcher.createClient(this.serverAddress, 500, new TestingSessionListenerFactory(),
-                this.nf, null, this.clientAddress);
+            this.nf, null, this.clientAddress);
 
         final TestingSessionListenerFactory slf = new TestingSessionListenerFactory();
-        final Channel channel = this.pcepDispatcher.createServer(this.serverAddress, slf, null).channel();
+        final ChannelFuture futureServer = this.pcepDispatcher.createServer(this.serverAddress, slf, null);
+        waitFutureSuccess(futureServer);
+        final Channel channel = futureServer.channel();
         Assert.assertNotNull(futureSession.get());
+        checkSessionListenerNotNull(slf, "127.0.4.0");
         final TestingSessionListener sl = slf.getSessionListenerByRemoteAddress(this.clientAddress.getAddress());
         Assert.assertNotNull(sl);
+        Assert.assertNotNull(sl.getSession());
         Assert.assertTrue(sl.isUp());
 
         channel.close().get();
@@ -82,14 +89,17 @@ public class PCCDispatcherImplTest {
         this.workerGroup = new NioEventLoopGroup();
         this.bossGroup = new NioEventLoopGroup();
         this.pcepDispatcher = new PCEPDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry(),
-                this.nf, this.bossGroup, this.workerGroup);
+            this.nf, this.bossGroup, this.workerGroup);
 
         final TestingSessionListenerFactory slf2 = new TestingSessionListenerFactory();
-        this.pcepDispatcher.createServer(this.serverAddress, slf2, null).channel();
+        final ChannelFuture future2 = this.pcepDispatcher.createServer(this.serverAddress, slf2, null);
+        waitFutureSuccess(future2);
+        future2.channel();
         Thread.sleep(500);
 
         final TestingSessionListener sl2 = slf2.getSessionListenerByRemoteAddress(this.clientAddress.getAddress());
         Assert.assertNotNull(sl2);
+        Assert.assertNotNull(sl2.getSession());
         Assert.assertTrue(sl2.isUp());
     }
 
index db4e246f3ef44cc5dd9f010336d58059c372f672..e9f410d9b48b7faec5b7ee52e3d03d13882d87ef 100644 (file)
@@ -24,7 +24,7 @@ import org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCServerPeerProposal;
 
 public class PCCIncrementalSyncTest extends PCCMockCommon {
 
-    private BigInteger lsp = BigInteger.valueOf(8);
+    private final BigInteger lsp = BigInteger.valueOf(8);
     /**
      * Test Incremental Synchronization
      * Create 8 lsp, then it disconnects after 5 sec and then after 5 sec reconnects with Pcc DBVersion 10
@@ -45,8 +45,6 @@ public class PCCIncrementalSyncTest extends PCCMockCommon {
         checkSynchronizedSession(8, pceSessionListener, numberOflspAndDBv);
         Thread.sleep(4000);
         assertFalse(pceSessionListener.isUp());
-        Thread.sleep(6000);
-        Thread.sleep(1000);
         final int expetedNumberOfLspAndEndOfSync = 3;
         final BigInteger expectedFinalDBVersion = BigInteger.valueOf(10);
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
index 98a31607d5f7831d52ff70db30532a3f02be66f1..d0488e49ba54c0cfb6e33192c5c8aad6081e1058 100644 (file)
@@ -12,10 +12,14 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.protocol.pcep.pcc.mock.WaitForFutureSucces.waitFutureSuccess;
 
 import com.google.common.base.Optional;
+import com.google.common.base.Stopwatch;
 import com.google.common.net.InetAddresses;
+import com.google.common.util.concurrent.Uninterruptibles;
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.concurrent.Future;
@@ -23,6 +27,8 @@ import java.math.BigInteger;
 import java.net.InetSocketAddress;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import org.junit.Assert;
 import org.junit.Before;
 import org.opendaylight.protocol.pcep.PCEPCapability;
 import org.opendaylight.protocol.pcep.PCEPDispatcher;
@@ -72,31 +78,61 @@ public abstract class PCCMockCommon {
             nf, new NioEventLoopGroup(), new NioEventLoopGroup());
     }
 
+    private static void checkNumberOfMessages(final int expectedNMessages, final TestingSessionListener listener) throws Exception {
+        Stopwatch sw = Stopwatch.createStarted();
+        while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
+            if (expectedNMessages != listener.messages().size()) {
+                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+            } else {
+                return;
+            }
+        }
+        Assert.assertEquals(expectedNMessages, listener.messages().size());
+    }
+
+    static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory, final String localAddress) {
+        Stopwatch sw = Stopwatch.createStarted();
+        TestingSessionListener listener = null;
+        while (sw.elapsed(TimeUnit.SECONDS) <= 20) {
+            listener = factory.getSessionListenerByRemoteAddress(InetAddresses.forString(localAddress));
+            if (listener == null) {
+                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
+            } else {
+                return listener;
+            }
+        }
+        throw new NullPointerException();
+    }
+
     protected static TestingSessionListener checkSessionListener(final int numMessages, final Channel channel, final TestingSessionListenerFactory factory, final String localAddress) throws
         ExecutionException, InterruptedException {
         final TestingSessionListener sessionListener = factory.getSessionListenerByRemoteAddress(InetAddresses.forString(localAddress));
         assertNotNull(sessionListener);
+        assertNotNull(sessionListener.getSession());
         assertTrue(sessionListener.isUp());
         assertEquals(numMessages, sessionListener.messages().size());
         channel.close().get();
         return sessionListener;
     }
 
-    protected Channel createServer(final TestingSessionListenerFactory factory, final InetSocketAddress serverAddress2) {
+    protected Channel createServer(final TestingSessionListenerFactory factory, final InetSocketAddress serverAddress2) throws InterruptedException {
         return createServer(factory, serverAddress2, null);
     }
 
     protected Channel createServer(final TestingSessionListenerFactory factory, final InetSocketAddress
-        serverAddress2, final PCEPPeerProposal peerProposal) {
+        serverAddress2, final PCEPPeerProposal peerProposal) throws InterruptedException {
         final PCEPExtensionProviderContext ctx = ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance();
         final StatefulActivator activator07 = new StatefulActivator();
         final SyncOptimizationsActivator optimizationsActivator = new SyncOptimizationsActivator();
         activator07.start(ctx);
         optimizationsActivator.start(ctx);
-        return this.pceDispatcher.createServer(serverAddress2, factory, peerProposal).channel();
+        final ChannelFuture futureServer = this.pceDispatcher.createServer(serverAddress2, factory, peerProposal);
+        waitFutureSuccess(futureServer);
+        return futureServer.channel();
     }
 
     protected static void checkSynchronizedSession(final int numberOfLsp, final TestingSessionListener pceSessionListener, final BigInteger expectedeInitialDb) throws InterruptedException {
+        assertNotNull(pceSessionListener.getSession());
         assertTrue(pceSessionListener.isUp());
         Thread.sleep(1000);
         //Send Open with LspDBV = 1
@@ -116,8 +152,10 @@ public abstract class PCCMockCommon {
     }
 
     protected static void checkResyncSession(final Optional<Integer> startAtNumberLsp, final int expectedNumberOfLsp, final BigInteger startingDBVersion,
-                                             final BigInteger expectedDBVersion, final TestingSessionListener pceSessionListener) {
+                                             final BigInteger expectedDBVersion, final TestingSessionListener pceSessionListener) throws InterruptedException {
+        assertNotNull(pceSessionListener.getSession());
         assertTrue(pceSessionListener.isUp());
+        Thread.sleep(50);
         List<Message> messages;
         if(startAtNumberLsp.isPresent()) {
             messages = pceSessionListener.messages().subList(startAtNumberLsp.get(), startAtNumberLsp.get() + expectedNumberOfLsp);
@@ -189,6 +227,6 @@ public abstract class PCCMockCommon {
     }
 
     protected TestingSessionListener getListener(final TestingSessionListenerFactory factory) {
-        return factory.getSessionListenerByRemoteAddress(InetAddresses.forString(PCCMockTest.LOCAL_ADDRESS));
+        return checkSessionListenerNotNull(factory, PCCMockTest.LOCAL_ADDRESS);
     }
 }
index 4adf663e36669a0f253957870c397bd55d0dd7b6..56574b5e7a924f501ed1151fa3686602fd92050e 100644 (file)
@@ -29,12 +29,11 @@ public class PCCSyncAvoidanceProcedureTest extends PCCMockCommon {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
 
         final Channel channel = createServer(factory, socket, new PCCPeerProposal());
-        Thread.sleep(200);
         PCEPSession session = createPCCSession(BigInteger.TEN).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
-        Thread.sleep(1000);
+        assertNotNull(pceSessionListener.getSession());
         checkResyncSession(Optional.<Integer>absent(), 11, null, BigInteger.valueOf(10), pceSessionListener);
         channel.close().get();
     }
index b869a667d1e007caa168ccd7ba3341cee6bf113e..87739b0cc6466f966a4690e01de16bd011f04906 100644 (file)
@@ -42,14 +42,12 @@ public class PCCTriggeredFullDBResyncTest extends PCCMockCommon {
         final int lspQuantity = 3;
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(lspQuantity);
         this.channel = createServer(factory, socket, new PCCPeerProposal());
-        Thread.sleep(300);
         PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(lspQuantity, pceSessionListener, numberOflspAndDBv);
         pccSessionListener.onMessage(session, createTriggerLspResync());
-        Thread.sleep(300);
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
         checkResyncSession(Optional.of(lspQuantity), 4, null, numberOflspAndDBv, sessionListenerAfterReconnect);
         channel.close().get();
index 973655cb89a8447fc5bf738dac09502ec7e2c17b..5084bab344c73696ae7bb61eb7acee58686fd0bf 100644 (file)
@@ -43,14 +43,12 @@ public class PCCTriggeredLspResyncTest extends PCCMockCommon {
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(lspQuantity);
 
         this.channel = createServer(factory, socket, new PCCPeerProposal());
-        Thread.sleep(200);
         PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(lspQuantity, pceSessionListener, numberOflspAndDBv);
         pccSessionListener.onMessage(session, createTriggerLspResync());
-        Thread.sleep(300);
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
         checkResyncSession(Optional.of(lspQuantity), 2, null, numberOflspAndDBv, sessionListenerAfterReconnect);
         channel.close().get();
index 2deca62e2a2e9bae1ed0229c5747b9a373e37c54..5f3072a87198b627f566711efa05c3b1bf981b5f 100644 (file)
@@ -40,7 +40,6 @@ public class PCCTriggeredSyncTest extends PCCMockCommon {
     public void testSessionTriggeredSync() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
         this.channel = createServer(factory, socket, new PCCPeerProposal());
-        Thread.sleep(200);
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(3);
         PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
@@ -48,7 +47,6 @@ public class PCCTriggeredSyncTest extends PCCMockCommon {
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(0, pceSessionListener, BigInteger.ZERO);
         pccSessionListener.onMessage(session, createTriggerMsg());
-        Thread.sleep(300);
         checkSynchronizedSession(3, pceSessionListener, numberOflspAndDBv);
         this.channel.close().get();
     }
index 0421d191ebfa25c5cbaab0ab10406badcd13378f..4c5fdaf79dbbd11c86d1eb7726811d9410c5a735 100644 (file)
@@ -9,7 +9,11 @@
 package org.opendaylight.protocol.pcep.pcc.mock;
 
 import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Uninterruptibles;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.junit.Assert;
 import org.opendaylight.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.PCEPSessionListener;
 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
@@ -22,21 +26,16 @@ public class TestingSessionListener implements PCEPSessionListener {
     private static final Logger LOG = LoggerFactory.getLogger(TestingSessionListener.class);
 
     private final List<Message> messages = Lists.newArrayList();
-
+    private final CountDownLatch sessionLatch = new CountDownLatch(1);
     private boolean up = false;
     private PCEPSession session = null;
 
-    @Override
-    public void onMessage(final PCEPSession session, final Message message) {
-        LOG.debug("Received message: {}", message);
-        this.messages.add(message);
-    }
-
     @Override
     public void onSessionUp(final PCEPSession session) {
         LOG.debug("Session up.");
         this.up = true;
         this.session = session;
+        sessionLatch.countDown();
     }
 
     @Override
@@ -51,15 +50,22 @@ public class TestingSessionListener implements PCEPSessionListener {
         LOG.debug("Session terminated. Cause : {}", cause);
     }
 
+    @Override
+    public void onMessage(final PCEPSession session, final Message message) {
+        LOG.debug("Received message: {}", message);
+        this.messages.add(message);
+    }
+
     public List<Message> messages() {
         return this.messages;
     }
 
-    public boolean isUp () {
+    public boolean isUp() {
         return this.up;
     }
 
     public PCEPSession getSession() {
+        Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(sessionLatch, 10, TimeUnit.SECONDS));
         return this.session;
     }
 }
diff --git a/pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/WaitForFutureSucces.java b/pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/WaitForFutureSucces.java
new file mode 100644 (file)
index 0000000..c821e1c
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.protocol.pcep.pcc.mock;
+
+import com.google.common.util.concurrent.Uninterruptibles;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.FutureListener;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+final class WaitForFutureSucces {
+    private WaitForFutureSucces() {
+        throw new UnsupportedOperationException();
+    }
+
+    static <T extends Future> void waitFutureSuccess(final T future) throws InterruptedException {
+        final CountDownLatch latch = new CountDownLatch(1);
+        future.addListener(new FutureListener() {
+            @Override
+            public void operationComplete(final Future future) throws Exception {
+                latch.countDown();
+            }
+        });
+        Uninterruptibles.awaitUninterruptibly(latch, 10, TimeUnit.SECONDS);
+    }
+}