BUG-7003: Remove sleeping from Tests 77/53077/2
authorClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Tue, 28 Feb 2017 12:20:49 +0000 (13:20 +0100)
committerClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Thu, 9 Mar 2017 14:39:34 +0000 (15:39 +0100)
Remove sleeping from test whenever possible.
Perform clean up under tests.

Change-Id: I734ca5721090669c75f09d107ee4c5ea1e3d14ee
Signed-off-by: Claudio D. Gasparini <claudio.gasparini@pantheon.tech>
50 files changed:
bgp/bmp-impl/pom.xml
bgp/bmp-impl/src/test/java/org/opendaylight/protocol/bmp/impl/app/BmpMonitorImplTest.java
bgp/bmp-impl/src/test/java/org/opendaylight/protocol/bmp/impl/session/BmpDispatcherImplTest.java
bgp/rib-impl/pom.xml
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractAddPathTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AbstractBGPDispatcherTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathAllPathsTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathBasePathsTest.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/AddPathNPathsTest.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/CheckUtil.java
bgp/rib-impl/src/test/java/org/opendaylight/protocol/bgp/rib/impl/SimpleSessionListener.java
data-change-counter/pom.xml
data-change-counter/src/test/java/org/opendaylight/protocol/data/change/counter/TopologyDataChangeCounterTest.java
pcep/impl/src/main/java/org/opendaylight/protocol/pcep/impl/PCEPSessionImpl.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/AbstractPCEPSessionTest.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/FiniteStateMachineTest.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/PCEPDispatcherImplTest.java
pcep/impl/src/test/java/org/opendaylight/protocol/pcep/impl/PCEPValidatorTest.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/PCCEndPointIpv4ObjectParserTest.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/PCCMockTest.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/PCCSessionListenerTest.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/PCCTunnelManagerImplTest.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/TestingSessionListenerFactory.java
pcep/pcc-mock/src/test/java/org/opendaylight/protocol/pcep/pcc/mock/WaitForFutureSucces.java [deleted file]
pcep/segment-routing/src/test/java/org/opendaylight/protocol/pcep/segment/routing/TopologyProviderTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/AbstractPCEPSessionTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/IncrementalSynchronizationProcedureTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/PCEPStatefulPeerProposalTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/PCEPTriggeredReSynchronizationProcedureTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/PCETriggeredInitialSyncProcedureTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/StateSynchronizationAvoidanceProcedureTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/Stateful07TopologySessionListenerTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/SyncOptimizationTest.java
pcep/topology-provider/src/test/java/org/opendaylight/bgpcep/pcep/topology/provider/TopologyProgrammingTest.java
programming/impl/pom.xml
programming/impl/src/test/java/org/opendaylight/bgpcep/programming/impl/MockedNotificationServiceWrapper.java
programming/impl/src/test/java/org/opendaylight/bgpcep/programming/impl/ProgrammingServiceImplTest.java
testtool-util/pom.xml
testtool-util/src/main/java/org/opendaylight/protocol/util/CheckUtil.java [new file with mode: 0644]
testtool-util/src/test/java/org/opendaylight/protocol/util/CheckUtilTest.java [new file with mode: 0644]

index 8c566187bd6b7de2f0f9504bf7a3ca929aea5981..58260b6bc4fbaceeaf6263d0fa58a88447de0d3e 100644 (file)
         <dependency>
             <groupId>io.netty</groupId>
             <artifactId>netty-transport-native-epoll</artifactId>
-            <classifier>${os.detected.classifier}</classifier>
+            <classifier>linux-x86_64</classifier>
         </dependency>
         <dependency>
             <groupId>io.netty</groupId>
             <artifactId>bgp-rib-impl</artifactId>
             <type>test-jar</type>
         </dependency>
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>testtool-util</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>sal-binding-broker-impl</artifactId>
index e5261cedb172964cb376add27e98d9da7a628e78..cbc1d74b82c43d61d266ed57b7e3864f9c01c816 100644 (file)
@@ -14,8 +14,8 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.readData;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.base.Optional;
 import com.google.common.net.InetAddresses;
@@ -57,6 +57,7 @@ import org.opendaylight.protocol.bmp.parser.message.TestUtil;
 import org.opendaylight.protocol.bmp.spi.registry.BmpMessageRegistry;
 import org.opendaylight.protocol.bmp.spi.registry.SimpleBmpExtensionProviderContext;
 import org.opendaylight.protocol.concepts.KeyMapping;
+import org.opendaylight.protocol.util.CheckUtil;
 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.opendaylight.params.xml.ns.yang.bgp.inet.rev150305.bmp.monitor.monitor.router.peer.pre.policy.rib.tables.routes.Ipv4RoutesCase;
@@ -206,11 +207,10 @@ public class BmpMonitorImplTest extends AbstractDataBrokerTest {
         // we expect the connection to be closed
         final Channel channel3 = connectTestClient(REMOTE_ROUTER_ADDRESS_1, this.msgRegistry);
 
-        Thread.sleep(500);
 
         // channel 1 should still be open, while channel3 should be closed
-        assertTrue(channel1.isOpen());
-        assertFalse(channel3.isOpen());
+        CheckUtil.checkEquals(()-> assertTrue(channel1.isOpen()));
+        CheckUtil.checkEquals(()-> assertFalse(channel3.isOpen()));
 
         // now if we close the channel 1 and try it again, it should succeed
         waitFutureSuccess(channel1.close());
@@ -229,7 +229,7 @@ public class BmpMonitorImplTest extends AbstractDataBrokerTest {
 
         // close all channel altogether
         waitFutureSuccess(channel2.close());
-        Thread.sleep(500);
+        Thread.sleep(100);
 
         // sleep for a while to avoid intermittent InMemoryDataTree modification conflict
         waitFutureSuccess(channel4.close());
index 82463e25a31b66ca15ae4c00735d614148df75bd..69edf89a186dbaf93d6013043eb62cfe1373fddf 100644 (file)
@@ -32,7 +32,6 @@ import org.opendaylight.protocol.bmp.impl.BmpDispatcherImpl;
 import org.opendaylight.protocol.bmp.parser.BmpActivator;
 import org.opendaylight.protocol.bmp.spi.registry.BmpMessageRegistry;
 import org.opendaylight.protocol.bmp.spi.registry.SimpleBmpExtensionProviderContext;
-import org.opendaylight.protocol.concepts.KeyMapping;
 
 public class BmpDispatcherImplTest {
 
@@ -88,9 +87,9 @@ public class BmpDispatcherImplTest {
 
     @Test
     public void testCreateServer() throws Exception {
-        final Channel serverChannel = this.dispatcher.createServer(SERVER, this.mockedListenerFactory, Optional.<KeyMapping>absent()).await().channel();
+        final Channel serverChannel = this.dispatcher.createServer(SERVER, this.mockedListenerFactory, Optional.absent()).await().channel();
         Assert.assertTrue(serverChannel.isActive());
-        final Channel clientChannel = this.dispatcher.createClient(CLIENT_REMOTE, this.mockedListenerFactory, Optional.<KeyMapping>absent()).await().channel();
+        final Channel clientChannel = this.dispatcher.createClient(CLIENT_REMOTE, this.mockedListenerFactory, Optional.absent()).await().channel();
         Assert.assertTrue(clientChannel.isActive());
         Thread.sleep(500);
         Mockito.verify(this.mockedSession, Mockito.times(2)).handlerAdded(Mockito.any(ChannelHandlerContext.class));
index 1e48e0b633d9d8350a90684e6459ed1556311dc5..dfda3eced09dd73c81c32630b93e5dbdd6d19b67 100644 (file)
         <dependency>
             <groupId>io.netty</groupId>
             <artifactId>netty-transport-native-epoll</artifactId>
-            <classifier>${os.detected.classifier}</classifier>
+            <classifier>linux-x86_64</classifier>
         </dependency>
         <dependency>
             <groupId>io.netty</groupId>
             <artifactId>org.osgi.compendium</artifactId>
         </dependency>
         <!-- Testing dependencies -->
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>testtool-util</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>${project.groupId}</groupId>
             <artifactId>bgp-path-selection-mode</artifactId>
index 7f9d0cb75693d8178896246b0523936f749edd09..575ed50e0544f040a61fff8a3cb52f69a1eb90e8 100644 (file)
@@ -9,8 +9,8 @@ package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doReturn;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.readData;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.base.Optional;
 import com.google.common.collect.ImmutableList;
index 366db6636268a8aa6d212a980d084851eacb91cb..0da275fa28742103bdc5cb2f77166cac55e894c0 100644 (file)
@@ -7,13 +7,11 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
-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.EventLoopGroup;
@@ -23,7 +21,6 @@ import java.net.InetSocketAddress;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
 import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
@@ -107,18 +104,6 @@ public class AbstractBGPDispatcherTest {
         return new BGPSessionPreferences(AS_NUMBER, HOLD_TIMER, bgpId, AS_NUMBER, tlvs, Optional.absent());
     }
 
-    public static void checkIdleState(final SimpleSessionListener listener) {
-        final Stopwatch sw = Stopwatch.createStarted();
-        while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
-            if (BGPSessionImpl.State.IDLE != listener.getState()) {
-                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
-            } else {
-                return;
-            }
-        }
-        Assert.fail();
-    }
-
     protected Channel createServer(final InetSocketAddress serverAddress) throws InterruptedException {
         this.registry.addPeer(new IpAddress(new Ipv4Address(serverAddress.getAddress().getHostAddress())), this.serverListener, createPreferences(serverAddress));
         LoggerFactory.getLogger(AbstractBGPDispatcherTest.class).info("createServer");
index 2e30e75f56232c471a1a2e1856cd5169deb887f8..1d6ffa8a50852186948d73991d6e5a725e390816 100644 (file)
@@ -8,8 +8,8 @@
 package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkReceivedMessages;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.collect.ImmutableMap;
 import io.netty.channel.Channel;
index 67595f9bfb675a10f19dff0f7906751aada8636d..04b55df7376cb0499e7fbf1dfc93f49a186752c4 100644 (file)
@@ -9,8 +9,8 @@
 package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkReceivedMessages;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.collect.ImmutableMap;
 import io.netty.channel.Channel;
index 46e02e9a42c68f5c45c93ef45751d3107d80f72c..fcfeafe89e05ad6410e4c7a7acb69441368b72f2 100644 (file)
@@ -9,8 +9,8 @@
 package org.opendaylight.protocol.bgp.rib.impl;
 
 import static org.junit.Assert.assertEquals;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkReceivedMessages;
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+import static org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.collect.ImmutableMap;
 import io.netty.channel.Channel;
index ba071e847c76e92563146edc2d4e59bf2966977e..ac5ad21ac28675a8581eebc4b7601b472cd56ce1 100755 (executable)
  * 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.bgp.rib.impl;
 
-import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.waitFutureSuccess;
+
+import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkIdleState;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Stopwatch;
-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.epoll.Epoll;
-import io.netty.channel.epoll.EpollEventLoopGroup;
-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.List;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import org.junit.After;
 import org.junit.Assert;
-import org.junit.Before;
 import org.junit.Test;
-import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
-import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
-import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
-import org.opendaylight.protocol.bgp.parser.spi.BGPExtensionProviderContext;
-import org.opendaylight.protocol.bgp.parser.spi.pojo.ServiceLoaderBGPExtensionProviderContext;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
-import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
 import org.opendaylight.protocol.util.InetSocketAddressUtil;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
-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.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.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.mp.capabilities.MultiprotocolCapabilityBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.types.rev130919.BgpId;
-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.slf4j.LoggerFactory;
-
-public class BGPDispatcherImplTest {
-    private static final short HOLD_TIMER = 30;
-    private static final AsNumber AS_NUMBER = new AsNumber(30L);
-    private static final int RETRY_TIMER = 1;
-    private static final BgpTableType IPV_4_TT = new BgpTableTypeImpl(Ipv4AddressFamily.class, UnicastSubsequentAddressFamily.class);
-    private BGPDispatcherImpl serverDispatcher;
-    private BGPDispatcherImpl clientDispatcher;
-    private BGPPeerRegistry registry;
-    private SimpleSessionListener clientListener;
-    private SimpleSessionListener serverListener;
-    private EventLoopGroup boss;
-    private EventLoopGroup worker;
-    private InetSocketAddress clientAddress;
-
-    @Before
-    public void setUp() throws BGPDocumentedException {
-        if (Epoll.isAvailable()) {
-            this.boss = new EpollEventLoopGroup();
-            this.worker = new EpollEventLoopGroup();
-        } else {
-            this.boss = new NioEventLoopGroup();
-            this.worker = new NioEventLoopGroup();
-        }
-        this.registry = new StrictBGPPeerRegistry();
-        this.clientListener = new SimpleSessionListener();
-        final BGPExtensionProviderContext ctx = ServiceLoaderBGPExtensionProviderContext.getSingletonInstance();
-        this.serverDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker);
-        configureClient(ctx);
-    }
-
-    public static void checkIdleState (final SimpleSessionListener listener){
-        Stopwatch sw = Stopwatch.createStarted();
-        while(sw.elapsed(TimeUnit.SECONDS) <= 10) {
-            if (BGPSessionImpl.State.IDLE != listener.getState()){
-                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
-            } else {
-                return;
-            }
-        }
-        Assert.fail();
-    }
-
-    private void configureClient(final BGPExtensionProviderContext ctx) {
-        this.clientAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
-        final IpAddress clientPeerIp = new IpAddress(new Ipv4Address(this.clientAddress.getAddress().getHostAddress()));
-        this.registry.addPeer(clientPeerIp, this.clientListener, createPreferences(this.clientAddress));
-        this.clientDispatcher = new BGPDispatcherImpl(ctx.getMessageRegistry(), this.boss, this.worker);
-    }
-
-    private Channel createServer(final InetSocketAddress serverAddress) throws InterruptedException {
-        this.serverListener = new SimpleSessionListener();
-        this.registry.addPeer(new IpAddress(new Ipv4Address(serverAddress.getAddress().getHostAddress())), this.serverListener, createPreferences(serverAddress));
-        LoggerFactory.getLogger(BGPDispatcherImplTest.class).info("createServer");
-        final ChannelFuture future = this.serverDispatcher.createServer(this.registry, serverAddress);
-        future.addListener(new GenericFutureListener<Future<Void>>() {
-            @Override
-            public void operationComplete(final Future<Void> future) {
-                Preconditions.checkArgument(future.isSuccess(), "Unable to start bgp server on %s", future.cause());
-            }
-        });
-        waitFutureSuccess(future);
-        return future.channel();
-    }
-
-    @After
-    public void tearDown() throws Exception {
-        this.serverDispatcher.close();
-        this.registry.close();
-        this.worker.shutdownGracefully().awaitUninterruptibly();
-        this.boss.shutdownGracefully().awaitUninterruptibly();
-    }
 
+public class BGPDispatcherImplTest extends AbstractBGPDispatcherTest {
     @Test
     public void testCreateClient() throws InterruptedException, ExecutionException {
         final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
         final Channel serverChannel = createServer(serverAddress);
-        final Future<BGPSessionImpl> futureClient = this.clientDispatcher.createClient(this.clientAddress, serverAddress, this.registry, 2, true);
+        final Future<BGPSessionImpl> futureClient = this.clientDispatcher.createClient(this.clientAddress,
+            serverAddress, this.registry, 2, true);
         waitFutureSuccess(futureClient);
         final BGPSessionImpl session = futureClient.get();
         Assert.assertEquals(BGPSessionImpl.State.UP, this.clientListener.getState());
@@ -151,9 +44,8 @@ public class BGPDispatcherImplTest {
     @Test
     public void testCreateReconnectingClient() throws Exception {
         final InetSocketAddress serverAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress();
-        final Future<Void> future = this.clientDispatcher.createReconnectingClient(serverAddress, this.registry, RETRY_TIMER, Optional.absent(),
-            this.clientAddress, true);
-        waitFutureSuccess(future);
+        final Future<Void> future = this.clientDispatcher.createReconnectingClient(serverAddress, this.registry,
+            RETRY_TIMER, Optional.absent(), this.clientAddress, true);
         final Channel serverChannel = createServer(serverAddress);
         Assert.assertEquals(BGPSessionImpl.State.UP, this.serverListener.getState());
         Assert.assertTrue(serverChannel.isWritable());
@@ -161,18 +53,4 @@ public class BGPDispatcherImplTest {
         this.serverListener.releaseConnection();
         checkIdleState(this.serverListener);
     }
-
-    private BGPSessionPreferences createPreferences(final InetSocketAddress socketAddress) {
-        final List<BgpParameters> tlvs = Lists.newArrayList();
-        final List<OptionalCapabilities> capas = Lists.newArrayList();
-        capas.add(new OptionalCapabilitiesBuilder().setCParameters(new CParametersBuilder().addAugmentation(
-            CParameters1.class, new CParameters1Builder().setMultiprotocolCapability(new MultiprotocolCapabilityBuilder()
-                .setAfi(IPV_4_TT.getAfi()).setSafi(IPV_4_TT.getSafi()).build()).build())
-            .setAs4BytesCapability(new As4BytesCapabilityBuilder().setAsNumber(new AsNumber(30L)).build())
-            .build()).build());
-        capas.add(new OptionalCapabilitiesBuilder().setCParameters(BgpExtendedMessageUtil.EXTENDED_MESSAGE_CAPABILITY).build());
-        tlvs.add(new BgpParametersBuilder().setOptionalCapabilities(capas).build());
-        final BgpId bgpId = new BgpId(new Ipv4Address(socketAddress.getAddress().getHostAddress()));
-        return new BGPSessionPreferences(AS_NUMBER, HOLD_TIMER, bgpId, AS_NUMBER, tlvs, Optional.absent());
-    }
 }
index a9b75bb33fa1cb88cac13a00cf48132907f34812..ceed3ee4a8422972e633f5e13292ab96b8018a70 100644 (file)
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
-import static org.opendaylight.protocol.bgp.rib.impl.BGPDispatcherImplTest.checkIdleState;
+import static org.opendaylight.protocol.bgp.rib.impl.CheckUtil.checkIdleState;
 
 import com.google.common.collect.Lists;
 import io.netty.channel.Channel;
index 6d0e3697dbccb6c6495878fd15e4bf6d8304e3bf..1f57beb8f2351ab38edcf1673668e895da9bc22c 100644 (file)
@@ -7,65 +7,22 @@
  */
 package org.opendaylight.protocol.bgp.rib.impl;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Stopwatch;
 import com.google.common.util.concurrent.Uninterruptibles;
-import io.netty.util.concurrent.Future;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
-import java.util.function.Function;
 import org.junit.Assert;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.protocol.bgp.rib.impl.BGPSessionImpl.State;
 
 public final class CheckUtil {
-    private static final int TIMEOUT = 40;
-    private static final int LATCH_TIMEOUT = 10;
-    private static final int SLEEP_FOR = 20;
-    private static final int SLEEP_UNINTERRUPTIBLY = 50;
-    static void checkReceivedMessages(final SimpleSessionListener listener, final int numberOfMessages)
-        throws ReadFailedException {
+    public static void checkIdleState(final SimpleSessionListener listener) {
         final Stopwatch sw = Stopwatch.createStarted();
-        while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
-            if (listener.getListMsg().size() != numberOfMessages) {
-                Uninterruptibles.sleepUninterruptibly(SLEEP_UNINTERRUPTIBLY, TimeUnit.MILLISECONDS);
+        while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
+            if (State.IDLE != listener.getState()) {
+                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
             } else {
                 return;
             }
         }
         Assert.fail();
     }
-
-    public static <R, T extends DataObject> R readData(final DataBroker dataBroker, final InstanceIdentifier<T> iid,
-        final Function<T, R> function)
-        throws ReadFailedException {
-        AssertionError lastError = null;
-        final Stopwatch sw = Stopwatch.createStarted();
-        while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
-            try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
-                final Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
-                if (data.isPresent()) {
-                    try {
-                        return function.apply(data.get());
-                    } catch (final AssertionError e) {
-                        lastError = e;
-                        Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
-                    }
-                }
-            }
-        }
-        Assert.fail(lastError.getMessage());
-        throw lastError;
-    }
-
-    @SuppressWarnings("unchecked")
-    public static <T extends Future> void waitFutureSuccess(final T future) {
-        final CountDownLatch latch = new CountDownLatch(1);
-        future.addListener(future1 -> latch.countDown());
-        Uninterruptibles.awaitUninterruptibly(latch, LATCH_TIMEOUT, TimeUnit.SECONDS);
-    }
 }
\ No newline at end of file
index d2e33cbe5eae9332b64c24e3223db177b7e26489..f1271650829de05dfe3ac3aa815af071ffa0df97 100644 (file)
@@ -14,10 +14,12 @@ import com.google.common.util.concurrent.Uninterruptibles;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.concurrent.GuardedBy;
 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;
+import org.opendaylight.protocol.util.CheckUtil.ListenerCheck;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev130925.rib.TablesKey;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.slf4j.Logger;
@@ -26,17 +28,18 @@ import org.slf4j.LoggerFactory;
 /**
  * Listener for the client.
  */
-public final class SimpleSessionListener implements BGPSessionListener {
+public final class SimpleSessionListener implements BGPSessionListener, ListenerCheck {
 
     private static final Logger LOG = LoggerFactory.getLogger(SimpleSessionListener.class);
+    @GuardedBy("this")
     private final List<Notification> listMsg = Lists.newArrayList();
     private BGPSession session;
     private final CountDownLatch sessionLatch = new CountDownLatch(1);
 
-    SimpleSessionListener() {
+    public SimpleSessionListener() {
     }
 
-    List<Notification> getListMsg() {
+    synchronized List<Notification> getListMsg() {
         return this.listMsg;
     }
 
@@ -63,7 +66,7 @@ public final class SimpleSessionListener implements BGPSessionListener {
     }
 
     @Override
-    public void onMessage(final BGPSession session, final Notification message) {
+    public synchronized void onMessage(final BGPSession session, final Notification message) {
         this.listMsg.add(message);
         LOG.debug("Message received: {}", message);
     }
@@ -81,7 +84,7 @@ public final class SimpleSessionListener implements BGPSessionListener {
         return Futures.immediateFuture(null);
     }
 
-    BGPSessionImpl.State getState() {
+    public BGPSessionImpl.State getState() {
         return getSession().getState();
     }
 
@@ -89,4 +92,9 @@ public final class SimpleSessionListener implements BGPSessionListener {
         Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(this.sessionLatch, 10, TimeUnit.SECONDS));
         return (BGPSessionImpl) this.session;
     }
+
+    @Override
+    public int getListMessageSize() {
+        return this.listMsg.size();
+    }
 }
index f413a66403db70709189a7de3ccb7b2c30980fbe..f25af1565af2ed2c1618e5a12bd6b6231820b2a5 100644 (file)
       <artifactId>config-manager</artifactId>
       <type>test-jar</type>
     </dependency>
+    <dependency>
+      <groupId>${project.groupId}</groupId>
+      <artifactId>testtool-util</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 
   <build>
index 828b953a63ec13fda9bdb1310244d9cd43293305..44c3bc832009e2343118094a0969459d4dff2332 100755 (executable)
@@ -9,15 +9,12 @@
 package org.opendaylight.protocol.data.change.counter;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.opendaylight.protocol.util.CheckUtil.checkNull;
+import static org.opendaylight.protocol.util.CheckUtil.checkPresent;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
 
-import com.google.common.base.Optional;
-import java.util.concurrent.ExecutionException;
 import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
 import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.data.change.counter.rev160315.DataChangeCounter;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.data.change.counter.rev160315.data.change.counter.Counter;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.data.change.counter.rev160315.data.change.counter.CounterKey;
@@ -27,65 +24,59 @@ public class TopologyDataChangeCounterTest extends AbstractDataBrokerTest {
 
     private static final String COUNTER_ID1 = "counter1";
     private static final String COUNTER_ID2 = "counter2";
+    private final InstanceIdentifier<Counter> counterInstanceId_1 = InstanceIdentifier.builder(DataChangeCounter.class)
+        .child(Counter.class, new CounterKey(COUNTER_ID1)).build();
+    private final InstanceIdentifier<Counter> counterInstanceId_2 = InstanceIdentifier.builder(DataChangeCounter.class)
+        .child(Counter.class, new CounterKey(COUNTER_ID2)).build();
 
     @Test
-    public void testDataChangeCounter() throws InterruptedException, ExecutionException {
+    public void testDataChangeCounter() throws Exception {
         final TopologyDataChangeCounter counter = new TopologyDataChangeCounter(getDataBroker(), COUNTER_ID1);
-        final Optional<Long> count = getCount(COUNTER_ID1);
-        assertTrue(count.isPresent());
-        assertEquals(0, count.get().longValue());
+        readData(getDataBroker(), this.counterInstanceId_1, count -> {
+            assertEquals(0, count.getCount().longValue());
+            return count;
+        });
 
         counter.onDataTreeChanged(null);
-        final Optional<Long> countAfterDataChange = getCount(COUNTER_ID1);
-        assertTrue(countAfterDataChange.isPresent());
-        assertEquals(1, countAfterDataChange.get().longValue());
+        readData(getDataBroker(), this.counterInstanceId_1, count -> {
+            assertEquals(1, count.getCount().longValue());
+            return count;
+        });
 
         counter.close();
-        final Optional<Long> countAfterClose = getCount(COUNTER_ID1);
-        assertFalse(countAfterClose.isPresent());
+        checkNull(getDataBroker(), this.counterInstanceId_1);
     }
 
     @Test
-    public void testDataChangeCounterTwoInstances() throws InterruptedException, ExecutionException {
+    public void testDataChangeCounterTwoInstances() throws Exception {
         final TopologyDataChangeCounter counter1 = new TopologyDataChangeCounter(getDataBroker(), COUNTER_ID1);
-        final Optional<Long> count1 = getCount(COUNTER_ID1);
-        assertTrue(count1.isPresent());
-        assertEquals(0, count1.get().longValue());
+        readData(getDataBroker(), this.counterInstanceId_1, count -> {
+            assertEquals(0, count.getCount().longValue());
+            return count;
+        });
 
         final TopologyDataChangeCounter counter2 = new TopologyDataChangeCounter(getDataBroker(), COUNTER_ID2);
-        final Optional<Long> count2 = getCount(COUNTER_ID2);
-        assertTrue(count2.isPresent());
-        assertEquals(0, count2.get().longValue());
+        readData(getDataBroker(), this.counterInstanceId_2, count -> {
+            assertEquals(0, count.getCount().longValue());
+            return count;
+        });
 
         counter1.onDataTreeChanged(null);
-        final Optional<Long> countAfterDataChange1 = getCount(COUNTER_ID1);
-        assertTrue(countAfterDataChange1.isPresent());
-        assertEquals(1, countAfterDataChange1.get().longValue());
-        // Check that counter2 does not get incremented
-        final Optional<Long> countAfterDataChange2 = getCount(COUNTER_ID2);
-        assertTrue(countAfterDataChange2.isPresent());
-        assertEquals(0, countAfterDataChange2.get().longValue());
+        readData(getDataBroker(), this.counterInstanceId_1, count -> {
+            assertEquals(1, count.getCount().longValue());
+            return count;
+        });
+        readData(getDataBroker(), this.counterInstanceId_2, count -> {
+            assertEquals(0, count.getCount().longValue());
+            return count;
+        });
 
         counter1.close();
-        final Optional<Long> countAfterClose1 = getCount(COUNTER_ID1);
-        assertFalse(countAfterClose1.isPresent());
+        checkNull(getDataBroker(), this.counterInstanceId_1);
         // Check that counter2 does not get deleted
-        final Optional<Long> countAfterClose2 = getCount(COUNTER_ID2);
-        assertTrue(countAfterClose2.isPresent());
+        checkPresent(getDataBroker(), this.counterInstanceId_2);
 
         counter2.close();
-        final Optional<Long> countAfterClose3 = getCount(COUNTER_ID2);
-        assertFalse(countAfterClose3.isPresent());
-    }
-
-    private Optional<Long> getCount(String counterId) throws InterruptedException, ExecutionException {
-        final ReadTransaction rTx = getDataBroker().newReadOnlyTransaction();
-        final InstanceIdentifier<Counter> counterInstanceId = InstanceIdentifier.builder(DataChangeCounter.class)
-                .child(Counter.class, new CounterKey(counterId)).build();
-        final Optional<Counter> dataMaybe = rTx.read(LogicalDatastoreType.OPERATIONAL, counterInstanceId).get();
-        if (dataMaybe.isPresent()) {
-            return Optional.of(dataMaybe.get().getCount());
-        }
-        return Optional.absent();
+        checkNull(getDataBroker(), this.counterInstanceId_2);
     }
 }
index ac4a93c253de7406e8b9a372bae230586278c360..9fe8c8a98f579b8b7f2b4e47458f6a508a39596c 100644 (file)
@@ -11,6 +11,7 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.MoreObjects;
 import com.google.common.base.MoreObjects.ToStringHelper;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Ticker;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelFutureListener;
@@ -55,6 +56,8 @@ import org.slf4j.LoggerFactory;
  */
 @VisibleForTesting
 public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implements PCEPSession {
+    private static final long MINUTE = TimeUnit.MINUTES.toNanos(1);
+    private static Ticker TICKER = Ticker.systemTicker();
     /**
      * System.nanoTime value about when was sent the last message Protected to be updated also in tests.
      */
@@ -99,7 +102,7 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
         this.channel = Preconditions.checkNotNull(channel);
         this.localOpen = Preconditions.checkNotNull(localOpen);
         this.remoteOpen = Preconditions.checkNotNull(remoteOpen);
-        this.lastMessageReceivedAt = System.nanoTime();
+        this.lastMessageReceivedAt = TICKER.read();
 
         if (maxUnknownMessages != 0) {
             this.maxUnknownMessages = maxUnknownMessages;
@@ -144,7 +147,7 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
      * state will become IDLE), that rescheduling won't occur.
      */
     private synchronized void handleDeadTimer() {
-        final long ct = System.nanoTime();
+        final long ct = TICKER.read();
 
         final long nextDead = this.lastMessageReceivedAt + TimeUnit.SECONDS.toNanos(getDeadTimerValue());
 
@@ -170,7 +173,7 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
      * starts to execute (the session state will become IDLE), that rescheduling won't occur.
      */
     private  void handleKeepaliveTimer() {
-        final long ct = System.nanoTime();
+        final long ct = TICKER.read();
 
         long nextKeepalive = this.lastMessageSentAt + TimeUnit.SECONDS.toNanos(getKeepAliveTimerValue());
 
@@ -197,7 +200,7 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
     @Override
     public Future<Void> sendMessage(final Message msg) {
         final ChannelFuture f = this.channel.writeAndFlush(msg);
-        this.lastMessageSentAt = System.nanoTime();
+        this.lastMessageSentAt = TICKER.read();
         this.sessionState.updateLastSentMsg();
         if (!(msg instanceof KeepaliveMessage)) {
             LOG.debug("PCEP Message enqueued: {}", msg);
@@ -293,11 +296,11 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
      */
     @VisibleForTesting
     public void handleMalformedMessage(final PCEPErrors error) {
-        final long ct = System.nanoTime();
+        final long ct = TICKER.read();
         this.sendErrorMessage(error);
         if (error == PCEPErrors.CAPABILITY_NOT_SUPPORTED) {
             this.unknownMessagesTimes.add(ct);
-            while (ct - this.unknownMessagesTimes.peek() > TimeUnit.MINUTES.toNanos(1)) {
+            while ( ct - this.unknownMessagesTimes.peek() > MINUTE) {
                 this.unknownMessagesTimes.poll();
             }
             if (this.unknownMessagesTimes.size() > this.maxUnknownMessages) {
@@ -314,7 +317,7 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
      */
     public synchronized void handleMessage(final Message msg) {
         // Update last reception time
-        this.lastMessageReceivedAt = System.nanoTime();
+        this.lastMessageReceivedAt = TICKER.read();
         this.sessionState.updateLastReceivedMsg();
         if (!(msg instanceof KeepaliveMessage)) {
             LOG.debug("PCEP message {} received.", msg);
@@ -412,6 +415,11 @@ public class PCEPSessionImpl extends SimpleChannelInboundHandler<Message> implem
 
     @Override
     public Tlvs localSessionCharacteristics() {
-        return localOpen.getTlvs();
+        return this.localOpen.getTlvs();
+    }
+
+    @VisibleForTesting
+    static void setTicker(final Ticker ticker) {
+        TICKER = ticker;
     }
 }
index f42aca5f751e7da532709349d888e931f2337b0b..59ad5969e898cfc8fb1115bff593de881617efe5 100644 (file)
@@ -29,8 +29,6 @@ import java.util.concurrent.TimeUnit;
 import org.junit.Before;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 import org.opendaylight.protocol.util.InetSocketAddressUtil;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
@@ -82,13 +80,10 @@ public class AbstractPCEPSessionTest {
     public final void setUp() {
         MockitoAnnotations.initMocks(this);
         final ChannelFuture future = new DefaultChannelPromise(this.channel);
-        doAnswer(new Answer<Object>() {
-            @Override
-            public Object answer(final InvocationOnMock invocation) {
-                final Object[] args = invocation.getArguments();
-                AbstractPCEPSessionTest.this.msgsSend.add((Notification) args[0]);
-                return future;
-            }
+        doAnswer(invocation -> {
+            final Object[] args = invocation.getArguments();
+            AbstractPCEPSessionTest.this.msgsSend.add((Notification) args[0]);
+            return future;
         }).when(this.channel).writeAndFlush(any(Notification.class));
         doReturn(this.channelFuture).when(this.channel).closeFuture();
         doReturn(this.channelFuture).when(this.channelFuture).addListener(any(GenericFutureListener.class));
@@ -103,8 +98,8 @@ public class AbstractPCEPSessionTest {
         doReturn(this.pipeline).when(this.pipeline).addFirst(any(ChannelHandler.class));
         doReturn(true).when(this.channel).isActive();
         doReturn(mock(ChannelFuture.class)).when(this.channel).close();
-        doReturn(new InetSocketAddress(ipAddress, port)).when(this.channel).remoteAddress();
-        doReturn(new InetSocketAddress(ipAddress, port)).when(this.channel).localAddress();
+        doReturn(new InetSocketAddress(this.ipAddress, this.port)).when(this.channel).remoteAddress();
+        doReturn(new InetSocketAddress(this.ipAddress, this.port)).when(this.channel).localAddress();
         this.openMsg = new OpenBuilder().setOpenMessage(
                 new OpenMessageBuilder().setOpen(
                         new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder().setDeadTimer(
index b50b1a3df62fc474f958723a637e4c0568fb8b30..95721489ca201ccaafdf787f9e09814783d2b167 100644 (file)
@@ -9,14 +9,18 @@ package org.opendaylight.protocol.pcep.impl;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.protocol.util.CheckUtil.checkEquals;
+
+import com.google.common.base.Ticker;
 import io.netty.util.concurrent.DefaultPromise;
 import io.netty.util.concurrent.GlobalEventExecutor;
+import java.util.Queue;
 import org.junit.After;
 import org.junit.Before;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.impl.spi.Util;
 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
+import org.opendaylight.protocol.util.CheckUtil;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.app.config.rev160707.pcep.dispatcher.config.TlsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Open;
@@ -31,14 +35,15 @@ public class FiniteStateMachineTest extends AbstractPCEPSessionTest {
 
     private DefaultPCEPSessionNegotiator serverSession;
     private DefaultPCEPSessionNegotiator tlsSessionNegotiator;
+    private final TestTicker ticker = new TestTicker();
 
     @Before
     public void setup() {
         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open localPrefs = new OpenBuilder().setKeepalive(
                 (short) 1).build();
-        this.serverSession = new DefaultPCEPSessionNegotiator(new DefaultPromise<PCEPSessionImpl>(GlobalEventExecutor.INSTANCE),
+        this.serverSession = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
                 this.channel, this.listener, (short) 1, 20, localPrefs);
-        this.tlsSessionNegotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<PCEPSessionImpl>(GlobalEventExecutor.INSTANCE),
+        this.tlsSessionNegotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
                 this.channel, this.listener, (short) 1, 20, localPrefs, new TlsBuilder().build());
     }
 
@@ -65,7 +70,7 @@ public class FiniteStateMachineTest extends AbstractPCEPSessionTest {
      */
     @Test
     public void testEstablishTLS() {
-        final DefaultPCEPSessionNegotiator negotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<PCEPSessionImpl>(GlobalEventExecutor.INSTANCE),
+        final DefaultPCEPSessionNegotiator negotiator = new DefaultPCEPSessionNegotiator(new DefaultPromise<>(GlobalEventExecutor.INSTANCE),
                 this.channel, this.listener, (short) 1, 20, new OpenBuilder().setKeepalive((short) 1).build(),
                 SslContextFactoryTest.createTlsConfig());
         negotiator.channelActive(null);
@@ -150,13 +155,15 @@ public class FiniteStateMachineTest extends AbstractPCEPSessionTest {
         assertEquals(1, this.msgsSend.size());
         assertTrue(this.msgsSend.get(0) instanceof Open);
         this.serverSession.handleMessage(this.kaMsg);
-        for (final Notification m : this.msgsSend) {
-            if (m instanceof Pcerr) {
-                final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
-                assertEquals(new Short((short) 1), obj.getErrorObject().getType());
-                assertEquals(new Short((short) 1), obj.getErrorObject().getValue());
+        checkEquals(()-> {
+            for (final Notification m : this.msgsSend) {
+                if (m instanceof Pcerr) {
+                    final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
+                    assertEquals(new Short((short) 1), obj.getErrorObject().getType());
+                    assertEquals(new Short((short) 1), obj.getErrorObject().getValue());
+                }
             }
-        }
+        });
     }
 
     /**
@@ -170,78 +177,89 @@ public class FiniteStateMachineTest extends AbstractPCEPSessionTest {
         assertEquals(1, this.msgsSend.size());
         assertTrue(this.msgsSend.get(0) instanceof Open);
         this.serverSession.handleMessage(this.openMsg);
-        Thread.sleep(1000);
-        for (final Notification m : this.msgsSend) {
-            if (m instanceof Pcerr) {
-                final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
-                assertEquals(new Short((short) 1), obj.getErrorObject().getType());
-                assertEquals(new Short((short) 7), obj.getErrorObject().getValue());
+        checkEquals(() -> {
+            for (final Notification m : this.msgsSend) {
+                if (m instanceof Pcerr) {
+                    final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
+                    assertEquals(new Short((short) 1), obj.getErrorObject().getType());
+                    assertEquals(new Short((short) 7), obj.getErrorObject().getValue());
+                }
             }
-        }
+        });
     }
 
-    /************* Tests commented because of their long duration (tested timers) **************/
-
     /**
      * OpenWait timer expired.
      *
      * @throws InterruptedException exception
      */
     @Test
-    @Ignore
-    public void testErrorOneTwo() throws InterruptedException {
+    public void testErrorOneTwo() throws Exception {
         this.serverSession.channelActive(null);
         assertEquals(1, this.msgsSend.size());
         assertTrue(this.msgsSend.get(0) instanceof OpenMessage);
-        Thread.sleep(60 * 1000);
-        for (final Notification m : this.msgsSend) {
-            if (m instanceof Pcerr) {
-                final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
-                assertEquals(new Short((short) 1), obj.getErrorObject().getType());
-                assertEquals(new Short((short) 2), obj.getErrorObject().getValue());
+        checkEquals(() -> {
+            for (final Notification m : this.msgsSend) {
+                if (m instanceof Pcerr) {
+                    final Errors obj = ((Pcerr) m).getPcerrMessage().getErrors().get(0);
+                    assertEquals(new Short((short) 1), obj.getErrorObject().getType());
+                    assertEquals(new Short((short) 2), obj.getErrorObject().getValue());
+                }
             }
-        }
+        });
     }
 
     @Test
-    @Ignore
-    public void testUnknownMessage() throws InterruptedException {
+    public void testUnknownMessage() throws Exception {
         final SimpleSessionListener client = new SimpleSessionListener();
-        final PCEPSessionImpl s = new PCEPSessionImpl(client, 5, this.channel, this.openMsg.getOpenMessage().getOpen(), this.openMsg.getOpenMessage().getOpen());
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(1, s.getUnknownMessagesTimes().size());
-        Thread.sleep(10000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(2, s.getUnknownMessagesTimes().size());
-        Thread.sleep(10000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(3, s.getUnknownMessagesTimes().size());
-        Thread.sleep(20000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(4, s.getUnknownMessagesTimes().size());
-        Thread.sleep(30000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(3, s.getUnknownMessagesTimes().size());
-        Thread.sleep(10000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(3, s.getUnknownMessagesTimes().size());
-        Thread.sleep(5000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(4, s.getUnknownMessagesTimes().size());
-        Thread.sleep(1000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
-        assertEquals(5, s.getUnknownMessagesTimes().size());
-        Thread.sleep(1000);
-        s.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        final PCEPSessionImpl session = new PCEPSessionImpl(client, 5, this.channel,
+            this.openMsg.getOpenMessage().getOpen(), this.openMsg.getOpenMessage().getOpen());
+        PCEPSessionImpl.setTicker(this.ticker);
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        final Queue<Long> qeue = session.getUnknownMessagesTimes();
+        CheckUtil.checkEquals(()-> assertEquals(1, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(2, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(3, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(4, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(3, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(3, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(4, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
+        CheckUtil.checkEquals(()-> assertEquals(5, qeue.size()));
+        session.handleMalformedMessage(PCEPErrors.CAPABILITY_NOT_SUPPORTED);
         synchronized (client) {
             while (client.up) {
                 client.wait();
             }
         }
-        assertTrue(!client.up);
+        CheckUtil.checkEquals(()-> assertTrue(!client.up));
     }
 
     @After
     public void tearDown() {
     }
+
+    private final class TestTicker extends Ticker {
+        private long counter = 0L;
+
+        TestTicker() {
+        }
+
+        public long read() {
+            if (this.counter == 8) {
+                this.counter++;
+                return 60000000003L;
+            } else if (this.counter == 10) {
+                this.counter++;
+                return 60000000006L;
+            }
+            return this.counter++;
+        }
+    }
 }
index 82d74c86e45fac736eaf3cee5ab500d70b1b786d..1a04a229502315b6bc3a1338ceb37ab07d83eb17 100755 (executable)
@@ -8,6 +8,8 @@
 
 package org.opendaylight.protocol.pcep.impl;
 
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
+
 import com.google.common.base.Preconditions;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.ChannelFuture;
@@ -76,7 +78,9 @@ public class PCEPDispatcherImplTest {
             eventLoopGroup, eventLoopGroup);
 
         Mockito.doReturn("mockChannel").when(this.mockChannel).toString();
-        final PCEPDispatcherImpl dispatcher2 = new PCEPDispatcherImpl(msgReg, new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0), eventLoopGroup, eventLoopGroup);
+        final PCEPDispatcherImpl dispatcher2 = new PCEPDispatcherImpl(msgReg,
+            new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
+            eventLoopGroup, eventLoopGroup);
         this.disp2Spy = Mockito.spy(dispatcher2);
 
         this.pccMock = new PCCMock(new DefaultPCEPSessionNegotiatorFactory(sessionProposal, 0),
@@ -91,6 +95,7 @@ public class PCEPDispatcherImplTest {
         final InetSocketAddress clientAddr2 = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
         final ChannelFuture futureChannel = this.dispatcher.createServer(serverAddr,
             SimpleSessionListener::new, null);
+        waitFutureSuccess(futureChannel);
         final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(clientAddr1,
             RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
@@ -116,9 +121,11 @@ public class PCEPDispatcherImplTest {
         final int port = InetSocketAddressUtil.getRandomPort();
         final InetSocketAddress serverAddr = new InetSocketAddress("0.0.0.0", port);
         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
-        this.dispatcher.createServer(serverAddr, SimpleSessionListener::new, null);
-        final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(clientAddr,
-            RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
+        waitFutureSuccess(this.dispatcher.createServer(serverAddr, SimpleSessionListener::new, null));
+        final Future<PCEPSession> futureClient = this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
+            SimpleSessionListener::new);
+        waitFutureSuccess(futureClient);
+        final PCEPSessionImpl session1 = (PCEPSessionImpl) futureClient.get();
 
         try {
             this.pccMock.createClient(clientAddr, RETRY_TIMER, CONNECT_TIMEOUT,
@@ -135,8 +142,8 @@ public class PCEPDispatcherImplTest {
     public void testReconectClient() throws InterruptedException, ExecutionException {
         final int port = InetSocketAddressUtil.getRandomPort();
         final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
-        this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", port),
-            SimpleSessionListener::new, null);
+        waitFutureSuccess(this.dispatcher.createServer(new InetSocketAddress("0.0.0.0", port),
+            SimpleSessionListener::new, null));
         final PCEPSessionImpl session1 = (PCEPSessionImpl) this.pccMock.createClient(clientAddr,
             RETRY_TIMER, CONNECT_TIMEOUT, SimpleSessionListener::new).get();
 
@@ -165,6 +172,7 @@ public class PCEPDispatcherImplTest {
 
         final ChannelFuture futureChannel = this.disp2Spy.createServer(new InetSocketAddress("0.0.0.0", port),
             SimpleSessionListener::new, null);
+        waitFutureSuccess(futureChannel);
         Mockito.verify(this.disp2Spy).createServerBootstrap(Mockito.any(PCEPDispatcherImpl.ChannelPipelineInitializer.class));
     }
 
@@ -175,20 +183,19 @@ public class PCEPDispatcherImplTest {
     }
 
     private static class PCCMock {
-
         private final PCEPSessionNegotiatorFactory negotiatorFactory;
         private final PCEPHandlerFactory factory;
         private final EventExecutor executor;
         private final EventLoopGroup workerGroup;
 
-        public PCCMock(final PCEPSessionNegotiatorFactory negotiatorFactory, final PCEPHandlerFactory factory) {
+        PCCMock(final PCEPSessionNegotiatorFactory negotiatorFactory, final PCEPHandlerFactory factory) {
             this.workerGroup = Preconditions.checkNotNull(new NioEventLoopGroup());
             this.negotiatorFactory = Preconditions.checkNotNull(negotiatorFactory);
             this.factory = Preconditions.checkNotNull(factory);
             this.executor = Preconditions.checkNotNull(GlobalEventExecutor.INSTANCE);
         }
 
-        public Future<PCEPSession> createClient(final InetSocketAddress address, final int retryTimer,
+        Future<PCEPSession> createClient(final InetSocketAddress address, final int retryTimer,
             final int connectTimeout, final PCEPSessionListenerFactory listenerFactory) {
             return createClient(address, retryTimer, connectTimeout, (ch, promise) -> {
                 ch.pipeline().addLast(this.factory.getDecoders());
@@ -198,8 +205,8 @@ public class PCEPDispatcherImplTest {
             });
         }
 
-        Future<PCEPSession> createClient(final InetSocketAddress address, final int retryTimer, final int connectTimeout,
-            final PCEPDispatcherImpl.ChannelPipelineInitializer initializer) {
+        Future<PCEPSession> createClient(final InetSocketAddress address, final int retryTimer,
+            final int connectTimeout, final PCEPDispatcherImpl.ChannelPipelineInitializer initializer) {
             final Bootstrap b = new Bootstrap();
             final PCEPProtocolSessionPromise p = new PCEPProtocolSessionPromise(this.executor, address, retryTimer,
                 connectTimeout, b);
index dbf4a56b3dbac3a580b46a271df29c9523e0c30f..e654d3ac52454dfb15522dbb3315f6a34344f54b 100644 (file)
@@ -50,7 +50,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.mes
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.PcrepBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.PcreqBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.StarttlsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OfId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.ProtocolVersion;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.RequestId;
@@ -120,7 +119,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.typ
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcrep.message.pcrep.message.replies.result.success._case.success.PathsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.PcreqMessageBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.pcreq.message.MonitoringRequestBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.pcreq.message.Requests;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.pcreq.message.monitoring.request.PceIdList;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.pcreq.message.monitoring.request.PceIdListBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcreq.message.pcreq.message.requests.SegmentComputationBuilder;
@@ -322,7 +320,7 @@ public class PCEPValidatorTest {
         builder.setOpen(b.build());
 
         assertEquals(new OpenBuilder().setOpenMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new OpenBuilder().setOpenMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -341,7 +339,7 @@ public class PCEPValidatorTest {
         final PCEPKeepAliveMessageParser parser = new PCEPKeepAliveMessageParser(this.objectRegistry);
         final KeepaliveBuilder builder = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build());
 
-        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.<Message> emptyList()));
+        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(builder.build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -353,7 +351,7 @@ public class PCEPValidatorTest {
         final PCEPStartTLSMessageParser parser = new PCEPStartTLSMessageParser(this.objectRegistry);
         final StarttlsBuilder builder = new StarttlsBuilder().setStartTlsMessage(new StartTlsMessageBuilder().build());
 
-        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.<Message> emptyList()));
+        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(builder.build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -367,7 +365,7 @@ public class PCEPValidatorTest {
         final CloseBuilder builder = new CloseBuilder().setCCloseMessage(new CCloseMessageBuilder().setCClose(
             new CCloseBuilder().setIgnore(false).setProcessingRule(false).setReason((short) 5).setTlvs(new TlvsBuilder().build()).build()).build());
 
-        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.<Message> emptyList()));
+        assertEquals(builder.build(), parser.parseMessage(result.slice(4, result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(builder.build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -395,7 +393,7 @@ public class PCEPValidatorTest {
         builder.setRequests(reqs1);
 
         assertEquals(new PcreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcreqBuilder().setPcreqMessage(builder.build()).build(), buf);
 
@@ -417,7 +415,7 @@ public class PCEPValidatorTest {
             this.svec).build()));
 
         assertEquals(new PcreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcreqBuilder().setPcreqMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -429,7 +427,7 @@ public class PCEPValidatorTest {
             assertEquals("Requests cannot be null or empty.", e.getMessage());
         }
         try {
-            parser.serializeMessage(new PcreqBuilder().setPcreqMessage(new PcreqMessageBuilder().setRequests(Collections.<Requests> emptyList()).build()).build(), null);
+            parser.serializeMessage(new PcreqBuilder().setPcreqMessage(new PcreqMessageBuilder().setRequests(Collections.emptyList()).build()).build(), null);
             fail();
         } catch (final IllegalArgumentException e) {
             assertEquals("Requests cannot be null or empty.", e.getMessage());
@@ -452,7 +450,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies1);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -470,7 +468,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies2);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -486,7 +484,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies3);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -509,7 +507,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies4);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -521,7 +519,7 @@ public class PCEPValidatorTest {
             assertEquals("Replies cannot be null or empty.", e.getMessage());
         }
         try {
-            parser.serializeMessage(new PcrepBuilder().setPcrepMessage(new PcrepMessageBuilder().setReplies(Collections.<Replies> emptyList()).build()).build(), null);
+            parser.serializeMessage(new PcrepBuilder().setPcrepMessage(new PcrepMessageBuilder().setReplies(Collections.emptyList()).build()).build(), null);
             fail();
         } catch (final IllegalArgumentException e) {
             assertEquals("Replies cannot be null or empty.", e.getMessage());
@@ -565,7 +563,7 @@ public class PCEPValidatorTest {
         builder.setNotifications(nots);
 
         assertEquals(new PcntfBuilder().setPcntfMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcntfBuilder().setPcntfMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -593,7 +591,7 @@ public class PCEPValidatorTest {
         builder.setErrorType(new RequestCaseBuilder().setRequest(new RequestBuilder().setRps(rps).build()).build());
 
         assertEquals(new PcerrBuilder().setPcerrMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcerrBuilder().setPcerrMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -609,7 +607,7 @@ public class PCEPValidatorTest {
         builder.setErrorType(new SessionCaseBuilder().setSession(new SessionBuilder().setOpen(this.open).build()).build());
 
         assertEquals(new PcerrBuilder().setPcerrMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcerrBuilder().setPcerrMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -621,7 +619,7 @@ public class PCEPValidatorTest {
             assertEquals("Errors should not be empty.", e.getMessage());
         }
         try {
-            parser.serializeMessage(new PcerrBuilder().setPcerrMessage(new PcerrMessageBuilder().setErrors(Collections.<Errors> emptyList()).build()).build(), null);
+            parser.serializeMessage(new PcerrBuilder().setPcerrMessage(new PcerrMessageBuilder().setErrors(Collections.emptyList()).build()).build(), null);
             fail();
         } catch (final IllegalArgumentException e) {
             assertEquals("Errors should not be empty.", e.getMessage());
@@ -647,7 +645,7 @@ public class PCEPValidatorTest {
         builder.setRequests(reqs1);
 
         assertEquals(new PcreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcreqBuilder().setPcreqMessage(builder.build()).build(), buf);
 
@@ -674,7 +672,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -697,7 +695,7 @@ public class PCEPValidatorTest {
 
         ByteBuf result = Unpooled.wrappedBuffer(msgBytes);
         assertEquals(new PcmonrepBuilder().setPcmonrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-                result.readableBytes() - 4), Collections.<Message> emptyList()));
+                result.readableBytes() - 4), Collections.emptyList()));
         ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcmonrepBuilder().setPcmonrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -719,7 +717,7 @@ public class PCEPValidatorTest {
 
         result = Unpooled.wrappedBuffer(ByteArray.fileToBytes("src/test/resources/PCMonRep.bin"));
         assertEquals(new PcmonrepBuilder().setPcmonrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-                result.readableBytes() - 4), Collections.<Message> emptyList()));
+                result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcmonrepBuilder().setPcmonrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -737,7 +735,7 @@ public class PCEPValidatorTest {
         rBuilder = new RepliesBuilder();
         rBuilder.setRp(this.rpTrue);
         rBuilder.setMonitoring(this.monitoring);
-        rBuilder.setPccIdReq(pccIdReq);
+        rBuilder.setPccIdReq(this.pccIdReq);
         rBuilder.setMetricPce(Lists.newArrayList(new MetricPceBuilder().setPceId(this.pceId).build()));
         final List<Paths> paths = Lists.newArrayList();
         final PathsBuilder paBuilder = new PathsBuilder();
@@ -752,7 +750,7 @@ public class PCEPValidatorTest {
         builder.setReplies(replies4);
 
         assertEquals(new PcrepBuilder().setPcrepMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcrepBuilder().setPcrepMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -778,7 +776,7 @@ public class PCEPValidatorTest {
         builder.setRequests(reqs1);
 
         assertEquals(new PcreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-                result.readableBytes() - 4), Collections.<Message> emptyList()));
+                result.readableBytes() - 4), Collections.emptyList()));
         final ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcreqBuilder().setPcreqMessage(builder.build()).build(), buf);
 
@@ -803,7 +801,7 @@ public class PCEPValidatorTest {
         };
         ByteBuf result = Unpooled.wrappedBuffer(msgBytes);
         assertEquals(new PcmonreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-                result.readableBytes() - 4), Collections.<Message> emptyList()));
+                result.readableBytes() - 4), Collections.emptyList()));
         ByteBuf buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcmonreqBuilder().setPcreqMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
@@ -828,7 +826,7 @@ public class PCEPValidatorTest {
         builder.setMonitoringRequest(monReqBuilder.build());
 
         assertEquals(new PcmonreqBuilder().setPcreqMessage(builder.build()).build(), parser.parseMessage(result.slice(4,
-            result.readableBytes() - 4), Collections.<Message> emptyList()));
+            result.readableBytes() - 4), Collections.emptyList()));
         buf = Unpooled.buffer(result.readableBytes());
         parser.serializeMessage(new PcmonreqBuilder().setPcreqMessage(builder.build()).build(), buf);
         assertArrayEquals(result.array(), buf.array());
index fb19558affc50ffc71aa87b2caa2615d6ac4b8d5..55718ac9bea02b7e78604c2c41e63b0bb65d4742 100644 (file)
@@ -9,7 +9,7 @@
 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 static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
@@ -39,7 +39,7 @@ import org.opendaylight.protocol.util.InetSocketAddressUtil;
 public class PCCDispatcherImplTest {
 
     private static final List<PCEPCapability> CAPS = new ArrayList<>();
-    private static final PCEPSessionProposalFactory PROPOSAL = new BasePCEPSessionProposalFactory(30, 120, CAPS);
+    private static final PCEPSessionProposalFactory PROPOSAL = new BasePCEPSessionProposalFactory(10, 40, CAPS);
     private final DefaultPCEPSessionNegotiatorFactory nf = new DefaultPCEPSessionNegotiatorFactory(PROPOSAL, 0);
     private PCCDispatcherImpl dispatcher;
     private PCEPDispatcher pcepDispatcher;
@@ -65,7 +65,7 @@ public class PCCDispatcherImplTest {
         closeEventLoopGroups();
     }
 
-    private void closeEventLoopGroups() throws ExecutionException, InterruptedException {
+    private void closeEventLoopGroups() {
         this.workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
         this.bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
     }
@@ -74,7 +74,6 @@ public class PCCDispatcherImplTest {
     public void testClientReconnect() throws Exception {
         final Future<PCEPSession> futureSession = this.dispatcher.createClient(this.serverAddress, 1, new TestingSessionListenerFactory(),
             this.nf, null, this.clientAddress);
-        waitFutureSuccess(futureSession);
         final TestingSessionListenerFactory slf = new TestingSessionListenerFactory();
         final ChannelFuture futureServer = this.pcepDispatcher.createServer(this.serverAddress, slf, null);
         waitFutureSuccess(futureServer);
index b0cd7ccb128ac8d4bf2623bd6e56472f092037ad..4504683e3f74c7056895b449eeae450565214202 100644 (file)
@@ -23,8 +23,8 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.typ
 
 public class PCCEndPointIpv4ObjectParserTest {
 
-    private final static String ip1 = "1.2.3.4";
-    private final static String ip2 = "1.2.3.5";
+    private final static String IP1 = "1.2.3.4";
+    private final static String IP2 = "1.2.3.5";
 
     @Test(expected=PCEPDeserializerException.class)
     public void testParseEmptyObject() throws PCEPDeserializerException {
@@ -38,12 +38,12 @@ public class PCCEndPointIpv4ObjectParserTest {
     public void testParseObject() throws PCEPDeserializerException {
         final ObjectHeader header = new ObjectHeaderImpl(false, false);
         final ByteBuf bytes = Unpooled.buffer();
-        bytes.writeBytes(Ipv4Util.bytesForAddress(new Ipv4Address(this.ip1)));
-        bytes.writeBytes(Ipv4Util.bytesForAddress(new Ipv4Address(this.ip2)));
+        bytes.writeBytes(Ipv4Util.bytesForAddress(new Ipv4Address(IP1)));
+        bytes.writeBytes(Ipv4Util.bytesForAddress(new Ipv4Address(IP2)));
         final EndpointsObj output = (EndpointsObj) new PCCEndPointIpv4ObjectParser().parseObject(header, bytes);
 
-        assertEquals(this.ip1, ((Ipv4Case) output.getAddressFamily()).getIpv4().getSourceIpv4Address().getValue());
-        assertEquals(this.ip2, ((Ipv4Case) output.getAddressFamily()).getIpv4().getDestinationIpv4Address().getValue());
+        assertEquals(IP1, ((Ipv4Case) output.getAddressFamily()).getIpv4().getSourceIpv4Address().getValue());
+        assertEquals(IP2, ((Ipv4Case) output.getAddressFamily()).getIpv4().getDestinationIpv4Address().getValue());
         assertFalse(output.isIgnore());
         assertFalse(output.isProcessingRule());
     }
index 1079e7e56c101c27aa55c13c3aaab64ea0778d77..2bc1ded806e71cef6544b3c1a801e85689e344dc 100644 (file)
@@ -8,15 +8,11 @@
 
 package org.opendaylight.protocol.pcep.pcc.mock;
 
-import static org.junit.Assert.assertFalse;
-
 import com.google.common.base.Optional;
 import io.netty.channel.Channel;
 import java.math.BigInteger;
-import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.PCEPCapability;
 import org.opendaylight.protocol.pcep.ietf.stateful07.PCEPStatefulCapability;
@@ -33,31 +29,31 @@ public class PCCIncrementalSyncTest extends PCCMockCommon {
      */
     private final String[] mainInputIncrementalSync = new String[]{"--local-address", this.localAddress.getHostString(),
         "--remote-address", InetSocketAddressUtil.toHostAndPort(this.remoteAddress).toString(), "--pcc", "1", "--lsp",
-        lsp.toString(), "--log-level", "DEBUG", "-ka", "30", "-d", "120", "--reconnect", "-1", "--redelegation-timeout",
-        "0", "--state-timeout", "-1", "--incremental-sync-procedure", "10", "5", "5"};
+        this.lsp.toString(), "--log-level", "DEBUG", "-ka", "30", "-d", "120", "--reconnect", "-1",
+        "--redelegation-timeout", "0", "--state-timeout", "-1", "--incremental-sync-procedure", "10", "5", "5"};
 
     @Test
-    public void testSessionIncrementalSyncEstablishment() throws UnknownHostException, InterruptedException, ExecutionException {
+    public void testSessionIncrementalSyncEstablishment() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(8);
         final Channel channel = createServer(factory, this.remoteAddress, new PCCServerPeerProposal(numberOflspAndDBv));
-        Main.main(mainInputIncrementalSync);
-        Thread.sleep(1000);
+        Main.main(this.mainInputIncrementalSync);
         final TestingSessionListener pceSessionListener = getListener(factory);
         checkSynchronizedSession(8, pceSessionListener, numberOflspAndDBv);
-        Thread.sleep(4000);
-        assertFalse(pceSessionListener.isUp());
-        final int expetedNumberOfLspAndEndOfSync = 3;
+        Thread.sleep(6000);
+        final int expetecdNumberOfLspAndEndOfSync = 3;
         final BigInteger expectedFinalDBVersion = BigInteger.valueOf(10);
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
-        checkResyncSession(Optional.absent(), expetedNumberOfLspAndEndOfSync, numberOflspAndDBv, expectedFinalDBVersion, sessionListenerAfterReconnect);
+        checkResyncSession(Optional.absent(), expetecdNumberOfLspAndEndOfSync, 3, numberOflspAndDBv,
+            expectedFinalDBVersion, sessionListenerAfterReconnect);
         channel.close().get();
     }
 
     @Override
     protected List<PCEPCapability> getCapabilities() {
         final List<PCEPCapability> caps = new ArrayList<>();
-        caps.add(new PCEPStatefulCapability(true, true, true, false, false, true, true));
+        caps.add(new PCEPStatefulCapability(true, true, true, false,
+            false, true, true));
         return caps;
     }
 }
index 4c77fc2e83b1fe756ff616708e272649f05c7def..603be76f74995f10df801c436c425745b5592b9b 100644 (file)
@@ -12,7 +12,9 @@ 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 static org.opendaylight.protocol.util.CheckUtil.checkEquals;
+import static org.opendaylight.protocol.util.CheckUtil.checkReceivedMessages;
+import static org.opendaylight.protocol.util.CheckUtil.waitFutureSuccess;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Stopwatch;
@@ -28,7 +30,6 @@ import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.util.List;
 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;
@@ -43,6 +44,7 @@ import org.opendaylight.protocol.pcep.impl.PCEPSessionImpl;
 import org.opendaylight.protocol.pcep.pcc.mock.api.PCCTunnelManager;
 import org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCDispatcherImpl;
 import org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCSessionListener;
+import org.opendaylight.protocol.pcep.spi.MessageRegistry;
 import org.opendaylight.protocol.pcep.spi.PCEPExtensionProviderContext;
 import org.opendaylight.protocol.pcep.spi.pojo.ServiceLoaderPCEPExtensionProviderContext;
 import org.opendaylight.protocol.pcep.sync.optimizations.SyncOptimizationsActivator;
@@ -56,50 +58,45 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 
 public abstract class PCCMockCommon {
-    private final static short KEEP_ALIVE = 30;
-    private final static short DEAD_TIMER = 120;
+    private static final short KEEP_ALIVE = 30;
+    private static final short DEAD_TIMER = 120;
     private static final long SLEEP_FOR = 50;
-    protected final int port = InetSocketAddressUtil.getRandomPort();
-    protected final InetSocketAddress remoteAddress = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(port);
-    protected final InetSocketAddress localAddress = new InetSocketAddress("127.0.0.1", port);
+    private final int port = InetSocketAddressUtil.getRandomPort();
+    protected final InetSocketAddress remoteAddress = InetSocketAddressUtil
+        .getRandomLoopbackInetSocketAddress(this.port);
+    protected final InetSocketAddress localAddress = new InetSocketAddress("127.0.0.1", this.port);
     protected PCCSessionListener pccSessionListener;
     private PCEPDispatcher pceDispatcher;
-    private PCCDispatcherImpl pccDispatcher;
+    private PCEPExtensionProviderContext extensionProvider;
+    private MessageRegistry messageRegistry;
 
     protected abstract List<PCEPCapability> getCapabilities();
 
     @Before
     public void setUp() {
-        final BasePCEPSessionProposalFactory proposal = new BasePCEPSessionProposalFactory(DEAD_TIMER, KEEP_ALIVE, getCapabilities());
+        final BasePCEPSessionProposalFactory proposal = new BasePCEPSessionProposalFactory(DEAD_TIMER, KEEP_ALIVE,
+            getCapabilities());
         final DefaultPCEPSessionNegotiatorFactory nf = new DefaultPCEPSessionNegotiatorFactory(proposal, 0);
-        this.pceDispatcher = new PCEPDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry(),
-            nf, new NioEventLoopGroup(), new NioEventLoopGroup());
+        this.extensionProvider  = ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance();
+        this.messageRegistry = this.extensionProvider.getMessageHandlerRegistry();
+        this.pceDispatcher = new PCEPDispatcherImpl(this.messageRegistry, nf, new NioEventLoopGroup(),
+            new NioEventLoopGroup());
     }
 
-    protected static TestingSessionListener checkSessionListener(final int numMessages, final Channel channel, final TestingSessionListenerFactory factory,
+    protected static TestingSessionListener checkSessionListener(final int numMessages, final Channel channel,
+        final TestingSessionListenerFactory factory,
         final String localAddress) throws
         Exception {
         final TestingSessionListener sessionListener = checkSessionListenerNotNull(factory, localAddress);
         assertTrue(sessionListener.isUp());
-        checkNumberOfMessages(numMessages, sessionListener);
+        checkReceivedMessages(sessionListener, numMessages);
         assertEquals(numMessages, sessionListener.messages().size());
         channel.close().get();
         return sessionListener;
     }
 
-    private static void checkNumberOfMessages(final int expectedNMessages, final TestingSessionListener listener) throws Exception {
-        final Stopwatch sw = Stopwatch.createStarted();
-        while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
-            if (expectedNMessages != listener.messages().size()) {
-                Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
-            } else {
-                return;
-            }
-        }
-        Assert.assertEquals(expectedNMessages, listener.messages().size());
-    }
-
-    static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory, final String localAddress) {
+    static TestingSessionListener checkSessionListenerNotNull(final TestingSessionListenerFactory factory,
+        final String localAddress) {
         final Stopwatch sw = Stopwatch.createStarted();
         TestingSessionListener listener;
         final InetAddress address = InetAddresses.forString(localAddress);
@@ -114,73 +111,81 @@ public abstract class PCCMockCommon {
         throw new NullPointerException();
     }
 
-    protected Channel createServer(final TestingSessionListenerFactory factory, final InetSocketAddress serverAddress2) throws InterruptedException {
+    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) throws InterruptedException {
-        final PCEPExtensionProviderContext ctx = ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance();
+        serverAddress2, final PCEPPeerProposal peerProposal) {
         final StatefulActivator activator07 = new StatefulActivator();
         final SyncOptimizationsActivator optimizationsActivator = new SyncOptimizationsActivator();
-        activator07.start(ctx);
-        optimizationsActivator.start(ctx);
+        activator07.start(this.extensionProvider);
+        optimizationsActivator.start(this.extensionProvider);
         final ChannelFuture future = this.pceDispatcher.createServer(serverAddress2, factory, peerProposal);
         waitFutureSuccess(future);
         return future.channel();
     }
 
-    protected static void checkSynchronizedSession(final int numberOfLsp, final TestingSessionListener pceSessionListener, final BigInteger expectedeInitialDb) throws InterruptedException {
+    protected static void checkSynchronizedSession(final int numberOfLsp,
+        final TestingSessionListener pceSessionListener, final BigInteger expectedeInitialDb) throws Exception {
         assertTrue(pceSessionListener.isUp());
-        Thread.sleep(1000);
         //Send Open with LspDBV = 1
-        final List<Message> messages = pceSessionListener.messages();
         final int numberOfSyncMessage = 1;
         int numberOfLspExpected = numberOfLsp;
         if (!expectedeInitialDb.equals(BigInteger.ZERO)) {
-            checkSequequenceDBVersionSync(messages, expectedeInitialDb);
+            checkEquals(()-> checkSequequenceDBVersionSync(pceSessionListener, expectedeInitialDb));
             numberOfLspExpected += numberOfSyncMessage;
         }
-        assertEquals(numberOfLspExpected, messages.size());
+        checkReceivedMessages(pceSessionListener, numberOfLspExpected);
         final PCEPSession session = pceSessionListener.getSession();
         checkSession(session, DEAD_TIMER, KEEP_ALIVE);
 
-        assertTrue(session.getRemoteTlvs().getAugmentation(Tlvs1.class).getStateful().getAugmentation(Stateful1.class).isInitiation());
-        assertNull(session.localSessionCharacteristics().getAugmentation(Tlvs3.class).getLspDbVersion().getLspDbVersionValue());
+        assertTrue(session.getRemoteTlvs().getAugmentation(Tlvs1.class).getStateful()
+            .getAugmentation(Stateful1.class).isInitiation());
+        assertNull(session.localSessionCharacteristics().getAugmentation(Tlvs3.class)
+            .getLspDbVersion().getLspDbVersionValue());
     }
 
-    protected static void checkResyncSession(final Optional<Integer> startAtNumberLsp, final int expectedNumberOfLsp, final BigInteger startingDBVersion,
-        final BigInteger expectedDBVersion, final TestingSessionListener pceSessionListener) throws InterruptedException {
+    protected static void checkResyncSession(final Optional<Integer> startAtNumberLsp, final int expectedNumberOfLsp,
+        final int expectedTotalMessages, final BigInteger startingDBVersion, final BigInteger expectedDBVersion,
+        final TestingSessionListener pceSessionListener) throws Exception {
         assertNotNull(pceSessionListener.getSession());
         assertTrue(pceSessionListener.isUp());
-        Thread.sleep(50);
         final List<Message> messages;
+        checkReceivedMessages(pceSessionListener, expectedTotalMessages);
         if (startAtNumberLsp.isPresent()) {
-            messages = pceSessionListener.messages().subList(startAtNumberLsp.get(), startAtNumberLsp.get() + expectedNumberOfLsp);
+            messages = pceSessionListener.messages().subList(startAtNumberLsp.get(),
+                startAtNumberLsp.get() + expectedNumberOfLsp);
         } else {
             messages = pceSessionListener.messages();
         }
-        checkSequequenceDBVersionSync(messages, expectedDBVersion);
+        checkEquals(()-> checkSequequenceDBVersionSync(pceSessionListener, expectedDBVersion));
         assertEquals(expectedNumberOfLsp, messages.size());
         final PCEPSession session = pceSessionListener.getSession();
 
         checkSession(session, DEAD_TIMER, KEEP_ALIVE);
 
-        assertTrue(session.getRemoteTlvs().getAugmentation(Tlvs1.class).getStateful().getAugmentation(Stateful1.class).isInitiation());
-        final BigInteger pceDBVersion = session.localSessionCharacteristics().getAugmentation(Tlvs3.class).getLspDbVersion().getLspDbVersionValue();
+        assertTrue(session.getRemoteTlvs().getAugmentation(Tlvs1.class).getStateful()
+            .getAugmentation(Stateful1.class).isInitiation());
+        final BigInteger pceDBVersion = session.localSessionCharacteristics().getAugmentation(Tlvs3.class)
+            .getLspDbVersion().getLspDbVersionValue();
         assertEquals(startingDBVersion, pceDBVersion);
     }
 
-    protected static void checkSession(final PCEPSession session, final int expectedDeadTimer, final int expectedKeepAlive) {
+    protected static void checkSession(final PCEPSession session, final int expectedDeadTimer,
+        final int expectedKeepAlive) {
         assertNotNull(session);
         assertEquals(expectedDeadTimer, session.getPeerPref().getDeadtimer().shortValue());
         assertEquals(expectedKeepAlive, session.getPeerPref().getKeepalive().shortValue());
-        final Stateful1 stateful = session.getRemoteTlvs().getAugmentation(Tlvs1.class).getStateful().getAugmentation(Stateful1.class);
+        final Stateful1 stateful = session.getRemoteTlvs().getAugmentation(Tlvs1.class)
+            .getStateful().getAugmentation(Stateful1.class);
         assertTrue(stateful.isInitiation());
     }
 
-    protected static void checkSequequenceDBVersionSync(final List<Message> messages, final BigInteger expectedDbVersion) {
-        for (final Message msg : messages) {
+    protected static void checkSequequenceDBVersionSync(final TestingSessionListener pceSessionListener,
+        final BigInteger expectedDbVersion) {
+        for (final Message msg : pceSessionListener.messages()) {
             final List<Reports> pcrt = ((Pcrpt) msg).getPcrptMessage().getReports();
             for (final Reports report : pcrt) {
                 final Lsp lsp = report.getLsp();
@@ -189,28 +194,30 @@ public abstract class PCCMockCommon {
                 } else {
                     assertEquals(true, lsp.isSync().booleanValue());
                 }
-                final BigInteger actuaLspDBVersion = lsp.getTlvs().getAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params
-                    .xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class).getLspDbVersion().getLspDbVersionValue();
+                final BigInteger actuaLspDBVersion = lsp.getTlvs().getAugmentation(org.opendaylight.yang.gen
+                    .v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class)
+                    .getLspDbVersion().getLspDbVersionValue();
                 assertEquals(expectedDbVersion, actuaLspDBVersion);
             }
         }
     }
 
-    protected Future<PCEPSession> createPCCSession(final BigInteger DBVersion) {
-        this.pccDispatcher = new PCCDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext.getSingletonInstance().getMessageHandlerRegistry());
+    protected Future<PCEPSession> createPCCSession(final BigInteger dbVersion) {
+        final PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(this.messageRegistry);
         final PCEPSessionNegotiatorFactory<PCEPSessionImpl> snf = getSessionNegotiatorFactory();
-        final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(3, this.localAddress.getAddress(), 0, -1, new HashedWheelTimer(),
-            Optional.absent());
+        final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(3, this.localAddress.getAddress(),
+            0, -1, new HashedWheelTimer(), Optional.absent());
 
         return pccDispatcher.createClient(this.remoteAddress, -1,
-                () -> {
-                    pccSessionListener = new PCCSessionListener(1, tunnelManager, false);
-                    return pccSessionListener;
-                }, snf, null, this.localAddress, DBVersion);
+            () -> {
+                this.pccSessionListener = new PCCSessionListener(1, tunnelManager, false);
+                return this.pccSessionListener;
+            }, snf, null, this.localAddress, dbVersion);
     }
 
     private PCEPSessionNegotiatorFactory<PCEPSessionImpl> getSessionNegotiatorFactory() {
-        return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(DEAD_TIMER, KEEP_ALIVE, getCapabilities()), 0);
+        return new DefaultPCEPSessionNegotiatorFactory(new BasePCEPSessionProposalFactory(DEAD_TIMER, KEEP_ALIVE,
+            getCapabilities()), 0);
     }
 
     protected TestingSessionListener getListener(final TestingSessionListenerFactory factory) {
index cb989257dca4b9eb041965b4246d18250cfe4af6..1c4093cb24cbd8d8f75c13f3ca6acd33e24c0843 100644 (file)
@@ -28,7 +28,7 @@ public final class PCCMockTest extends PCCMockCommon {
     public void testSessionEstablishment() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
         final Channel channel = createServer(factory, this.remoteAddress);
-        Main.main(mainInput);
+        Main.main(this.mainInput);
         Thread.sleep(1000);
         //3 reported LSPs + syc
         final int numMessages = 4;
@@ -58,7 +58,7 @@ public final class PCCMockTest extends PCCMockCommon {
             "--pcc", "2"});
         Thread.sleep(1000);
         //PCE1
-        int numMessages = 2;
+        final int numMessages = 2;
         checkSessionListener(numMessages, channel, factory, this.localAddress.getHostString());
         checkSessionListener(numMessages, channel, factory, localAddress2);
         //PCE2
index 96244f33af34e97a386857a6011970a8a2adc993..de6821956fb0dda8e2aac1fdab213e52044761a7 100644 (file)
@@ -8,6 +8,8 @@
 
 package org.opendaylight.protocol.pcep.pcc.mock;
 
+import static org.mockito.Mockito.verify;
+
 import com.google.common.collect.Lists;
 import java.util.List;
 import org.junit.After;
@@ -17,8 +19,6 @@ 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.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.pcc.mock.api.PCCSession;
 import org.opendaylight.protocol.pcep.pcc.mock.api.PCCTunnelManager;
@@ -65,13 +65,10 @@ public class PCCSessionListenerTest {
     @Before
     public void setup() {
         MockitoAnnotations.initMocks(this);
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                PCCSessionListenerTest.this.sendMessages.add((Message) invocation.getArguments()[0]);
-                return null;
-            }
-        }).when(mockedSession).sendMessage(Mockito.any(Message.class));
+        Mockito.doAnswer(invocation -> {
+            PCCSessionListenerTest.this.sendMessages.add((Message) invocation.getArguments()[0]);
+            return null;
+        }).when(this.mockedSession).sendMessage(Mockito.any(Message.class));
     }
 
     @After
@@ -81,65 +78,72 @@ public class PCCSessionListenerTest {
 
     @Test
     public void testOnMessage() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
-        listener.onMessage(mockedSession, createUpdMsg(true));
-        Mockito.verify(tunnelManager).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
-        Mockito.verify(tunnelManager, Mockito.never()).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
-        listener.onMessage(mockedSession, createUpdMsg(false));
-        Mockito.verify(tunnelManager, Mockito.times(2)).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
-        Mockito.verify(tunnelManager, Mockito.never()).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
-
-        listener.onMessage(mockedSession, createInitMsg(false, true));
-        Mockito.verify(tunnelManager, Mockito.times(2)).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
-        Mockito.verify(tunnelManager).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
-        listener.onMessage(mockedSession, createInitMsg(true, false));
-        Mockito.verify(tunnelManager, Mockito.times(2)).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
-        Mockito.verify(tunnelManager, Mockito.times(2)).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
-        listener.onMessage(mockedSession, createInitMsg(false, false));
-        Mockito.verify(tunnelManager, Mockito.times(2)).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
-        Mockito.verify(tunnelManager, Mockito.times(3)).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
+        listener.onMessage(this.mockedSession, createUpdMsg(true));
+        verify(this.tunnelManager).onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
+        verify(this.tunnelManager, Mockito.never())
+            .onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
+        listener.onMessage(this.mockedSession, createUpdMsg(false));
+        verify(this.tunnelManager, Mockito.times(2))
+            .onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
+        verify(this.tunnelManager, Mockito.never())
+            .onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
+        listener.onMessage(this.mockedSession, createInitMsg(false, true));
+        verify(this.tunnelManager, Mockito.times(2))
+            .onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
+        verify(this.tunnelManager).onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
+        listener.onMessage(this.mockedSession, createInitMsg(true, false));
+        verify(this.tunnelManager, Mockito.times(2))
+            .onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
+        verify(this.tunnelManager, Mockito.times(2))
+            .onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
+        listener.onMessage(this.mockedSession, createInitMsg(false, false));
+        verify(this.tunnelManager, Mockito.times(2))
+            .onMessagePcupd(Mockito.any(Updates.class), Mockito.any(PCCSession.class));
+        verify(this.tunnelManager, Mockito.times(3))
+            .onMessagePcInitiate(Mockito.any(Requests.class), Mockito.any(PCCSession.class));
     }
 
     @Test
     public void testOnMessageErrorMode() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, true);
-        listener.onMessage(mockedSession, createUpdMsg(true));
-        Mockito.verify(mockedSession).sendMessage(Mockito.any(Message.class));
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, true);
+        listener.onMessage(this.mockedSession, createUpdMsg(true));
+        verify(this.mockedSession).sendMessage(Mockito.any(Message.class));
     }
 
     @Test
     public void testOnSessionUp() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
-        listener.onSessionUp(mockedSession);
-        Mockito.verify(tunnelManager).onSessionUp(Mockito.any(PCCSession.class));
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
+        listener.onSessionUp(this.mockedSession);
+        verify(this.tunnelManager).onSessionUp(Mockito.any(PCCSession.class));
     }
 
     @Test
     public void testOnSessionDown() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
-        listener.onSessionDown(mockedSession, new Exception());
-        Mockito.verify(tunnelManager).onSessionDown(Mockito.any(PCCSession.class));
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
+        listener.onSessionDown(this.mockedSession, new Exception());
+        verify(this.tunnelManager).onSessionDown(Mockito.any(PCCSession.class));
     }
 
     @Test
     public void testSendError() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
-        listener.onSessionUp(mockedSession);
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
+        listener.onSessionUp(this.mockedSession);
         listener.sendError(MsgBuilderUtil.createErrorMsg(PCEPErrors.ATTEMPT_2ND_SESSION, 0));
-        Mockito.verify(mockedSession).sendMessage(Mockito.<Message>any());
+        verify(this.mockedSession).sendMessage(Mockito.any());
     }
 
     @Test
     public void testSendReport() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
-        listener.onSessionUp(mockedSession);
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
+        listener.onSessionUp(this.mockedSession);
         listener.sendReport(null);
-        Mockito.verify(mockedSession).sendMessage(Mockito.<Message>any());
+        verify(this.mockedSession).sendMessage(Mockito.any());
     }
 
     @Test
     public void testGetId() {
-        final PCCSessionListener listener = new PCCSessionListener(1, tunnelManager, false);
+        final PCCSessionListener listener = new PCCSessionListener(1, this.tunnelManager, false);
         Assert.assertEquals(1, listener.getId());
     }
 
@@ -158,7 +162,8 @@ public class PCCSessionListenerTest {
         final List<Requests> requests = Lists.newArrayList();
         final RequestsBuilder reqBuilder = new RequestsBuilder()
             .setLsp(lspBuilder.build())
-            .setSrp(new SrpBuilder(MsgBuilderUtil.createSrp(123)).addAugmentation(Srp1.class, new Srp1Builder().setRemove(remove).build()).build());
+            .setSrp(new SrpBuilder(MsgBuilderUtil.createSrp(123)).addAugmentation(Srp1.class,
+                new Srp1Builder().setRemove(remove).build()).build());
         if (endpoint) {
             reqBuilder.setEndpointsObj(new EndpointsObjBuilder().build());
         }
@@ -173,10 +178,9 @@ public class PCCSessionListenerTest {
         final UpdatesBuilder updsBuilder = new UpdatesBuilder();
         updsBuilder.setLsp(new LspBuilder().setDelegate(delegation).setPlspId(new PlspId(1L)).build());
         final PathBuilder pathBuilder = new PathBuilder();
-        pathBuilder.setEro(
-                new EroBuilder()
-                    .setSubobject(Lists.newArrayList(new SubobjectBuilder().setSubobjectType(new IpPrefixCaseBuilder().setIpPrefix(
-                        new IpPrefixBuilder().setIpPrefix(new IpPrefix(new Ipv4Prefix("127.0.0.2/32"))).build()).build()).build())).build());
+        pathBuilder.setEro(new EroBuilder().setSubobject(Lists.newArrayList(new SubobjectBuilder()
+            .setSubobjectType(new IpPrefixCaseBuilder().setIpPrefix(new IpPrefixBuilder()
+                .setIpPrefix(new IpPrefix(new Ipv4Prefix("127.0.0.2/32"))).build()).build()).build())).build());
         updsBuilder.setPath(pathBuilder.build());
         updsBuilder.setSrp(new SrpBuilder().setOperationId(new SrpIdNumber(0L)).build());
         msgBuilder.setUpdates(Lists.newArrayList(updsBuilder.build()));
index 18bb21ebd49d4428b8e3a31dc7c256ccbbc7f681..00df509619a3b255575c037fc848b8cb419c4ce8 100644 (file)
@@ -13,10 +13,8 @@ import static org.junit.Assert.assertNotNull;
 import com.google.common.base.Optional;
 import io.netty.channel.Channel;
 import java.math.BigInteger;
-import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.PCEPCapability;
 import org.opendaylight.protocol.pcep.PCEPSession;
@@ -25,16 +23,16 @@ import org.opendaylight.protocol.pcep.pcc.mock.protocol.PCCPeerProposal;
 
 public class PCCSyncAvoidanceProcedureTest extends PCCMockCommon {
     @Test
-    public void testSessionAvoidanceDesynchronizedEstablishment() throws UnknownHostException, InterruptedException, ExecutionException {
+    public void testSessionAvoidanceDesynchronizedEstablishment() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
 
         final Channel channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
-        PCEPSession session = createPCCSession(BigInteger.TEN).get();
+        final PCEPSession session = createPCCSession(BigInteger.TEN).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         assertNotNull(pceSessionListener.getSession());
-        checkResyncSession(Optional.<Integer>absent(), 11, null, BigInteger.valueOf(10), pceSessionListener);
+        checkResyncSession(Optional.absent(), 11, 11, null, BigInteger.valueOf(10), pceSessionListener);
         channel.close().get();
     }
 
index df48b5eb95b3ad8140a4f58a7fe27337e9fefcc7..4f5ea7098576e2fb56212994c1acc4d089e8c32b 100644 (file)
@@ -34,22 +34,21 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 
 public class PCCTriggeredFullDBResyncTest extends PCCMockCommon {
-    private Channel channel;
 
     @Test
     public void testSessionTriggeredFullDBReSync() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
         final int lspQuantity = 3;
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(lspQuantity);
-        this.channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
-        PCEPSession session = createPCCSession(numberOflspAndDBv).get();
+        final Channel channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
+        final PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(lspQuantity, pceSessionListener, numberOflspAndDBv);
-        pccSessionListener.onMessage(session, createTriggerLspResync());
+        this.pccSessionListener.onMessage(session, createTriggerLspResync());
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
-        checkResyncSession(Optional.of(lspQuantity), 4, null, numberOflspAndDBv, sessionListenerAfterReconnect);
+        checkResyncSession(Optional.of(lspQuantity), 4,8, null, numberOflspAndDBv, sessionListenerAfterReconnect);
         channel.close().get();
     }
 
index ed7bb6c231e846837a3510455c3a6bf6e06d1f19..1c923231e0ecf907a9723bb7dd257461ba20ac28 100644 (file)
@@ -34,23 +34,21 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 
 public class PCCTriggeredLspResyncTest extends PCCMockCommon {
-    private Channel channel;
-
     @Test
     public void testSessionTriggeredLspReSync() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
         final int lspQuantity = 3;
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(lspQuantity);
 
-        this.channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
-        PCEPSession session = createPCCSession(numberOflspAndDBv).get();
+        final Channel channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
+        final PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(lspQuantity, pceSessionListener, numberOflspAndDBv);
-        pccSessionListener.onMessage(session, createTriggerLspResync());
+        this.pccSessionListener.onMessage(session, createTriggerLspResync());
         final TestingSessionListener sessionListenerAfterReconnect = getListener(factory);
-        checkResyncSession(Optional.of(lspQuantity), 2, null, numberOflspAndDBv, sessionListenerAfterReconnect);
+        checkResyncSession(Optional.of(lspQuantity), 2, 6, null, numberOflspAndDBv, sessionListenerAfterReconnect);
         channel.close().get();
     }
 
index d129313db7b29d6892e26acc1ed676f100b352f4..b337c76b7a789855e22b561a784089811f469d4a 100644 (file)
@@ -33,22 +33,19 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 
 public class PCCTriggeredSyncTest extends PCCMockCommon {
-
-    private Channel channel;
-
     @Test
     public void testSessionTriggeredSync() throws Exception {
         final TestingSessionListenerFactory factory = new TestingSessionListenerFactory();
-        this.channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
+        final Channel channel = createServer(factory, this.remoteAddress, new PCCPeerProposal());
         final BigInteger numberOflspAndDBv = BigInteger.valueOf(3);
-        PCEPSession session = createPCCSession(numberOflspAndDBv).get();
+        final PCEPSession session = createPCCSession(numberOflspAndDBv).get();
         assertNotNull(session);
         final TestingSessionListener pceSessionListener = getListener(factory);
         assertNotNull(pceSessionListener);
         checkSynchronizedSession(0, pceSessionListener, BigInteger.ZERO);
-        pccSessionListener.onMessage(session, createTriggerMsg());
+        this.pccSessionListener.onMessage(session, createTriggerMsg());
         checkSynchronizedSession(3, pceSessionListener, numberOflspAndDBv);
-        this.channel.close().get();
+        channel.close().get();
     }
 
     private Message createTriggerMsg() {
index a1b462031cd1b9fd8d4ba3c2801c4969e91a1ef8..aa960dad85cc7b917bdd8305a71ab9ad9f73267c 100644 (file)
@@ -75,24 +75,24 @@ public class PCCTunnelManagerImplTest {
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
-        Mockito.doNothing().when(session1).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.doNothing().when(this.session1).sendReport(Mockito.any(Pcrpt.class));
         Mockito.doAnswer(new Answer<Void>() {
             @Override
             public Void answer(final InvocationOnMock invocation) throws Throwable {
-                errorsSession1.add(getError((Pcerr) invocation.getArguments()[0]));
+                PCCTunnelManagerImplTest.this.errorsSession1.add(getError((Pcerr) invocation.getArguments()[0]));
                 return null;
             }
-        }).when(session1).sendError(Mockito.any(Pcerr.class));
-        Mockito.doReturn(0).when(session1).getId();
-        Mockito.doNothing().when(session2).sendReport(Mockito.any(Pcrpt.class));
+        }).when(this.session1).sendError(Mockito.any(Pcerr.class));
+        Mockito.doReturn(0).when(this.session1).getId();
+        Mockito.doNothing().when(this.session2).sendReport(Mockito.any(Pcrpt.class));
         Mockito.doAnswer(new Answer<Void>() {
             @Override
             public Void answer(final InvocationOnMock invocation) throws Throwable {
-                errorsSession2.add(getError((Pcerr) invocation.getArguments()[0]));
+                PCCTunnelManagerImplTest.this.errorsSession2.add(getError((Pcerr) invocation.getArguments()[0]));
                 return null;
             }
-        }).when(session2).sendError(Mockito.any(Pcerr.class));
-        Mockito.doReturn(1).when(session2).getId();
+        }).when(this.session2).sendError(Mockito.any(Pcerr.class));
+        Mockito.doReturn(1).when(this.session2).getId();
     }
 
     @After
@@ -104,19 +104,19 @@ public class PCCTunnelManagerImplTest {
     @Test
     public void testOnSessionUp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        checkSessionUp(session1, tunnelManager);
-        checkSessionUp(session2, tunnelManager);
+        checkSessionUp(this.session1, tunnelManager);
+        checkSessionUp(this.session2, tunnelManager);
     }
 
     @Test
     public void testOnSessionDownAndDelegateBack() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 1, 10, TIMER, this.timerHandler);
-        checkSessionUp(session1, tunnelManager);
-        checkSessionUp(session2, tunnelManager);
-        checkSessionDown(session1, tunnelManager);
-        tunnelManager.onSessionUp(session1);
-        Mockito.verify(session1, Mockito.times(4)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        checkSessionUp(this.session1, tunnelManager);
+        checkSessionUp(this.session2, tunnelManager);
+        checkSessionDown(this.session1, tunnelManager);
+        tunnelManager.onSessionUp(this.session1);
+        Mockito.verify(this.session1, Mockito.times(4)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     private static void checkSessionDown(final PCCSession session, final PCCTunnelManager tunnelManager) {
@@ -133,178 +133,178 @@ public class PCCTunnelManagerImplTest {
     @Test
     public void testOnSessionDownAndDelegateToOther() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, -1, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session2);
-        checkSessionUp(session1, tunnelManager);
-        checkSessionDown(session1, tunnelManager);
+        tunnelManager.onSessionUp(this.session2);
+        checkSessionUp(this.session1, tunnelManager);
+        checkSessionDown(this.session1, tunnelManager);
         //wait for re-delegation timeout expires
         Thread.sleep(500);
-        Mockito.verify(session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
-        tunnelManager.onSessionUp(session1);
-        Mockito.verify(session1, Mockito.times(4)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        Mockito.verify(this.session1, Mockito.times(4)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testReportToAll() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcupd(createUpdateDelegate(1), session1);
-        Mockito.verify(session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcupd(createUpdateDelegate(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testReportToAllUnknownLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcupd(createUpdateDelegate(2), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcupd(createUpdateDelegate(2), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, this.errorsSession1.get(0));
     }
 
     @Test
     public void testReportToAllNonDelegatedLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcupd(createUpdateDelegate(1), session2);
-        Mockito.verify(session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, errorsSession2.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcupd(createUpdateDelegate(1), this.session2);
+        Mockito.verify(this.session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, this.errorsSession2.get(0));
     }
 
     @Test
     public void testReturnDelegationPccLsp() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 1, -1, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcupd(createUpdate(1), session1);
-        Mockito.verify(session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcupd(createUpdate(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
         //wait for re-delegation timer expires
         Thread.sleep(1200);
-        Mockito.verify(session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testReturnDelegationUnknownLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcupd(createUpdate(2), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcupd(createUpdate(2), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, this.errorsSession1.get(0));
     }
 
     @Test
     public void testReturnDelegationNonDelegatedLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcupd(createUpdate(1), session2);
-        Mockito.verify(session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, errorsSession2.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcupd(createUpdate(1), this.session2);
+        Mockito.verify(this.session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, this.errorsSession2.get(0));
     }
 
     @Test
     public void testAddTunnel() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcInitiate(createRequests(1), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcInitiate(createRequests(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testRemoveTunnel() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcInitiate(createRequests(1), session1);
-        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), session1);
-        Mockito.verify(session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcInitiate(createRequests(1), this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testRemoveTunnelUnknownLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, this.errorsSession1.get(0));
     }
 
     @Test
     public void testRemoveTunnelNotPceInitiatedLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.LSP_NOT_PCE_INITIATED, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.LSP_NOT_PCE_INITIATED, this.errorsSession1.get(0));
     }
 
     @Test
     public void testRemoveTunnelNotDelegated() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcInitiate(createRequests(1), session1);
-        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), session2);
-        Mockito.verify(session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, errorsSession2.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcInitiate(createRequests(1), this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsRemove(1), this.session2);
+        Mockito.verify(this.session2, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UPDATE_REQ_FOR_NON_LSP, this.errorsSession2.get(0));
     }
 
     @Test
     public void testTakeDelegation() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, -1, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcInitiate(createRequests(1), session1); //AddTunel
-        tunnelManager.onMessagePcupd(createUpdate(1), session1); //returnDelegation
-        Mockito.verify(session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcInitiate(createRequests(1), this.session1); //AddTunel
+        tunnelManager.onMessagePcupd(createUpdate(1), this.session1); //returnDelegation
+        Mockito.verify(this.session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(1)).sendReport(Mockito.any(Pcrpt.class));
         Thread.sleep(500);
-        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), session2);//takeDelegation
-        Mockito.verify(session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), this.session2);//takeDelegation
+        Mockito.verify(this.session1, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
     }
 
     @Test
     public void testTakeDelegationUnknownLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, this.errorsSession1.get(0));
     }
 
     @Test
     public void testTakeDelegationNotPceInitiatedLsp() {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(1, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), session1);
-        Mockito.verify(session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
-        assertEquals(PCEPErrors.LSP_NOT_PCE_INITIATED, errorsSession1.get(0));
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onMessagePcInitiate(createRequestsDelegate(1), this.session1);
+        Mockito.verify(this.session1, Mockito.times(1)).sendError(Mockito.any(Pcerr.class));
+        assertEquals(PCEPErrors.LSP_NOT_PCE_INITIATED, this.errorsSession1.get(0));
     }
 
     @Test
     public void testReturnDelegationNoRetake() throws InterruptedException {
         final PCCTunnelManager tunnelManager = new PCCTunnelManagerImpl(0, ADDRESS, 0, 0, TIMER, this.timerHandler);
-        tunnelManager.onSessionUp(session1);
-        tunnelManager.onSessionUp(session2);
-        tunnelManager.onMessagePcInitiate(createRequests(1), session1);
-        tunnelManager.onMessagePcupd(createUpdate(1), session1);
+        tunnelManager.onSessionUp(this.session1);
+        tunnelManager.onSessionUp(this.session2);
+        tunnelManager.onMessagePcInitiate(createRequests(1), this.session1);
+        tunnelManager.onMessagePcupd(createUpdate(1), this.session1);
         //wait for state timeout expires
         Thread.sleep(500);
-        Mockito.verify(session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
-        Mockito.verify(session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session1, Mockito.times(3)).sendReport(Mockito.any(Pcrpt.class));
+        Mockito.verify(this.session2, Mockito.times(2)).sendReport(Mockito.any(Pcrpt.class));
     }
     private Updates createUpdateDelegate(final long plspId) {
         return createUpdate(plspId, Optional.of(true));
     }
 
     private Updates createUpdate(final long plspId) {
-        return createUpdate(plspId, Optional.<Boolean>absent());
+        return createUpdate(plspId, Optional.absent());
     }
 
     private static Updates createUpdate(final long plspId, final Optional<Boolean> delegate) {
@@ -340,15 +340,15 @@ public class PCCTunnelManagerImplTest {
     }
 
     private static Requests createRequestsRemove(final long plspId) {
-        return createRequests(plspId, Optional.of(true), Optional.<Boolean>absent());
+        return createRequests(plspId, Optional.of(true), Optional.absent());
     }
 
     private static Requests createRequestsDelegate(final long plspId) {
-        return createRequests(plspId, Optional.<Boolean>absent(), Optional.of(true));
+        return createRequests(plspId, Optional.absent(), Optional.of(true));
     }
 
     private static Requests createRequests(final long plspId) {
-        return createRequests(plspId, Optional.<Boolean>absent(), Optional.<Boolean>absent());
+        return createRequests(plspId, Optional.absent(), Optional.absent());
     }
 
     private static PCEPErrors getError(final Pcerr errorMessage) {
index 8b68925003fb5f520e62c0d22d40e886bd00e355..0c9e055a0ba9a467db344b437a06b97357c62169 100644 (file)
@@ -8,31 +8,35 @@
 
 package org.opendaylight.protocol.pcep.pcc.mock;
 
-import com.google.common.collect.Lists;
+import com.google.common.collect.ImmutableList;
 import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
+import javax.annotation.concurrent.GuardedBy;
 import org.junit.Assert;
 import org.opendaylight.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.PCEPSessionListener;
 import org.opendaylight.protocol.pcep.PCEPTerminationReason;
+import org.opendaylight.protocol.util.CheckUtil.ListenerCheck;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class TestingSessionListener implements PCEPSessionListener {
+public class TestingSessionListener implements PCEPSessionListener, ListenerCheck {
 
     private static final Logger LOG = LoggerFactory.getLogger(TestingSessionListener.class);
     private final CountDownLatch sessionLatch = new CountDownLatch(1);
 
-    private final List<Message> messages = Lists.newArrayList();
+    @GuardedBy("this")
+    private final List<Message> messages = new ArrayList();
 
     private boolean up = false;
     private PCEPSession session = null;
 
     @Override
-    public void onMessage(final PCEPSession session, final Message message) {
+    public synchronized void onMessage(final PCEPSession session, final Message message) {
         LOG.debug("Received message: {}", message);
         this.messages.add(message);
     }
@@ -42,7 +46,7 @@ public class TestingSessionListener implements PCEPSessionListener {
         LOG.debug("Session up.");
         this.up = true;
         this.session = session;
-        sessionLatch.countDown();
+        this.sessionLatch.countDown();
 
     }
 
@@ -58,8 +62,8 @@ public class TestingSessionListener implements PCEPSessionListener {
         LOG.debug("Session terminated. Cause : {}", cause);
     }
 
-    List<Message> messages() {
-        return this.messages;
+    synchronized List<Message> messages() {
+        return ImmutableList.copyOf(this.messages);
     }
 
     boolean isUp () {
@@ -67,7 +71,12 @@ public class TestingSessionListener implements PCEPSessionListener {
     }
 
     public PCEPSession getSession() {
-        Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(sessionLatch, 10, TimeUnit.SECONDS));
+        Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(this.sessionLatch, 10, TimeUnit.SECONDS));
         return this.session;
     }
+
+    @Override
+    public synchronized int getListMessageSize() {
+        return this.messages.size();
+    }
 }
index c4a50e1d037f3638063485bb63ce964db1cb126a..c186deeb1865f98290c7dbb994afea23e17abad7 100644 (file)
@@ -16,7 +16,7 @@ import org.opendaylight.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.PCEPSessionListener;
 import org.opendaylight.protocol.pcep.PCEPSessionListenerFactory;
 
-public class TestingSessionListenerFactory implements PCEPSessionListenerFactory {
+class TestingSessionListenerFactory implements PCEPSessionListenerFactory {
 
     @GuardedBy("this")
     private final List<TestingSessionListener> sessionListeners = new ArrayList<>();
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
deleted file mode 100644 (file)
index 46ecc9e..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2015 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 java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-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(future1 -> latch.countDown());
-        Uninterruptibles.awaitUninterruptibly(latch, 20, TimeUnit.SECONDS);
-    }
-}
index 5f1ee6a9c466be4a87ebcc14af8285e1364fcfc6..0b8d9c8f3e19efc437e6c20ea8d5612f8a9130d9 100644 (file)
@@ -8,16 +8,18 @@
 
 package org.opendaylight.protocol.pcep.segment.routing;
 
+import static org.opendaylight.protocol.util.CheckUtil.readData;
+
 import com.google.common.collect.Lists;
 import java.nio.charset.StandardCharsets;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.bgpcep.pcep.topology.provider.AbstractPCEPSessionTest;
 import org.opendaylight.bgpcep.pcep.topology.provider.AbstractTopologySessionListener;
 import org.opendaylight.bgpcep.pcep.topology.provider.Stateful07TopologySessionListenerFactory;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.protocol.pcep.PCEPSession;
 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;
@@ -46,9 +48,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.typ
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.SubobjectBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.path.setup.type.tlv.PathSetupTypeBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
 
 public class TopologyProviderTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
 
@@ -65,42 +65,51 @@ public class TopologyProviderTest extends AbstractPCEPSessionTest<Stateful07Topo
     }
 
     @Test
-    public void testOnReportMessage() throws InterruptedException, ExecutionException {
+    public void testOnReportMessage() throws ReadFailedException {
         this.listener.onSessionUp(this.session);
 
         Pcrpt pcRptMsg = createSrPcRpt("1.1.1.1", "sr-path1", 1L, true);
         this.listener.onMessage(this.session, pcRptMsg);
-        //check sr-path
-        Topology topology = getTopology().get();
-        List<ReportedLsp> reportedLsps = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient().getReportedLsp();
-        Assert.assertEquals(1, reportedLsps.size());
-        final ReportedLsp lsp = reportedLsps.get(0);
-        Assert.assertEquals("sr-path1", lsp.getName());
-        Assert.assertEquals(1, lsp.getPath().get(0).getAugmentation(Path1.class).getPathSetupType().getPst().intValue());
-        List<Subobject> subobjects = lsp.getPath().get(0).getEro().getSubobject();
-        Assert.assertEquals(1, subobjects.size());
-        Assert.assertEquals("1.1.1.1", ((IpNodeId)((SrEroType)subobjects.get(0).getSubobjectType()).getNai()).getIpAddress().getIpv4Address().getValue());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check sr-path
+            final List<ReportedLsp> reportedLsps = pcc.getReportedLsp();
+            Assert.assertEquals(1, reportedLsps.size());
+            final ReportedLsp lsp = reportedLsps.get(0);
+            Assert.assertEquals("sr-path1", lsp.getName());
+            Assert.assertEquals(1, lsp.getPath().get(0).getAugmentation(Path1.class).getPathSetupType()
+                .getPst().intValue());
+            final List<Subobject> subobjects = lsp.getPath().get(0).getEro().getSubobject();
+            Assert.assertEquals(1, subobjects.size());
+            Assert.assertEquals("1.1.1.1", ((IpNodeId)((SrEroType)subobjects.get(0).getSubobjectType())
+                .getNai()).getIpAddress().getIpv4Address().getValue());
+            return pcc;
+        });
 
         pcRptMsg = createSrPcRpt("1.1.1.3", "sr-path2", 2L, false);
         this.listener.onMessage(this.session, pcRptMsg);
-        //check second lsp sr-path
-        topology = getTopology().get();
-        reportedLsps = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient().getReportedLsp();
-        Assert.assertEquals(2, reportedLsps.size());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check second lsp sr-path
+            Assert.assertEquals(2, pcc.getReportedLsp().size());
+            return pcc;
+        });
+
 
         pcRptMsg = createSrPcRpt("1.1.1.2", "sr-path1", 1L, true);
         this.listener.onMessage(this.session, pcRptMsg);
-        //check updated sr-path
-        topology = getTopology().get();
-        reportedLsps = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient().getReportedLsp();
-        Assert.assertEquals(2, reportedLsps.size());
-        for (final ReportedLsp rlsp : reportedLsps) {
-            if (rlsp.getName().equals("sr-path1")) {
-                subobjects = rlsp.getPath().get(0).getEro().getSubobject();
-                Assert.assertEquals(1, subobjects.size());
-                Assert.assertEquals("1.1.1.2", ((IpNodeId)((SrEroType)subobjects.get(0).getSubobjectType()).getNai()).getIpAddress().getIpv4Address().getValue());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check updated sr-path
+            final List<ReportedLsp> reportedLsps = pcc.getReportedLsp();
+            Assert.assertEquals(2, reportedLsps.size());
+            for (final ReportedLsp rlsp : reportedLsps) {
+                if (rlsp.getName().equals("sr-path1")) {
+                    final List<Subobject> subobjects = rlsp.getPath().get(0).getEro().getSubobject();
+                    Assert.assertEquals(1, subobjects.size());
+                    Assert.assertEquals("1.1.1.2", ((IpNodeId)((SrEroType)subobjects.get(0)
+                        .getSubobjectType()).getNai()).getIpAddress().getIpv4Address().getValue());
+                }
             }
-        }
+            return pcc;
+        });
     }
 
     private static Pcrpt createSrPcRpt(final String nai, final String pathName, final long plspId, final boolean hasLspIdTlv) {
index 73d2b4b623785b6294f1c9b02be49d264439343b..f37a0fdfa026b8780dd1ae587265b92229bb601b 100644 (file)
@@ -14,37 +14,29 @@ import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
-import com.google.common.base.Optional;
 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.Promise;
 import java.lang.reflect.ParameterizedType;
 import java.net.InetSocketAddress;
 import java.net.SocketAddress;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
 import org.junit.Before;
 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.pcep.topology.provider.ListenerStateRuntimeMXBean;
 import org.opendaylight.controller.config.yang.pcep.topology.provider.ListenerStateRuntimeRegistration;
 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeMXBean;
 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeRegistration;
 import org.opendaylight.controller.config.yang.pcep.topology.provider.PCEPTopologyProviderRuntimeRegistrator;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.PCEPSessionListener;
@@ -62,18 +54,22 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.basic.explicit.route.subobjects.subobject.type.IpPrefixCaseBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.basic.explicit.route.subobjects.subobject.type.ip.prefix._case.IpPrefixBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.NetworkTopologyPcepService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
 public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerFactory> extends AbstractDataBrokerTest {
 
     protected static final String TEST_TOPOLOGY_NAME = "testtopo";
-    protected static final InstanceIdentifier<Topology> TOPO_IID = InstanceIdentifier.builder(NetworkTopology.class).child(
+    static final InstanceIdentifier<Topology> TOPO_IID = InstanceIdentifier.builder(NetworkTopology.class).child(
             Topology.class, new TopologyKey(new TopologyId(TEST_TOPOLOGY_NAME))).build();
     protected static final String IPV4_MASK = "/32";
     protected static final short DEAD_TIMER = 30;
@@ -81,10 +77,12 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
     protected static final int RPC_TIMEOUT = 4;
 
     protected final String testAddress = InetSocketAddressUtil.getRandomLoopbackIpAddress();
-    protected final NodeId nodeId = new NodeId("pcc://" + testAddress);
-    protected final String eroIpPrefix = testAddress + IPV4_MASK;
+    protected final NodeId nodeId = new NodeId("pcc://" + this.testAddress);
+    protected final InstanceIdentifier<PathComputationClient> pathComputationClientIId = TOPO_IID.builder().child(Node.class,
+        new NodeKey(this.nodeId)).augmentation(Node1.class).child(PathComputationClient.class).build();
+    protected final String eroIpPrefix = this.testAddress + IPV4_MASK;
     protected final String newDestinationAddress = InetSocketAddressUtil.getRandomLoopbackIpAddress();
-    protected final String dstIpPrefix = newDestinationAddress + IPV4_MASK;
+    protected final String dstIpPrefix = this.newDestinationAddress + IPV4_MASK;
 
     protected List<Notification> receivedMsgs;
 
@@ -107,7 +105,7 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
 
     private final Open localPrefs = new OpenBuilder().setDeadTimer((short) 30).setKeepalive((short) 10).setSessionId((short) 0).build();
 
-    private final Open remotePrefs = localPrefs;
+    private final Open remotePrefs = this.localPrefs;
 
     protected ServerSessionManager manager;
 
@@ -119,24 +117,21 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         this.receivedMsgs = new ArrayList<>();
-        doAnswer(new Answer<Object>() {
-            @Override
-            public Object answer(final InvocationOnMock invocation) {
-                final Object[] args = invocation.getArguments();
-                AbstractPCEPSessionTest.this.receivedMsgs.add((Notification) args[0]);
-                return channelFuture;
-            }
+        doAnswer(invocation -> {
+            final Object[] args = invocation.getArguments();
+            AbstractPCEPSessionTest.this.receivedMsgs.add((Notification) args[0]);
+            return this.channelFuture;
         }).when(this.clientListener).writeAndFlush(any(Notification.class));
-        doReturn(null).when(this.channelFuture).addListener(Mockito.<GenericFutureListener<? extends Future<? super Void>>>any());
+        doReturn(null).when(this.channelFuture).addListener(Mockito.any());
         doReturn("TestingChannel").when(this.clientListener).toString();
         doReturn(this.pipeline).when(this.clientListener).pipeline();
         doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class));
         doReturn(this.eventLoop).when(this.clientListener).eventLoop();
         doReturn(null).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class));
         doReturn(true).when(this.clientListener).isActive();
-        final SocketAddress ra = new InetSocketAddress(testAddress, 4189);
+        final SocketAddress ra = new InetSocketAddress(this.testAddress, 4189);
         doReturn(ra).when(this.clientListener).remoteAddress();
-        final SocketAddress la = new InetSocketAddress(testAddress, InetSocketAddressUtil.getRandomPort());
+        final SocketAddress la = new InetSocketAddress(this.testAddress, InetSocketAddressUtil.getRandomPort());
         doReturn(la).when(this.clientListener).localAddress();
 
         doReturn(mock(ChannelFuture.class)).when(this.clientListener).close();
@@ -161,14 +156,8 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
         this.manager.close();
     }
 
-    protected Optional<Topology> getTopology() throws InterruptedException, ExecutionException {
-        try (ReadOnlyTransaction t = getDataBroker().newReadOnlyTransaction()) {
-            return t.read(LogicalDatastoreType.OPERATIONAL, TOPO_IID).get();
-        }
-    }
-
     protected Ero createEroWithIpPrefixes(final List<String> ipPrefixes) {
-        final List<Subobject> subobjs = new ArrayList<Subobject>(ipPrefixes.size());
+        final List<Subobject> subobjs = new ArrayList<>(ipPrefixes.size());
         final SubobjectBuilder subobjBuilder = new SubobjectBuilder();
         for (final String ipPrefix : ipPrefixes) {
             subobjBuilder.setSubobjectType(new IpPrefixCaseBuilder().setIpPrefix(new IpPrefixBuilder().setIpPrefix(
@@ -195,6 +184,6 @@ public abstract class AbstractPCEPSessionTest<T extends TopologySessionListenerF
     }
 
     protected final PCEPSession getPCEPSession(final Open localOpen, final Open remoteOpen) {
-        return neg.createSession(this.clientListener, localOpen, remoteOpen);
+        return this.neg.createSession(this.clientListener, localOpen, remoteOpen);
     }
 }
index 621e56596f2cd02d749edf50cb61f03847aae20b..ab46aa9bba757f6660d94c7683b5185a7508835c 100644 (file)
@@ -9,14 +9,15 @@
 package org.opendaylight.bgpcep.pcep.topology.provider;
 
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLsp;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createPath;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
 
 import com.google.common.base.Optional;
 import java.math.BigInteger;
 import java.util.Collections;
-import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.PCEPSession;
@@ -35,24 +36,18 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.identifiers.tlv.LspIdentifiersBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.Srp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.Subobject;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
 
 public class IncrementalSynchronizationProcedureTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
 
     private Stateful07TopologySessionListener listener;
 
-    private PCEPSession session;
-
     @Override
     @Before
     public void setUp() throws Exception {
@@ -61,84 +56,100 @@ public class IncrementalSynchronizationProcedureTest extends AbstractPCEPSession
     }
 
     @Test
-    public void testStateSynchronizationPerformed() throws InterruptedException, ExecutionException {
-        this.session = getPCEPSession(getOpen(null), getOpen(null));
+    public void testStateSynchronizationPerformed() throws Exception {
+        PCEPSession session = getPCEPSession(getOpen(null), getOpen(null));
         this.listener.onSessionUp(session);
         //report LSP + LSP-DB version number
         final Pcrpt pcRpt = getPcrpt(1L, "test");
         this.listener.onMessage(session, pcRpt);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
-        final PathComputationClient pcc = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertFalse(pcc.getReportedLsp().isEmpty());
         this.listener.onSessionDown(session, new IllegalArgumentException());
         this.listener = (Stateful07TopologySessionListener) getSessionListener();
 
         //session up - expect sync (LSP-DBs do not match)
-        final LspDbVersion localDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2l)).build();
-        this.session = getPCEPSession(getOpen(localDbVersion), getOpen(null));
+        final LspDbVersion localDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2L)).build();
+        session = getPCEPSession(getOpen(localDbVersion), getOpen(null));
         this.listener.onSessionUp(session);
-
-        final PathComputationClient pcc2 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - IncrementalSync state
-        Assert.assertEquals(PccSyncState.IncrementalSync, pcc2.getStateSync());
-        //check reported LSP - persisted from previous session
-        Assert.assertFalse(pcc2.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - IncrementalSync state
+            assertEquals(PccSyncState.IncrementalSync, pcc.getStateSync());
+            //check reported LSP - persisted from previous session
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
         //report LSP2 + LSP-DB version number 2
         final Pcrpt pcRpt2 = getPcrpt(2L,"testsecond");
         this.listener.onMessage(session, pcRpt2);
-
-        final PathComputationClient pcc3 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.IncrementalSync, pcc3.getStateSync());
-        //check reported LSP is not empty
-        Assert.assertEquals(2, pcc3.getReportedLsp().size());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.IncrementalSync, pcc.getStateSync());
+            //check reported LSP is not empty
+            assertEquals(2, pcc.getReportedLsp().size());
+            return pcc;
+        });
 
         //sync rpt + LSP-DB
         final Pcrpt syncMsg = getSyncPcrt();
         this.listener.onMessage(session, syncMsg);
-        final PathComputationClient pcc4 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc4.getStateSync());
-        //check reported LSP is empty, LSP state from previous session was purged
-        Assert.assertEquals(2, pcc4.getReportedLsp().size());
-
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP is empty, LSP state from previous session was purged
+            assertEquals(2, pcc.getReportedLsp().size());
+            return pcc;
+        });
 
         //report LSP3 + LSP-DB version number 4
         final Pcrpt pcRpt3 = getPcrpt(3L,"testthird");
         this.listener.onMessage(session, pcRpt3);
-
-        final PathComputationClient pcc5 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc5.getStateSync());
-        Assert.assertEquals(3,pcc5.getReportedLsp().size());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            assertEquals(3,pcc.getReportedLsp().size());
+            return pcc;
+        });
     }
 
     private Open getOpen(final LspDbVersion dbVersion) {
-        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class, new Tlvs1Builder().setStateful(new StatefulBuilder()
-            .addAugmentation(Stateful1.class, new Stateful1Builder().setInitiation(Boolean.TRUE).build())
-            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder()
+        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class,
+            new Tlvs1Builder().setStateful(new StatefulBuilder().addAugmentation(Stateful1.class,
+                new Stateful1Builder().setInitiation(Boolean.TRUE).build())
+            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.
+                optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml
+                .ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder()
                 .setIncludeDbVersion(Boolean.TRUE).setDeltaLspSyncCapability(Boolean.TRUE).build())
-            .build()).build()).addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(dbVersion).build()).build()).build();
+            .build()).build()).addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(dbVersion).build())
+            .build()).build();
     }
 
-    private Pcrpt getPcrpt(Long val, String pathname) {
+    private Pcrpt getPcrpt(final Long val, final String pathname) {
         return MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(val)).setTlvs(
-            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.
-                TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(val)).build())
-                .setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(pathname.getBytes())).build())
-                .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync
-                    .optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(val)).build()).build()).build()).setPlspId(new PlspId(val)
-        ).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.<Srp>absent(), createPath(Collections.<Subobject>emptyList()));
+            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.
+                object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(val)).build())
+                .setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(
+                    pathname.getBytes())).build()).addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params
+                .xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class, new org.opendaylight.yang.gen.v1.
+                urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder()
+                .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(val)).build())
+                .build()).build()).setPlspId(new PlspId(val)
+        ).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.absent(),
+            createPath(Collections.emptyList()));
     }
 
     private Pcrpt getSyncPcrt() {
         return MsgBuilderUtil.createPcRtpMessage(createLsp(0, false, Optional.of(
-                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.
+                    lsp.object.lsp.TlvsBuilder().addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.
+                        xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
                     new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync
-                        .optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(3l)).build()).build()).build()), true, false), Optional.<Srp>absent(),
-            createPath(Collections.<Subobject>emptyList()));
+                        .optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder()
+                        .setLspDbVersionValue(BigInteger.valueOf(3L)).build()).build()).build()),
+            true, false), Optional.absent(),
+            createPath(Collections.emptyList()));
     }
 }
index c14569ac24fc2f946ae4ef2549422da8641f45a5..213c9481676ad2b2d66cedcd9015fc85bc000cf7 100644 (file)
@@ -21,8 +21,6 @@ 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.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -49,7 +47,7 @@ public class PCEPStatefulPeerProposalTest {
             .child(Topology.class, new TopologyKey(new TopologyId("topology")));
     private static final NodeId NODE_ID = new NodeId("node");
     private static final LspDbVersion LSP_DB_VERSION = new LspDbVersionBuilder().setLspDbVersionValue(
-            BigInteger.valueOf(1l)).build();
+            BigInteger.ONE).build();
 
     @Mock
     private DataBroker dataBroker;
@@ -68,45 +66,42 @@ public class PCEPStatefulPeerProposalTest {
                         new StatefulBuilder().addAugmentation(Stateful1.class, new Stateful1Builder().build()).build())
                         .build());
         final ReadOnlyTransaction rTxMock = Mockito.mock(ReadOnlyTransaction.class);
-        Mockito.doReturn(rTxMock).when(dataBroker).newReadOnlyTransaction();
-        Mockito.doReturn(listenableFutureMock).when(rTxMock)
+        Mockito.doReturn(rTxMock).when(this.dataBroker).newReadOnlyTransaction();
+        Mockito.doReturn(this.listenableFutureMock).when(rTxMock)
                 .read(Mockito.any(LogicalDatastoreType.class), Mockito.any(InstanceIdentifier.class));
 
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable runnable = (Runnable) invocation.getArguments()[0];
-                runnable.run();
-                return null;
-            }
-        }).when(listenableFutureMock).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
+        Mockito.doAnswer(invocation -> {
+            final Runnable runnable = (Runnable) invocation.getArguments()[0];
+            runnable.run();
+            return null;
+        }).when(this.listenableFutureMock).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
     }
 
     @Test
     public void testSetPeerProposalSuccess() throws InterruptedException, ExecutionException {
-        Mockito.doReturn(Optional.of(LSP_DB_VERSION)).when(listenableFutureMock).get();
-        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(dataBroker,
+        Mockito.doReturn(Optional.of(LSP_DB_VERSION)).when(this.listenableFutureMock).get();
+        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(this.dataBroker,
                 TOPOLOGY_IID);
-        peerProposal.setPeerProposal(NODE_ID, tlvsBuilder);
-        assertEquals(LSP_DB_VERSION, tlvsBuilder.getAugmentation(Tlvs3.class).getLspDbVersion());
+        peerProposal.setPeerProposal(NODE_ID, this.tlvsBuilder);
+        assertEquals(LSP_DB_VERSION, this.tlvsBuilder.getAugmentation(Tlvs3.class).getLspDbVersion());
     }
 
     @Test
     public void testSetPeerProposalAbsent() throws InterruptedException, ExecutionException {
-        Mockito.doReturn(Optional.absent()).when(listenableFutureMock).get();
-        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(dataBroker,
+        Mockito.doReturn(Optional.absent()).when(this.listenableFutureMock).get();
+        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(this.dataBroker,
                 TOPOLOGY_IID);
-        peerProposal.setPeerProposal(NODE_ID, tlvsBuilder);
-        assertNull(tlvsBuilder.getAugmentation(Tlvs3.class));
+        peerProposal.setPeerProposal(NODE_ID, this.tlvsBuilder);
+        assertNull(this.tlvsBuilder.getAugmentation(Tlvs3.class));
     }
 
     @Test
     public void testSetPeerProposalFailure() throws InterruptedException, ExecutionException {
-        Mockito.doThrow(new RuntimeException()).when(listenableFutureMock).get();
-        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(dataBroker,
+        Mockito.doThrow(new RuntimeException()).when(this.listenableFutureMock).get();
+        final PCEPStatefulPeerProposal peerProposal = PCEPStatefulPeerProposal.createStatefulPeerProposal(this.dataBroker,
                 TOPOLOGY_IID);
-        peerProposal.setPeerProposal(NODE_ID, tlvsBuilder);
-        assertNull(tlvsBuilder.getAugmentation(Tlvs3.class));
+        peerProposal.setPeerProposal(NODE_ID, this.tlvsBuilder);
+        assertNull(this.tlvsBuilder.getAugmentation(Tlvs3.class));
     }
 
 }
index f75a17df263d8f3b61576b259653f3fd95f54f4e..542416e71ec01554d7d425f9bea574971e453c82 100644 (file)
@@ -7,15 +7,16 @@
  */
 package org.opendaylight.bgpcep.pcep.topology.provider;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLsp;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createPath;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
 
 import com.google.common.base.Optional;
 import java.math.BigInteger;
 import java.util.Collections;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.PCEPSession;
@@ -35,25 +36,22 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.identifiers.tlv.LspIdentifiersBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.Srp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.SrpBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.Subobject;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.TriggerSyncInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
 
 public class PCEPTriggeredReSynchronizationProcedureTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
     private Stateful07TopologySessionListener listener;
 
     private PCEPSession session;
+    private final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.ONE).build();
 
     @Override
     @Before
@@ -63,104 +61,120 @@ public class PCEPTriggeredReSynchronizationProcedureTest extends AbstractPCEPSes
     }
 
     @Test
-    public void testTriggeredResynchronization() throws InterruptedException, ExecutionException {
+    public void testTriggeredResynchronization() throws Exception {
         //session up - sync skipped (LSP-DBs match)
-        final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build();
-        this.session = getPCEPSession(getOpen(lspDbVersion), getOpen(lspDbVersion));
-        this.listener.onSessionUp(session);
+        this.session = getPCEPSession(getOpen(), getOpen());
+        this.listener.onSessionUp(this.session);
 
         //report LSP + LSP-DB version number
         final Pcrpt pcRpt = getPcrt();
-        this.listener.onMessage(session, pcRpt);
+        this.listener.onMessage(this.session, pcRpt);
 
-        final PathComputationClient pcc = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
-        Assert.assertFalse(pcc.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
         //PCEP Trigger Full Resync
-        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(nodeId).build());
-
-        final PathComputationClient pcc1 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertEquals(PccSyncState.PcepTriggeredResync, pcc1.getStateSync());
+        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(this.nodeId).build());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(PccSyncState.PcepTriggeredResync, pcc.getStateSync());
+            return pcc;
+        });
 
         //end of sync
         final Pcrpt syncMsg = getSyncMsg();
-        this.listener.onMessage(session, syncMsg);
-        final PathComputationClient pcc2 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc2.getStateSync());
-
-        this.listener.onMessage(session, pcRpt);
-        final PathComputationClient pcc3 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertEquals(1, pcc3.getReportedLsp().size());
+        this.listener.onMessage(this.session, syncMsg);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            return pcc;
+        });
+
+        this.listener.onMessage(this.session, pcRpt);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(1, pcc.getReportedLsp().size());
+            return pcc;
+        });
 
         //Trigger Full Resync
-        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(nodeId).build());
-        this.listener.onMessage(session, pcRpt);
+        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(this.nodeId).build());
+        this.listener.onMessage(this.session, pcRpt);
         //end of sync
-        this.listener.onMessage(session, syncMsg);
-        final PathComputationClient pcc4 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc4.getStateSync());
-        //check reported LSP is not empty, Stale LSP state were purged
-        Assert.assertEquals(1, pcc4.getReportedLsp().size());
+        this.listener.onMessage(this.session, syncMsg);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP is not empty, Stale LSP state were purged
+            assertEquals(1, pcc.getReportedLsp().size());
+            return pcc;
+        });
     }
 
     @Test
-    public void testTriggeredResynchronizationLsp() throws InterruptedException, ExecutionException {
+    public void testTriggeredResynchronizationLsp() throws Exception {
         //session up - sync skipped (LSP-DBs match)
-        final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build();
-        this.session = getPCEPSession(getOpen(lspDbVersion), getOpen(lspDbVersion));
-        this.listener.onSessionUp(session);
+
+        this.session = getPCEPSession(getOpen(), getOpen());
+        this.listener.onSessionUp(this.session);
 
         //report LSP + LSP-DB version number
         final Pcrpt pcRpt = getPcrt();
-        this.listener.onMessage(session, pcRpt);
-
-        final PathComputationClient pcc = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
-        final List<ReportedLsp> reportedLspPcc = pcc.getReportedLsp();
-        Assert.assertFalse(reportedLspPcc.isEmpty());
+        this.listener.onMessage(this.session, pcRpt);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            final List<ReportedLsp> reportedLspPcc = pcc.getReportedLsp();
+            assertFalse(reportedLspPcc.isEmpty());
+            return pcc;
+        });
 
         //Trigger Full Resync
-        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(nodeId).setName("test").build());
-
-        final PathComputationClient pcc1 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertEquals(PccSyncState.PcepTriggeredResync, pcc1.getStateSync());
-        Assert.assertFalse(pcc1.getReportedLsp().isEmpty());
-
-        this.listener.onMessage(session, pcRpt);
-
-        Assert.assertFalse(reportedLspPcc.isEmpty());
+        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(this.nodeId).setName("test").build());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(PccSyncState.PcepTriggeredResync, pcc.getStateSync());
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
+
+        this.listener.onMessage(this.session, pcRpt);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
         //sync rpt + LSP-DB
         final Pcrpt syncMsg = getSyncMsg();
-        this.listener.onMessage(session, syncMsg);
-        final PathComputationClient pcc2 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc2.getStateSync());
-        //check reported LSP
-        Assert.assertEquals(1, pcc2.getReportedLsp().size());
+        this.listener.onMessage(this.session, syncMsg);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP
+            assertEquals(1, pcc.getReportedLsp().size());
+            return pcc;
+        });
 
         //Trigger Full Resync
-        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(nodeId).setName("test").build());
-        this.listener.onMessage(session, syncMsg);
-
-        final PathComputationClient pcc3 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc3.getStateSync());
-        //check reported LSP
-        Assert.assertEquals(0, pcc3.getReportedLsp().size());
-
+        this.listener.triggerSync(new TriggerSyncInputBuilder().setNode(this.nodeId).setName("test").build());
+        this.listener.onMessage(this.session, syncMsg);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP
+            assertEquals(0, pcc.getReportedLsp().size());
+            return pcc;
+        });
     }
 
-    private Open getOpen(final LspDbVersion dbVersion) {
-        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class, new Tlvs1Builder().setStateful(new StatefulBuilder()
-            .addAugmentation(Stateful1.class, new Stateful1Builder().setInitiation(Boolean.TRUE).build())
-            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1.class,
-                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder()
-                    .setIncludeDbVersion(Boolean.TRUE).setTriggeredResync(Boolean.TRUE).build())
-            .build()).build()).addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(dbVersion).build()).build()).build();
+    private Open getOpen() {
+        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class,
+            new Tlvs1Builder().setStateful(new StatefulBuilder().addAugmentation(Stateful1.class, new Stateful1Builder()
+                .setInitiation(Boolean.TRUE).build()).addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight
+                    .params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1.class,
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations
+                    .rev150714.Stateful1Builder().setIncludeDbVersion(Boolean.TRUE).setTriggeredResync(Boolean.TRUE)
+                    .build()).build()).build()).addAugmentation(Tlvs3.class, new Tlvs3Builder()
+            .setLspDbVersion(this.lspDbVersion).build()).build()).build();
     }
 
     private Pcrpt getSyncMsg() {
@@ -171,19 +185,19 @@ public class PCEPTriggeredReSynchronizationProcedureTest extends AbstractPCEPSes
                 new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().addAugmentation(
                     org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
                     new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder()
-                        .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(3l)).build()).build()).build()), true, false),
-                            Optional.of(srpBuilder.build()), createPath(Collections.<Subobject>emptyList()));
+                        .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(3L)).build()).build()).build()), true, false),
+                            Optional.of(srpBuilder.build()), createPath(Collections.emptyList()));
     }
 
     private Pcrpt getPcrt() {
-        return MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1l)).setTlvs(
+        return MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1L)).setTlvs(
                 new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.
-                    TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1l)).build()).setSymbolicPathName(
+                    TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1L)).build()).setSymbolicPathName(
                     new SymbolicPathNameBuilder().setPathName(new SymbolicPathName("test".getBytes())).build())
                     .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
                         new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder()
-                            .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build()).build()).build())
-                .setPlspId(new PlspId(1L)).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.<Srp>absent(),
-            createPath(Collections.<Subobject>emptyList()));
+                            .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.ONE).build()).build()).build())
+                .setPlspId(new PlspId(1L)).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.absent(),
+            createPath(Collections.emptyList()));
     }
 }
index 0be8b120bf435f7cfcaf4689fb490ba4f9ea5502..7c177a6928462d78cd7ac013d33912076952ef63 100644 (file)
@@ -8,14 +8,16 @@
 
 package org.opendaylight.bgpcep.pcep.topology.provider;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLsp;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createPath;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
 
 import com.google.common.base.Optional;
 import java.math.BigInteger;
 import java.util.Collections;
-import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.protocol.pcep.PCEPSession;
@@ -34,23 +36,17 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.identifiers.tlv.LspIdentifiersBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.Srp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.Subobject;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
 
 public class PCETriggeredInitialSyncProcedureTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
     private Stateful07TopologySessionListener listener;
 
-    private PCEPSession session;
-
     @Override
     @Before
     public void setUp() throws Exception {
@@ -62,32 +58,41 @@ public class PCETriggeredInitialSyncProcedureTest extends AbstractPCEPSessionTes
      * Test Triggered Initial Sync procedure
      **/
     @Test
-    public void testPcepTriggeredInitialSyncPerformed() throws InterruptedException, ExecutionException {
+    public void testPcepTriggeredInitialSyncPerformed() throws Exception {
         this.listener = (Stateful07TopologySessionListener) getSessionListener();
 
         //session up - expect triggered sync (LSP-DBs do not match)
-        final LspDbVersion localDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build();
-        final LspDbVersion localDbVersion2 = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2l)).build();
-        this.session = getPCEPSession(getOpen(localDbVersion, Boolean.FALSE), getOpen(localDbVersion2, Boolean.FALSE));
+        final LspDbVersion localDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.ONE).build();
+        final LspDbVersion localDbVersion2 = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2L)).build();
+        final PCEPSession session = getPCEPSession(getOpen(localDbVersion, Boolean.FALSE), getOpen(localDbVersion2, Boolean.FALSE));
         this.listener.onSessionUp(session);
 
-        final PathComputationClient pcc2 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - not synchronized and TriggeredInitialSync state
-        Assert.assertEquals(PccSyncState.TriggeredInitialSync, pcc2.getStateSync());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - not synchronized and TriggeredInitialSync state
+            assertEquals(PccSyncState.TriggeredInitialSync, pcc.getStateSync());
+            return pcc;
+        });
+
         //sync rpt + LSP-DB
         final Pcrpt syncMsg = getsyncMsg();
         this.listener.onMessage(session, syncMsg);
-        final PathComputationClient pcc3 = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc3.getStateSync());
-        //check reported LSP is empty, LSP state from previous session was purged
-        Assert.assertTrue(pcc3.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP is empty, LSP state from previous session was purged
+            assertTrue(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
         //report LSP + LSP-DB version number
         final Pcrpt pcRpt = getPcrpt();
         this.listener.onMessage(session, pcRpt);
-        final PathComputationClient pcc = getTopology().get().getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertFalse(pcc.getReportedLsp().isEmpty());
+
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
+
     }
 
     private Open getOpen(final LspDbVersion dbVersion, final boolean incremental) {
@@ -107,20 +112,20 @@ public class PCETriggeredInitialSyncProcedureTest extends AbstractPCEPSessionTes
                         .xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class, new org.opendaylight
                         .yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714
                         .Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger
-                        .valueOf(2l)).build()).build()).build()), true, false), Optional.<Srp>absent(),
-                        createPath(Collections.<Subobject>emptyList()));
+                        .valueOf(2L)).build()).build()).build()), true, false), Optional.absent(),
+                        createPath(Collections.emptyList()));
     }
 
     private Pcrpt getPcrpt() {
-        return MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1l)).setTlvs(
+        return MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1L)).setTlvs(
             new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp
-                .object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1l)).build
+                .object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1L)).build
                 ()).setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(new SymbolicPathName("test"
                 .getBytes())).build()).addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns
                 .yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class, new org.opendaylight.yang.gen.v1
                 .urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder()
-                .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(3l)).build())
+                .setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(3L)).build())
                 .build()).build()).setPlspId(new PlspId(1L)).setSync(true).setRemove(false).setOperational
-            (OperationalStatus.Active).build(), Optional.<Srp>absent(), createPath(Collections.<Subobject>emptyList()));
+            (OperationalStatus.Active).build(), Optional.absent(), createPath(Collections.emptyList()));
     }
 }
index 4efb8162e5c601044ff51bc63285dc3c7aa50e23..8a8e8f2ab5f8528bc2da16cf072dbf5289fdf9ad 100644 (file)
@@ -8,16 +8,19 @@
 
 package org.opendaylight.bgpcep.pcep.topology.provider;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLsp;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createPath;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
 
 import com.google.common.base.Optional;
 import java.math.BigInteger;
 import java.util.Collections;
-import java.util.concurrent.ExecutionException;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.protocol.pcep.PCEPSession;
 import org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.PathComputationClient1;
@@ -35,25 +38,19 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.iet
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.identifiers.tlv.LspIdentifiersBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.srp.object.Srp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.Subobject;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.PccSyncState;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
 
-public class StateSynchronizationAvoidanceProcedureTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
+public class StateSynchronizationAvoidanceProcedureTest extends
+    AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
 
     private Stateful07TopologySessionListener listener;
 
-    private PCEPSession session;
-
     @Override
     @Before
     public void setUp() throws Exception {
@@ -62,83 +59,112 @@ public class StateSynchronizationAvoidanceProcedureTest extends AbstractPCEPSess
     }
 
     @Test
-    public void testNodePersisted() throws InterruptedException, ExecutionException {
-        this.session = getPCEPSession(getOpen(null), getOpen(null));
+    public void testNodePersisted() throws ReadFailedException {
+        final PCEPSession session = getPCEPSession(getOpen(null), getOpen(null));
         this.listener.onSessionUp(session);
         //report LSP + LSP-DB version number
         final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setTlvs(
                 new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder()
                     .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
-                            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build()).build()).build()).setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(1l)), null);
+                            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.ONE).build()).build()).build()).setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(1L)), null);
         this.listener.onMessage(session, pcRpt);
         //check topology
-        final Topology topo1 = getTopology().get();
-        final LspDbVersion lspDb1 = topo1.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient().getAugmentation(PathComputationClient1.class).getLspDbVersion();
-        Assert.assertEquals(1l, lspDb1.getLspDbVersionValue().longValue());
+        readData(getDataBroker(), this.pathComputationClientIId.builder().augmentation(PathComputationClient1.class)
+            .child(LspDbVersion.class).build(), dbVersion -> {
+            assertEquals(1L, dbVersion.getLspDbVersionValue().longValue());
+            return dbVersion;
+        });
+
         //drop session
         this.listener.onSessionDown(session, new IllegalStateException());
         //check topology - node is persisted
-        final Topology topo2 = getTopology().get();
-        Assert.assertFalse(topo2.getNode().isEmpty());
+        readData(getDataBroker(), TOPO_IID, topology -> {
+            assertFalse(topology.getNode().isEmpty());
+            return topology;
+        });
     }
 
     @Test
-    public void testStateSynchronizationSkipped() throws InterruptedException, ExecutionException {
+    public void testStateSynchronizationSkipped() throws Exception {
         //session up - sync skipped (LSP-DBs match)
-        final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build();
-        this.session = getPCEPSession(getOpen(lspDbVersion), getOpen(lspDbVersion));
+        final LspDbVersion lspDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.ONE).build();
+        final PCEPSession session = getPCEPSession(getOpen(lspDbVersion), getOpen(lspDbVersion));
         this.listener.onSessionUp(session);
         //check node - synchronized
-        final Topology topo = getTopology().get();
-        Assert.assertEquals(PccSyncState.Synchronized, topo.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient().getStateSync());
-    }
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            return pcc;
+        });
+  }
 
     @Test
-    public void testStateSynchronizationPerformed() throws InterruptedException, ExecutionException {
-        this.session = getPCEPSession(getOpen(null), getOpen(null));
+    public void testStateSynchronizationPerformed() throws Exception {
+        PCEPSession session = getPCEPSession(getOpen(null), getOpen(null));
         this.listener.onSessionUp(session);
         //report LSP + LSP-DB version number
-        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1l)).setTlvs(
-                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1l)).build()).setSymbolicPathName(new SymbolicPathNameBuilder().setPathName(new SymbolicPathName("test".getBytes())).build())
-                    .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
-                            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(1l)).build()).build()).build()).setPlspId(new PlspId(1L)).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.<Srp>absent(), createPath(Collections.<Subobject> emptyList()));
+        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setPlspId(new PlspId(1L)).setTlvs(
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.
+                    object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder()
+                    .setLspId(new LspId(1L)).build()).setSymbolicPathName(new SymbolicPathNameBuilder()
+                    .setPathName(new SymbolicPathName("test".getBytes())).build()).addAugmentation(org.opendaylight.
+                        yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714
+                        .Tlvs1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller
+                    .pcep.sync.optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder()
+                    .setLspDbVersionValue(BigInteger.ONE).build()).build()).build())
+            .setPlspId(new PlspId(1L)).setSync(true).setRemove(false).setOperational(OperationalStatus.Active)
+            .build(), Optional.absent(), createPath(Collections.emptyList()));
         this.listener.onMessage(session, pcRpt);
-        final Topology topo = getTopology().get();
-        final PathComputationClient pcc = topo.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        Assert.assertFalse(pcc.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
+
         this.listener.onSessionDown(session, new IllegalArgumentException());
         this.listener = (Stateful07TopologySessionListener) getSessionListener();
 
         //session up - expect sync (LSP-DBs do not match)
-        final LspDbVersion localDbVersion = new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2l)).build();
-        this.session = getPCEPSession(getOpen(localDbVersion), getOpen(null));
+        final LspDbVersion localDbVersion = new LspDbVersionBuilder()
+            .setLspDbVersionValue(BigInteger.valueOf(2L)).build();
+        session = getPCEPSession(getOpen(localDbVersion), getOpen(null));
         this.listener.onSessionUp(session);
 
-        final Topology topo2 = getTopology().get();
-        final PathComputationClient pcc2 = topo2.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - not synchronized
-        Assert.assertEquals(PccSyncState.InitialResync, pcc2.getStateSync());
-        //check reported LSP - persisted from previous session
-        Assert.assertFalse(pcc2.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - not synchronized
+            assertEquals(PccSyncState.InitialResync, pcc.getStateSync());
+            //check reported LSP - persisted from previous session
+            assertFalse(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
+
         //sync rpt + LSP-DB
         final Pcrpt syncMsg = MsgBuilderUtil.createPcRtpMessage(createLsp(0, false, Optional.of(
-                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
-                        new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder().setLspDbVersionValue(BigInteger.valueOf(2l)).build()).build()).build()), true, false), Optional.<Srp>absent(),
-                createPath(Collections.<Subobject> emptyList()));
+            new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222
+                .lsp.object.lsp.TlvsBuilder().addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.
+                    params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Tlvs1.class,
+                new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync
+                    .optimizations.rev150714.Tlvs1Builder().setLspDbVersion(new LspDbVersionBuilder()
+                    .setLspDbVersionValue(BigInteger.valueOf(2L)).build()).build()).build()),
+            true, false), Optional.absent(),
+                createPath(Collections.emptyList()));
         this.listener.onMessage(session, syncMsg);
-        final Topology topo3 = getTopology().get();
-        final PathComputationClient pcc3 = topo3.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        //check node - synchronized
-        Assert.assertEquals(PccSyncState.Synchronized, pcc3.getStateSync());
-        //check reported LSP is empty, LSP state from previous session was purged
-        Assert.assertTrue(pcc3.getReportedLsp().isEmpty());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            //check node - synchronized
+            assertEquals(PccSyncState.Synchronized, pcc.getStateSync());
+            //check reported LSP is empty, LSP state from previous session was purged
+            assertTrue(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
     }
 
-    protected Open getOpen(final LspDbVersion dbVersion) {
-        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class, new Tlvs1Builder().setStateful(new StatefulBuilder()
+    private Open getOpen(final LspDbVersion dbVersion) {
+        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class,
+            new Tlvs1Builder().setStateful(new StatefulBuilder()
             .addAugmentation(Stateful1.class, new Stateful1Builder().setInitiation(Boolean.TRUE).build())
-            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder().setIncludeDbVersion(Boolean.TRUE).build())
-            .build()).build()).addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(dbVersion).build()).build()).build();
+            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.
+                optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.
+                xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder()
+                .setIncludeDbVersion(Boolean.TRUE).build()).build()).build()).addAugmentation(Tlvs3.class,
+            new Tlvs3Builder().setLspDbVersion(dbVersion).build()).build()).build();
     }
 
 }
index 3ea8113dc334044f11f1431446f4b4ba7fe8e8c4..319dfb3375bc5d2ae2fbfe4d96064308f68613cd 100755 (executable)
@@ -17,6 +17,9 @@ import static org.junit.Assert.fail;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLspTlvs;
+import static org.opendaylight.protocol.util.CheckUtil.checkNull;
+import static org.opendaylight.protocol.util.CheckUtil.readData;
+
 import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
 import java.net.UnknownHostException;
@@ -29,6 +32,7 @@ import java.util.concurrent.TimeoutException;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.config.yang.pcep.topology.provider.SessionState;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.protocol.pcep.PCEPCloseTermination;
 import org.opendaylight.protocol.pcep.PCEPSession;
@@ -36,6 +40,7 @@ import org.opendaylight.protocol.pcep.TerminationReason;
 import org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil;
 import org.opendaylight.protocol.pcep.spi.AbstractMessageParser;
 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
+import org.opendaylight.protocol.util.CheckUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.topology.rev140113.NetworkTopologyRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Pcinitiate;
@@ -71,12 +76,10 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.typ
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.endpoints.address.family.ipv4._case.Ipv4Builder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.endpoints.object.EndpointsObjBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.EroBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.ero.Subobject;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcep.error.object.ErrorObject;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.rp.object.Rp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspInputBuilder;
@@ -84,7 +87,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.FailureType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspInputBuilder;
@@ -92,15 +94,13 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.add.lsp.args.ArgumentsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
 public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> {
 
-    private final String TUNNEL_NAME = "pcc_" + testAddress + "_tunnel_0";
+    private final String TUNNEL_NAME = "pcc_" + this.testAddress + "_tunnel_0";
 
     private Stateful07TopologySessionListener listener;
 
@@ -118,17 +118,17 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
     public void testStateful07TopologySessionListener() throws Exception {
         this.listener.onSessionUp(this.session);
 
-        assertEquals(testAddress, this.listener.getPeerId());
+        assertEquals(this.testAddress, this.listener.getPeerId());
         final SessionState state = this.listener.getSessionState();
         assertNotNull(state);
         assertEquals(DEAD_TIMER, state.getLocalPref().getDeadtimer().shortValue());
         assertEquals(KEEP_ALIVE, state.getLocalPref().getKeepalive().shortValue());
         assertEquals(0, state.getLocalPref().getSessionId().intValue());
-        assertEquals(testAddress, state.getLocalPref().getIpAddress());
+        assertEquals(this.testAddress, state.getLocalPref().getIpAddress());
         assertEquals(DEAD_TIMER, state.getPeerPref().getDeadtimer().shortValue());
         assertEquals(KEEP_ALIVE, state.getPeerPref().getKeepalive().shortValue());
         assertEquals(0, state.getPeerPref().getSessionId().intValue());
-        assertEquals(testAddress, state.getPeerPref().getIpAddress());
+        assertEquals(this.testAddress, state.getPeerPref().getIpAddress());
 
         // add-lsp
         this.topologyRpcs.addLsp(createAddLspInput());
@@ -138,32 +138,34 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0);
         final long srpId = req.getSrp().getOperationId().getValue();
         final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true,
-            testAddress, testAddress, testAddress, Optional.<byte[]>absent());
-        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs).setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject()));
-        final Pcrpt esm = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setSync(false).build(), Optional.of(MsgBuilderUtil.createSrp(0L)), null);
+            this.testAddress, this.testAddress, this.testAddress, Optional.absent());
+        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp())
+            .setTlvs(tlvs).setPlspId(new PlspId(1L)).setSync(false).setRemove(false)
+            .setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)),
+            MsgBuilderUtil.createPath(req.getEro().getSubobject()));
+        final Pcrpt esm = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setSync(false).build(),
+            Optional.of(MsgBuilderUtil.createSrp(0L)), null);
         this.listener.onMessage(this.session, esm);
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(this.testAddress, pcc.getIpAddress().getIpv4Address().getValue());
+            // reported lsp so far empty, has not received response (PcRpt) yet
+            assertTrue(pcc.getReportedLsp().isEmpty());
+            return pcc;
+        });
 
-        final Optional<Topology> topoOptional = getTopology();
-        assertTrue(topoOptional.isPresent());
-        Topology topology = topoOptional.get();
-        assertEquals(1, topology.getNode().size());
-        final Node1 node = topology.getNode().get(0).getAugmentation(Node1.class);
-        assertNotNull(node);
-        PathComputationClient pcc = node.getPathComputationClient();
-        assertEquals(testAddress, pcc.getIpAddress().getIpv4Address().getValue());
-        // reported lsp so far empty, has not received response (PcRpt) yet
-        assertTrue(pcc.getReportedLsp().isEmpty());
         this.listener.onMessage(this.session, pcRpt);
         // check created lsp
-        topology = getTopology().get();
-        pcc = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        assertEquals(1, pcc.getReportedLsp().size());
-        ReportedLsp reportedLsp = pcc.getReportedLsp().get(0);
-        assertEquals(TUNNEL_NAME, reportedLsp.getName());
-        assertEquals(1, reportedLsp.getPath().size());
-        Path path = reportedLsp.getPath().get(0);
-        assertEquals(1, path.getEro().getSubobject().size());
-        assertEquals(eroIpPrefix, getLastEroIpPrefix(path.getEro()));
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(1, pcc.getReportedLsp().size());
+            final ReportedLsp reportedLsp = pcc.getReportedLsp().get(0);
+            assertEquals(this.TUNNEL_NAME, reportedLsp.getName());
+            assertEquals(1, reportedLsp.getPath().size());
+            final Path path = reportedLsp.getPath().get(0);
+            assertEquals(1, path.getEro().getSubobject().size());
+            assertEquals(this.eroIpPrefix, getLastEroIpPrefix(path.getEro()));
+            return pcc;
+        });
+
         // check stats
         assertEquals(1, this.listener.getDelegatedLspsCount().intValue());
         assertTrue(this.listener.getSynchronized());
@@ -174,10 +176,15 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         assertNotNull(this.listener.getSessionState());
 
         // update-lsp
-        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder();
-        updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(eroIpPrefix, dstIpPrefix)));
-        updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder().setDelegate(true).setAdministrative(true).build()).build());
-        final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build()).setName(TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args
+            .ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.
+            topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder();
+        updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix, this.dstIpPrefix)));
+        updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder()
+            .setDelegate(true).setAdministrative(true).build()).build());
+        final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build())
+            .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID))
+            .setNode(this.nodeId).build();
         this.topologyRpcs.updateLsp(update);
         assertEquals(2, this.receivedMsgs.size());
         assertTrue(this.receivedMsgs.get(1) instanceof Pcupd);
@@ -185,19 +192,25 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         final Updates upd = updateMsg.getPcupdMessage().getUpdates().get(0);
         final long srpId2 = upd.getSrp().getOperationId().getValue();
         final Tlvs tlvs2 = createLspTlvs(upd.getLsp().getPlspId().getValue(), false,
-            newDestinationAddress, testAddress, testAddress, Optional.<byte[]>absent());
-        final Pcrpt pcRpt2 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(upd.getLsp()).setTlvs(tlvs2).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId2)), MsgBuilderUtil.createPath(upd.getPath().getEro().getSubobject()));
+            this.newDestinationAddress, this.testAddress, this.testAddress, Optional.absent());
+        final Pcrpt pcRpt2 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(upd.getLsp()).setTlvs(tlvs2)
+            .setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(),
+            Optional.of(MsgBuilderUtil.createSrp(srpId2)), MsgBuilderUtil.createPath(upd.getPath()
+                .getEro().getSubobject()));
         this.listener.onMessage(this.session, pcRpt2);
+
         //check updated lsp
-        topology = getTopology().get();
-        pcc = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        assertEquals(1, pcc.getReportedLsp().size());
-        reportedLsp = pcc.getReportedLsp().get(0);
-        assertEquals(TUNNEL_NAME, reportedLsp.getName());
-        assertEquals(1, reportedLsp.getPath().size());
-        path = reportedLsp.getPath().get(0);
-        assertEquals(2, path.getEro().getSubobject().size());
-        assertEquals(dstIpPrefix, getLastEroIpPrefix(path.getEro()));
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(1, pcc.getReportedLsp().size());
+            final ReportedLsp reportedLsp = pcc.getReportedLsp().get(0);
+            assertEquals(this.TUNNEL_NAME, reportedLsp.getName());
+            assertEquals(1, reportedLsp.getPath().size());
+            final Path path = reportedLsp.getPath().get(0);
+            assertEquals(2, path.getEro().getSubobject().size());
+            assertEquals(this.dstIpPrefix, getLastEroIpPrefix(path.getEro()));
+            return pcc;
+        });
+
         // check stats
         assertEquals(1, this.listener.getDelegatedLspsCount().intValue());
         assertTrue(this.listener.getSynchronized());
@@ -212,15 +225,21 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         assertTrue(this.listener.getPeerCapabilities().getStateful());
 
         // ensure-operational
-        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.ensure.lsp.operational.args.ArgumentsBuilder ensureArgs = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.ensure.lsp.operational.args.ArgumentsBuilder();
-        ensureArgs.addAugmentation(Arguments1.class, new Arguments1Builder().setOperational(OperationalStatus.Active).build());
-        final EnsureLspOperationalInput ensure = new EnsureLspOperationalInputBuilder().setArguments(ensureArgs.build()).setName(TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.ensure.lsp.
+            operational.args.ArgumentsBuilder ensureArgs = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.
+            xml.ns.yang.topology.pcep.rev131024.ensure.lsp.operational.args.ArgumentsBuilder();
+        ensureArgs.addAugmentation(Arguments1.class, new Arguments1Builder().setOperational(OperationalStatus.Active)
+            .build());
+        final EnsureLspOperationalInput ensure = new EnsureLspOperationalInputBuilder().setArguments(ensureArgs.build())
+            .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID))
+            .setNode(this.nodeId).build();
         final OperationResult result = this.topologyRpcs.ensureLspOperational(ensure).get().getResult();
         //check result
         assertNull(result.getFailure());
 
         // remove-lsp
-        final RemoveLspInput remove = new RemoveLspInputBuilder().setName(TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        final RemoveLspInput remove = new RemoveLspInputBuilder().setName(this.TUNNEL_NAME)
+            .setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build();
         this.topologyRpcs.removeLsp(remove);
         assertEquals(3, this.receivedMsgs.size());
         assertTrue(this.receivedMsgs.get(2) instanceof Pcinitiate);
@@ -228,13 +247,17 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         final Requests req2 = pcinitiate2.getPcinitiateMessage().getRequests().get(0);
         final long srpId3 = req2.getSrp().getOperationId().getValue();
         final Tlvs tlvs3 = createLspTlvs(req2.getLsp().getPlspId().getValue(), false,
-            testAddress, testAddress, testAddress, Optional.<byte[]>absent());
-        final Pcrpt pcRpt3 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req2.getLsp()).setTlvs(tlvs3).setRemove(true).setSync(true).setOperational(OperationalStatus.Down).build(), Optional.of(MsgBuilderUtil.createSrp(srpId3)), MsgBuilderUtil.createPath(Collections.<Subobject>emptyList()));
+            this.testAddress, this.testAddress, this.testAddress, Optional.absent());
+        final Pcrpt pcRpt3 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req2.getLsp()).setTlvs(tlvs3)
+            .setRemove(true).setSync(true).setOperational(OperationalStatus.Down).build(),
+            Optional.of(MsgBuilderUtil.createSrp(srpId3)), MsgBuilderUtil.createPath(Collections.emptyList()));
         this.listener.onMessage(this.session, pcRpt3);
+
         // check if lsp was removed
-        topology = getTopology().get();
-        pcc = topology.getNode().get(0).getAugmentation(Node1.class).getPathComputationClient();
-        assertEquals(0, pcc.getReportedLsp().size());
+        readData(getDataBroker(), this.pathComputationClientIId, pcc -> {
+            assertEquals(0, pcc.getReportedLsp().size());
+            return pcc;
+        });
         // check stats
         assertEquals(0, this.listener.getDelegatedLspsCount().intValue());
         assertTrue(this.listener.getSynchronized());
@@ -254,7 +277,7 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
 
     @Test
     public void testOnUnhandledErrorMessage() {
-        final Message errorMsg = AbstractMessageParser.createErrorMsg(PCEPErrors.NON_ZERO_PLSPID, Optional.<Rp>absent());
+        final Message errorMsg = AbstractMessageParser.createErrorMsg(PCEPErrors.NON_ZERO_PLSPID, Optional.absent());
         this.listener.onSessionUp(this.session);
         assertTrue(this.listener.onMessage(Optional.<AbstractTopologySessionListener.MessageContext>absent().orNull(), errorMsg));
     }
@@ -294,7 +317,8 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
      * @throws TransactionCommitFailedException
      */
     @Test
-    public void testOnServerSessionManagerDown() throws InterruptedException, ExecutionException, TransactionCommitFailedException {
+    public void testOnServerSessionManagerDown() throws InterruptedException, ExecutionException,
+        TransactionCommitFailedException {
         this.listener.onSessionUp(this.session);
         verify(this.listenerReg, times(0)).close();
         // send request
@@ -314,13 +338,14 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
      * @throws TransactionCommitFailedException
      */
     @Test
-    public void testOnServerSessionManagerUnstarted() throws InterruptedException, ExecutionException, TransactionCommitFailedException {
+    public void testOnServerSessionManagerUnstarted() throws InterruptedException, ExecutionException,
+        TransactionCommitFailedException, ReadFailedException {
         this.manager.close();
         // the registration should not be closed since it's never initialized
         verify(this.listenerReg, times(0)).close();
         this.listener.onSessionUp(this.session);
         // verify the session was NOT added to topology
-        assertFalse(getTopology().isPresent());
+        checkNull(getDataBroker(), TOPO_IID);
         // still, the session should not be registered and thus close() is never called
         verify(this.listenerReg, times(0)).close();
         // send request
@@ -331,7 +356,7 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
     }
 
     @Test
-    public void testOnSessionTermination() throws UnknownHostException, InterruptedException, ExecutionException {
+    public void testOnSessionTermination() throws Exception {
         this.listener.onSessionUp(this.session);
         verify(this.listenerReg, times(0)).close();
 
@@ -341,37 +366,53 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0);
         final long srpId = req.getSrp().getOperationId().getValue();
         final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true,
-            testAddress, testAddress, testAddress, Optional.<byte[]>absent());
-        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs).setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject()));
+            this.testAddress, this.testAddress, this.testAddress, Optional.absent());
+        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs).setSync(true)
+            .setRemove(false).setOperational(OperationalStatus.Active).build(),
+            Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject()));
         this.listener.onMessage(this.session, pcRpt);
-        assertEquals(1, getTopology().get().getNode().size());
+        readData(getDataBroker(), TOPO_IID, topology -> {
+            assertEquals(1, topology.getNode().size());
+            return topology;
+        });
 
         // node should be removed after termination
         this.listener.onSessionTerminated(this.session, new PCEPCloseTermination(TerminationReason.UNKNOWN));
         verify(this.listenerReg, times(1)).close();
-        assertEquals(0, getTopology().get().getNode().size());
+        checkNull(getDataBroker(), this.pathComputationClientIId);
     }
 
     @Test
     public void testUnknownLsp() throws Exception {
-        final List<Reports> reports = Lists.newArrayList(new ReportsBuilder().setPath(new PathBuilder().setEro(new EroBuilder().build()).build()).setLsp(
-                new LspBuilder().setPlspId(new PlspId(5L)).setSync(false).setRemove(false).setTlvs(
-                        new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().setLspIdentifiers(new LspIdentifiersBuilder().setLspId(new LspId(1L)).build()).setSymbolicPathName(
-                                new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(new byte[] { 22, 34 })).build()).build()).build()).build());
-        final Pcrpt rptmsg = new PcrptBuilder().setPcrptMessage(new PcrptMessageBuilder().setReports(reports).build()).build();
+        final List<Reports> reports = Lists.newArrayList(new ReportsBuilder().setPath(new PathBuilder()
+            .setEro(new EroBuilder().build()).build()).setLsp(new LspBuilder().setPlspId(new PlspId(5L))
+            .setSync(false).setRemove(false).setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.
+                yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().setLspIdentifiers(
+                    new LspIdentifiersBuilder().setLspId(new LspId(1L)).build()).setSymbolicPathName(
+                        new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(new byte[] { 22, 34 }))
+                            .build()).build()).build()).build());
+        final Pcrpt rptmsg = new PcrptBuilder().setPcrptMessage(new PcrptMessageBuilder().setReports(reports).build())
+            .build();
         this.listener.onSessionUp(this.session);
         this.listener.onMessage(this.session, rptmsg);
-        final Topology topology = getTopology().get();
-        assertFalse(topology.getNode().isEmpty());
+        readData(getDataBroker(), TOPO_IID, node -> {
+            assertFalse(node.getNode().isEmpty());
+            return node;
+        });
     }
 
     @Test
     public void testUpdateUnknownLsp() throws InterruptedException, ExecutionException {
         this.listener.onSessionUp(this.session);
-        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder();
-        updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(eroIpPrefix, dstIpPrefix)));
-        updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder().setDelegate(true).setAdministrative(true).build()).build());
-        final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build()).setName(TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args
+            .ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.
+            topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder();
+        updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix, this.dstIpPrefix)));
+        updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder()
+            .setDelegate(true).setAdministrative(true).build()).build());
+        final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build())
+            .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId)
+            .build();
         final UpdateLspOutput result = this.topologyRpcs.updateLsp(update).get().getResult();
         assertEquals(FailureType.Unsent, result.getFailure());
         assertEquals(1, result.getError().size());
@@ -383,7 +424,8 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
     @Test
     public void testRemoveUnknownLsp() throws InterruptedException, ExecutionException {
         this.listener.onSessionUp(this.session);
-        final RemoveLspInput remove = new RemoveLspInputBuilder().setName(TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        final RemoveLspInput remove = new RemoveLspInputBuilder().setName(this.TUNNEL_NAME).setNetworkTopologyRef(
+            new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build();
         final OperationResult result = this.topologyRpcs.removeLsp(remove).get().getResult();
         assertEquals(FailureType.Unsent, result.getFailure());
         assertEquals(1, result.getError().size());
@@ -402,8 +444,11 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0);
         final long srpId = req.getSrp().getOperationId().getValue();
         final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true,
-            testAddress, testAddress, testAddress, Optional.<byte[]>absent());
-        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs).setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject()));
+            this.testAddress, this.testAddress, this.testAddress, Optional.absent());
+        final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs)
+            .setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active)
+            .build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro()
+            .getSubobject()));
         this.listener.onMessage(this.session, pcRpt);
 
         //try to add already existing LSP
@@ -412,30 +457,37 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
         assertEquals(1, result.getError().size());
         final ErrorObject errorObject = result.getError().get(0).getErrorObject();
         assertNotNull(errorObject);
-        assertEquals(PCEPErrors.USED_SYMBOLIC_PATH_NAME, PCEPErrors.forValue(errorObject.getType(), errorObject.getValue()));
+        assertEquals(PCEPErrors.USED_SYMBOLIC_PATH_NAME, PCEPErrors.forValue(errorObject.getType(),
+            errorObject.getValue()));
     }
 
     @Test
-    public void testPccResponseTimeout() throws InterruptedException, ExecutionException {
+    public void testPccResponseTimeout() throws Exception {
         this.listener.onSessionUp(this.session);
-        Future<RpcResult<AddLspOutput>> addLspResult = this.topologyRpcs.addLsp(createAddLspInput());
+        final Future<RpcResult<AddLspOutput>> addLspResult = this.topologyRpcs.addLsp(createAddLspInput());
         try {
             addLspResult.get(2, TimeUnit.SECONDS);
             fail();
-        } catch (Exception e) {
+        } catch (final Exception e) {
             assertTrue(e instanceof TimeoutException);
         }
         Thread.sleep(AbstractPCEPSessionTest.RPC_TIMEOUT);
-        RpcResult<AddLspOutput> rpcResult = addLspResult.get();
-        assertNotNull(rpcResult);
-        assertEquals(rpcResult.getResult().getFailure(), FailureType.Unsent);
+        CheckUtil.checkEquals(()-> {
+            final RpcResult<AddLspOutput> rpcResult = addLspResult.get();
+            assertNotNull(rpcResult);
+            assertEquals(rpcResult.getResult().getFailure(), FailureType.Unsent);
+        });
     }
 
     @Override
     protected Open getLocalPref() {
-        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class, new Tlvs1Builder().setStateful(new StatefulBuilder()
+        return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class,
+            new Tlvs1Builder().setStateful(new StatefulBuilder()
             .addAugmentation(Stateful1.class, new Stateful1Builder().setInitiation(Boolean.TRUE).build())
-            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder().setTriggeredInitialSync(Boolean.TRUE).build())
+            .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync.
+                optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.
+                ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder()
+                .setTriggeredInitialSync(Boolean.TRUE).build())
             .build()).build()).build()).build();
     }
 
@@ -447,10 +499,13 @@ public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTe
     private AddLspInput createAddLspInput() {
         final ArgumentsBuilder argsBuilder = new ArgumentsBuilder();
         final Ipv4CaseBuilder ipv4Builder = new Ipv4CaseBuilder();
-        ipv4Builder.setIpv4(new Ipv4Builder().setSourceIpv4Address(new Ipv4Address(testAddress)).setDestinationIpv4Address(new Ipv4Address(testAddress)).build());
+        ipv4Builder.setIpv4(new Ipv4Builder().setSourceIpv4Address(new Ipv4Address(this.testAddress))
+            .setDestinationIpv4Address(new Ipv4Address(this.testAddress)).build());
         argsBuilder.setEndpointsObj(new EndpointsObjBuilder().setAddressFamily(ipv4Builder.build()).build());
-        argsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(eroIpPrefix)));
-        argsBuilder.addAugmentation(Arguments2.class, new Arguments2Builder().setLsp(new LspBuilder().setDelegate(true).setAdministrative(true).build()).build());
-        return new AddLspInputBuilder().setName(TUNNEL_NAME).setArguments(argsBuilder.build()).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(nodeId).build();
+        argsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix)));
+        argsBuilder.addAugmentation(Arguments2.class, new Arguments2Builder().setLsp(new LspBuilder()
+            .setDelegate(true).setAdministrative(true).build()).build());
+        return new AddLspInputBuilder().setName(this.TUNNEL_NAME).setArguments(argsBuilder.build())
+            .setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build();
     }
 }
index 105e1dab871f573d00a6beab72653069b81780ae..6617781a6f56d42b2a5f8413f6b7f8e7d40e9b77 100644 (file)
@@ -41,77 +41,77 @@ public class SyncOptimizationTest {
 
     @Test
     public void testDoesLspDbMatchPositive() {
-        final Tlvs tlvs = createTlvs(1l, false, false);
-        Mockito.doReturn(tlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(tlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs tlvs = createTlvs(1L, false, false);
+        Mockito.doReturn(tlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(tlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertTrue(syncOpt.doesLspDbMatch());
     }
 
     @Test
     public void testDoesLspDbMatchNegative() {
-        final Tlvs localTlvs = createTlvs(1l, false, false);
-        final Tlvs remoteTlvs = createTlvs(2l, false, false);
-        Mockito.doReturn(localTlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(remoteTlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs localTlvs = createTlvs(1L, false, false);
+        final Tlvs remoteTlvs = createTlvs(2L, false, false);
+        Mockito.doReturn(localTlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(remoteTlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertFalse(syncOpt.doesLspDbMatch());
     }
 
     @Test
     public void testIsSyncAvoidanceEnabledPositive() {
-        final Tlvs tlvs = createTlvs(1l, true, false);
-        Mockito.doReturn(tlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(tlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs tlvs = createTlvs(1L, true, false);
+        Mockito.doReturn(tlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(tlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertTrue(syncOpt.isSyncAvoidanceEnabled());
     }
 
     @Test
     public void testIsSyncAvoidanceEnabledNegative() {
-        final Tlvs localTlvs = createTlvs(1l, true, false);
-        final Tlvs remoteTlvs = createTlvs(2l, false, false);
-        Mockito.doReturn(localTlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(remoteTlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs localTlvs = createTlvs(1L, true, false);
+        final Tlvs remoteTlvs = createTlvs(2L, false, false);
+        Mockito.doReturn(localTlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(remoteTlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertFalse(syncOpt.isSyncAvoidanceEnabled());
     }
 
     @Test
     public void testIsDeltaSyncEnabledPositive() {
-        final Tlvs tlvs = createTlvs(1l, true, true);
-        Mockito.doReturn(tlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(tlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs tlvs = createTlvs(1L, true, true);
+        Mockito.doReturn(tlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(tlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertTrue(syncOpt.isDeltaSyncEnabled());
     }
 
     @Test
     public void testIsDeltaSyncEnabledNegative() {
-        final Tlvs localTlvs = createTlvs(1l, true, true);
-        final Tlvs remoteTlvs = createTlvs(2l, false, false);
-        Mockito.doReturn(localTlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(remoteTlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs localTlvs = createTlvs(1L, true, true);
+        final Tlvs remoteTlvs = createTlvs(2L, false, false);
+        Mockito.doReturn(localTlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(remoteTlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertFalse(syncOpt.isDeltaSyncEnabled());
     }
 
     @Test
     public void testIsDbVersionPresentPositive() {
         final Tlvs localTlvs = createTlvs(null, false, false);
-        final Tlvs remoteTlvs = createTlvs(2l, false, false);
-        Mockito.doReturn(localTlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(remoteTlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        final Tlvs remoteTlvs = createTlvs(2L, false, false);
+        Mockito.doReturn(localTlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(remoteTlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertTrue(syncOpt.isDbVersionPresent());
     }
 
     @Test
     public void testIsDbVersionPresentNegative() {
         final Tlvs tlvs = createTlvs(null, true, false);
-        Mockito.doReturn(tlvs).when(pcepSession).localSessionCharacteristics();
-        Mockito.doReturn(tlvs).when(pcepSession).getRemoteTlvs();
-        final SyncOptimization syncOpt = new SyncOptimization(pcepSession);
+        Mockito.doReturn(tlvs).when(this.pcepSession).localSessionCharacteristics();
+        Mockito.doReturn(tlvs).when(this.pcepSession).getRemoteTlvs();
+        final SyncOptimization syncOpt = new SyncOptimization(this.pcepSession);
         assertFalse(syncOpt.isDbVersionPresent());
     }
 
@@ -124,5 +124,4 @@ public class SyncOptimizationTest {
             .addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(
                 new LspDbVersionBuilder().setLspDbVersionValue(lspDbVersion != null ? BigInteger.valueOf(lspDbVersion) : null).build()).build()).build();
     }
-
 }
index 93cd460edab4ae11a55ed1696f3d76487584365a..4c7af1a3440a1a643efac394f844d2ad661c99f8 100644 (file)
@@ -10,14 +10,11 @@ package org.opendaylight.bgpcep.pcep.topology.provider;
 import com.google.common.util.concurrent.ListenableFuture;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Executor;
-import java.util.concurrent.Future;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 import org.opendaylight.bgpcep.pcep.topology.provider.TopologyProgrammingTest.MockedTopologySessionListenerFactory;
 import org.opendaylight.bgpcep.programming.spi.Instruction;
 import org.opendaylight.bgpcep.programming.spi.InstructionScheduler;
@@ -83,161 +80,126 @@ public class TopologyProgrammingTest extends AbstractPCEPSessionTest<MockedTopol
 
     private TopologyProgramming topologyProgramming;
 
-    private PCEPSession session;
-
     @Override
     @Before
     public void setUp() throws Exception {
         super.setUp();
         Mockito.doReturn(true).when(this.instruction).checkedExecutionStart();
         Mockito.doNothing().when(this.instruction).executionCompleted(InstructionStatus.Failed, null);
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.instructionFuture).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.futureAddLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.futureUpdateLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.futureRemoveLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.futureTriggerSyncOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Runnable callback = (Runnable) invocation.getArguments()[0];
-                callback.run();
-                return null;
-            }
+        Mockito.doAnswer(invocation -> {
+            final Runnable callback = (Runnable) invocation.getArguments()[0];
+            callback.run();
+            return null;
         }).when(this.futureEnsureLspOutput).addListener(Mockito.any(Runnable.class), Mockito.any(Executor.class));
-        Mockito.doAnswer(new Answer<Future<RpcResult<AddLspOutput>>>() {
-            @Override
-            public Future<RpcResult<AddLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
-                TopologyProgrammingTest.this.addLspArgs = (AddLspArgs) invocation.getArguments()[0];
-                return TopologyProgrammingTest.this.futureAddLspOutput;
-            }
+        Mockito.doAnswer(invocation -> {
+            TopologyProgrammingTest.this.addLspArgs = (AddLspArgs) invocation.getArguments()[0];
+            return TopologyProgrammingTest.this.futureAddLspOutput;
         }).when(listener).addLsp(Mockito.any(AddLspInput.class));
-        Mockito.doAnswer(new Answer<Future<RpcResult<UpdateLspOutput>>>() {
-            @Override
-            public Future<RpcResult<UpdateLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
-                TopologyProgrammingTest.this.updateLspArgs = (UpdateLspArgs) invocation.getArguments()[0];
-                return TopologyProgrammingTest.this.futureUpdateLspOutput;
-            }
+        Mockito.doAnswer(invocation -> {
+            TopologyProgrammingTest.this.updateLspArgs = (UpdateLspArgs) invocation.getArguments()[0];
+            return TopologyProgrammingTest.this.futureUpdateLspOutput;
         }).when(listener).updateLsp(Mockito.any(UpdateLspInput.class));
-        Mockito.doAnswer(new Answer<Future<RpcResult<RemoveLspOutput>>>() {
-            @Override
-            public Future<RpcResult<RemoveLspOutput>> answer(final InvocationOnMock invocation) throws Throwable {
-                TopologyProgrammingTest.this.removeLspArgs = (RemoveLspArgs) invocation.getArguments()[0];
-                return TopologyProgrammingTest.this.futureRemoveLspOutput;
-            }
+        Mockito.doAnswer(invocation -> {
+            TopologyProgrammingTest.this.removeLspArgs = (RemoveLspArgs) invocation.getArguments()[0];
+            return TopologyProgrammingTest.this.futureRemoveLspOutput;
         }).when(listener).removeLsp(Mockito.any(RemoveLspInput.class));
-        Mockito.doAnswer(new Answer<Future<RpcResult<TriggerSyncOutput>>>() {
-            @Override
-            public Future<RpcResult<TriggerSyncOutput>> answer(final InvocationOnMock invocation) throws Throwable {
-                TopologyProgrammingTest.this.triggerSyncArgs = (TriggerSyncArgs) invocation.getArguments()[0];
-                return TopologyProgrammingTest.this.futureTriggerSyncOutput;
-            }
+        Mockito.doAnswer(invocation -> {
+            TopologyProgrammingTest.this.triggerSyncArgs = (TriggerSyncArgs) invocation.getArguments()[0];
+            return TopologyProgrammingTest.this.futureTriggerSyncOutput;
         }).when(listener).triggerSync(Mockito.any(TriggerSyncInput.class));
-        Mockito.doAnswer(new Answer<Future<RpcResult<EnsureLspOperationalOutput>>>() {
-            @Override
-            public Future<RpcResult<EnsureLspOperationalOutput>> answer(final InvocationOnMock invocation) throws Throwable {
-                TopologyProgrammingTest.this.ensureLspInput = (EnsureLspOperationalInput) invocation.getArguments()[0];
-                return TopologyProgrammingTest.this.futureEnsureLspOutput;
-            }
+        Mockito.doAnswer(invocation -> {
+            TopologyProgrammingTest.this.ensureLspInput = (EnsureLspOperationalInput) invocation.getArguments()[0];
+            return TopologyProgrammingTest.this.futureEnsureLspOutput;
         }).when(listener).ensureLspOperational(Mockito.any(EnsureLspOperationalInput.class));
         Mockito.doNothing().when(listener).close();
-        Mockito.doReturn(instruction).when(this.instructionFuture).get();
+        Mockito.doReturn(this.instruction).when(this.instructionFuture).get();
         Mockito.doNothing().when(this.instruction).executionCompleted(Mockito.any(InstructionStatus.class), Mockito.any(Details.class));
         Mockito.doReturn(this.instructionFuture).when(this.scheduler).scheduleInstruction(Mockito.any(SubmitInstructionInput.class));
         this.topologyProgramming = new TopologyProgramming(this.scheduler, this.manager);
-        this.session = getPCEPSession(getLocalPref(), getRemotePref());
-        listener.onSessionUp(this.session);
+        final PCEPSession session = getPCEPSession(getLocalPref(), getRemotePref());
+        listener.onSessionUp(session);
     }
 
     @Test
     public void testSubmitAddLsp() throws InterruptedException, ExecutionException {
         final SubmitAddLspInputBuilder inputBuilder = new SubmitAddLspInputBuilder();
         inputBuilder.setName(NAME);
-        inputBuilder.setNode(nodeId);
+        inputBuilder.setNode(this.nodeId);
         inputBuilder.setArguments(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.add.lsp.args.ArgumentsBuilder().build());
         this.topologyProgramming.submitAddLsp(inputBuilder.build());
         Assert.assertNotNull(this.addLspArgs);
         Assert.assertEquals(NAME, this.addLspArgs.getName());
-        Assert.assertEquals(nodeId, this.addLspArgs.getNode());
+        Assert.assertEquals(this.nodeId, this.addLspArgs.getNode());
     }
 
     @Test
     public void testSubmitUpdateLsp() {
         final SubmitUpdateLspInputBuilder inputBuilder = new SubmitUpdateLspInputBuilder();
         inputBuilder.setName(NAME);
-        inputBuilder.setNode(nodeId);
+        inputBuilder.setNode(this.nodeId);
         this.topologyProgramming.submitUpdateLsp(inputBuilder.build());
         Assert.assertNotNull(this.updateLspArgs);
         Assert.assertEquals(NAME, this.updateLspArgs.getName());
-        Assert.assertEquals(nodeId, this.updateLspArgs.getNode());
+        Assert.assertEquals(this.nodeId, this.updateLspArgs.getNode());
     }
 
     @Test
     public void testSubmitEnsureLsp() {
         final SubmitEnsureLspOperationalInputBuilder inputBuilder = new SubmitEnsureLspOperationalInputBuilder();
         inputBuilder.setName(NAME);
-        inputBuilder.setNode(nodeId);
+        inputBuilder.setNode(this.nodeId);
         inputBuilder.setArguments(new ArgumentsBuilder().build());
         this.topologyProgramming.submitEnsureLspOperational(inputBuilder.build());
         Assert.assertNotNull(this.ensureLspInput);
         Assert.assertEquals(NAME, this.ensureLspInput.getName());
-        Assert.assertEquals(nodeId, this.ensureLspInput.getNode());
+        Assert.assertEquals(this.nodeId, this.ensureLspInput.getNode());
     }
 
     @Test
     public void testSubmitRemoveLsp() {
         final SubmitRemoveLspInputBuilder inputBuilder = new SubmitRemoveLspInputBuilder();
         inputBuilder.setName(NAME);
-        inputBuilder.setNode(nodeId);
+        inputBuilder.setNode(this.nodeId);
         this.topologyProgramming.submitRemoveLsp(inputBuilder.build());
         Assert.assertNotNull(this.removeLspArgs);
         Assert.assertEquals(NAME, this.removeLspArgs.getName());
-        Assert.assertEquals(nodeId, this.removeLspArgs.getNode());
+        Assert.assertEquals(this.nodeId, this.removeLspArgs.getNode());
     }
 
     @Test
     public void testSubmitTriggerSync() {
         final SubmitTriggerSyncInputBuilder inputBuilder = new SubmitTriggerSyncInputBuilder();
         inputBuilder.setName(NAME);
-        inputBuilder.setNode(nodeId);
+        inputBuilder.setNode(this.nodeId);
         this.topologyProgramming.submitTriggerSync(inputBuilder.build());
         Assert.assertNotNull(this.triggerSyncArgs);
         Assert.assertEquals(NAME, this.triggerSyncArgs.getName());
-        Assert.assertEquals(nodeId, this.triggerSyncArgs.getNode());
+        Assert.assertEquals(this.nodeId, this.triggerSyncArgs.getNode());
     }
 
     protected static final class MockedTopologySessionListenerFactory implements TopologySessionListenerFactory {
index 486614ba9b3991996c40a2bcff6ac56477aa9e7a..13b7b59139b86ca83c2ad57dcf0a025c2fbac786 100644 (file)
             <version>${project.version}</version>
             <scope>test</scope>
         </dependency>
-
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>testtool-util</artifactId>
+            <scope>test</scope>
+        </dependency>
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
index a12f9db32853de6cf73f2d24d5dd98904aa8bdbb..37da9b056e9efb3c67809b52cb96fb8473eb84d4 100644 (file)
@@ -12,12 +12,11 @@ import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.opendaylight.protocol.util.CheckUtil.checkEquals;
 
 import com.google.common.collect.Lists;
 import java.util.List;
 import org.junit.Assert;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.InstructionStatus;
@@ -34,20 +33,17 @@ final class MockedNotificationServiceWrapper {
     NotificationProviderService getMockedNotificationService() {
         final NotificationProviderService mockedNotificationService = mock(NotificationProviderService.class);
 
-        doAnswer(new Answer<Void>() {
-            @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
-                final Object notif = invocation.getArguments()[0];
-                assertTrue(Notification.class.isAssignableFrom(notif.getClass()));
-                MockedNotificationServiceWrapper.this.publishedNotifications.add((Notification) notif);
-                return null;
-            }
+        doAnswer(invocation -> {
+            final Object notif = invocation.getArguments()[0];
+            assertTrue(Notification.class.isAssignableFrom(notif.getClass()));
+            MockedNotificationServiceWrapper.this.publishedNotifications.add((Notification) notif);
+            return null;
         }).when(mockedNotificationService).publish(any(Notification.class));
         return mockedNotificationService;
     }
 
-    void assertNotificationsCount(final int count) {
-        assertEquals(count, this.publishedNotifications.size());
+    void assertNotificationsCount(final int count) throws Exception {
+        checkEquals(()-> assertEquals(count, this.publishedNotifications.size()));
     }
 
     public void assertInstructionStatusChangedNotification(final int idx, final InstructionId id, final InstructionStatus status) {
index ea44f7419e60335e199cd281a44b5e1b90efe215..f93067d9d8e21b6eabb8651c7e696f62e68434bf 100644 (file)
@@ -9,14 +9,14 @@ package org.opendaylight.bgpcep.programming.impl;
 
 import static org.hamcrest.CoreMatchers.containsString;
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
+import static org.opendaylight.protocol.util.CheckUtil.checkPresent;
+import static org.opendaylight.protocol.util.CheckUtil.checkNull;
 
-import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
 import com.google.common.util.concurrent.ListenableFuture;
 import io.netty.util.HashedWheelTimer;
@@ -24,7 +24,7 @@ import io.netty.util.Timer;
 import java.io.IOException;
 import java.math.BigInteger;
 import java.util.List;
-import java.util.concurrent.ExecutionException;
+import java.util.Optional;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -32,7 +32,6 @@ import org.opendaylight.bgpcep.programming.NanotimeUtil;
 import org.opendaylight.bgpcep.programming.spi.Instruction;
 import org.opendaylight.bgpcep.programming.spi.SchedulerException;
 import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CancelInstructionInputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.CleanInstructionsInput;
@@ -49,13 +48,14 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programm
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.status.changed.DetailsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.tunnel.pcep.programming.rev131030.PcepUpdateTunnelInput;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
 
 public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
 
-    public static final int INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS = 3;
-    private static final InstructionsQueueKey INSTRUCTIONS_QUEUE_KEY = new InstructionsQueueKey("test-instraction-queue");
+    private static final int INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS = 3;
+    private static final String INSTRUCTIONS_QUEUE_KEY = "test-instraction-queue";
 
     private MockedExecutorWrapper mockedExecutorWrapper;
     private MockedNotificationServiceWrapper mockedNotificationServiceWrapper;
@@ -64,12 +64,13 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
 
     @Before
     public void setUp() throws IOException, YangSyntaxErrorException {
-        mockedExecutorWrapper = new MockedExecutorWrapper();
-        mockedNotificationServiceWrapper = new MockedNotificationServiceWrapper();
+        this.mockedExecutorWrapper = new MockedExecutorWrapper();
+        this.mockedNotificationServiceWrapper = new MockedNotificationServiceWrapper();
 
-        testedProgrammingService = new ProgrammingServiceImpl(getDataBroker(),
-                mockedNotificationServiceWrapper.getMockedNotificationService(),
-                mockedExecutorWrapper.getMockedExecutor(), timer, INSTRUCTIONS_QUEUE_KEY);
+        this.testedProgrammingService = new ProgrammingServiceImpl(getDataBroker(),
+            this.mockedNotificationServiceWrapper.getMockedNotificationService(),
+            this.mockedExecutorWrapper.getMockedExecutor(), this.timer,
+            new InstructionsQueueKey(INSTRUCTIONS_QUEUE_KEY));
     }
 
     @After
@@ -79,37 +80,40 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
     @Test
     public void testScheduleInstruction() throws Exception {
         final SubmitInstructionInput mockedSubmit = getMockedSubmitInstructionInput("mockedSubmit");
-        testedProgrammingService.scheduleInstruction(mockedSubmit);
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit);
 
-        assertTrue(assertInstructionExists(mockedSubmit.getId()));
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit.getId()));
 
         // assert Schedule to executor
-        mockedExecutorWrapper.assertSubmittedTasksSize(1);
+        this.mockedExecutorWrapper.assertSubmittedTasksSize(1);
 
         // assert Notification
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(0, mockedSubmit.getId(), InstructionStatus.Scheduled);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(0, mockedSubmit.getId(),
+            InstructionStatus.Scheduled);
     }
 
     @Test
     public void testScheduleDependingInstruction() throws Exception {
-        testedProgrammingService.scheduleInstruction(getMockedSubmitInstructionInput("mockedSubmit1"));
-        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        this.testedProgrammingService.scheduleInstruction(getMockedSubmitInstructionInput("mockedSubmit1"));
+        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2",
+            "mockedSubmit1");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
 
-        mockedExecutorWrapper.assertSubmittedTasksSize(2);
+        this.mockedExecutorWrapper.assertSubmittedTasksSize(2);
 
         // First is in state scheduled, so second could not be scheduled yet
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
     }
 
     @Test
     public void testScheduleDependingInstructionToFail() throws Exception {
         try {
-            testedProgrammingService.scheduleInstruction(getMockedSubmitInstructionInput("mockedSubmit", "dep1"));
+            this.testedProgrammingService.scheduleInstruction(getMockedSubmitInstructionInput("mockedSubmit",
+                "dep1"));
         } catch (final SchedulerException e) {
             assertThat(e.getMessage(), containsString("Unknown dependency ID"));
-            mockedNotificationServiceWrapper.assertNotificationsCount(0);
+            this.mockedNotificationServiceWrapper.assertNotificationsCount(0);
             return;
         }
         fail("Instruction schedule should fail on unresolved dependencies");
@@ -118,69 +122,77 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
     @Test
     public void testCancelInstruction() throws Exception {
         final SubmitInstructionInput mockedSubmit = getMockedSubmitInstructionInput("mockedSubmit");
-        testedProgrammingService.scheduleInstruction(mockedSubmit);
-
-        assertTrue(assertInstructionExists(mockedSubmit.getId()));
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit);
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit.getId()));
 
         final CancelInstructionInput mockedCancel = getCancelInstruction("mockedSubmit");
-        testedProgrammingService.cancelInstruction(mockedCancel);
+        this.testedProgrammingService.cancelInstruction(mockedCancel);
 
-        assertTrue(assertInstructionExists(mockedSubmit.getId()));
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit.getId()));
+        this.mockedExecutorWrapper.assertSubmittedTasksSize(2);
 
-        mockedExecutorWrapper.assertSubmittedTasksSize(2);
-
-        mockedNotificationServiceWrapper.assertNotificationsCount(2);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit.getId(), InstructionStatus.Cancelled);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(2);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit.getId(),
+            InstructionStatus.Cancelled);
     }
 
     @Test
     public void testCancelDependantInstruction() throws Exception {
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit1);
-        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit2);
-        final SubmitInstructionInput mockedSubmit3 = getMockedSubmitInstructionInput("mockedSubmit3", "mockedSubmit1", "mockedSubmit2");
-        testedProgrammingService.scheduleInstruction(mockedSubmit3);
-
-        testedProgrammingService.cancelInstruction(getCancelInstruction("mockedSubmit1"));
-
-        mockedNotificationServiceWrapper.assertNotificationsCount(1 /*First Scheduled*/+ 3 /*First and all dependencies cancelled*/);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(0, mockedSubmit1.getId(), InstructionStatus.Scheduled);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(), InstructionStatus.Cancelled);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit2.getId(), InstructionStatus.Cancelled);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit3.getId(), InstructionStatus.Cancelled);
-
-        assertTrue(assertInstructionExists(mockedSubmit1.getId()));
-        assertTrue(assertInstructionExists(mockedSubmit2.getId()));
-        assertTrue(assertInstructionExists(mockedSubmit3.getId()));
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2",
+            "mockedSubmit1");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        final SubmitInstructionInput mockedSubmit3 = getMockedSubmitInstructionInput("mockedSubmit3",
+            "mockedSubmit1", "mockedSubmit2");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit3);
+
+        this.testedProgrammingService.cancelInstruction(getCancelInstruction("mockedSubmit1"));
+
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1 /*First Scheduled*/+ 3 /*First and all dependencies cancelled*/);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(0, mockedSubmit1.getId(),
+            InstructionStatus.Scheduled);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(),
+            InstructionStatus.Cancelled);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit2.getId(),
+            InstructionStatus.Cancelled);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit3.getId(),
+            InstructionStatus.Cancelled);
+
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit1.getId()));
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit2.getId()));
+        checkPresent(getDataBroker(), buildInstructionIID(mockedSubmit3.getId()));
     }
 
     @Test
     public void testCleanInstructions() throws Exception {
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit1);
-        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2",
+            "mockedSubmit1");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
 
         final CleanInstructionsInputBuilder cleanInstructionsInputBuilder = new CleanInstructionsInputBuilder();
         final CleanInstructionsInput cleanInstructionsInput = cleanInstructionsInputBuilder.setId(
                 Lists.newArrayList(mockedSubmit1.getId(), mockedSubmit2.getId())).build();
 
-        ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanedInstructionOutput = testedProgrammingService.cleanInstructions(cleanInstructionsInput);
+        ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanedInstructionOutput = this.testedProgrammingService
+            .cleanInstructions(cleanInstructionsInput);
 
         assertCleanInstructionOutput(cleanedInstructionOutput, 2);
 
-        testedProgrammingService.cancelInstruction(getCancelInstruction("mockedSubmit1"));
+        this.testedProgrammingService.cancelInstruction(getCancelInstruction("mockedSubmit1"));
 
-        cleanedInstructionOutput = testedProgrammingService.cleanInstructions(cleanInstructionsInput);
+        cleanedInstructionOutput = this.testedProgrammingService.cleanInstructions(cleanInstructionsInput);
         assertCleanInstructionOutput(cleanedInstructionOutput, 0);
 
-        assertFalse(assertInstructionExists(mockedSubmit1.getId()));
-        assertFalse(assertInstructionExists(mockedSubmit2.getId()));
+        checkNull(getDataBroker(), buildInstructionIID(mockedSubmit1.getId()));
+        checkNull(getDataBroker(), buildInstructionIID(mockedSubmit2.getId()));
     }
 
-    private void assertCleanInstructionOutput(final ListenableFuture<RpcResult<CleanInstructionsOutput>> cleanedInstructionOutput,
-            final int unflushedCount) throws InterruptedException, java.util.concurrent.ExecutionException {
+    private void assertCleanInstructionOutput(final ListenableFuture<RpcResult<CleanInstructionsOutput>>
+        cleanedInstructionOutput, final int unflushedCount) throws InterruptedException,
+        java.util.concurrent.ExecutionException {
         if (unflushedCount == 0) {
             final List<InstructionId> unflushed = cleanedInstructionOutput.get().getResult().getUnflushed();
             assertTrue(unflushed == null || unflushed.isEmpty());
@@ -193,83 +205,89 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
     @Test
     public void testCloseProgrammingService() throws Exception {
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit1);
-        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2",
+            "mockedSubmit1");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
 
-        testedProgrammingService.close();
+        this.testedProgrammingService.close();
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(1/* First scheduled */+ 2/* Both cancelled at close */);
+        this.mockedNotificationServiceWrapper
+            .assertNotificationsCount(1/* First scheduled */+ 2/* Both cancelled at close */);
     }
 
     @Test(timeout = 30 * 1000)
     public void testTimeoutWhileScheduledTransaction() throws Exception {
-        final BigInteger deadlineOffset = BigInteger.valueOf(1000l * 1000 * 1000 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
+        final BigInteger deadlineOffset = BigInteger.valueOf(1000L * 1000 * 1000 *
+            INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
         final Nanotime current = NanotimeUtil.currentTime();
         final Nanotime deadlineNano = new Nanotime(current.getValue().add(deadlineOffset));
 
         final Optional<Nanotime> deadline = Optional.of(deadlineNano);
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1", deadline);
-        final ListenableFuture<Instruction> future = testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final ListenableFuture<Instruction> future = this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
 
         future.get();
 
-        Thread.sleep(2 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS * 1000);
-
-        mockedNotificationServiceWrapper.assertNotificationsCount(2);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(), InstructionStatus.Cancelled);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(2);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(),
+            InstructionStatus.Cancelled);
     }
 
     @Test(timeout = 30 * 1000)
     public void testTimeoutWhileSuccessfulTransaction() throws Exception {
-        final BigInteger deadlineOffset = BigInteger.valueOf(1000l * 1000 * 1000 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
+        final BigInteger deadlineOffset = BigInteger.valueOf(1000L * 1000 * 1000 *
+            INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
         final Nanotime current = NanotimeUtil.currentTime();
         final Nanotime deadlineNano = new Nanotime(current.getValue().add(deadlineOffset));
 
         final Optional<Nanotime> deadline = Optional.of(deadlineNano);
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1", deadline);
-        final ListenableFuture<Instruction> future = testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final ListenableFuture<Instruction> future = this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
 
         final Instruction i = future.get();
         i.checkedExecutionStart();
         i.executionCompleted(InstructionStatus.Successful, getDetails());
 
-        Thread.sleep(2 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS * 1000);
-
-        mockedNotificationServiceWrapper.assertNotificationsCount(3);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(), InstructionStatus.Executing);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(), InstructionStatus.Successful);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(3);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(),
+            InstructionStatus.Executing);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(),
+            InstructionStatus.Successful);
         // Timeout in success should not do anything
     }
 
     @Test(timeout = 30 * 1000)
     public void testTimeoutWhileExecutingWithDependenciesTransaction() throws Exception {
-        final BigInteger deadlineOffset = BigInteger.valueOf(1000l * 1000 * 1000 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
+        final BigInteger deadlineOffset = BigInteger.valueOf(1000L * 1000 * 1000 *
+            INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS /* seconds */);
         final Nanotime current = NanotimeUtil.currentTime();
         final Nanotime deadlineNano = new Nanotime(current.getValue().add(deadlineOffset));
 
         final Optional<Nanotime> deadline = Optional.of(deadlineNano);
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1", deadline);
-        final ListenableFuture<Instruction> future = testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final ListenableFuture<Instruction> future = this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
 
-        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2",
+            "mockedSubmit1");
+        this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
 
         final Instruction i = future.get();
         i.checkedExecutionStart();
 
-        Thread.sleep(2 * INSTRUCTION_DEADLINE_OFFSET_IN_SECONDS * 1000);
-
-        mockedNotificationServiceWrapper.assertNotificationsCount(4);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(), InstructionStatus.Executing);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(), InstructionStatus.Unknown);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit2.getId(), InstructionStatus.Cancelled);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(4);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(),
+            InstructionStatus.Executing);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(),
+            InstructionStatus.Unknown);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit2.getId(),
+            InstructionStatus.Cancelled);
     }
 
     // TODO test deadline with state Queued
@@ -277,29 +295,34 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
     @Test
     public void testSuccessExecutingWithDependenciesTransaction() throws Exception {
         final SubmitInstructionInput mockedSubmit1 = getMockedSubmitInstructionInput("mockedSubmit1");
-        final ListenableFuture<Instruction> future = testedProgrammingService.scheduleInstruction(mockedSubmit1);
+        final ListenableFuture<Instruction> future = this.testedProgrammingService.scheduleInstruction(mockedSubmit1);
 
         final SubmitInstructionInput mockedSubmit2 = getMockedSubmitInstructionInput("mockedSubmit2", "mockedSubmit1");
-        final ListenableFuture<Instruction> future2 = testedProgrammingService.scheduleInstruction(mockedSubmit2);
+        final ListenableFuture<Instruction> future2 = this.testedProgrammingService.scheduleInstruction(mockedSubmit2);
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(1);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(1);
 
         Instruction i = future.get();
         i.checkedExecutionStart();
         i.executionCompleted(InstructionStatus.Successful, getDetails());
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(4);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(), InstructionStatus.Executing);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(), InstructionStatus.Successful);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit2.getId(), InstructionStatus.Scheduled);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(4);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(1, mockedSubmit1.getId(),
+            InstructionStatus.Executing);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(2, mockedSubmit1.getId(),
+            InstructionStatus.Successful);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(3, mockedSubmit2.getId(),
+            InstructionStatus.Scheduled);
 
         i = future2.get();
         i.checkedExecutionStart();
         i.executionCompleted(InstructionStatus.Successful, getDetails());
 
-        mockedNotificationServiceWrapper.assertNotificationsCount(6);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(4, mockedSubmit2.getId(), InstructionStatus.Executing);
-        mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(5, mockedSubmit2.getId(), InstructionStatus.Successful);
+        this.mockedNotificationServiceWrapper.assertNotificationsCount(6);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(4, mockedSubmit2.getId(),
+            InstructionStatus.Executing);
+        this.mockedNotificationServiceWrapper.assertInstructionStatusChangedNotification(5, mockedSubmit2.getId(),
+            InstructionStatus.Successful);
     }
 
     private Details getDetails() {
@@ -307,10 +330,11 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
     }
 
     private SubmitInstructionInput getMockedSubmitInstructionInput(final String id, final String... dependencyIds) {
-        return getMockedSubmitInstructionInput(id, Optional.<Nanotime> absent(), dependencyIds);
+        return getMockedSubmitInstructionInput(id, Optional.empty(), dependencyIds);
     }
 
-    private SubmitInstructionInput getMockedSubmitInstructionInput(final String id, final Optional<Nanotime> deadline, final String... dependencyIds) {
+    private SubmitInstructionInput getMockedSubmitInstructionInput(final String id, final Optional<Nanotime> deadline,
+        final String... dependencyIds) {
         final SubmitInstructionInput mockedSubmitInstruction = mock(SubmitInstructionInput.class);
 
         doReturn(PcepUpdateTunnelInput.class).when(mockedSubmitInstruction).getImplementedInterface();
@@ -321,7 +345,8 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
 
         doReturn(dependencies).when(mockedSubmitInstruction).getPreconditions();
         doReturn(getInstructionId(id)).when(mockedSubmitInstruction).getId();
-        doReturn(deadline.isPresent() ? deadline.get() : new Nanotime(BigInteger.valueOf(Long.MAX_VALUE))).when(mockedSubmitInstruction).getDeadline();
+        doReturn(deadline.isPresent() ? deadline.get() : new Nanotime(BigInteger.valueOf(Long.MAX_VALUE)))
+            .when(mockedSubmitInstruction).getDeadline();
         return mockedSubmitInstruction;
     }
 
@@ -335,12 +360,10 @@ public class ProgrammingServiceImplTest extends AbstractDataBrokerTest {
         return new InstructionId(id);
     }
 
-    private boolean assertInstructionExists(final InstructionId id) {
-        try {
-            return getDataBroker().newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.builder(InstructionsQueue.class, INSTRUCTIONS_QUEUE_KEY).build().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720.instruction.queue.Instruction.class,
-                    new InstructionKey(id))).get().isPresent();
-        } catch (InterruptedException | ExecutionException e) {
-            return false;
-        }
+    private KeyedInstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.
+        rev150720.instruction.queue.Instruction, InstructionKey> buildInstructionIID(final InstructionId id) {
+        return InstanceIdentifier.builder(InstructionsQueue.class, new InstructionsQueueKey(INSTRUCTIONS_QUEUE_KEY))
+            .build().child(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.programming.rev150720
+                .instruction.queue.Instruction.class, new InstructionKey(id));
     }
 }
index 3b5ffc3aa8de0b9f263c0f7c9431ca6607b0a2a1..8069bb0b19d48ca01dcbeebc7135e03551edd6f4 100644 (file)
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-classic</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.opendaylight.controller</groupId>
+            <artifactId>sal-binding-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty-common</artifactId>
+        </dependency>
         <!-- Testing dependencies -->
         <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>io.netty</groupId>
+            <artifactId>netty-transport</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/testtool-util/src/main/java/org/opendaylight/protocol/util/CheckUtil.java b/testtool-util/src/main/java/org/opendaylight/protocol/util/CheckUtil.java
new file mode 100644 (file)
index 0000000..bd87f70
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * 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.util;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Stopwatch;
+import com.google.common.base.Verify;
+import com.google.common.util.concurrent.Uninterruptibles;
+import io.netty.util.concurrent.Future;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public final class CheckUtil {
+    private static final int LATCH_TIMEOUT = 10;
+    private static final int SLEEP_FOR = 200;
+    private static final int TIMEOUT = 30;
+
+    private CheckUtil() {
+        throw new UnsupportedOperationException();
+    }
+
+    @SuppressWarnings("unchecked")
+    public static <T extends Future> void waitFutureSuccess(final T future) {
+        final CountDownLatch latch = new CountDownLatch(1);
+        future.addListener(future1 -> latch.countDown());
+        Uninterruptibles.awaitUninterruptibly(latch, LATCH_TIMEOUT, TimeUnit.SECONDS);
+        Verify.verify(future.isSuccess());
+    }
+
+    public static <R, T extends DataObject> R readData(final DataBroker dataBroker, final InstanceIdentifier<T> iid,
+        final Function<T, R> function) throws ReadFailedException {
+        AssertionError lastError = null;
+        final Stopwatch sw = Stopwatch.createStarted();
+        while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
+            try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
+                final Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
+                if (data.isPresent()) {
+                    try {
+                        return function.apply(data.get());
+                    } catch (final AssertionError e) {
+                        lastError = e;
+                        Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
+                    }
+                }
+            }
+        }
+        throw lastError;
+    }
+
+    public static <T extends DataObject> T checkPresent(final DataBroker dataBroker, final InstanceIdentifier<T> iid)
+        throws ReadFailedException {
+        return readData(dataBroker, iid, bgpRib -> bgpRib);
+    }
+
+    public static <T extends DataObject> void checkNull(final DataBroker dataBroker, final InstanceIdentifier<T> iid)
+        throws ReadFailedException {
+        AssertionError lastError = null;
+        final Stopwatch sw = Stopwatch.createStarted();
+        while (sw.elapsed(TimeUnit.SECONDS) <= 10) {
+            try (final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction()) {
+                final com.google.common.base.Optional<T> data = tx.read(LogicalDatastoreType.OPERATIONAL, iid).checkedGet();
+                try {
+                    assert !data.isPresent();
+                    return;
+                } catch (final AssertionError e) {
+                    lastError = e;
+                    Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
+                }
+            }
+        }
+        throw lastError;
+    }
+
+    public static void checkEquals(final CheckEquals function) throws Exception {
+        AssertionError lastError = null;
+        final Stopwatch sw = Stopwatch.createStarted();
+        while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
+            try {
+                function.check();
+                return;
+            } catch (final AssertionError e) {
+                lastError = e;
+                Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
+            }
+        }
+        throw lastError;
+    }
+
+    public static void checkReceivedMessages(final ListenerCheck listener, final int numberOfMessages)
+        throws ReadFailedException {
+        final Stopwatch sw = Stopwatch.createStarted();
+        while (sw.elapsed(TimeUnit.SECONDS) <= TIMEOUT) {
+            if (listener.getListMessageSize() != numberOfMessages) {
+                Uninterruptibles.sleepUninterruptibly(SLEEP_FOR, TimeUnit.MILLISECONDS);
+            } else {
+                return;
+            }
+        }
+        throw new AssertionError("Expected " + numberOfMessages + " but received "
+            + listener.getListMessageSize());
+    }
+
+    public interface ListenerCheck {
+        int getListMessageSize();
+    }
+    @FunctionalInterface
+    public interface CheckEquals {
+        void check() throws ExecutionException, InterruptedException;
+    }
+}
\ No newline at end of file
diff --git a/testtool-util/src/test/java/org/opendaylight/protocol/util/CheckUtilTest.java b/testtool-util/src/test/java/org/opendaylight/protocol/util/CheckUtilTest.java
new file mode 100644 (file)
index 0000000..14aa473
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.util;
+
+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.when;
+
+import com.google.common.base.Optional;
+import com.google.common.base.VerifyException;
+import com.google.common.util.concurrent.CheckedFuture;
+import io.netty.channel.ChannelFuture;
+import io.netty.util.concurrent.GenericFutureListener;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.protocol.util.CheckUtil.ListenerCheck;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public class CheckUtilTest {
+    private final InstanceIdentifier<MockInterface> instanceIdentifier = InstanceIdentifier.create(MockInterface.class);
+    @Mock
+    private ChannelFuture future;
+    @Mock
+    private DataBroker dataBroker;
+    @Mock
+    private ReadOnlyTransaction readOnlyTransaction;
+    @Mock
+    private CheckedFuture checkedFuture;
+    @Mock
+    private Optional opt;
+    @Mock
+    private MockInterface mockInterface;
+    @Mock
+    private ListenerCheck listenerCheck;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        doReturn(this.readOnlyTransaction).when(this.dataBroker).newReadOnlyTransaction();
+        doReturn(this.checkedFuture).when(this.readOnlyTransaction).read(any(), any());
+        doReturn(this.opt).when(this.checkedFuture).checkedGet();
+        doReturn(this.mockInterface).when(this.opt).get();
+    }
+
+    @Test(expected = UnsupportedOperationException.class)
+    public void testPrivateConstructor() throws Throwable {
+        final Constructor<CheckUtil> c = CheckUtil.class.getDeclaredConstructor();
+        c.setAccessible(true);
+        try {
+            c.newInstance();
+        } catch (final InvocationTargetException e) {
+            throw e.getCause();
+        }
+    }
+
+    @Test(expected = VerifyException.class)
+    public void waitFutureSuccessFail() throws Exception {
+        when(this.future.isDone()).thenReturn(false);
+        doReturn(this.future).when(this.future).addListener(any());
+        CheckUtil.waitFutureSuccess(this.future);
+    }
+
+    @Test
+    public void waitFutureSuccess() throws Exception {
+        when(this.future.isSuccess()).thenReturn(true);
+        doAnswer(invocation -> {
+            invocation.getArgumentAt(0, GenericFutureListener.class).operationComplete(CheckUtilTest.this.future);
+            return CheckUtilTest.this.future;
+        }).when(this.future).addListener(any());
+        CheckUtil.waitFutureSuccess(this.future);
+    }
+
+    @Test(expected = NullPointerException.class)
+    public void readDataNull() throws Exception {
+        doReturn(false).when(this.opt).isPresent();
+        final InstanceIdentifier instanceIdentifier = null;
+        CheckUtil.readData(this.dataBroker, instanceIdentifier, test -> false);
+    }
+
+    @Test(expected = AssertionError.class)
+    public void readDataNotEquall() throws Exception {
+        doReturn(true).when(this.opt).isPresent();
+        doReturn(false).when(this.mockInterface).getResult();
+        CheckUtil.readData(this.dataBroker, this.instanceIdentifier, test -> {
+            assertTrue(test.getResult());
+            return test;
+        });
+    }
+
+    @Test(expected = AssertionError.class)
+    public void checkNull() throws Exception {
+        doReturn(true).when(this.opt).isPresent();
+        CheckUtil.checkNull(this.dataBroker, this.instanceIdentifier);
+    }
+
+    @Test(expected = AssertionError.class)
+    public void checkEquals() throws Exception {
+        CheckUtil.checkEquals(()-> assertTrue(false));
+    }
+
+    @Test(expected = AssertionError.class)
+    public void checkReceivedMessagesNotEqual() throws Exception {
+        doReturn(0).when(this.listenerCheck).getListMessageSize();
+        CheckUtil.checkReceivedMessages(this.listenerCheck, 1);
+    }
+
+    @Test
+    public void checkReceivedMessagesEqual() throws Exception {
+        doReturn(1).when(this.listenerCheck).getListMessageSize();
+        CheckUtil.checkReceivedMessages(this.listenerCheck, 1);
+    }
+
+    private interface MockInterface extends DataObject {
+        boolean getResult();
+    }
+}
\ No newline at end of file