import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelHandlerContext;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
+ * Unit tests for DelegatingInboundHandler.
+ *
* @author jameshall
*/
public class DelegatingInboundHandlerTest {
- @Mock ChannelHandlerContext mockChHndlrCtx ;
- @Mock MessageConsumer mockMsgConsumer ;
+ @Mock ChannelHandlerContext mockChHndlrCtx;
+ @Mock MessageConsumer mockMsgConsumer;
@Mock DataObject mockDataObject ;
- DelegatingInboundHandler dih ;
+ DelegatingInboundHandler dih;
/**
- * Sets up test environment
+ * Sets up test environment.
*/
@Before
public void setUp() {
dih = new DelegatingInboundHandler(mockMsgConsumer) ;
}
- /**
- *
- */
@Test
public void testChannelReadSuccess() {
dih.channelRead(mockChHndlrCtx, mockDataObject) ;
// Verify that the message buf was released...
- verify( mockMsgConsumer, times(1)).consume(mockDataObject);
+ verify(mockMsgConsumer, times(1)).consume(mockDataObject);
}
- /**
- *
- */
+
@Test
public void testChannelInactive() {
dih.channelInactive(mockChHndlrCtx);
- verify( mockMsgConsumer, times(1)).consume(any(DataObject.class));
+ verify(mockMsgConsumer, times(1)).consume(any(DataObject.class));
}
- /**
- * ChannelUnregistered
- */
@Test
public void testChannelUnregistered() {
dih.channelUnregistered(mockChHndlrCtx);
- verify( mockMsgConsumer, times(1)).consume(any(DataObject.class));
+ verify(mockMsgConsumer, times(1)).consume(any(DataObject.class));
}
}
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
-
import java.util.List;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * @author michal.polkorab
+ * Dummy DelegatingInboundHandlerTest.
*
+ * @author michal.polkorab
*/
public class DummyDecoder extends ByteToMessageDecoder {
- private static final Logger LOG = LoggerFactory
- .getLogger(DummyDecoder.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DummyDecoder.class);
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
LOG.debug("decoding");
ctx.fireChannelReadComplete();
}
-
}
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelHandlerContext;
import java.util.concurrent.TimeUnit;
-
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.system.rev130927.SwitchIdleEvent;
/**
+ * Unit tests for IdleHandler.
*
* @author jameshall
*/
IdleHandler idleHandler ;
/**
- * Sets up test environment
- *
+ * Sets up test environment.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- idleHandler = new IdleHandler(60L, TimeUnit.MINUTES ) ;
+ idleHandler = new IdleHandler(60L, TimeUnit.MINUTES);
}
/**
- * Test message passing on channel read
+ * Test message passing on channel read.
*/
@Test
- public void testChannelRead() {
- try {
- idleHandler.channelRead(mockChHndlrCtx, new Object() );
- } catch (Exception e) {
- Assert.fail();
- }
+ public void testChannelRead() throws Exception {
+ idleHandler.channelRead(mockChHndlrCtx, new Object());
// Verify that a read was fired for the next handler ...
verify(mockChHndlrCtx, times(1)).fireChannelRead(any(SwitchIdleEvent.class)) ;
}
/**
- * Test channel read timeout
+ * Test channel read timeout.
*/
@Test
- public void testReadTimedOut() {
- try {
- idleHandler.readTimedOut( mockChHndlrCtx );
- } catch (Exception e) {
- Assert.fail();
- }
+ public void testReadTimedOut() throws Exception {
+ idleHandler.readTimedOut(mockChHndlrCtx);
// Verify a read was fired for the next handler to process ...
verify(mockChHndlrCtx, times(1)).fireChannelRead(any(SwitchIdleEvent.class)) ;
}
/**
- * Test only one timeout notification
+ * Test only one timeout notification.
*/
@Test
- public void testReadTimedOutNoOpNotFirst() {
- try {
- idleHandler.readTimedOut(mockChHndlrCtx);
- idleHandler.readTimedOut(mockChHndlrCtx);
- } catch (Exception e) {
- Assert.fail();
- }
+ public void testReadTimedOutNoOpNotFirst() throws Exception {
+ idleHandler.readTimedOut(mockChHndlrCtx);
+ idleHandler.readTimedOut(mockChHndlrCtx);
// Verify that only one notification was sent to the next handler ...
verify(mockChHndlrCtx, times(1)).fireChannelRead(any(Object.class)) ;
}
/**
- * Test two timeout notifications
+ * Test two timeout notifications.
*/
@Test
- public void testReadTimedOutTwice() {
- try {
- idleHandler.readTimedOut(mockChHndlrCtx);
- verify(mockChHndlrCtx, times(1)).fireChannelRead(any(Object.class)) ;
-
- idleHandler.channelRead(mockChHndlrCtx, new String() );
- verify(mockChHndlrCtx, times(2)).fireChannelRead(any(Object.class)) ;
-
- idleHandler.readTimedOut(mockChHndlrCtx);
- verify(mockChHndlrCtx, times(3)).fireChannelRead(any(Object.class)) ;
- } catch (Exception e) {
- Assert.fail();
- }
- }
+ public void testReadTimedOutTwice() throws Exception {
+ idleHandler.readTimedOut(mockChHndlrCtx);
+ verify(mockChHndlrCtx, times(1)).fireChannelRead(any(Object.class));
+
+ idleHandler.channelRead(mockChHndlrCtx, new String());
+ verify(mockChHndlrCtx, times(2)).fireChannelRead(any(Object.class));
+ idleHandler.readTimedOut(mockChHndlrCtx);
+ verify(mockChHndlrCtx, times(3)).fireChannelRead(any(Object.class));
+ }
}
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
-
import java.net.InetSocketAddress;
-
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.openflowjava.protocol.impl.deserialization.DeserializationFactory;
/**
- * @author madamjak
+ * Unit tests for OFDatagramPacketDecoder.
*
+ * @author madamjak
*/
public class OFDatagramPacketDecoderTest {
@Mock DeserializationFactory deserializationFactory;
private VersionMessageUdpWrapper msgWrapper;
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
}
@Test
- public void test() {
+ public void test() throws Exception {
OFDatagramPacketDecoder decoder = new OFDatagramPacketDecoder();
decoder.setDeserializationFactory(deserializationFactory);
- msgWrapper = new VersionMessageUdpWrapper(EncodeConstants.OF13_VERSION_ID, messageBufferMock, new InetSocketAddress("10.0.0.1", 6653));
- try {
- decoder.channelRead0(ctx, msgWrapper);
- } catch (Exception e) {
- Assert.fail("Exception occured");
- }
+ msgWrapper = new VersionMessageUdpWrapper(EncodeConstants.OF13_VERSION_ID, messageBufferMock,
+ new InetSocketAddress("10.0.0.1", 6653));
+
+ decoder.channelRead0(ctx, msgWrapper);
verify(messageBufferMock, times(1)).release();
}
}
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
-
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder;
/**
- * @author michal.polkorab
+ * Unit tests for OFDatagramPacketEncoder.
*
+ * @author michal.polkorab
*/
public class OFDatagramPacketEncoderTest {
@Mock SerializationFactory factory;
private UdpMessageListenerWrapper wrapper;
- private InetSocketAddress address = new InetSocketAddress("10.0.0.1", 6653);
+ private final InetSocketAddress address = new InetSocketAddress("10.0.0.1", 6653);
private List<Object> out;
/**
- * Initializes mocks and other objects
+ * Initializes mocks and other objects.
+ *
* @param version openflow protocol wire version
*/
public void startUp(Short version) {
}
/**
- * Tests encoding
+ * Tests encoding.
*/
@Test
- public void testCorrectEncode() {
+ public void testCorrectEncode() throws Exception {
startUp((short) EncodeConstants.OF13_VERSION_ID);
OFDatagramPacketEncoder encoder = new OFDatagramPacketEncoder();
encoder.setSerializationFactory(factory);
- try {
- encoder.encode(ctx, wrapper, out);
- } catch (Exception e) {
- Assert.fail();
- }
+ encoder.encode(ctx, wrapper, out);
}
/**
- * Tests encoding
+ * Tests encoding.
*/
@Test
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void testIncorrectEncode() {
startUp(null);
OFDatagramPacketEncoder encoder = new OFDatagramPacketEncoder();
Assert.assertEquals("List should be empty", 0, out.size());
}
}
-}
\ No newline at end of file
+}
package org.opendaylight.openflowjava.protocol.impl.core;
import static org.mockito.Mockito.when;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
-
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.openflowjava.util.ByteBufUtils;
/**
- * @author madamjak
+ * Unit tests for OFDatagramPacketHandler.
*
+ * @author madamjak
*/
public class OFDatagramPacketHandlerTest {
@Mock ChannelHandlerContext ctxMock;
@Mock Channel channelMock;
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
when(ctxMock.channel()).thenReturn(channelMock);
}
/**
- * Test {@link OFDatagramPacketHandler}
+ * Test {@link OFDatagramPacketHandler}.
*/
@Test
- public void test(){
+ public void test() throws Exception {
OFDatagramPacketHandler handler = new OFDatagramPacketHandler(switchConnHandler);
byte version = EncodeConstants.OF13_VERSION_ID;
ByteBuf messageBuffer = ByteBufUtils.hexStringToByteBuf("04 02 00 08 01 02 03 04");
DatagramPacket datagramPacket = new DatagramPacket(messageBuffer, recipientISA, senderISA);
UdpConnectionMap.addConnection(datagramPacket.sender(), consumerMock);
List<Object> outList = new ArrayList<>();
- try {
- handler.decode(ctxMock, datagramPacket, outList);
- } catch (Exception e) {
- Assert.fail("Wrong - Unexcepted exception occurred");
- }
+
+ handler.decode(ctxMock, datagramPacket, outList);
+
VersionMessageUdpWrapper versionUdpWrapper = (VersionMessageUdpWrapper) outList.get(0);
Assert.assertEquals("Wrong - incorrect version has been decoded",version, versionUdpWrapper.getVersion());
Assert.assertEquals("Wrong - sender addresses are different", senderISA, versionUdpWrapper.getAddress());
messageBuffer.readerIndex(1);
- Assert.assertEquals("Wrong - undecoded part of input ByteBuff is differnt to output",0, messageBuffer.compareTo(versionUdpWrapper.getMessageBuffer()));
+ Assert.assertEquals("Wrong - undecoded part of input ByteBuff is differnt to output", 0,
+ messageBuffer.compareTo(versionUdpWrapper.getMessageBuffer()));
}
}
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Mockito.when;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
/**
* Test to count decoder events (counters US_DECODE_SUCCESS, US_DECODE_FAIL and
- * US_RECEIVED_IN_OFJAVA have to be enabled)
+ * US_RECEIVED_IN_OFJAVA have to be enabled).
*
* @author madamjak
- *
*/
public class OFDecoderStatisticsTest {
private StatisticsCounters statCounters;
/**
- * Sets up test environment Start counting and reset counters before each
- * test
+ * Sets up test environment Start counting and reset counters before each test.
*/
@Before
public void setUp() {
}
/**
- * Stop counting after each test
+ * Stop counting after each test.
*/
@After
public void tierDown() {
}
/**
- * Test decode success counter
+ * Test decode success counter.
*/
@Test
- public void testDecodeSuccesfullCounter() {
+ public void testDecodeSuccesfullCounter() throws Exception {
if (!statCounters.isCounterEnabled(CounterEventTypes.US_DECODE_SUCCESS)) {
Assert.fail("Counter " + CounterEventTypes.US_DECODE_SUCCESS + " is not enable");
}
}
int count = 4;
when(mockDeserializationFactory.deserialize(any(ByteBuf.class),anyShort())).thenReturn(mockDataObject);
- try {
- for (int i = 0; i < count; i++) {
- writeObj = ByteBufUtils.hexStringToByteBuf("16 03 01 00");
- inMsg = new VersionMessageWrapper((short) 8, writeObj);
- ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
- }
- } catch (Exception e) {
- Assert.fail();
+
+ for (int i = 0; i < count; i++) {
+ writeObj = ByteBufUtils.hexStringToByteBuf("16 03 01 00");
+ inMsg = new VersionMessageWrapper((short) 8, writeObj);
+ ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
}
+
Assert.assertEquals("Wrong - bad counter value for OFEncoder encode succesfully ",
count,statCounters.getCounter(CounterEventTypes.US_DECODE_SUCCESS).getCounterValue());
Assert.assertEquals(
}
/**
- * Test fail decode counter
+ * Test fail decode counter.
*/
@Test
- public void testDecodeFailCounter() {
+ public void testDecodeFailCounter() throws Exception {
if (!statCounters.isCounterEnabled(CounterEventTypes.US_DECODE_SUCCESS)) {
Assert.fail("Counter " + CounterEventTypes.US_DECODE_SUCCESS + " is not enable");
}
Assert.fail("Counter " + CounterEventTypes.US_RECEIVED_IN_OFJAVA + " is not enable");
}
int count = 2;
- when( mockDeserializationFactory.deserialize(any(ByteBuf.class),anyShort())).thenThrow(new IllegalArgumentException());
- try {
- for (int i = 0; i < count; i++) {
- writeObj = ByteBufUtils.hexStringToByteBuf("16 03 01 00");
- inMsg = new VersionMessageWrapper((short) 8, writeObj);
- ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
- }
- } catch (Exception e) {
- Assert.fail();
+ when(mockDeserializationFactory.deserialize(any(ByteBuf.class),anyShort()))
+ .thenThrow(new IllegalArgumentException());
+
+ for (int i = 0; i < count; i++) {
+ writeObj = ByteBufUtils.hexStringToByteBuf("16 03 01 00");
+ inMsg = new VersionMessageWrapper((short) 8, writeObj);
+ ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
}
+
Assert.assertEquals(
"Wrong - bad counter value for OFEncoder encode succesfully ",
count, statCounters.getCounter(CounterEventTypes.US_DECODE_FAIL).getCounterValue());
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyShort;
import static org.mockito.Mockito.when;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
-
import java.util.ArrayList;
import java.util.List;
-
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
+ * Unit tests for OFDecoder.
*
* @author jameshall
*/
private List<Object> outList;
/**
- * Sets up test environment
- *
+ * Sets up test environment.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- ofDecoder = new OFDecoder() ;
- ofDecoder.setDeserializationFactory( mockDeserializationFactory ) ;
+ ofDecoder = new OFDecoder();
+ ofDecoder.setDeserializationFactory(mockDeserializationFactory);
writeObj = ByteBufUtils.hexStringToByteBuf("16 03 01 00");
- inMsg = new VersionMessageWrapper( (short)8, writeObj );
+ inMsg = new VersionMessageWrapper((short) 8, writeObj);
outList = new ArrayList<>();
}
- /**
- *
- */
@Test
- public void testDecode() {
- when(mockDeserializationFactory.deserialize( any(ByteBuf.class), anyShort() )).thenReturn(mockDataObject);
- try {
- ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
- } catch (Exception e) {
- Assert.fail();
- }
+ public void testDecode() throws Exception {
+ when(mockDeserializationFactory.deserialize(any(ByteBuf.class), anyShort())).thenReturn(mockDataObject);
+
+ ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
// Verify that the message buf was released...
- assertEquals( mockDataObject, outList.get(0) ) ;
- assertEquals( 0, writeObj.refCnt() ) ;
+ assertEquals(mockDataObject, outList.get(0));
+ assertEquals(0, writeObj.refCnt());
}
- /**
- *
- */
@Test
- public void testDecodeDeserializeException() {
- when(mockDeserializationFactory.deserialize( any(ByteBuf.class), anyShort() ))
- .thenThrow(new IllegalArgumentException()) ;
+ public void testDecodeDeserializeException() throws Exception {
+ when(mockDeserializationFactory.deserialize(any(ByteBuf.class), anyShort()))
+ .thenThrow(new IllegalArgumentException());
- try {
- ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
- } catch (Exception e) {
- Assert.fail();
- }
+ ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
// Verify that the message buf was released...
- assertEquals( 0, outList.size() ) ;
- assertEquals( 0, writeObj.refCnt() ) ;
+ assertEquals(0, outList.size());
+ assertEquals(0, writeObj.refCnt());
}
- /**
- *
- */
@Test
- public void testDecodeDeserializeNull() {
- when(mockDeserializationFactory.deserialize( any(ByteBuf.class), anyShort() ))
- .thenReturn(null) ;
+ public void testDecodeDeserializeNull() throws Exception {
+ when(mockDeserializationFactory.deserialize(any(ByteBuf.class), anyShort())).thenReturn(null);
- try {
- ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
- } catch (Exception e) {
- Assert.fail();
- }
+ ofDecoder.decode(mockChHndlrCtx, inMsg, outList);
// Verify that the message buf was released...
- assertEquals( 0, outList.size() ) ;
- assertEquals( 0, writeObj.refCnt() ) ;
+ assertEquals(0, outList.size());
+ assertEquals(0, writeObj.refCnt());
}
}
import static org.mockito.Matchers.anyShort;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
- * Test counters for encoding (at least DS_ENCODE_SUCCESS, DS_ENCODE_FAIL and DS_FLOW_MODS_SENT counters have to be enabled)
- * @author madamjak
+ * Test counters for encoding (at least DS_ENCODE_SUCCESS, DS_ENCODE_FAIL and DS_FLOW_MODS_SENT counters have to
+ * be enabled).
*
+ * @author madamjak
*/
public class OFEncoderStatisticsTest {
private OFEncoder ofEncoder;
/**
- * Initialize tests, start and reset counters before each test
+ * Initialize tests, start and reset counters before each test.
*/
@Before
- public void initTlest(){
+ public void initTlest() {
MockitoAnnotations.initMocks(this);
ofEncoder = new OFEncoder() ;
ofEncoder.setSerializationFactory(mockSerializationFactory) ;
}
/**
- * Stop counting after each test
+ * Stop counting after each test.
*/
@After
- public void tierDown(){
+ public void tierDown() {
statCounters.stopCounting();
}
/**
- * Test counting of success encode (counter DS_ENCODE_SUCCESS has to be enabled)
+ * Test counting of success encode (counter DS_ENCODE_SUCCESS has to be enabled).
*/
@Test
- public void testEncodeSuccessCounter() {
+ public void testEncodeSuccessCounter() throws Exception {
CounterEventTypes cet = CounterEventTypes.DS_ENCODE_SUCCESS;
- if(! statCounters.isCounterEnabled(cet)){
+ if (!statCounters.isCounterEnabled(cet)) {
Assert.fail("Counter " + cet + " is not enabled.");
}
- int count = 4;
+
when(mockOut.readableBytes()).thenReturn(1);
when(wrapper.getMsg()).thenReturn(mockMsg);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- try {
- for(int i = 0; i< count; i++){
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- }
- } catch (Exception e) {
- Assert.fail();
+
+ int count = 4;
+ for (int i = 0; i < count; i++) {
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
}
- Assert.assertEquals("Wrong - bad counter value for OFEncoder encode succesfully ", count, statCounters.getCounter(cet).getCounterValue());
+
+ Assert.assertEquals("Wrong - bad counter value for OFEncoder encode succesfully ", count,
+ statCounters.getCounter(cet).getCounterValue());
}
/**
- * Test counting of flow-mod sent (counter DS_FLOW_MODS_SENT has to be enabled)
+ * Test counting of flow-mod sent (counter DS_FLOW_MODS_SENT has to be enabled).
*/
@Test
- public void testFlowModSentCounter() {
+ public void testFlowModSentCounter() throws Exception {
CounterEventTypes cet = CounterEventTypes.DS_FLOW_MODS_SENT;
- if(! statCounters.isCounterEnabled(cet)){
+ if (!statCounters.isCounterEnabled(cet)) {
Assert.fail("Counter " + cet + " is not enabled.");
}
- int count = 4;
when(mockOut.readableBytes()).thenReturn(1);
when(wrapper.getMsg()).thenReturn(mockFlowModInput);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- try {
- for(int i = 0; i< count; i++){
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- }
- } catch (Exception e) {
- Assert.fail();
+
+ int count = 4;
+ for (int i = 0; i < count; i++) {
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
}
- Assert.assertEquals("Wrong - bad counter value for OFEncoder flow-mod sent", count, statCounters.getCounter(cet).getCounterValue());
+
+ Assert.assertEquals("Wrong - bad counter value for OFEncoder flow-mod sent", count,
+ statCounters.getCounter(cet).getCounterValue());
}
+
/**
- * Test counting of encode fail (counter DS_ENCODE_FAIL has to be enabled)
+ * Test counting of encode fail (counter DS_ENCODE_FAIL has to be enabled).
*/
-
@Test
- public void testEncodeEncodeFailCounter() {
+ public void testEncodeEncodeFailCounter() throws Exception {
CounterEventTypes cet = CounterEventTypes.DS_ENCODE_FAIL;
- if(! statCounters.isCounterEnabled(cet)){
+ if (!statCounters.isCounterEnabled(cet)) {
Assert.fail("Counter " + cet + " is not enabled.");
}
- int count = 2;
+
when(wrapper.getMsg()).thenReturn(mockMsg);
when(wrapper.getListener()).thenReturn(listener);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- doThrow(new IllegalArgumentException()).when(mockSerializationFactory).messageToBuffer(anyShort(),any(ByteBuf.class), any(DataObject.class));
- try {
- for(int i = 0; i< count; i++){
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- }
- } catch (Exception e) {
- Assert.fail();
+ doThrow(new IllegalArgumentException()).when(mockSerializationFactory).messageToBuffer(anyShort(),
+ any(ByteBuf.class), any(DataObject.class));
+
+ int count = 2;
+ for (int i = 0; i < count; i++) {
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
}
- Assert.assertEquals("Wrong - bad counter value for OFEncoder fail encode", count, statCounters.getCounter(cet).getCounterValue());
+
+ Assert.assertEquals("Wrong - bad counter value for OFEncoder fail encode", count,
+ statCounters.getCounter(cet).getCounterValue());
}
}
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
-
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
+ * Unit tests for OFEncoder.
*
* @author jameshall
*/
OFEncoder ofEncoder = new OFEncoder() ;
/**
- * Sets up test environment
+ * Sets up test environment.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ofEncoder = new OFEncoder() ;
- ofEncoder.setSerializationFactory( mockSerializationFactory ) ;
+ ofEncoder.setSerializationFactory(mockSerializationFactory);
}
/**
- * Test successful write (no clear)
+ * Test successful write (no clear).
*/
@Test
- public void testEncodeSuccess() {
+ public void testEncodeSuccess() throws Exception {
when(mockOut.readableBytes()).thenReturn(1);
when(wrapper.getMsg()).thenReturn(mockMsg);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- try {
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
// Verify that the channel was flushed after the ByteBuf was retained.
verify(mockOut, times(0)).clear();
}
/**
- * Test Bytebuf clearing after serialization failure
+ * Test Bytebuf clearing after serialization failure.
*/
@Test
- public void testEncodeSerializationException() {
+ public void testEncodeSerializationException() throws Exception {
when(wrapper.getMsg()).thenReturn(mockMsg);
when(wrapper.getListener()).thenReturn(listener);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- doThrow(new IllegalArgumentException()).when(mockSerializationFactory).messageToBuffer(anyShort(),any(ByteBuf.class), any(DataObject.class));
- try {
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- } catch (Exception e) {
- Assert.fail();
- }
+ doThrow(new IllegalArgumentException()).when(mockSerializationFactory).messageToBuffer(anyShort(),
+ any(ByteBuf.class), any(DataObject.class));
+
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
// Verify that the output message buf was cleared...
verify(mockOut, times(1)).clear();
}
/**
- * Test no action on empty bytebuf
+ * Test no action on empty bytebuf.
*/
@Test
- public void testEncodeSerializesNoBytes() {
+ public void testEncodeSerializesNoBytes() throws Exception {
when(mockOut.readableBytes()).thenReturn(0);
when(wrapper.getMsg()).thenReturn(mockMsg);
when(wrapper.getMsg().getVersion()).thenReturn((short) EncodeConstants.OF13_VERSION_ID);
- try {
- ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ ofEncoder.encode(mockChHndlrCtx, wrapper, mockOut);
// Verify that the output message buf was cleared...
verify(mockOut, times(0)).clear();
verify(mockChHndlrCtx, times(0)).writeAndFlush(mockOut);
verify(mockOut, times(0)).retain();
}
-}
\ No newline at end of file
+}
package org.opendaylight.openflowjava.protocol.impl.core;
import static org.junit.Assert.assertEquals;
+
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
-
import java.util.ArrayList;
import java.util.List;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.openflowjava.util.ByteBufUtils;
/**
- * Testing class of {@link OFFrameDecoder}
+ * Testing class of {@link OFFrameDecoder}.
*
* @author michal.polkorab
*/
@Mock
ConnectionFacade connectionFacade;
private OFFrameDecoder decoder;
- private List<Object> list = new ArrayList<>();
+ private final List<Object> list = new ArrayList<>();
/**
- * Sets up tests
+ * Sets up tests.
*/
@Before
public void setUp() {
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecode8BMessage() {
- try {
- decoder.decode(channelHandlerContext,
+ public void testDecode8BMessage() throws Exception {
+ decoder.decode(channelHandlerContext,
ByteBufUtils.hexStringToByteBuf("04 00 00 08 00 00 00 01"),
list);
- } catch (Exception e) {
- Assert.fail();
- }
-
assertEquals(8, ((ByteBuf) list.get(0)).readableBytes());
}
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecode16BMessage() {
+ public void testDecode16BMessage() throws Exception {
ByteBuf byteBuffer = ByteBufUtils
.hexStringToByteBuf("04 00 00 10 00 00 00 00 00 00 00 00 00 00 00 42");
- try {
- decoder.decode(channelHandlerContext, byteBuffer, list);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ decoder.decode(channelHandlerContext, byteBuffer, list);
assertEquals(16, ((ByteBuf) list.get(0)).readableBytes());
assertEquals(0, byteBuffer.readableBytes());
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecode5BIncompleteMessage() {
+ public void testDecode5BIncompleteMessage() throws Exception {
ByteBuf byteBuffer = ByteBufUtils.hexStringToByteBuf("04 00 00 08 00");
- try {
- decoder.decode(channelHandlerContext, byteBuffer, list);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ decoder.decode(channelHandlerContext, byteBuffer, list);
Assert.assertEquals("List is not empty", 0, list.size());
assertEquals(5, byteBuffer.readableBytes());
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecode16BIncompleteMessage() {
+ public void testDecode16BIncompleteMessage() throws Exception {
ByteBuf byteBuffer = ByteBufUtils
.hexStringToByteBuf("04 00 00 11 00 00 00 00 00 00 00 00 00 00 00 42");
- try {
- decoder.decode(channelHandlerContext, byteBuffer, list);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ decoder.decode(channelHandlerContext, byteBuffer, list);
Assert.assertEquals("List is not empty", 0, list.size());
assertEquals(16, byteBuffer.readableBytes());
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecodeCompleteAndPartialMessage() {
+ public void testDecodeCompleteAndPartialMessage() throws Exception {
ByteBuf byteBuffer = ByteBufUtils
.hexStringToByteBuf("04 00 00 08 00 00 00 01 04 00 00 08 00");
- try {
- decoder.decode(channelHandlerContext, byteBuffer, list);
- } catch (Exception e) {
- Assert.fail();
- }
+
+ decoder.decode(channelHandlerContext, byteBuffer, list);
Assert.assertEquals(8, ((ByteBuf) list.get(0)).readableBytes());
Assert.assertEquals(1, list.size());
/**
* Test of decoding
- * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}
+ * {@link OFFrameDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)}.
*/
@Test
- public void testDecode8BMessageWithTls() {
+ public void testDecode8BMessageWithTls() throws Exception {
decoder = new OFFrameDecoder(connectionFacade, true);
- try {
- decoder.decode(channelHandlerContext,
+
+ decoder.decode(channelHandlerContext,
ByteBufUtils.hexStringToByteBuf("04 00 00 08 00 00 00 01"),
list);
- } catch (Exception e) {
- Assert.fail();
- }
assertEquals(8, ((ByteBuf) list.get(0)).readableBytes());
}
import static org.junit.Assert.assertNotNull;
+import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
-import com.google.common.collect.Lists;
-
/**
+ * Unit tests for ChannelInitializerFactory.
*
* @author jameshall
*/
@Mock DeserializationFactory deserializationFactory ;
/**
- * Sets up test environment
+ * Sets up test environment.
*/
@Before
public void setUp() {
}
/**
- * Test {@link TcpChannelInitializer} creation
+ * Test {@link TcpChannelInitializer} creation.
*/
@Test
public void testCreatePublishingChannelInitializer() {
TcpChannelInitializer initializer = factory.createPublishingChannelInitializer() ;
- assertNotNull( initializer );
+ assertNotNull(initializer);
}
-}
\ No newline at end of file
+}
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
/**
+ * Unit tests for ChannelInitializer.
*
* @author james.hall
*/
TcpChannelInitializer pubChInitializer ;
/**
- * Sets up test environment
- * @throws Exception
+ * Sets up test environment.
*/
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- pubChInitializer= new TcpChannelInitializer(mockChGrp, mockConnAdaptorFactory) ;
+ pubChInitializer = new TcpChannelInitializer(mockChGrp, mockConnAdaptorFactory) ;
pubChInitializer.setSerializationFactory(mockSerializationFactory);
pubChInitializer.setDeserializationFactory(mockDeserializationFactory);
pubChInitializer.setSwitchIdleTimeout(1) ;
pubChInitializer.getConnectionIterator() ;
pubChInitializer.setUseBarrier(true);
- when( mockChGrp.size()).thenReturn(1) ;
- pubChInitializer.setSwitchConnectionHandler( mockSwConnHandler ) ;
+ when(mockChGrp.size()).thenReturn(1);
+ pubChInitializer.setSwitchConnectionHandler(mockSwConnHandler);
- inetSockAddr = new InetSocketAddress(InetAddress.getLocalHost(), 8675 ) ;
+ inetSockAddr = new InetSocketAddress(InetAddress.getLocalHost(), 8675);
- when(mockConnAdaptorFactory.createConnectionFacade(mockSocketCh, null, true))
- .thenReturn(mockConnFacade);
+ when(mockConnAdaptorFactory.createConnectionFacade(mockSocketCh, null, true)).thenReturn(mockConnFacade);
when(mockSocketCh.remoteAddress()).thenReturn(inetSockAddr) ;
when(mockSocketCh.localAddress()).thenReturn(inetSockAddr) ;
when(mockSocketCh.remoteAddress()).thenReturn(inetSockAddr) ;
/**
- * Test channel initialization with encryption config set
+ * Test channel initialization with encryption config set.
*/
@Test
public void testinitChannelEncryptionSet() {
}
/**
- * Test channel initialization with null encryption config
+ * Test channel initialization with null encryption config.
*/
@Test
public void testinitChannelEncryptionSetNullTls() {
}
/**
- * Test channel initialization without setting the encryption
+ * Test channel initialization without setting the encryption.
*/
@Test
public void testinitChannelEncryptionNotSet() {
}
/**
- * Test disconnect on new connection rejected
- * @throws UnknownHostException
+ * Test disconnect on new connection rejected.
*/
@Test
public void testinitChannelNoEncryptionAcceptFails() throws UnknownHostException {
pubChInitializer.initChannel(mockSocketCh) ;
verify(mockSocketCh, times(1)).disconnect();
- verify(mockChPipeline, times(0))
- .addLast( any(String.class), any(ChannelHandler.class) ) ;
+ verify(mockChPipeline, times(0)).addLast(any(String.class), any(ChannelHandler.class));
}
/**
- * Test channel close on exception during initialization
+ * Test channel close on exception during initialization.
*/
@Test
public void testExceptionThrown() {
doThrow(new IllegalArgumentException()).when(mockSocketCh).pipeline() ;
pubChInitializer.initChannel(mockSocketCh);
- verify( mockSocketCh, times(1)).close() ;
+ verify(mockSocketCh, times(1)).close();
}
/**
- * All paths should install these six handlers:
+ * All paths should install these six handlers.
*/
private void verifyCommonHandlers() {
verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.IDLE_HANDLER.name()),any(IdleHandler.class)) ;
verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_DECODER.name()),any(OFDecoder.class)) ;
verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_ENCODER.name()),any(OFEncoder.class)) ;
- verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_FRAME_DECODER.name()),any(OFFrameDecoder.class)) ;
- verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_VERSION_DETECTOR.name()),any(OFVersionDetector.class)) ;
- verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name()),any(DelegatingInboundHandler.class));
+ verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_FRAME_DECODER.name()),
+ any(OFFrameDecoder.class));
+ verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.OF_VERSION_DETECTOR.name()),
+ any(OFVersionDetector.class));
+ verify(mockChPipeline, times(1)).addLast(eq(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name()),
+ any(DelegatingInboundHandler.class));
assertEquals(1, pubChInitializer.size()) ;
}
}
import static org.junit.Assert.assertNotNull;
+import com.google.common.collect.Lists;
import javax.net.ssl.SSLContext;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
-import com.google.common.collect.Lists;
-
/**
+ * Unit tests for SslContextFactory.
*
* @author jameshall
*/
TlsConfiguration tlsConfiguration ;
/**
- * Sets up test environment
+ * Sets up test environment.
*/
@Before
public void setUp() {
sslContextFactory = new SslContextFactory(tlsConfiguration);
}
- /**
- * @throws Exception
- */
@Test
public void testGetServerContext() throws Exception {
SSLContext context = sslContextFactory.getServerContext() ;
- assertNotNull( context );
+ assertNotNull(context);
}
-
}
import static org.junit.Assert.assertNotNull;
import java.io.InputStream;
-
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
/**
+ * Unit tests for SslKeyStore.
*
* @author jameshall
*/
public class SslKeyStoreTest {
/**
- * Sets up test environment
+ * Sets up test environment.
*/
@Before
public void setUp() {
}
/**
- * Test keystore file access - via classpath
- * @throws Exception
+ * Test keystore file access - via classpath.
*/
@Test
public void testAsInputStream() throws Exception {
InputStream inputStream = SslKeyStore.asInputStream("/key.bin", PathType.CLASSPATH);
- assertNotNull( inputStream );
+ assertNotNull(inputStream);
inputStream.close();
}
/**
- * Test keystore file access - via relative path
- * @throws Exception
+ * Test keystore file access - via relative path.
*/
@Test
public void testAsInputStream2() throws Exception {
InputStream inputStream = SslKeyStore.asInputStream("src/test/resources/key.bin", PathType.PATH);
- assertNotNull( inputStream );
+ assertNotNull(inputStream);
inputStream.close();
}
}
package org.opendaylight.openflowjava.protocol.impl.core;
import static org.junit.Assert.assertEquals;
-import io.netty.channel.ChannelHandlerContext;
+import static org.junit.Assert.fail;
+import com.google.common.util.concurrent.ListenableFuture;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.unix.Errors;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
-
-import io.netty.channel.unix.Errors;
-import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.openflowjava.protocol.impl.deserialization.DeserializationFactory;
import org.opendaylight.openflowjava.protocol.impl.serialization.SerializationFactory;
-import com.google.common.util.concurrent.ListenableFuture;
-
/**
+ * Unit tests for TcpHandler.
*
* @author jameshall
*/
public class TcpHandlerTest {
- private InetAddress serverAddress = InetAddress.getLoopbackAddress() ;
+ private final InetAddress serverAddress = InetAddress.getLoopbackAddress() ;
@Mock ChannelHandlerContext mockChHndlrCtx ;
@Mock TcpChannelInitializer mockChannelInitializer;
@Mock SwitchConnectionHandler mockSwitchConnHndler ;
TcpHandler tcpHandler ;
/**
- * Initialize mocks
+ * Initialize mocks.
*/
public TcpHandlerTest() {
MockitoAnnotations.initMocks(this);
}
/**
- * Test run with null address set
- * @throws IOException
- * @throws InterruptedException
- * @throws ExecutionException
+ * Test run with null address set.
*/
@Test
public void testRunWithNullAddress() throws IOException, InterruptedException, ExecutionException {
}
/**
- * Test run with null address set on Epoll native transport
- * @throws IOException
- * @throws InterruptedException
- * @throws ExecutionException
+ * Test run with null address set on Epoll native transport.
*/
@Test
public void testRunWithNullAddressOnEpoll() throws IOException, InterruptedException, ExecutionException {
}
/**
- * Test run with address set
- * @throws IOException
- * @throws InterruptedException
- * @throws ExecutionException
+ * Test run with address set.
*/
@Test
public void testRunWithAddress() throws IOException, InterruptedException, ExecutionException {
}
/**
- * Test run with address set on Epoll native transport
- * @throws IOException
- * @throws InterruptedException
- * @throws ExecutionException
+ * Test run with address set on Epoll native transport.
*/
@Test
public void testRunWithAddressOnEpoll() throws IOException, InterruptedException, ExecutionException {
}
/**
- * Test run with encryption
- * @throws InterruptedException
- * @throws IOException
- * @throws ExecutionException
+ * Test run with encryption.
*/
@Test
public void testRunWithEncryption() throws InterruptedException, IOException, ExecutionException {
tcpHandler = new TcpHandler(serverAddress, serverPort);
tcpHandler.setChannelInitializer(mockChannelInitializer);
- assertEquals( "failed to start server", true, startupServer(false));
- assertEquals( "wrong connection count", 0, tcpHandler.getNumberOfConnections());
- assertEquals( "wrong port", serverPort, tcpHandler.getPort());
- assertEquals( "wrong address", serverAddress.getHostAddress(), tcpHandler.getAddress());
+ assertEquals("failed to start server", true, startupServer(false));
+ assertEquals("wrong connection count", 0, tcpHandler.getNumberOfConnections());
+ assertEquals("wrong port", serverPort, tcpHandler.getPort());
+ assertEquals("wrong address", serverAddress.getHostAddress(), tcpHandler.getAddress());
assertEquals("failed to connect client", true, clientConnection(tcpHandler.getPort()));
}
/**
- * Test run with encryption on Epoll native transport
- * @throws InterruptedException
- * @throws IOException
- * @throws ExecutionException
+ * Test run with encryption on Epoll native transport.
*/
@Test
public void testRunWithEncryptionOnEpoll() throws InterruptedException, IOException, ExecutionException {
tcpHandler.setChannelInitializer(mockChannelInitializer);
//Use Epoll native transport
- assertEquals( "failed to start server", true, startupServer(true));
- assertEquals( "wrong connection count", 0, tcpHandler.getNumberOfConnections());
- assertEquals( "wrong port", serverPort, tcpHandler.getPort());
- assertEquals( "wrong address", serverAddress.getHostAddress(), tcpHandler.getAddress());
+ assertEquals("failed to start server", true, startupServer(true));
+ assertEquals("wrong connection count", 0, tcpHandler.getNumberOfConnections());
+ assertEquals("wrong port", serverPort, tcpHandler.getPort());
+ assertEquals("wrong address", serverAddress.getHostAddress(), tcpHandler.getAddress());
assertEquals("failed to connect client", true, clientConnection(tcpHandler.getPort()));
}
/**
- * Test run on already used port
- * @throws IOException
+ * Test run on already used port.
*/
- @Test
+ @Test(expected = BindException.class)
public void testSocketAlreadyInUse() throws IOException {
int serverPort = 28001;
Socket firstBinder = new Socket();
- boolean exceptionThrown = false;
+
try {
firstBinder.bind(new InetSocketAddress(serverAddress, serverPort));
- } catch (Exception e) {
- Assert.fail("Test precondition failed - not able to bind socket to port " + serverPort);
- }
- try {
tcpHandler = new TcpHandler(serverAddress, serverPort);
tcpHandler.setChannelInitializer(mockChannelInitializer);
tcpHandler.initiateEventLoopGroups(null, false);
tcpHandler.run();
- } catch (Exception e) {
- if (e instanceof BindException) {
- exceptionThrown = true;
- }
+ } finally {
+ firstBinder.close();
}
- firstBinder.close();
- Assert.assertTrue("Expected BindException has not been thrown", exceptionThrown == true);
}
/**
- * Test run on already used port
- * @throws IOException
+ * Test run on already used port.
*/
@Test
public void testSocketAlreadyInUseOnEpoll() throws IOException {
int serverPort = 28001;
Socket firstBinder = new Socket();
- boolean exceptionThrown = false;
+
try {
firstBinder.bind(new InetSocketAddress(serverAddress, serverPort));
- } catch (Exception e) {
- Assert.fail("Test precondition failed - not able to bind socket to port " + serverPort);
- }
- try {
+
tcpHandler = new TcpHandler(serverAddress, serverPort);
tcpHandler.setChannelInitializer(mockChannelInitializer);
//Use Epoll native transport
tcpHandler.initiateEventLoopGroups(null, true);
tcpHandler.run();
- } catch (Exception e) {
- if (e instanceof BindException || e instanceof Errors.NativeIoException) {
- exceptionThrown = true;
- }
+ fail("Expected BindException or Errors.NativeIoException");
+ } catch (BindException | Errors.NativeIoException e) {
+ // expected
+ } finally {
+ firstBinder.close();
}
- firstBinder.close();
- Assert.assertTrue("Expected BindException has not been thrown", exceptionThrown == true);
}
/**
- * Trigger the server shutdown and wait 2 seconds for completion
+ * Trigger the server shutdown and wait 2 seconds for completion.
*/
private void shutdownServer() throws InterruptedException, ExecutionException {
ListenableFuture<Boolean> shutdownRet = tcpHandler.shutdown() ;
- while ( shutdownRet.isDone() != true )
+ while (shutdownRet.isDone() != true) {
Thread.sleep(100) ;
+ }
assertEquals("shutdown failed", true, shutdownRet.get());
}
- /**
- * @throws InterruptedException
- * @throws IOException
- * @throws ExecutionException
- */
private Boolean startupServer(boolean isEpollEnabled) throws InterruptedException, IOException, ExecutionException {
ListenableFuture<Boolean> online = tcpHandler.getIsOnlineFuture();
/**
* Else use Nio based transport.
*/
tcpHandler.initiateEventLoopGroups(null, isEpollEnabled);
- (new Thread(tcpHandler)).start();
- int retry = 0;
- while (online.isDone() != true && retry++ < 20) {
- Thread.sleep(100);
- }
+ new Thread(tcpHandler).start();
+ int retry = 0;
+ while (online.isDone() != true && retry++ < 20) {
+ Thread.sleep(100);
+ }
return online.isDone() ;
}
- /**
- * @throws IOException
- */
+
private static Boolean clientConnection(int port) throws IOException {
// Connect, and disconnect
- Socket socket = new Socket(InetAddress.getLoopbackAddress(), port );
+ Socket socket = new Socket(InetAddress.getLoopbackAddress(), port);
Boolean result = socket.isConnected();
socket.close() ;
return result ;
import io.netty.buffer.ByteBuf;
import io.netty.channel.socket.DatagramPacket;
-
import java.net.InetSocketAddress;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.openflowjava.protocol.impl.core.connection.MessageConsumer;
/**
- * @author madamjak
+ * Unit tests for UdpConnectionMap.
*
+ * @author madamjak
*/
public class UdpConnectionMapTest {
@Mock MessageConsumer consumerMock;
- @Mock ByteBuf messageBuffer;
+ @Mock ByteBuf messageBuffer;
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
}
/**
- * Test {@link UdpConnectionMap} - sender address is not null
+ * Test {@link UdpConnectionMap} - sender address is not null.
*/
@Test
- public void testWithSenderAddress(){
+ public void testWithSenderAddress() {
InetSocketAddress recipientISA = InetSocketAddress.createUnresolved("localhost", 9876);
InetSocketAddress senderISA = InetSocketAddress.createUnresolved("192.168.15.2", 21021);
DatagramPacket datagramPacket = new DatagramPacket(messageBuffer, recipientISA, senderISA);
}
/**
- * Test {@link UdpConnectionMap} - sender address is null to add connection
+ * Test {@link UdpConnectionMap} - sender address is null to add connection.
*/
@Test(expected = IllegalArgumentException.class)
- public void testWithoutSenderAddressOnAdd(){
+ public void testWithoutSenderAddressOnAdd() {
UdpConnectionMap.addConnection(null, consumerMock);
}
/**
- * Test {@link UdpConnectionMap} - sender address is not null to get message consumer
+ * Test {@link UdpConnectionMap} - sender address is not null to get message consumer.
*/
@Test(expected = IllegalArgumentException.class)
- public void testWithoutSenderAddressOnGet(){
+ public void testWithoutSenderAddressOnGet() {
UdpConnectionMap.getMessageConsumer(null);
}
/**
- * Test {@link UdpConnectionMap} - sender address is not null to remove connection
+ * Test {@link UdpConnectionMap} - sender address is not null to remove connection.
*/
@Test(expected = IllegalArgumentException.class)
- public void testWithoutSenderAddressOnRemove(){
+ public void testWithoutSenderAddressOnRemove() {
UdpConnectionMap.removeConnection(null);
}
}
import io.netty.buffer.ByteBuf;
import java.net.InetSocketAddress;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import org.junit.Assert;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
+ * Unit tests for VersionMessageUdpWrapper.
*
* @author madamjak
- *
*/
-
public class VersionMessageUdpWrapperTest {
@Mock ByteBuf byteBuff;
+
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
}
@Test
- public void test(){
+ public void test() {
short version = 35;
int port = 9876;
- String host ="localhost";
+ String host = "localhost";
InetSocketAddress inetSockAddr = InetSocketAddress.createUnresolved(host, port);
VersionMessageUdpWrapper wrapper = new VersionMessageUdpWrapper(version,byteBuff,inetSockAddr);
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.ExperimenterInput;
/**
- * @author madamjak
+ * Unit tests for ChannelOutboundQueue02.
*
+ * @author madamjak
*/
public class ChannelOutboundQueue02Test {
private static int counter;
private static final int RPC_RESPONSE_EXPIRATION = 1;
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
@Mock EchoInput echoInput;
@Mock BarrierInput barrierInput;
@Mock ExperimenterInput experimenterInput;
private ConnectionAdapterImpl adapter;
private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache;
+
/**
- * Initialize mocks
+ * Initialize mocks.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
+
/**
- * Disconnect adapter after each test
+ * Disconnect adapter after each test.
*/
@After
- public void tierDown(){
+ public void tierDown() {
if (adapter != null && adapter.isAlive()) {
adapter.disconnect();
}
}
/**
- * Test write to closed / opened channel
- * @throws Exception
+ * Test write to closed / opened channel.
*/
@Test
public void test01() throws Exception {
final EmbeddedChannel ec = new EmbeddedChannel(new EmbededChannelHandler());
adapter = new ConnectionAdapterImpl(ec, InetSocketAddress.createUnresolved("localhost", 9876), true);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(
+ RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
final ChannelOutboundQueue cq = (ChannelOutboundQueue) ec.pipeline().last();
- counter=0;
+ counter = 0;
adapter.barrier(barrierInput);
adapter.echo(echoInput);
cq.channelInactive(ec.pipeline().lastContext());
ec.runPendingTasks();
Assert.assertEquals("Wrong - ChannelOutboundHandlerAdapter.write was invoked on closed channel",0, counter);
cq.channelActive(ec.pipeline().lastContext());
- counter=0;
+ counter = 0;
adapter.barrier(barrierInput);
adapter.experimenter(experimenterInput);
ec.runPendingTasks();
- Assert.assertEquals("Wrong - ChannelOutboundHandlerAdapter.write has not been invoked on opened channel",2, counter);
+ Assert.assertEquals("Wrong - ChannelOutboundHandlerAdapter.write has not been invoked on opened channel",
+ 2, counter);
}
/**
- * Test write to read only / writable channel
+ * Test write to read only / writable channel.
*/
@Test
- public void test02(){
+ public void test02() {
final ChangeWritableEmbededChannel ec = new ChangeWritableEmbededChannel(new EmbededChannelHandler());
adapter = new ConnectionAdapterImpl(ec, InetSocketAddress.createUnresolved("localhost", 9876), true);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(
+ RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES) .removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
ec.setReadOnly();
- counter=0;
+ counter = 0;
adapter.barrier(barrierInput);
adapter.echo(echoInput);
ec.runPendingTasks();
}
/**
- * Channel Handler for testing
+ * Channel Handler for testing.
* @author madamjak
- *
*/
private class EmbededChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(final ChannelHandlerContext ctx, final Object msg,
final ChannelPromise promise) throws Exception {
- if(msg instanceof MessageListenerWrapper){
+ if (msg instanceof MessageListenerWrapper) {
counter++;
}
}
}
/**
- * Class for testing - channel can change state to read only or writable
+ * Class for testing - channel can change state to read only or writable.
* @author madamjak
- *
*/
- private class ChangeWritableEmbededChannel extends EmbeddedChannel {
+ private static class ChangeWritableEmbededChannel extends EmbeddedChannel {
private boolean isWrittable;
- public ChangeWritableEmbededChannel(final ChannelHandler channelHandler){
+
+ ChangeWritableEmbededChannel(final ChannelHandler channelHandler) {
super(channelHandler);
setReadOnly();
}
return isWrittable;
}
- public void setWritable(){
+ public void setWritable() {
isWrittable = true;
}
- public void setReadOnly(){
+ public void setReadOnly() {
isWrittable = false;
}
}
package org.opendaylight.openflowjava.protocol.impl.core.connection;
import io.netty.channel.Channel;
-
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.ChannelOutboundQueue;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.SimpleRpcListener;
/**
- * @author michal.polkorab
+ * UNit tests for ChannelOutboundQueue.
*
+ * @author michal.polkorab
*/
public class ChannelOutboundQueueTest {
@Mock Channel channel;
/**
- * Initialize mocks
+ * Initialize mocks.
*/
public ChannelOutboundQueueTest() {
MockitoAnnotations.initMocks(this);
}
/**
- * Test incorrect queue creation handling
+ * Test incorrect queue creation handling.
*/
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void testIncorrectQueueCreation() {
new ChannelOutboundQueue(channel, 0, null);
}
/**
- * Test correct enqueue handling
+ * Test correct enqueue handling.
*/
@Test
public void testEnqueue() {
enqueued = queue.enqueue(new SimpleRpcListener("INPUT", "Failed to send INPUT"));
Assert.assertFalse("Enqueue problem", enqueued);
}
-}
\ No newline at end of file
+}
package org.opendaylight.openflowjava.protocol.impl.core.connection;
import static org.mockito.Mockito.when;
+
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import java.net.InetSocketAddress;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+
/**
+ * Unit tests for ConnectionAdapterFactoryImpl.
*
* @author madamjak
- *
*/
public class ConnectionAdapterFactoryImplTest {
@Mock InetSocketAddress address;
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
when(channel.pipeline()).thenReturn(channnelPipe);
}
@Test
- public void test(){
+ public void test() {
final ConnectionAdapterFactoryImpl connAdapterFactory = new ConnectionAdapterFactoryImpl();
final ConnectionFacade connFacade = connAdapterFactory.createConnectionFacade(channel, address, true);
Assert.assertNotNull("Wrong - ConnectionFacade has not created.", connFacade);
- Assert.assertEquals("Wrong - diffrence between channel.isOpen() and ConnectionFacade.isAlive()", channel.isOpen(), connFacade.isAlive());
+ Assert.assertEquals("Wrong - diffrence between channel.isOpen() and ConnectionFacade.isAlive()",
+ channel.isOpen(), connFacade.isAlive());
}
}
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
/**
+ * Unit tests for ConnectionAdapterImp02l.
+ *
* @author madamjak
* @author michal.polkorab
*/
public class ConnectionAdapterImp02lTest {
private static final int RPC_RESPONSE_EXPIRATION = 1;
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
@Mock EchoInput echoInput;
@Mock BarrierInput barrierInput;
private ConnectionAdapterImpl adapter;
private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache;
private OfHeader responseOfCall;
+
/**
- * Initialize mocks
+ * Initialize mocks.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
+
/**
- * Disconnect adapter
+ * Disconnect adapter.
*/
@After
- public void tierDown(){
+ public void tierDown() {
if (adapter != null && adapter.isAlive()) {
adapter.disconnect();
}
}
+
/**
- * Test Rpc Calls
+ * Test Rpc Calls.
*/
@Test
public void testRcp() {
final EmbeddedChannel embChannel = new EmbeddedChannel(new EmbededChannelHandler());
adapter = new ConnectionAdapterImpl(embChannel, InetSocketAddress.createUnresolved("localhost", 9876), true);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(
+ RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
// -- barrier
adapter.barrier(barrierInput);
}
/**
- * Channel Handler for testing
+ * Channel Handler for testing.
* @author madamjak
- *
*/
private class EmbededChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(final ChannelHandlerContext ctx, final Object msg,
final ChannelPromise promise) throws Exception {
responseOfCall = null;
- if(msg instanceof MessageListenerWrapper){
+ if (msg instanceof MessageListenerWrapper) {
final MessageListenerWrapper listener = (MessageListenerWrapper) msg;
final OfHeader ofHeader = listener.getMsg();
responseOfCall = ofHeader;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.TableModInput;
/**
+ * Unit tests for ConnectionAdapterImpl02.
+ *
* @author madamjak
* @author michal.polkorab
*/
public class ConnectionAdapterImpl02Test {
private static final int RPC_RESPONSE_EXPIRATION = 1;
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
@Mock EchoInput echoInput;
@Mock BarrierInput barrierInput;
private ConnectionAdapterImpl adapter;
private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache;
private OfHeader responseOfCall;
+
/**
- * Initialize mocks
+ * Initialize mocks.
*/
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
+
/**
- * Disconnect adapter
+ * Disconnect adapter.
*/
@After
- public void tierDown(){
+ public void tierDown() {
if (adapter != null && adapter.isAlive()) {
adapter.disconnect();
}
}
+
/**
- * Test Rpc Calls
+ * Test Rpc Calls.
*/
@Test
public void testRcp() {
final EmbeddedChannel embChannel = new EmbeddedChannel(new EmbededChannelHandler());
adapter = new ConnectionAdapterImpl(embChannel, InetSocketAddress.createUnresolved("localhost", 9876), true);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(
+ RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
// -- barrier
adapter.barrier(barrierInput);
}
/**
- * Channel Handler for testing
+ * Channel Handler for testing.
* @author madamjak
- *
*/
private class EmbededChannelHandler extends ChannelOutboundHandlerAdapter {
@Override
public void write(final ChannelHandlerContext ctx, final Object msg,
final ChannelPromise promise) throws Exception {
responseOfCall = null;
- if(msg instanceof MessageListenerWrapper){
+ if (msg instanceof MessageListenerWrapper) {
final MessageListenerWrapper listener = (MessageListenerWrapper) msg;
final OfHeader ofHeader = listener.getMsg();
responseOfCall = ofHeader;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
- * Test counters in ConnectionAdapter (at least DS_ENTERED_OFJAVA, DS_FLOW_MODS_ENTERED and US_MESSAGE_PASS counters have to be enabled)
- * @author madamjak
+ * Test counters in ConnectionAdapter (at least DS_ENTERED_OFJAVA, DS_FLOW_MODS_ENTERED and US_MESSAGE_PASS counters
+ * have to be enabled).
*
+ * @author madamjak
*/
public class ConnectionAdapterImplStatisticsTest {
private static final int RPC_RESPONSE_EXPIRATION = 1;
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
@Mock SystemNotificationsListener systemListener;
@Mock ConnectionReadyListener readyListener;
private StatisticsCounters statCounters;
/**
- * Initialize mocks
- * Start counting and reset counters before each test
+ * Initialize mocks.
+ * Start counting and reset counters before each test.
*/
@Before
public void setUp() {
}
/**
- * Disconnect adapter
- * Stop counting after each test
+ * Disconnect adapter.
+ * Stop counting after each test.
*/
@After
- public void tierDown(){
+ public void tierDown() {
if (adapter != null && adapter.isAlive()) {
adapter.disconnect();
}
}
/**
- * Test statistic counter for all rpc calls (counters DS_ENTERED_OFJAVA and DS_FLOW_MODS_ENTERED have to be enabled)
+ * Test statistic counter for all rpc calls (counters DS_ENTERED_OFJAVA and DS_FLOW_MODS_ENTERED have to be
+ * enabled).
*/
@Test
public void testEnterOFJavaCounter() {
- if(!statCounters.isCounterEnabled(CounterEventTypes.DS_ENTERED_OFJAVA)){
+ if (!statCounters.isCounterEnabled(CounterEventTypes.DS_ENTERED_OFJAVA)) {
Assert.fail("Counter " + CounterEventTypes.DS_ENTERED_OFJAVA + " is not enabled");
}
- if(!statCounters.isCounterEnabled(CounterEventTypes.DS_FLOW_MODS_ENTERED)){
+ if (!statCounters.isCounterEnabled(CounterEventTypes.DS_FLOW_MODS_ENTERED)) {
Assert.fail("Counter " + CounterEventTypes.DS_FLOW_MODS_ENTERED + " is not enabled");
}
final EmbeddedChannel embChannel = new EmbeddedChannel(new EmbededChannelHandler());
adapter = new ConnectionAdapterImpl(embChannel, InetSocketAddress.createUnresolved("localhost", 9876), true);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1)
+ .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
adapter.barrier(barrierInput);
embChannel.runPendingTasks();
embChannel.runPendingTasks();
adapter.setAsync(setAsyncInput);
embChannel.runPendingTasks();
- Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl rpc methods", 19, statCounters.getCounter(CounterEventTypes.DS_ENTERED_OFJAVA).getCounterValue());
- Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl flow-mod entered", 1, statCounters.getCounter(CounterEventTypes.DS_FLOW_MODS_ENTERED).getCounterValue());
+ Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl rpc methods", 19,
+ statCounters.getCounter(CounterEventTypes.DS_ENTERED_OFJAVA).getCounterValue());
+ Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl flow-mod entered", 1,
+ statCounters.getCounter(CounterEventTypes.DS_FLOW_MODS_ENTERED).getCounterValue());
adapter.disconnect();
}
/**
- * Test counter for pass messages to consumer (counter US_MESSAGE_PASS has to be enabled)
+ * Test counter for pass messages to consumer (counter US_MESSAGE_PASS has to be enabled).
*/
@Test
public void testMessagePassCounter() {
- if(!statCounters.isCounterEnabled(CounterEventTypes.US_MESSAGE_PASS)){
+ if (!statCounters.isCounterEnabled(CounterEventTypes.US_MESSAGE_PASS)) {
Assert.fail("Counter " + CounterEventTypes.US_MESSAGE_PASS + " is not enabled");
}
when(channel.pipeline()).thenReturn(pipeline);
adapter.setMessageListener(messageListener);
adapter.setSystemListener(systemListener);
adapter.setConnectionReadyListener(readyListener);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1)
+ .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
when(channel.disconnect()).thenReturn(channelFuture);
DataObject message = new EchoRequestMessageBuilder().build();
adapter.consume(message);
message = new EchoRequestMessageBuilder().build();
adapter.consume(message);
- Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl consume method", 9, statCounters.getCounter(CounterEventTypes.US_MESSAGE_PASS).getCounterValue());
+ Assert.assertEquals("Wrong - bad counter value for ConnectionAdapterImpl consume method", 9,
+ statCounters.getCounter(CounterEventTypes.US_MESSAGE_PASS).getCounterValue());
adapter.disconnect();
}
/**
- * Empty channel Handler for testing
+ * Empty channel Handler for testing.
* @author madamjak
- *
*/
private class EmbededChannelHandler extends ChannelOutboundHandlerAdapter {
// no operation need to test
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import org.opendaylight.yangtools.yang.binding.DataObject;
/**
+ * Unit test for ConnectionAdapterImpl.
+ *
* @author michal.polkorab
* @author madamjak
- *
*/
public class ConnectionAdapterImplTest {
private static final int RPC_RESPONSE_EXPIRATION = 1;
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
@Mock SocketChannel channel;
@Mock ChannelPipeline pipeline;
private Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> cache;
/**
- * Initializes ConnectionAdapter
+ * Initializes ConnectionAdapter.
*/
@Before
public void setUp() {
adapter.setMessageListener(messageListener);
adapter.setSystemListener(systemListener);
adapter.setConnectionReadyListener(readyListener);
- cache = CacheBuilder.newBuilder().concurrencyLevel(1).expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES)
- .removalListener(REMOVAL_LISTENER).build();
+ cache = CacheBuilder.newBuilder().concurrencyLevel(1)
+ .expireAfterWrite(RPC_RESPONSE_EXPIRATION, TimeUnit.MINUTES).removalListener(REMOVAL_LISTENER).build();
adapter.setResponseCache(cache);
when(channel.disconnect()).thenReturn(channelFuture);
}
/**
- * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with notifications
+ * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with notifications.
*/
@Test
public void testConsume() {
}
/**
- * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with unexpected rpc
+ * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with unexpected rpc.
*/
@Test
public void testConsume2() {
}
/**
- * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with expected rpc
+ * Tests {@link ConnectionAdapterImpl#consume(DataObject)} with expected rpc.
*/
@Test
public void testConsume3() {
inputBuilder.setVersion((short) EncodeConstants.OF13_VERSION_ID);
inputBuilder.setXid(42L);
final BarrierInput barrierInput = inputBuilder.build();
- final RpcResponseKey key = new RpcResponseKey(42L, "org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput");
+ final RpcResponseKey key = new RpcResponseKey(42L,
+ "org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.BarrierOutput");
final ResponseExpectedRpcListener<OfHeader> listener = new ResponseExpectedRpcListener<>(barrierInput,
"failure", mockCache, key);
cache.put(key, listener);
final ResponseExpectedRpcListener<?> ifPresent = cache.getIfPresent(key);
Assert.assertNull("Listener was not discarded", ifPresent);
}
+
/**
- * Test IsAlive method
+ * Test IsAlive method.
*/
@Test
- public void testIsAlive(){
+ public void testIsAlive() {
final int port = 9876;
- final String host ="localhost";
+ final String host = "localhost";
final InetSocketAddress inetSockAddr = InetSocketAddress.createUnresolved(host, port);
final ConnectionAdapterImpl connAddapter = new ConnectionAdapterImpl(channel, inetSockAddr, true);
- Assert.assertEquals("Wrong - diffrence between channel.isOpen() and ConnectionAdapterImpl.isAlive()", channel.isOpen(), connAddapter.isAlive());
+ Assert.assertEquals("Wrong - diffrence between channel.isOpen() and ConnectionAdapterImpl.isAlive()",
+ channel.isOpen(), connAddapter.isAlive());
connAddapter.disconnect();
Assert.assertFalse("Wrong - ConnectionAdapterImpl can not be alive after disconnet.", connAddapter.isAlive());
}
/**
- * Test throw exception if no listeners are present
+ * Test throw exception if no listeners are present.
*/
@Test(expected = java.lang.IllegalStateException.class)
- public void testMissingListeners(){
+ public void testMissingListeners() {
final int port = 9876;
- final String host ="localhost";
+ final String host = "localhost";
final InetSocketAddress inetSockAddr = InetSocketAddress.createUnresolved(host, port);
final ConnectionAdapterImpl connAddapter = new ConnectionAdapterImpl(channel, inetSockAddr, true);
connAddapter.setSystemListener(null);
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.TransportProtocol;
/**
- * @author michal.polkorab
+ * Test implementation for ConnectionConfiguration.
*
+ * @author michal.polkorab
*/
public class ConnectionConfigurationImpl implements ConnectionConfiguration {
private final boolean isGroupAddModEnabled;
/**
- * Creates {@link ConnectionConfigurationImpl}
- *
- * @param address
- * @param port
- * @param tlsConfig
- * @param switchIdleTimeout
- * @param useBarrier
+ * Creates {@link ConnectionConfigurationImpl}.
*/
public ConnectionConfigurationImpl(final InetAddress address, final int port, final TlsConfiguration tlsConfig,
final long switchIdleTimeout, final boolean useBarrier, final boolean isGroupAddModEnabled) {
}
/**
- * Used for testing - sets transport protocol
- * @param protocol
+ * Used for testing - sets transport protocol.
*/
public void setTransferProtocol(final TransportProtocol protocol) {
this.transferProtocol = protocol;
}
/**
- * @param threadConfig thread model configuration (configures threads used)
+ * Sets the ThreadConfiguration.
+ *
+ * @param config thread model configuration (configures threads used)
*/
- public void setThreadConfiguration(final ThreadConfiguration threadConfig) {
- this.threadConfig = threadConfig;
+ public void setThreadConfiguration(final ThreadConfiguration config) {
+ this.threadConfig = config;
}
@Override
public boolean isGroupAddModEnabled() {
return isGroupAddModEnabled;
}
-}
\ No newline at end of file
+}
import org.junit.Assert;
import org.junit.Test;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.MessageListenerWrapper;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.SimpleRpcListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloInputBuilder;
/**
- * @author michal.polkorab
+ * UNit tests for MessageListenerWrapper.
*
+ * @author michal.polkorab
*/
public class MessageListenerWrapperTest {
/**
- * Test MessageListenerWrapper creation
+ * Test MessageListenerWrapper creation.
*/
@Test
public void test() {
Assert.assertEquals("Wrong message", hello, wrapper.getMsg());
Assert.assertEquals("Wrong listener", listener, wrapper.getListener());
}
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory;
/**
- * {@link OutboundQueueEntry} class test
+ * {@link OutboundQueueEntry} class test.
*/
@RunWith(MockitoJUnitRunner.class)
public class OutboundQueueEntryTest {
private final OutboundQueueEntry outboundQueueEntry = new OutboundQueueEntry();
private final OfHeader barrierInput = new BarrierInputBuilder().setVersion(VERSION).setXid(VALUE).build();
private final OfHeader packetOutInput = new PacketOutInputBuilder().setVersion(VERSION).setXid(VALUE).build();
- private final OfHeader multipartReplyMessage =
- new MultipartReplyMessageBuilder().setVersion(VERSION).setXid(VALUE).setFlags(new MultipartRequestFlags(false)).build();
+ private final OfHeader multipartReplyMessage = new MultipartReplyMessageBuilder().setVersion(VERSION).setXid(VALUE)
+ .setFlags(new MultipartRequestFlags(false)).build();
private final OfHeader flowModInput = new FlowModInputBuilder().setVersion(VERSION).setXid(VALUE).build();
private final OfHeader flowRemoved = new FlowRemovedMessageBuilder().setVersion(VERSION).setXid(VALUE).build();
@Test
public void test() throws Exception {
- final FutureCallback<OfHeader> result =
- new FutureCallback<OfHeader>() {
+ final FutureCallback<OfHeader> result = new FutureCallback<OfHeader>() {
+ @Override
+ public void onSuccess(@Nullable OfHeader header) {
+ LOG.info("onSuccess: xid: {}", header.getXid());
+ }
- @Override
- public void onSuccess(@Nullable OfHeader ofHeader) {
- LOG.info("onSuccess: xid: {}", ofHeader.getXid());
- }
-
- @Override
- public void onFailure(Throwable throwable) {
- LOG.info("onFailure! Error: {}", throwable);
- LOG.info("Failure called {} time", increaseFailCounter());
- }
- };
+ @Override
+ public void onFailure(Throwable throwable) {
+ LOG.info("onFailure! Error: {}", throwable);
+ LOG.info("Failure called {} time", increaseFailCounter());
+ }
+ };
/** This scenario creates entry with XID 1 then commit it, fail it and again commit it */
/** Simulates behavior when entry is committed after fail */
Assert.assertTrue(this.failCounter == 1);
}
-
}
package org.opendaylight.openflowjava.protocol.impl.core.connection;
import static org.junit.Assert.fail;
+
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
-import com.google.common.cache.RemovalNotification;
import com.google.common.util.concurrent.SettableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
/**
- * @author michal.polkorab
+ * Unit tests for ResponseExpectedRpcListener.
*
+ * @author michal.polkorab
*/
public class ResponseExpectedRpcListenerTest {
private static final RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>> REMOVAL_LISTENER =
- new RemovalListener<RpcResponseKey, ResponseExpectedRpcListener<?>>() {
- @Override
- public void onRemoval(
- final RemovalNotification<RpcResponseKey, ResponseExpectedRpcListener<?>> notification) {
- notification.getValue().discard();
- }
- };
+ notification -> notification.getValue().discard();
private static final int RPC_RESPONSE_EXPIRATION = 1;
private final Cache<RpcResponseKey, ResponseExpectedRpcListener<?>> responseCache = CacheBuilder.newBuilder()
.concurrencyLevel(1)
.removalListener(REMOVAL_LISTENER).build();
/**
- * Test object creation
+ * Test object creation.
*/
- @Test(expected=NullPointerException.class)
+ @Test(expected = NullPointerException.class)
public void testCreation() {
RpcResponseKey key = new RpcResponseKey(12345L, BarrierOutput.class.getName());
new ResponseExpectedRpcListener<>("MESSAGE", "Failed to send message", null, key);
}
/**
- * Test object creation
+ * Test object creation.
*/
- @Test(expected=NullPointerException.class)
+ @Test(expected = NullPointerException.class)
public void testCreation2() {
new ResponseExpectedRpcListener<>("MESSAGE", "Failed to send message", responseCache, null);
}
/**
- * Test object creation
+ * Test object creation.
*/
@Test
public void testDiscard() {
}
/**
- * Test object creation
+ * Test object creation.
*/
@Test
public void testCompleted() {
}
/**
- * Test object creation
+ * Test object creation.
*/
@Test
public void testOperationSuccessful() {
ResponseExpectedRpcListener<?> present = responseCache.getIfPresent(key);
Assert.assertEquals(present, listener);
}
-}
\ No newline at end of file
+}
package org.opendaylight.openflowjava.protocol.impl.core.connection;
-import org.junit.Test;
import org.junit.Assert;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.RpcResponseKey;
+import org.junit.Test;
/**
+ * Unit tests for RpcResponseKey.
*
* @author madamjak
- *
*/
public class RpcResponseKeyTest {
/**
- * Test equals (xid is not tested)
+ * Test equals (xid is not tested).
*/
@Test
- public void testEquals(){
+ public void testEquals() {
long xid1 = 12L;
long xid2 = 66L;
- String outputClazz1 = "Clazz01";
+ final String outputClazz1 = "Clazz01";
String outputClazz2 = "Clazz02";
RpcResponseKey key1 = new RpcResponseKey(xid1, null);
RpcResponseKey key2 = new RpcResponseKey(xid2, outputClazz2);
}
/**
- * Test getters
+ * Test getters.
*/
@Test
- public void testGetters(){
+ public void testGetters() {
long xid1 = 12L;
String outputClazz1 = "Clazz01";
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+
import com.google.common.util.concurrent.SettableFuture;
import io.netty.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
/**
- * @author michal.polkorab
+ * UNit tests for SimpleRpcListener.
*
+ * @author michal.polkorab
*/
public class SimpleRpcListenerTest {
@Mock Future<Void> future;
/**
- * Initializes mocks
+ * Initializes mocks.
*/
@Before
public void startUp() {
}
/**
- * Test SimpleRpcListener creation
+ * Test SimpleRpcListener creation.
*/
@Test
public void test() {
}
/**
- * Test rpc success
+ * Test rpc success.
*/
@Test
public void testSuccessfulRpc() {
}
/**
- * Test rpc success
+ * Test rpc success.
*/
@Test
public void testOperationComplete() {
}
/**
- * Test rpc success
+ * Test rpc success.
*/
@Test
public void testOperationComplete2() {
Assert.fail();
}
}
-}
\ No newline at end of file
+}
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.queue.property.header.QueueProperty;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.table.features.properties.grouping.TableFeatureProperties;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
/**
+ * Unit tests for SwitchConnectionProviderImpl02.
+ *
* @author madamjak
* @author michal.polkorab
*/
@Mock OFSerializer<MeterBandExperimenterCase> serializerMeterBandExpCase;
@Mock ConnectionConfigurationImpl config;
private static final int SWITCH_IDLE_TIMEOUT = 2000;
- private InetAddress startupAddress;
private TlsConfiguration tlsConfiguration;
private SwitchConnectionProviderImpl provider;
/**
- * Creates new {@link SwitchConnectionProvider} instance for each test
+ * Creates new {@link SwitchConnectionProvider} instance for each test.
+ *
* @param protocol communication protocol
*/
- public void startUp(final TransportProtocol protocol) {
+ public void startUp(final TransportProtocol protocol) throws UnknownHostException {
MockitoAnnotations.initMocks(this);
config = null;
if (protocol != null) {
provider = new SwitchConnectionProviderImpl(config);
}
- private void createConfig(final TransportProtocol protocol) {
- try {
- startupAddress = InetAddress.getLocalHost();
- } catch (final UnknownHostException e) {
- e.printStackTrace();
- }
+ private void createConfig(final TransportProtocol protocol) throws UnknownHostException {
+ InetAddress startupAddress = InetAddress.getLocalHost();
+
tlsConfiguration = null;
if (protocol.equals(TransportProtocol.TLS)) {
tlsConfiguration = new TlsConfigurationImpl(KeystoreType.JKS,
/**
- * Test getServerFacade
+ * Test getServerFacade.
*/
@Test
- public void testServerFacade(){
+ public void testServerFacade() throws UnknownHostException {
startUp(TransportProtocol.TCP);
final ListenableFuture<Boolean> future = provider.startup();
final ServerFacade serverFacade = provider.getServerFacade();
}
/**
- * Test shutdown on unconfigured provider
+ * Test shutdown on unconfigured provider.
*/
@Test(expected = IllegalStateException.class)
- public void testShutdownUnconfigured(){
+ public void testShutdownUnconfigured() throws UnknownHostException {
startUp(TransportProtocol.TCP);
provider.shutdown();
}
+
/**
- * Test unregister by wrong key
+ * Test unregister by wrong key.
*/
@Test
- public void testUnregisterWrongKeys(){
+ public void testUnregisterWrongKeys() throws UnknownHostException {
startUp(TransportProtocol.TCP);
final ExperimenterInstructionSerializerKey testSerKey
= new ExperimenterInstructionSerializerKey(EncodeConstants.OF10_VERSION_ID,42L);
}
/**
- * Test register and unregister method
+ * Test register and unregister method.
*/
@Test
- public void testUnregisterExistingKeys(){
+ public void testUnregisterExistingKeys() throws UnknownHostException {
startUp(TransportProtocol.TCP);
// -- registerActionSerializer
final ExperimenterActionSerializerKey key1
= new ExperimenterActionSerializerKey(EncodeConstants.OF10_VERSION_ID, 42L, TestSubType.class);
provider.registerActionSerializer(key1, serializer);
Assert.assertTrue("Wrong -- unregister ActionSerializer", provider.unregisterSerializer(key1));
- Assert.assertFalse("Wrong -- unregister ActionSerializer by not existing key", provider.unregisterSerializer(key1));
+ Assert.assertFalse("Wrong -- unregister ActionSerializer by not existing key",
+ provider.unregisterSerializer(key1));
// -- registerActionDeserializer
final ExperimenterActionDeserializerKey key2
= new ExperimenterActionDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L);
provider.registerActionDeserializer(key2, deserializer);
Assert.assertTrue("Wrong -- unregister ActionDeserializer", provider.unregisterDeserializer(key2));
- Assert.assertFalse("Wrong -- unregister ActionDeserializer by not existing key", provider.unregisterDeserializer(key2));
+ Assert.assertFalse("Wrong -- unregister ActionDeserializer by not existing key",
+ provider.unregisterDeserializer(key2));
// -- registerInstructionSerializer
final ExperimenterInstructionSerializerKey key3
= new ExperimenterInstructionSerializerKey(EncodeConstants.OF10_VERSION_ID,42L);
provider.registerInstructionSerializer(key3, serializer);
Assert.assertTrue("Wrong -- unregister InstructionSerializer", provider.unregisterSerializer(key3));
- Assert.assertFalse("Wrong -- unregister InstructionSerializer by not existing key", provider.unregisterSerializer(key3));
+ Assert.assertFalse("Wrong -- unregister InstructionSerializer by not existing key",
+ provider.unregisterSerializer(key3));
// -- registerInstructionDeserializer
final ExperimenterInstructionDeserializerKey key4
= new ExperimenterInstructionDeserializerKey(EncodeConstants.OF10_VERSION_ID,42L);
provider.registerInstructionDeserializer(key4, deserializer);
Assert.assertTrue("Wrong -- unregister InstructionDeserializer", provider.unregisterDeserializer(key4));
- Assert.assertFalse("Wrong -- unregister InstructionDeserializer by not existing key", provider.unregisterDeserializer(key4));
+ Assert.assertFalse("Wrong -- unregister InstructionDeserializer by not existing key",
+ provider.unregisterDeserializer(key4));
// -- registerMatchEntryDeserializer
final MatchEntryDeserializerKey key5
= new MatchEntryDeserializerKey(EncodeConstants.OF10_VERSION_ID, 0x8000, 42);
provider.registerMatchEntryDeserializer(key5, deserializer);
Assert.assertTrue("Wrong -- unregister MatchEntryDeserializer", provider.unregisterDeserializer(key5));
- Assert.assertFalse("Wrong -- unregister MatchEntryDeserializer by not existing key", provider.unregisterDeserializer(key5));
+ Assert.assertFalse("Wrong -- unregister MatchEntryDeserializer by not existing key",
+ provider.unregisterDeserializer(key5));
// -- registerErrorDeserializer
final ExperimenterIdDeserializerKey key6
= new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, ErrorMessage.class);
provider.registerErrorDeserializer(key6, deserializerError);
Assert.assertTrue("Wrong -- unregister ErrorDeserializer", provider.unregisterDeserializer(key6));
- Assert.assertFalse("Wrong -- unregister ErrorDeserializer by not existing key", provider.unregisterDeserializer(key6));
+ Assert.assertFalse("Wrong -- unregister ErrorDeserializer by not existing key",
+ provider.unregisterDeserializer(key6));
// -- registerExperimenterMessageDeserializer
final ExperimenterIdDeserializerKey key7
= new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, ExperimenterMessage.class);
provider.registerExperimenterMessageDeserializer(key7, deserializerExpMsg);
Assert.assertTrue("Wrong -- unregister ExperimenterMessageDeserializer", provider.unregisterDeserializer(key7));
- Assert.assertFalse("Wrong -- unregister ExperimenterMessageDeserializer by not existing key", provider.unregisterDeserializer(key7));
+ Assert.assertFalse("Wrong -- unregister ExperimenterMessageDeserializer by not existing key",
+ provider.unregisterDeserializer(key7));
// -- registerMultipartReplyMessageDeserializer
final ExperimenterIdDeserializerKey key8
= new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, MultipartReplyMessage.class);
provider.registerMultipartReplyMessageDeserializer(key8, deserializerMultipartRplMsg);
- Assert.assertTrue("Wrong -- unregister MultipartReplyMessageDeserializer", provider.unregisterDeserializer(key8));
- Assert.assertFalse("Wrong -- unregister MultipartReplyMessageDeserializer by not existing key", provider.unregisterDeserializer(key8));
+ Assert.assertTrue("Wrong -- unregister MultipartReplyMessageDeserializer",
+ provider.unregisterDeserializer(key8));
+ Assert.assertFalse("Wrong -- unregister MultipartReplyMessageDeserializer by not existing key",
+ provider.unregisterDeserializer(key8));
// -- registerMultipartReplyTFDeserializer
final ExperimenterIdDeserializerKey key9 =
new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, MultipartReplyMessage.class);
provider.registerMultipartReplyTFDeserializer(key9, deserializer);
Assert.assertTrue("Wrong -- unregister MultipartReplyTFDeserializer", provider.unregisterDeserializer(key9));
- Assert.assertFalse("Wrong -- unregister MultipartReplyTFDeserializer by non existing key", provider.unregisterDeserializer(key9));
+ Assert.assertFalse("Wrong -- unregister MultipartReplyTFDeserializer by non existing key",
+ provider.unregisterDeserializer(key9));
// -- registerQueuePropertyDeserializer
final ExperimenterIdDeserializerKey key10
= new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, QueueProperty.class);
provider.registerQueuePropertyDeserializer(key10, deserializerQueueProperty);
Assert.assertTrue("Wrong -- unregister QueuePropertyDeserializer", provider.unregisterDeserializer(key10));
- Assert.assertFalse("Wrong -- unregister QueuePropertyDeserializer by not existing key", provider.unregisterDeserializer(key10));
+ Assert.assertFalse("Wrong -- unregister QueuePropertyDeserializer by not existing key",
+ provider.unregisterDeserializer(key10));
// -- registerMeterBandDeserializer
final ExperimenterIdDeserializerKey key11
= new ExperimenterIdDeserializerKey(EncodeConstants.OF10_VERSION_ID, 42L, MeterBandExperimenterCase.class);
provider.registerMeterBandDeserializer(key11, deserializerMeterBandExpCase);
Assert.assertTrue("Wrong -- unregister MeterBandDeserializer", provider.unregisterDeserializer(key11));
- Assert.assertFalse("Wrong -- unregister MeterBandDeserializer by not existing key", provider.unregisterDeserializer(key11));
+ Assert.assertFalse("Wrong -- unregister MeterBandDeserializer by not existing key",
+ provider.unregisterDeserializer(key11));
// -- registerExperimenterMessageSerializer
ExperimenterIdSerializerKey<ExperimenterDataOfChoice> key12
- = new ExperimenterIdSerializerKey<>(EncodeConstants.OF10_VERSION_ID, 42L, ExperimenterDataOfChoice.class);
+ = new ExperimenterIdSerializerKey<>(EncodeConstants.OF10_VERSION_ID, 42L,
+ ExperimenterDataOfChoice.class);
provider.registerExperimenterMessageSerializer(key12, serializerExperimenterInput);
Assert.assertTrue("Wrong -- unregister ExperimenterMessageSerializer", provider.unregisterSerializer(key12));
- Assert.assertFalse("Wrong -- unregister ExperimenterMessageSerializer by not existing key", provider.unregisterSerializer(key12));
+ Assert.assertFalse("Wrong -- unregister ExperimenterMessageSerializer by not existing key",
+ provider.unregisterSerializer(key12));
//registerMultipartRequestSerializer
ExperimenterIdSerializerKey<ExperimenterDataOfChoice> key13
- = new ExperimenterIdSerializerKey<>(EncodeConstants.OF10_VERSION_ID, 42L, ExperimenterDataOfChoice.class);
+ = new ExperimenterIdSerializerKey<>(EncodeConstants.OF10_VERSION_ID, 42L,
+ ExperimenterDataOfChoice.class);
provider.registerMultipartRequestSerializer(key13, serializerMultipartRequestExpCase);
Assert.assertTrue("Wrong -- unregister MultipartRequestSerializer", provider.unregisterSerializer(key13));
- Assert.assertFalse("Wrong -- unregister MultipartRequestSerializer by not existing key", provider.unregisterSerializer(key13));
+ Assert.assertFalse("Wrong -- unregister MultipartRequestSerializer by not existing key",
+ provider.unregisterSerializer(key13));
// -- registerMultipartRequestTFSerializer
final ExperimenterIdSerializerKey<TableFeatureProperties> key14
= new ExperimenterIdSerializerKey<>(EncodeConstants.OF10_VERSION_ID,42L,TableFeatureProperties.class);
provider.registerMultipartRequestTFSerializer(key14, serializer);
Assert.assertTrue("Wrong -- unregister MultipartRequestTFSerializer", provider.unregisterSerializer(key14));
- Assert.assertFalse("Wrong -- unregister MultipartRequestTFSerializer by not existing key", provider.unregisterSerializer(key14));
+ Assert.assertFalse("Wrong -- unregister MultipartRequestTFSerializer by not existing key",
+ provider.unregisterSerializer(key14));
// -- registerMeterBandSerializer
final ExperimenterIdMeterSubTypeSerializerKey<MeterBandExperimenterCase> key15
- = new ExperimenterIdMeterSubTypeSerializerKey<>(EncodeConstants.OF10_VERSION_ID,42L,MeterBandExperimenterCase.class,null);
+ = new ExperimenterIdMeterSubTypeSerializerKey<>(EncodeConstants.OF10_VERSION_ID,42L,
+ MeterBandExperimenterCase.class,null);
provider.registerMeterBandSerializer(key15, serializerMeterBandExpCase);
Assert.assertTrue("Wrong -- unregister MeterBandSerializer", provider.unregisterSerializer(key15));
- Assert.assertFalse("Wrong -- unregister MeterBandSerializer by not existing key", provider.unregisterSerializer(key15));
+ Assert.assertFalse("Wrong -- unregister MeterBandSerializer by not existing key",
+ provider.unregisterSerializer(key15));
// -- registerMatchEntrySerializer
final MatchEntrySerializerKey<OpenflowBasicClass, InPort> key16
= new MatchEntrySerializerKey<>(EncodeConstants.OF13_VERSION_ID, OpenflowBasicClass.class, InPort.class);
provider.registerMatchEntrySerializer(key16, serializer);
Assert.assertTrue("Wrong -- unregister MatchEntrySerializer", provider.unregisterSerializer(key16));
- Assert.assertFalse("Wrong -- unregister MatchEntrySerializer by not existing key", provider.unregisterSerializer(key15));
+ Assert.assertFalse("Wrong -- unregister MatchEntrySerializer by not existing key",
+ provider.unregisterSerializer(key15));
// -- registerSerializer
final MessageTypeKey key17 = new MessageTypeKey<>(EncodeConstants.OF13_VERSION_ID, TestSubType.class);
provider.registerSerializer(key17, serializer);
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.TransportProtocol;
+import org.slf4j.LoggerFactory;
/**
- * @author michal.polkorab
+ * Unit tests for SwitchConnectionProviderImpl.
*
+ * @author michal.polkorab
*/
public class SwitchConnectionProviderImplTest {
private static final int SWITCH_IDLE_TIMEOUT = 2000;
private static final int WAIT_TIMEOUT = 2000;
- private InetAddress startupAddress;
private TlsConfiguration tlsConfiguration;
private SwitchConnectionProviderImpl provider;
private ConnectionConfigurationImpl config;
/**
- * Creates new {@link SwitchConnectionProvider} instance for each test
+ * Creates new {@link SwitchConnectionProvider} instance for each test.
* @param protocol communication protocol
*/
- public void startUp(final TransportProtocol protocol) {
+ public void startUp(final TransportProtocol protocol) throws UnknownHostException {
MockitoAnnotations.initMocks(this);
config = null;
if (protocol != null) {
provider = new SwitchConnectionProviderImpl(config);
}
- private void createConfig(final TransportProtocol protocol) {
- try {
- startupAddress = InetAddress.getLocalHost();
- } catch (final UnknownHostException e) {
- e.printStackTrace();
- }
+ private void createConfig(final TransportProtocol protocol) throws UnknownHostException {
+ InetAddress startupAddress = InetAddress.getLocalHost();
+
tlsConfiguration = null;
if (protocol.equals(TransportProtocol.TLS)) {
tlsConfiguration = new TlsConfigurationImpl(KeystoreType.JKS,
}
/**
- * Tests provider startup - without configuration and {@link SwitchConnectionHandler}
+ * Tests provider startup - without configuration and {@link SwitchConnectionHandler}.
*/
@Test
public void testStartup1() {
}
/**
- * Tests provider startup - without configuration
+ * Tests provider startup - without configuration.
*/
@Test
- public void testStartup2() {
+ public void testStartup2() throws UnknownHostException {
startUp(null);
provider.setSwitchConnectionHandler(handler);
final ListenableFuture<Boolean> future = provider.startup();
}
/**
- * Tests provider startup - without {@link SwitchConnectionHandler}
+ * Tests provider startup - without {@link SwitchConnectionHandler}.
*/
@Test
- public void testStartup3() {
+ public void testStartup3() throws UnknownHostException {
startUp(TransportProtocol.TCP);
final ListenableFuture<Boolean> future = provider.startup();
try {
}
/**
- * Tests correct provider startup - over TCP
+ * Tests correct provider startup - over TCP.
*/
@Test
- public void testStartup4() {
+ public void testStartup4() throws UnknownHostException {
startUp(TransportProtocol.TCP);
provider.setSwitchConnectionHandler(handler);
try {
}
/**
- * Tests correct provider startup - over TLS
+ * Tests correct provider startup - over TLS.
*/
@Test
- public void testStartup5() {
+ public void testStartup5() throws UnknownHostException {
startUp(TransportProtocol.TLS);
provider.setSwitchConnectionHandler(handler);
try {
}
/**
- * Tests correct provider startup - over UDP
+ * Tests correct provider startup - over UDP.
*/
@Test
- public void testStartup6() {
+ public void testStartup6() throws UnknownHostException {
startUp(TransportProtocol.UDP);
provider.setSwitchConnectionHandler(handler);
try {
} catch (InterruptedException | ExecutionException | TimeoutException e) {
Assert.fail();
}
- }
+ }
/**
- * Tests correct provider shutdown
+ * Tests correct provider shutdown.
*/
@Test
- public void testShutdown() {
+ public void testShutdown() throws UnknownHostException {
startUp(TransportProtocol.TCP);
provider.setSwitchConnectionHandler(handler);
try {
Assert.assertTrue("Failed to start", provider.startup().get(WAIT_TIMEOUT, TimeUnit.MILLISECONDS));
Assert.assertTrue("Failed to stop", provider.shutdown().get(5 * WAIT_TIMEOUT, TimeUnit.MILLISECONDS));
} catch (InterruptedException | ExecutionException | TimeoutException e) {
- e.printStackTrace();
+ LoggerFactory.getLogger(SwitchConnectionProviderImplTest.class).error("Unexpected error", e);
}
}
-}
\ No newline at end of file
+}
import org.slf4j.LoggerFactory;
/**
- * @author madamjak
+ * Unit tests for UdpHandler.
*
+ * @author madamjak
*/
public class UdpHandlerTest {
@Mock
private UdpChannelInitializer udpChannelInitializerMock;
private UdpHandler udpHandler;
+
/**
- * Mock init
+ * Mock init.
*/
@Before
public void startUp() {
}
/**
- * Test to create UdpHandler with empty address and zero port
- * @throws InterruptedException
- * @throws ExecutionException
- * @throws IOException
+ * Test to create UdpHandler with empty address and zero port.
*/
@Test
public void testWithEmptyAddress() throws Exception {
}
/**
- * Test to create UdpHandler with empty address and zero port on Epoll native transport
- * @throws InterruptedException
- * @throws ExecutionException
- * @throws IOException
+ * Test to create UdpHandler with empty address and zero port on Epoll native transport.
*/
@Test
public void testWithEmptyAddressOnEpoll() throws Exception {
}
/**
- * Test to create UdpHandler with fill address and given port
- * @throws InterruptedException
- * @throws ExecutionException
- * @throws IOException
+ * Test to create UdpHandler with fill address and given port.
*/
@Test
- public void testWithAddressAndPort() throws Exception{
+ public void testWithAddressAndPort() throws Exception {
int port = 9874;
udpHandler = new UdpHandler(InetAddress.getLocalHost(), port);
udpHandler.setChannelInitializer(udpChannelInitializerMock);
}
/**
- * Test to create UdpHandler with fill address and given port on Epoll native transport
- * @throws InterruptedException
- * @throws ExecutionException
- * @throws IOException
+ * Test to create UdpHandler with fill address and given port on Epoll native transport.
*/
@Test
public void testWithAddressAndPortOnEpoll() throws Exception {
shutdownServer();
}
- private Boolean startupServer(final boolean isEpollEnabled) throws InterruptedException, IOException, ExecutionException {
+ private Boolean startupServer(final boolean isEpollEnabled)
+ throws InterruptedException, IOException, ExecutionException {
ListenableFuture<Boolean> online = udpHandler.getIsOnlineFuture();
/**
* Test EPoll based native transport if isEpollEnabled is true.
* Else use Nio based transport.
*/
udpHandler.initiateEventLoopGroups(null, isEpollEnabled);
- (new Thread(udpHandler)).start();
+ new Thread(udpHandler).start();
- boolean startedSuccessfully = false;
try {
- startedSuccessfully = online.get(10, TimeUnit.SECONDS);
+ online.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
LOG.warn("Timeout while waiting for UDP handler to start", e);
}
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
-
import java.net.InetSocketAddress;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.opendaylight.openflowjava.protocol.impl.core.connection.UdpMessageListenerWrapper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
/**
+ * Unit tests for UdpMessageListenerWrapper.
*
* @author madamjak
- *
*/
public class UdpMessageListenerWrapperTest {
@Mock OfHeader msg;
@Before
- public void startUp(){
+ public void startUp() {
MockitoAnnotations.initMocks(this);
}
+
/**
- * Getters test
+ * Getters test.
*/
@Test
- public void test(){
+ public void test() {
int port = 9876;
- String host ="localhost";
+ String host = "localhost";
InetSocketAddress inetSockAddr = InetSocketAddress.createUnresolved(host, port);
UdpMessageListenerWrapper wrapper = new UdpMessageListenerWrapper(msg,listener,inetSockAddr);
Assert.assertEquals("Wrong getListener", listener, wrapper.getListener());
Assert.assertEquals("Wrong getMsg", msg, wrapper.getMsg());
}
-
}