Remove sleeping from test whenever possible.
Perform clean up under tests.
Change-Id: I734ca5721090669c75f09d107ee4c5ea1e3d14ee
Signed-off-by: Claudio D. Gasparini <claudio.gasparini@pantheon.tech>
<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>
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;
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;
// 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());
// 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());
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 {
@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));
<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>
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;
*/
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;
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;
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");
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;
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;
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;
* 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());
@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());
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());
- }
}
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;
*/
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
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;
/**
* 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;
}
}
@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);
}
return Futures.immediateFuture(null);
}
- BGPSessionImpl.State getState() {
+ public BGPSessionImpl.State getState() {
return getSession().getState();
}
Assert.assertEquals("Session up", true, Uninterruptibles.awaitUninterruptibly(this.sessionLatch, 10, TimeUnit.SECONDS));
return (BGPSessionImpl) this.session;
}
+
+ @Override
+ public int getListMessageSize() {
+ return this.listMsg.size();
+ }
}
<artifactId>config-manager</artifactId>
<type>test-jar</type>
</dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>testtool-util</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
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;
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);
}
}
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;
*/
@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.
*/
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;
* 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());
* 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());
@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);
*/
@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) {
*/
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);
@Override
public Tlvs localSessionCharacteristics() {
- return localOpen.getTlvs();
+ return this.localOpen.getTlvs();
+ }
+
+ @VisibleForTesting
+ static void setTicker(final Ticker ticker) {
+ TICKER = ticker;
}
}
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;
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));
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(
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;
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());
}
*/
@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);
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());
+ }
}
- }
+ });
}
/**
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++;
+ }
+ }
}
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;
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),
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();
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,
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();
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));
}
}
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());
});
}
- 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);
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;
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;
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());
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());
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());
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());
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);
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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());
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);
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());
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());
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());
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();
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());
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);
};
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());
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());
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;
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;
closeEventLoopGroups();
}
- private void closeEventLoopGroups() throws ExecutionException, InterruptedException {
+ private void closeEventLoopGroups() {
this.workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
this.bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS);
}
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);
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 {
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());
}
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;
*/
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;
}
}
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;
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;
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;
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);
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();
} 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) {
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;
"--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
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;
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;
@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
@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());
}
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());
}
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()));
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;
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();
}
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();
}
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();
}
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() {
@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
@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) {
@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) {
}
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) {
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);
}
LOG.debug("Session up.");
this.up = true;
this.session = session;
- sessionLatch.countDown();
+ this.sessionLatch.countDown();
}
LOG.debug("Session terminated. Cause : {}", cause);
}
- List<Message> messages() {
- return this.messages;
+ synchronized List<Message> messages() {
+ return ImmutableList.copyOf(this.messages);
}
boolean isUp () {
}
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();
+ }
}
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<>();
+++ /dev/null
-/*
- * 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);
- }
-}
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;
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> {
}
@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) {
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;
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;
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;
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;
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();
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(
}
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);
}
}
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;
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 {
}
@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()));
}
}
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;
.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;
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));
}
}
*/
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;
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
}
@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() {
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()));
}
}
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;
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 {
* 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) {
.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()));
}
}
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;
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 {
}
@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();
}
}
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;
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;
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;
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;
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;
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;
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());
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());
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);
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());
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);
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());
@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));
}
* @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
* @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
}
@Test
- public void testOnSessionTermination() throws UnknownHostException, InterruptedException, ExecutionException {
+ public void testOnSessionTermination() throws Exception {
this.listener.onSessionUp(this.session);
verify(this.listenerReg, times(0)).close();
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());
@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());
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
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();
}
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();
}
}
@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());
}
.addAugmentation(Tlvs3.class, new Tlvs3Builder().setLspDbVersion(
new LspDbVersionBuilder().setLspDbVersionValue(lspDbVersion != null ? BigInteger.valueOf(lspDbVersion) : null).build()).build()).build();
}
-
}
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;
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 {
<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>
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;
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) {
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;
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;
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;
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;
@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
@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");
@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());
@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
@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() {
}
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();
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;
}
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));
}
}
<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>
--- /dev/null
+/*
+ * 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
--- /dev/null
+/*
+ * 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