Best Easymock code snippet using org.easymock.Capture.reset
Source:OFChannelHandlerVer10Test.java
...3import static org.easymock.EasyMock.createMock;4import static org.easymock.EasyMock.expect;5import static org.easymock.EasyMock.expectLastCall;6import static org.easymock.EasyMock.replay;7import static org.easymock.EasyMock.reset;8import static org.easymock.EasyMock.verify;9import static org.junit.Assert.assertEquals;10import static org.junit.Assert.assertFalse;11import static org.junit.Assert.assertThat;12import static org.junit.Assert.assertTrue;13import java.net.InetSocketAddress;14import java.util.ArrayList;15import java.util.Collections;16import java.util.EnumSet;17import java.util.HashSet;18import java.util.List;19import java.util.Set;20import org.easymock.Capture;21import org.easymock.CaptureType;22import org.easymock.EasyMock;23import org.easymock.IAnswer;24import org.hamcrest.CoreMatchers;25import io.netty.channel.Channel;26import io.netty.channel.ChannelHandlerContext;27import io.netty.channel.ChannelPipeline;28import io.netty.channel.ChannelPromise;29import io.netty.channel.DefaultChannelPromise;30import io.netty.util.HashedWheelTimer;31import io.netty.util.Timer;32import org.junit.After;33import org.junit.Before;34import org.junit.Test;35import net.floodlightcontroller.core.IOFConnectionBackend;36import net.floodlightcontroller.core.internal.OFChannelInitializer.PipelineHandler;37import net.floodlightcontroller.core.internal.OFChannelInitializer.PipelineHandshakeTimeout;38import net.floodlightcontroller.core.test.TestEventLoop;39import net.floodlightcontroller.debugcounter.DebugCounterServiceImpl;40import net.floodlightcontroller.debugcounter.IDebugCounterService;41import org.projectfloodlight.openflow.protocol.OFActionType;42import org.projectfloodlight.openflow.protocol.OFBarrierReply;43import org.projectfloodlight.openflow.protocol.OFCapabilities;44import org.projectfloodlight.openflow.protocol.OFFactories;45import org.projectfloodlight.openflow.protocol.OFFactory;46import org.projectfloodlight.openflow.protocol.OFFeaturesReply;47import org.projectfloodlight.openflow.protocol.OFFlowRemoved;48import org.projectfloodlight.openflow.protocol.OFFlowRemovedReason;49import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;50import org.projectfloodlight.openflow.protocol.OFGetConfigReply;51import org.projectfloodlight.openflow.protocol.OFMessage;52import org.projectfloodlight.openflow.protocol.OFNiciraControllerRole;53import org.projectfloodlight.openflow.protocol.OFNiciraControllerRoleReply;54import org.projectfloodlight.openflow.protocol.OFPacketIn;55import org.projectfloodlight.openflow.protocol.OFPacketInReason;56import org.projectfloodlight.openflow.protocol.OFPortDesc;57import org.projectfloodlight.openflow.protocol.OFPortReason;58import org.projectfloodlight.openflow.protocol.OFPortStatus;59import org.projectfloodlight.openflow.protocol.OFQueueGetConfigReply;60import org.projectfloodlight.openflow.protocol.OFType;61import org.projectfloodlight.openflow.protocol.OFVersion;62import org.projectfloodlight.openflow.types.DatapathId;63import org.projectfloodlight.openflow.types.OFPort;64import org.projectfloodlight.openflow.types.U32;65import com.google.common.base.Throwables;66import com.google.common.collect.ImmutableList;67public class OFChannelHandlerVer10Test {68 private IOFSwitchManager switchManager;69 private IOFConnectionListener connectionListener;70 private IDebugCounterService debugCounterService;71 private OFChannelHandler handler;72 private Channel channel;73 private Timer timer;74 private ChannelHandlerContext ctx;75 private ChannelPipeline pipeline;76 private final OFFactory factory = OFFactories.getFactory(OFVersion.OF_10);77 private Capture<Throwable> exceptionEventCapture;78 private Capture<List<OFMessage>> writeCapture;79 private OFPortDesc portDesc;80 private OFFeaturesReply featuresReply;81 private Set<Long> seenXids = null;82 private INewOFConnectionListener newConnectionListener;83 private Capture<IOFConnectionBackend> newConnection;84 private Capture<OFFeaturesReply> newFeaturesReply;85 86 private TestEventLoop eventLoop;87 public void setUpFeaturesReply() {88 portDesc = factory.buildPortDesc()89 .setName("Eth1")90 .setPortNo(OFPort.of(1))91 .build();92 featuresReply = factory.buildFeaturesReply()93 .setDatapathId(DatapathId.of(0x42L))94 .setNBuffers(1)95 .setNTables((short)1)96 .setCapabilities(EnumSet.<OFCapabilities>of(OFCapabilities.FLOW_STATS, OFCapabilities.TABLE_STATS))97 .setActions(EnumSet.<OFActionType>of(OFActionType.SET_VLAN_PCP))98 .setPorts(ImmutableList.<OFPortDesc>of(portDesc))99 .build();100 }101 @Before102 public void setUp() throws Exception {103 setUpFeaturesReply();104 switchManager = createMock(IOFSwitchManager.class);105 connectionListener = createMock(IOFConnectionListener.class);106 newConnectionListener = createMock(INewOFConnectionListener.class);107 newConnection = EasyMock.newCapture();108 newFeaturesReply = EasyMock.newCapture();109 eventLoop = new TestEventLoop();110 ctx = createMock(ChannelHandlerContext.class);111 channel = createMock(Channel.class);112 timer = new HashedWheelTimer();113 exceptionEventCapture = EasyMock.newCapture(CaptureType.ALL);114 pipeline = createMock(ChannelPipeline.class);115 writeCapture = EasyMock.newCapture(CaptureType.ALL);116 seenXids = null;117 // TODO: should mock IDebugCounterService and make sure118 // the expected counters are updated.119 debugCounterService = new DebugCounterServiceImpl();120 debugCounterService.registerModule(OFConnectionCounters.COUNTER_MODULE);121 SwitchManagerCounters counters =122 new SwitchManagerCounters(debugCounterService);123 expect(switchManager.getCounters()).andReturn(counters).anyTimes();124 replay(switchManager);125 handler = new OFChannelHandler(switchManager, newConnectionListener,126 pipeline, debugCounterService,127 timer, Collections.singletonList(U32.of(0)), OFFactories.getFactory(OFVersion.OF_14));128 verify(switchManager);129 reset(switchManager);130 resetChannel();131 // replay controller. Reset it if you need more specific behavior132 replay(switchManager);133 // Mock ctx and channelStateEvent134 expect(ctx.channel()).andReturn(channel).anyTimes();135 expect(ctx.fireExceptionCaught(capture(exceptionEventCapture))).andReturn(ctx).anyTimes();136 replay(ctx);137 /* Setup an exception event capture on the channel. Right now138 * we only expect exception events to be send up the channel.139 * However, it's easy to extend to other events if we need it140 */141 expect(pipeline.get(OFMessageDecoder.class)).andReturn(new OFMessageDecoder()).anyTimes();142 replay(pipeline);143 }144 @After145 public void tearDown() {146 /* ensure no exception was thrown */147 if (exceptionEventCapture.hasCaptured()) {148 Throwable ex = exceptionEventCapture.getValue();149 ex.printStackTrace();150 Throwables.propagate(ex);151 }152 assertFalse("Unexpected messages have been captured",153 writeCapture.hasCaptured());154 // verify all mocks.155 verify(channel);156 verify(switchManager);157 verify(ctx);158 verify(pipeline);159 }160 /** Reset the channel mock and set basic method call expectations */161 void resetChannel() {162 reset(channel);163 expect(channel.newPromise()).andAnswer(new IAnswer<ChannelPromise>() {164 @Override165 public ChannelPromise answer() throws Throwable {166 return new DefaultChannelPromise(channel);167 }168 }).anyTimes();169 eventLoop = new TestEventLoop();170 expect(channel.eventLoop()).andReturn(eventLoop).anyTimes();171 expect(channel.pipeline()).andReturn(pipeline).anyTimes();172 expect(channel.remoteAddress()).andReturn(InetSocketAddress.createUnresolved("1.1.1.1", 80)).anyTimes();173 }174 /** reset, setup, and replay the messageEvent mock for the given175 * messages, mock controller send message to channel handler176 *177 * This method will reset, start replay on controller, and then verify178 */179 void sendMessageToHandlerWithControllerReset(List<OFMessage> messages)180 throws Exception {181 sendMessageToHandlerNoControllerReset(messages);182 }183 /** reset, setup, and replay the messageEvent mock for the given184 * messages, mock controller send message to channel handler185 *186 * This method will start replay on controller, and then verify187 */188 void sendMessageToHandlerNoControllerReset(List<OFMessage> messages)189 throws Exception {190 handler.channelRead(ctx, messages);191 }192 /**193 * Extract the list of OFMessages that was captured by the Channel.write()194 * capture. Will check that something was actually captured first. We'll195 * collapse the messages from multiple writes into a single list of196 * OFMessages.197 * Resets the channelWriteCapture.198 */199 List<OFMessage> getMessagesFromCapture() {200 List<OFMessage> msgs = new ArrayList<OFMessage>();201 assertTrue("No write on channel was captured",202 writeCapture.hasCaptured());203 List<List<OFMessage>> capturedVals = writeCapture.getValues();204 for (List<OFMessage> oneWriteList: capturedVals)205 msgs.addAll(oneWriteList);206 writeCapture.reset();207 return msgs;208 }209 /**210 * Verify that the given exception event capture (as returned by211 * getAndInitExceptionCapture) has thrown an exception of the given212 * expectedExceptionClass.213 * Resets the capture214 */215 void verifyExceptionCaptured(216 Class<? extends Throwable> expectedExceptionClass) {217 assertTrue("Excpected exception not thrown",218 exceptionEventCapture.hasCaptured());219 Throwable caughtEx = exceptionEventCapture.getValue();220 assertEquals(expectedExceptionClass, caughtEx.getClass());221 exceptionEventCapture.reset();222 }223 /** make sure that the transaction ids in the given messages are224 * not 0 and differ between each other.225 * While it's not a defect per se if the xids are we want to ensure226 * we use different ones for each message we send.227 */228 void verifyUniqueXids(List<OFMessage> msgs) {229 if (seenXids == null)230 seenXids = new HashSet<Long>();231 for (OFMessage m: msgs) {232 long xid = m.getXid();233 assertTrue("Xid in messags is 0", xid != 0);234 assertFalse("Xid " + xid + " has already been used",235 seenXids.contains(xid));236 seenXids.add(xid);237 }238 }239 240 @Test241 public void testNullMsg() throws Exception {242 reset(ctx);243 expect(ctx.fireChannelRead(null)).andReturn(ctx).once();244 replay(ctx, channel);245 246 // null message is not passed to the handler247 handler.channelRead(ctx, null);248 verify(channel, ctx);249 }250 @Test251 public void testInitState() throws Exception {252 replay(channel);253 // We don't expect to receive /any/ messages in init state since254 // channelConnected moves us to a different state255 OFMessage m = factory.buildHello().build();256 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(m));257 verifyExceptionCaptured(SwitchStateException.class);258 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.InitState.class));259 }260 /* Move the channel from scratch to WAIT_HELLO state */261 @Test262 public void moveToWaitHello() throws Exception {263 resetChannel();264 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).once();265 replay(channel);266 handler.channelActive(ctx);267 List<OFMessage> msgs = getMessagesFromCapture();268 assertEquals(1, msgs.size());269 assertEquals(OFType.HELLO, msgs.get(0).getType());270 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitHelloState.class));271 verifyUniqueXids(msgs);272 }273 /** Move the channel from scratch to WAIT_FEATURES_REPLY state274 * Builds on moveToWaitHello()275 * adds testing for WAIT_HELLO state276 */277 @Test278 public void moveToWaitFeaturesReply() throws Exception {279 moveToWaitHello();280 resetChannel();281 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).atLeastOnce();282 replay(channel);283 OFMessage hello = factory.buildHello().build();284 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(hello));285 List<OFMessage> msgs = getMessagesFromCapture();286 assertEquals(1, msgs.size());287 assertEquals(OFType.FEATURES_REQUEST, msgs.get(0).getType());288 verifyUniqueXids(msgs);289 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitFeaturesReplyState.class));290 }291 /** Move the channel from scratch to WAIT_FEATURES_REPLY state292 * Builds on moveToWaitHello()293 * adds testing for WAIT_HELLO state294 */295 @Test296 public void moveToComplete() throws Exception {297 moveToWaitFeaturesReply();298 reset(pipeline);299 HandshakeTimeoutHandler newHandler = new HandshakeTimeoutHandler(300 handler,301 timer,302 PipelineHandshakeTimeout.SWITCH);303 expect(304 pipeline.replace(EasyMock.eq(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT),305 EasyMock.eq(PipelineHandler.SWITCH_HANDSHAKE_TIMEOUT),306 EasyMock.anyObject(HandshakeTimeoutHandler.class))).andReturn(newHandler)307 .once();308 replay(pipeline);309 reset(newConnectionListener);310 newConnectionListener.connectionOpened(capture(newConnection), capture(newFeaturesReply));311 expectLastCall().once();312 replay(newConnectionListener);313 sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(featuresReply));314 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.CompleteState.class));315 assertTrue("A connection has been created and set", handler.getConnectionForTesting() != null);316 }317 /**318 * Test dispatch of messages while in Complete state319 */320 @Test321 public void testMessageDispatchComplete() throws Exception {322 moveToComplete();323 newConnection.getValue().setListener(connectionListener);324 resetChannel();325 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).atLeastOnce();326 replay(channel);327 // Send echo request. expect reply328 OFMessage echoRequest = factory.buildEchoRequest().build();329 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(echoRequest));330 List<OFMessage> msgs = getMessagesFromCapture();331 assertEquals(1, msgs.size());332 assertEquals(OFType.ECHO_REPLY, msgs.get(0).getType());333 // Send barrier reply. expect dispatch334 OFBarrierReply barrierReply = factory.buildBarrierReply()335 .build();336 resetAndExpectConnectionListener(barrierReply);337 // Send packet in. expect dispatch338 OFFlowRemoved flowRemoved = factory.buildFlowRemoved().setReason(OFFlowRemovedReason.DELETE)339 .build();340 resetAndExpectConnectionListener(flowRemoved);341 // Send get config reply. expect dispatch342 OFGetConfigReply getConfigReply = factory.buildGetConfigReply()343 .build();344 resetAndExpectConnectionListener(getConfigReply);345 // Send packet in. expect dispatch346 OFPacketIn pi = factory.buildPacketIn()347 .setReason(OFPacketInReason.NO_MATCH)348 .build();349 resetAndExpectConnectionListener(pi);350 // Send port status. expect dispatch351 OFPortStatus portStatus = factory.buildPortStatus()352 .setReason(OFPortReason.DELETE)353 .setDesc(portDesc)354 .build();355 resetAndExpectConnectionListener(portStatus);356 // Send queue reply. expect dispatch357 OFQueueGetConfigReply queueReply = factory.buildQueueGetConfigReply()358 .build();359 resetAndExpectConnectionListener(queueReply);360 // Send stat reply. expect dispatch361 OFFlowStatsReply statReply = factory.buildFlowStatsReply()362 .build();363 resetAndExpectConnectionListener(statReply);364 // Send role reply. expect dispatch365 OFNiciraControllerRoleReply roleReply = factory.buildNiciraControllerRoleReply()366 .setRole(OFNiciraControllerRole.ROLE_MASTER)367 .build();368 resetAndExpectConnectionListener(roleReply);369 }370 public void resetAndExpectConnectionListener(OFMessage m) throws Exception{371 reset(connectionListener);372 connectionListener.messageReceived(handler.getConnectionForTesting(), m);373 expectLastCall().once();374 replay(connectionListener);375 sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(m));376 verify(connectionListener);377 }378}...
Source:OFChannelHandlerVer13Test.java
...3import static org.easymock.EasyMock.createMock;4import static org.easymock.EasyMock.expect;5import static org.easymock.EasyMock.expectLastCall;6import static org.easymock.EasyMock.replay;7import static org.easymock.EasyMock.reset;8import static org.easymock.EasyMock.verify;9import static org.hamcrest.CoreMatchers.equalTo;10import static org.junit.Assert.assertEquals;11import static org.junit.Assert.assertFalse;12import static org.junit.Assert.assertThat;13import static org.junit.Assert.assertTrue;14import java.util.ArrayList;15import java.util.Collections;16import java.util.EnumSet;17import java.util.HashSet;18import java.util.List;19import java.util.Set;20import org.easymock.Capture;21import org.easymock.CaptureType;22import org.easymock.EasyMock;23import org.easymock.IAnswer;24import org.hamcrest.CoreMatchers;25import io.netty.channel.Channel;26import io.netty.channel.ChannelHandlerContext;27import io.netty.channel.ChannelPipeline;28import io.netty.channel.ChannelPromise;29import io.netty.channel.DefaultChannelPromise;30import io.netty.util.HashedWheelTimer;31import io.netty.util.Timer;32import org.junit.After;33import org.junit.Before;34import org.junit.Test;35import net.floodlightcontroller.core.IOFConnectionBackend;36import net.floodlightcontroller.core.internal.OFChannelInitializer.PipelineHandler;37import net.floodlightcontroller.core.internal.OFChannelInitializer.PipelineHandshakeTimeout;38import net.floodlightcontroller.core.test.TestEventLoop;39import net.floodlightcontroller.debugcounter.DebugCounterServiceImpl;40import net.floodlightcontroller.debugcounter.IDebugCounterService;41import org.projectfloodlight.openflow.protocol.OFBarrierReply;42import org.projectfloodlight.openflow.protocol.OFBsnSetAuxCxnsReply;43import org.projectfloodlight.openflow.protocol.OFCapabilities;44import org.projectfloodlight.openflow.protocol.OFControllerRole;45import org.projectfloodlight.openflow.protocol.OFFactories;46import org.projectfloodlight.openflow.protocol.OFFactory;47import org.projectfloodlight.openflow.protocol.OFFeaturesReply;48import org.projectfloodlight.openflow.protocol.OFFlowRemoved;49import org.projectfloodlight.openflow.protocol.OFFlowRemovedReason;50import org.projectfloodlight.openflow.protocol.OFFlowStatsReply;51import org.projectfloodlight.openflow.protocol.OFGetConfigReply;52import org.projectfloodlight.openflow.protocol.OFMessage;53import org.projectfloodlight.openflow.protocol.OFPacketIn;54import org.projectfloodlight.openflow.protocol.OFPacketInReason;55import org.projectfloodlight.openflow.protocol.OFPortDesc;56import org.projectfloodlight.openflow.protocol.OFPortReason;57import org.projectfloodlight.openflow.protocol.OFPortStatus;58import org.projectfloodlight.openflow.protocol.OFQueueGetConfigReply;59import org.projectfloodlight.openflow.protocol.OFRoleReply;60import org.projectfloodlight.openflow.protocol.OFType;61import org.projectfloodlight.openflow.protocol.OFVersion;62import org.projectfloodlight.openflow.types.DatapathId;63import org.projectfloodlight.openflow.types.OFAuxId;64import org.projectfloodlight.openflow.types.OFPort;65import org.projectfloodlight.openflow.types.U32;66import com.google.common.base.Throwables;67import com.google.common.collect.ImmutableList;68public class OFChannelHandlerVer13Test {69 private static final DatapathId dpid = DatapathId.of(0x42L);70 private IOFSwitchManager switchManager;71 private IOFConnectionListener connectionListener;72 private INewOFConnectionListener newConnectionListener;73 private IDebugCounterService debugCounterService;74 private OFChannelHandler handler;75 private Channel channel;76 private Timer timer;77 private ChannelHandlerContext ctx;78 private ChannelPipeline pipeline;79 private final OFFactory factory = OFFactories.getFactory(OFVersion.OF_13);80 private Capture<Throwable> exceptionEventCapture;81 private Capture<List<OFMessage>> writeCapture;82 private OFFeaturesReply featuresReply;83 private OFPortDesc portDesc;84 private Set<Long> seenXids = null;85 private Capture<IOFConnectionBackend> newConnection;86 private Capture<OFFeaturesReply> newFeaturesReply;87 private TestEventLoop eventLoop;88 public void setUpFeaturesReply() {89 portDesc = factory.buildPortDesc()90 .setName("Eth1")91 .setPortNo(OFPort.of(1))92 .build();93 featuresReply = factory.buildFeaturesReply()94 .setDatapathId(dpid)95 .setNBuffers(1)96 .setNTables((short)1)97 .setCapabilities(EnumSet.<OFCapabilities>of(OFCapabilities.FLOW_STATS, OFCapabilities.TABLE_STATS))98 .setAuxiliaryId(OFAuxId.MAIN)99 .build();100 }101 @Before102 public void setUp() throws Exception {103 setUpFeaturesReply();104 switchManager = createMock(IOFSwitchManager.class);105 connectionListener = createMock(IOFConnectionListener.class);106 newConnectionListener = createMock(INewOFConnectionListener.class);107 newConnection = EasyMock.newCapture();108 newFeaturesReply = EasyMock.newCapture();109 eventLoop = new TestEventLoop();110 ctx = createMock(ChannelHandlerContext.class);111 channel = createMock(Channel.class);112 timer = new HashedWheelTimer();113 exceptionEventCapture = EasyMock.newCapture(CaptureType.ALL);114 pipeline = createMock(ChannelPipeline.class);115 writeCapture = EasyMock.newCapture(CaptureType.ALL);116 seenXids = null;117 // TODO: should mock IDebugCounterService and make sure118 // the expected counters are updated.119 debugCounterService = new DebugCounterServiceImpl();120 debugCounterService.registerModule(OFConnectionCounters.COUNTER_MODULE);121 SwitchManagerCounters counters =122 new SwitchManagerCounters(debugCounterService);123 expect(switchManager.getCounters()).andReturn(counters).anyTimes();124 replay(switchManager);125 handler = new OFChannelHandler(switchManager, newConnectionListener,126 pipeline, debugCounterService, /* 62 is OF versions 1.0 thru 1.4 in decimal */127 timer, Collections.singletonList(U32.of(62)), OFFactories.getFactory(OFVersion.OF_14));128 verify(switchManager);129 reset(switchManager);130 resetChannel();131 // replay controller. Reset it if you need more specific behavior132 replay(switchManager);133 // Mock ctx and channelStateEvent134 expect(ctx.channel()).andReturn(channel).anyTimes();135 expect(ctx.fireExceptionCaught(capture(exceptionEventCapture))).andReturn(ctx).anyTimes();136 replay(ctx);137 /* Setup an exception event capture on the channel. Right now138 * we only expect exception events to be send up the channel.139 * However, it's easy to extend to other events if we need it140 */141 expect(pipeline.get(OFMessageDecoder.class)).andReturn(new OFMessageDecoder()).anyTimes();142 replay(pipeline);143 }144 @After145 public void tearDown() {146 /* ensure no exception was thrown */147 if (exceptionEventCapture.hasCaptured()) {148 Throwable ex = exceptionEventCapture.getValue();149 ex.printStackTrace();150 Throwables.propagate(ex);151 }152 assertFalse("Unexpected messages have been captured",153 writeCapture.hasCaptured());154 // verify all mocks.155 verify(channel);156 verify(switchManager);157 verify(ctx);158 verify(pipeline);159 }160 /** Reset the channel mock and set basic method call expectations */161 void resetChannel() {162 reset(channel);163 expect(channel.newPromise()).andAnswer(new IAnswer<ChannelPromise>() {164 @Override165 public ChannelPromise answer() throws Throwable {166 return new DefaultChannelPromise(channel);167 }168 }).anyTimes();169 eventLoop = new TestEventLoop();170 expect(channel.eventLoop()).andReturn(eventLoop).anyTimes();171 expect(channel.pipeline()).andReturn(pipeline).anyTimes();172 expect(channel.remoteAddress()).andReturn(null).anyTimes();173 }174 /** reset, setup, and replay the messageEvent mock for the given175 * messages, mock controller send message to channel handler176 *177 * This method will reset, start replay on controller, and then verify178 */179 void sendMessageToHandlerWithControllerReset(List<OFMessage> messages)180 throws Exception {181 sendMessageToHandlerNoControllerReset(messages);182 }183 /** reset, setup, and replay the messageEvent mock for the given184 * messages, mock controller send message to channel handler185 *186 * This method will start replay on controller, and then verify187 */188 void sendMessageToHandlerNoControllerReset(List<OFMessage> messages)189 throws Exception {190 handler.channelRead(ctx, messages);191 }192 /**193 * Extract the list of OFMessages that was captured by the Channel.write()194 * capture. Will check that something was actually captured first. We'll195 * collapse the messages from multiple writes into a single list of196 * OFMessages.197 * Resets the channelWriteCapture.198 */199 List<OFMessage> getMessagesFromCapture() {200 List<OFMessage> msgs = new ArrayList<OFMessage>();201 assertTrue("No write on channel was captured",202 writeCapture.hasCaptured());203 List<List<OFMessage>> capturedVals = writeCapture.getValues();204 for (List<OFMessage> oneWriteList: capturedVals)205 msgs.addAll(oneWriteList);206 writeCapture.reset();207 return msgs;208 }209 /**210 * Verify that the given exception event capture (as returned by211 * getAndInitExceptionCapture) has thrown an exception of the given212 * expectedExceptionClass.213 * Resets the capture214 */215 void verifyExceptionCaptured(Class<? extends Throwable> expectedExceptionClass) {216 assertTrue("Excpected exception not thrown", exceptionEventCapture.hasCaptured());217 Throwable caughtEx = exceptionEventCapture.getValue();218 assertEquals(expectedExceptionClass, caughtEx.getClass());219 exceptionEventCapture.reset();220 }221 /** make sure that the transaction ids in the given messages are222 * not 0 and differ between each other.223 * While it's not a defect per se if the xids are we want to ensure224 * we use different ones for each message we send.225 */226 void verifyUniqueXids(List<OFMessage> msgs) {227 if (seenXids == null)228 seenXids = new HashSet<Long>();229 for (OFMessage m: msgs) {230 long xid = m.getXid();231 assertTrue("Xid in messags is 0", xid != 0);232 assertFalse("Xid " + xid + " has already been used",233 seenXids.contains(xid));234 seenXids.add(xid);235 }236 }237 @Test238 public void testNullMsg() throws Exception {239 reset(ctx);240 expect(ctx.fireChannelRead(null)).andReturn(ctx).once();241 replay(ctx, channel);242 // null message is not passed to the handler243 handler.channelRead(ctx, null);244 verify(channel, ctx);245 }246 @Test247 public void testInitState() throws Exception {248 replay(channel);249 // We don't expect to receive /any/ messages in init state since250 // channelConnected moves us to a different state251 OFMessage m = factory.buildHello().build();252 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(m));253 verifyExceptionCaptured(SwitchStateException.class);254 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.InitState.class));255 }256 /* Move the channel from scratch to WAIT_HELLO state */257 @Test258 public void moveToWaitHello() throws Exception {259 resetChannel();260 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).once();261 replay(channel);262 handler.channelActive(ctx);263 eventLoop.runTasks();264 List<OFMessage> msgs = getMessagesFromCapture();265 assertEquals(1, msgs.size());266 assertEquals(OFType.HELLO, msgs.get(0).getType());267 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitHelloState.class));268 verifyUniqueXids(msgs);269 }270 /** Move the channel from scratch to WAIT_FEATURES_REPLY state271 * Builds on moveToWaitHello()272 * adds testing for WAIT_HELLO state273 */274 @Test275 public void moveToWaitFeaturesReply() throws Exception {276 moveToWaitHello();277 resetChannel();278 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).once();279 replay(channel);280 OFMessage hello = factory.buildHello().build();281 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(hello));282 List<OFMessage> msgs = getMessagesFromCapture();283 assertEquals(1, msgs.size());284 assertEquals(OFType.FEATURES_REQUEST, msgs.get(0).getType());285 verifyUniqueXids(msgs);286 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.WaitFeaturesReplyState.class));287 }288 /** Move the channel from scratch to WAIT_FEATURES_REPLY state289 * Builds on moveToWaitHello()290 * adds testing for WAIT_HELLO state291 */292 @Test293 public void moveToComplete() throws Exception {294 moveToWaitFeaturesReply();295 reset(pipeline);296 HandshakeTimeoutHandler newHandler = new HandshakeTimeoutHandler(297 handler,298 timer,299 PipelineHandshakeTimeout.SWITCH);300 expect(301 pipeline.replace(EasyMock.eq(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT),302 EasyMock.eq(PipelineHandler.SWITCH_HANDSHAKE_TIMEOUT),303 EasyMock.anyObject(HandshakeTimeoutHandler.class))).andReturn(newHandler)304 .once();305 replay(pipeline);306 newConnectionListener.connectionOpened(capture(newConnection), capture(newFeaturesReply));307 expectLastCall().once();308 replay(newConnectionListener);309 sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(featuresReply));310 assertThat(handler.getStateForTesting(), CoreMatchers.instanceOf(OFChannelHandler.CompleteState.class));311 assertTrue("A connection has been created and set", handler.getConnectionForTesting() != null);312 verify(newConnectionListener);313 assertTrue(newConnection.hasCaptured());314 assertThat(newFeaturesReply.getValue(), equalTo(featuresReply));315 }316 /**317 * Test dispatch of messages while in Complete state318 */319 @Test320 public void testMessageDispatchComplete() throws Exception {321 moveToComplete();322 newConnection.getValue().setListener(connectionListener);323 resetChannel();324 expect(channel.writeAndFlush(capture(writeCapture))).andReturn(null).once();325 replay(channel);326 // Send echo request. expect reply327 OFMessage echoRequest = factory.buildEchoRequest().build();328 sendMessageToHandlerWithControllerReset(ImmutableList.<OFMessage>of(echoRequest));329 List<OFMessage> msgs = getMessagesFromCapture();330 assertEquals(1, msgs.size());331 assertEquals(OFType.ECHO_REPLY, msgs.get(0).getType());332 // Send barrier reply. expect dispatch333 OFBarrierReply barrierReply = factory.buildBarrierReply()334 .build();335 resetAndExpectConnectionListener(barrierReply);336 // Send packet in. expect dispatch337 OFFlowRemoved flowRemoved = factory.buildFlowRemoved()338 .setReason(OFFlowRemovedReason.DELETE)339 .build();340 resetAndExpectConnectionListener(flowRemoved);341 // Send get config reply. expect dispatch342 OFGetConfigReply getConfigReply = factory.buildGetConfigReply()343 .build();344 resetAndExpectConnectionListener(getConfigReply);345 // Send packet in. expect dispatch346 OFPacketIn pi = factory.buildPacketIn()347 .setReason(OFPacketInReason.NO_MATCH)348 .build();349 resetAndExpectConnectionListener(pi);350 // Send port status. expect dispatch351 OFPortStatus portStatus = factory.buildPortStatus()352 .setReason(OFPortReason.DELETE)353 .setDesc(portDesc)354 .build();355 resetAndExpectConnectionListener(portStatus);356 // Send queue reply. expect dispatch357 OFQueueGetConfigReply queueReply = factory.buildQueueGetConfigReply()358 .build();359 resetAndExpectConnectionListener(queueReply);360 // Send stat reply. expect dispatch361 OFFlowStatsReply statReply = factory.buildFlowStatsReply()362 .build();363 resetAndExpectConnectionListener(statReply);364 // Send role reply. expect dispatch365 OFRoleReply roleReply = factory.buildRoleReply()366 .setRole(OFControllerRole.ROLE_MASTER)367 .build();368 resetAndExpectConnectionListener(roleReply);369 // Send experimenter. expect dispatch370 OFBsnSetAuxCxnsReply auxReply = factory.buildBsnSetAuxCxnsReply()371 .build();372 resetAndExpectConnectionListener(auxReply);373 }374 public void resetAndExpectConnectionListener(OFMessage m) throws Exception{375 reset(connectionListener);376 connectionListener.messageReceived(handler.getConnectionForTesting(), m);377 expectLastCall().once();378 replay(connectionListener);379 sendMessageToHandlerWithControllerReset(Collections.<OFMessage>singletonList(m));380 verify(connectionListener);381 }382}...
reset
Using AI Code Generation
1package org.easymock.examples;2import static org.easymock.EasyMock.capture;3import static org.easymock.EasyMock.expect;4import static org.easymock.EasyMock.replay;5import static org.easymock.EasyMock.verify;6import java.util.List;7import org.easymock.Capture;8import org.easymock.EasyMock;9import org.junit.Test;10public class Example1 {11 public void test() {12 List<String> list = EasyMock.createMock(List.class);13 Capture<String> capture = new Capture<String>();14 expect(list.add(capture(capture))).andReturn(true);15 replay(list);16 list.add("one");17 list.add("two");18 verify(list);19 System.out.println(capture.getValue());20 }21}22package org.easymock.examples;23import static org.easymock.EasyMock.capture;24import static org.easymock.EasyMock.expect;25import static org.easymock.EasyMock.replay;26import static org.easymock.EasyMock.verify;27import java.util.List;28import org.easymock.Capture;29import org.easymock.EasyMock;30import org.junit.Test;31public class Example2 {32 public void test() {33 List<String> list = EasyMock.createMock(List.class);34 Capture<String> capture = new Capture<String>();35 expect(list.add(capture(capture))).andReturn(true);36 replay(list);37 list.add("one");38 list.add("two");39 verify(list);40 System.out.println(capture.getValue());41 }42}43package org.easymock.examples;44import static org.easymock.EasyMock.capture;45import static org.easymock.EasyMock.expect;46import static org.easymock.EasyMock.replay;47import static org.easymock.EasyMock.verify;48import java.util.List;49import org.easymock.Capture;50import org.easymock.EasyMock;51import org.junit.Test;52public class Example3 {53 public void test() {54 List<String> list = EasyMock.createMock(List.class);
reset
Using AI Code Generation
1package org.easymock.examples;2import org.easymock.Capture;3import org.easymock.EasyMock;4import org.easymock.IAnswer;5import org.junit.Test;6import static org.easymock.EasyMock.*;7import static org.junit.Assert.*;8public class Example1 {9 public interface IMethods {10 String doSomething(String s);11 }12 public void test() {13 IMethods mock = createMock(IMethods.class);14 Capture<String> capture = new Capture<String>();15 expect(mock.doSomething(capture(capture))).andAnswer(new IAnswer<String>() {16 public String answer() throws Throwable {17 String s = capture.getValue();18 return s + " World";19 }20 });21 replay(mock);22 assertEquals("Hello World", mock.doSomething("Hello"));23 reset(capture);24 assertEquals("Hello World", mock.doSomething("Hello"));25 verify(mock);26 }27}28package org.easymock.examples;29import org.easymock.Capture;30import org.easymock.EasyMock;31import org.easymock.IAnswer;32import org.junit.Test;33import static org.easymock.EasyMock.*;34import static org.junit.Assert.*;35public class Example2 {36 public interface IMethods {37 String doSomething(String s);38 }39 public void test() {40 IMethods mock = createMock(IMethods.class);41 Capture<String> capture = new Capture<String>();42 expect(mock.doSomething(capture(capture))).andAnswer(new IAnswer<String>() {43 public String answer() throws Throwable {44 String s = capture.getValue();45 return s + " World";46 }47 });48 replay(mock);49 assertEquals("Hello World", mock.doSomething("Hello"));50 capture.setValue("Hi");51 assertEquals("Hi World", mock.doSomething("Hi"));52 verify(mock);53 }54}55package org.easymock.examples;56import org.easymock.Capture;57import org.easymock.EasyMock;58import org.easymock.IAnswer;59import org.junit
reset
Using AI Code Generation
1import org.easymock.Capture;2import org.easymock.EasyMock;3import org.easymock.EasyMockSupport;4import org.easymock.IAnswer;5import org.junit.Test;6import static org.easymock.EasyMock.expect;7import static org.junit.Assert.assertEquals;8public class ResetCaptureTest extends EasyMockSupport {9 public void testResetCapture() {10 Capture<String> capture = Capture.newInstance();11 IAnswer<String> answer = new IAnswer<String>() {12 public String answer() throws Throwable {13 return capture.getValue();14 }15 };16 IAnswer<String> answer2 = new IAnswer<String>() {17 public String answer() throws Throwable {18 return capture.getValue();19 }20 };21 IInterface mock = createMock(IInterface.class);22 expect(mock.method(capture(capture))).andAnswer(answer);23 expect(mock.method(capture(capture))).andAnswer(answer2);24 replayAll();25 assertEquals("foo", mock.method("foo"));26 assertEquals("bar", mock.method("bar"));27 capture.reset();28 assertEquals("foo", mock.method("foo"));29 assertEquals("bar", mock.method("bar"));30 }31 public interface IInterface {32 String method(String arg);33 }34}35import org.easymock.Capture;36import org.easymock.EasyMock;37import org.easymock.EasyMockSupport;38import org.easymock.IAnswer;39import org.junit.Test;40import static org.easymock.EasyMock.expect;41import static org.junit.Assert.assertEquals;42public class ResetCaptureTest extends EasyMockSupport {43 public void testResetCapture() {44 Capture<String> capture = Capture.newInstance();45 IAnswer<String> answer = new IAnswer<String>() {46 public String answer() throws Throwable {47 return capture.getValue();48 }49 };50 IAnswer<String> answer2 = new IAnswer<String>() {51 public String answer() throws Throwable {52 return capture.getValue();53 }54 };55 IInterface mock = createMock(IInterface.class);56 expect(mock.method(capture(capture))).andAnswer(answer);57 expect(mock.method(capture(capture))).andAnswer(answer2);58 replayAll();59 assertEquals("foo
reset
Using AI Code Generation
1package org.easymock;2import org.easymock.Capture;3import org.easymock.EasyMock;4import org.easymock.IMocksControl;5import org.easymock.IExpectationSetters;6import java.util.List;7public class CaptureExample {8public static void main(String[] args) {9 IMocksControl control = EasyMock.createControl();10 List<String> list = control.createMock(List.class);11 Capture<String> capture = new Capture<String>();12 list.add(EasyMock.capture(capture));13 control.replay();14 list.add("Hello");15 control.verify();16 System.out.println("Captured value is: " + capture.getValue());17 capture.reset();18 System.out.println("Captured value is: " + capture.getValue());19}20}21package org.easymock;22import org.easymock.Capture;23import org.easymock.EasyMock;24import org.easymock.IMocksControl;25import org.easymock.IExpectationSetters;26import java.util.List;27public class CaptureExample {28public static void main(String[] args) {29 IMocksControl control = EasyMock.createControl();30 List<String> list = control.createMock(List.class);31 Capture<String> capture = new Capture<String>();32 list.add(EasyMock.capture(capture));33 control.replay();34 list.add("Hello");35 control.verify();36 System.out.println("Captured value is: " + capture.getValue());37 System.out.println("Has captured value? " + capture.hasCaptured());38}39}40package org.easymock;41import org.easymock.Capture;42import org.easymock.EasyMock;43import org.easymock.IMocksControl;44import org.easymock.IExpectationSetters;45import java.util.List;46public class CaptureExample {47public static void main(String[] args) {48 IMocksControl control = EasyMock.createControl();49 List<String> list = control.createMock(List.class);50 Capture<String> capture = new Capture<String>();51 list.add(EasyMock.capture(capture));52 control.replay();53 list.add("Hello");54 control.verify();55 System.out.println("Capt
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!