@Test(expected = RuntimeException.class) public void testIdentifyWhenWriteFailsAndChannelIsActiveClosesChannelAndThrows() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setFailure(new IOException("test")); when(channel.writeAndFlush(any())).thenReturn(promise); when(channel.isActive()).thenReturn(true); when(channel.close()).thenReturn(promise); Admin admin = new Admin(); admin.setBoxId("test"); admin.setAdminCommand(AdminCommand.IDENTIFY); try { clientSession.identify(admin); } finally { verify(channel).writeAndFlush(admin); verify(channel).close(); assertTrue(clientSession.isClosed()); } }
@Test(expected = RuntimeException.class) public void testIdentifyWhenWriteFailsAndChannelIsInactiveSetsClosedState() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setFailure(new IOException("test")); when(channel.writeAndFlush(any())).thenReturn(promise); when(channel.isActive()).thenReturn(false); Admin admin = new Admin(); admin.setBoxId("test"); admin.setAdminCommand(AdminCommand.IDENTIFY); try { clientSession.identify(admin); } finally { verify(channel).writeAndFlush(admin); verify(channel, times(0)).close(); assertTrue(clientSession.isClosed()); } }
@Test public void testDestroysClosesChannelAndDestroysTheWindow() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.isActive()).thenReturn(false); when(channel.close()).thenReturn(promise); WindowFuture windowFuture = clientSession.getWindow().offer(UUID.randomUUID(), new Sms(), 5000); clientSession.destroy(); verify(channel, times(0)).close(); assertNull("Session handler must be null after destruction", clientSession.getSessionHandler()); assertTrue("The outstanding requests should be canceled", windowFuture.isCancelled()); }
@Test(expected = DuplicateKeyException.class) public void testSendSmsReturnsFailedFutureWhenOfferToWindowFails() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); //add the sms so the next offer fails clientSession.getWindow().offer(sms.getId(), sms, 5000); WindowFuture<Sms, Ack> future = clientSession.sendSms(sms, 5000); assertFalse(future.isCancelled()); assertSame(sms, future.getRequest()); Futures.getChecked(future, DuplicateKeyException.class); }
@Test public void testSendSmsAndWaitReturnsCorrectResponse() throws Exception { final DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); final Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); final Ack expectedResponse = new Ack(); scheduledExecutorService.schedule(new Runnable() { @Override public void run() { clientSession.getWindow().complete(sms.getId(), expectedResponse); } }, 100, TimeUnit.MILLISECONDS); final Ack response = clientSession.sendSmsAndWait(sms, 5000); assertSame(expectedResponse, response); }
@Test public void testSendSmsAndWaitThrowsWhenOfferToWindowFails() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); //add the sms so the next offer fails clientSession.getWindow().offer(sms.getId(), sms, 5000); try { clientSession.sendSmsAndWait(sms, 5000); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof DuplicateKeyException); } }
@Test public void testSendSmsAndWaitThrowsWhenWriteFails() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setFailure(new IOException()); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); try { clientSession.sendSmsAndWait(sms, 5000); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof IOException); } }
/** * Validates successful {@link WebSessionResources#close()} with valid CloseFuture and other parameters. * @throws Exception */ @Test public void testChannelPromiseWithValidExecutor() throws Exception { try { EventExecutor mockExecutor = mock(EventExecutor.class); ChannelPromise closeFuture = new DefaultChannelPromise(null, mockExecutor); webSessionResources = new WebSessionResources(mock(BufferAllocator.class), mock(SocketAddress.class), mock (UserSession.class), closeFuture); webSessionResources.close(); verify(webSessionResources.getAllocator()).close(); verify(webSessionResources.getSession()).close(); verify(mockExecutor).inEventLoop(); verify(mockExecutor).execute(any(Runnable.class)); assertTrue(webSessionResources.getCloseFuture() == null); assertTrue(!listenerComplete); } catch (Exception e) { fail(); } }
/** * Validates double call to {@link WebSessionResources#close()} doesn't throw any exception. * @throws Exception */ @Test public void testDoubleClose() throws Exception { try { ChannelPromise closeFuture = new DefaultChannelPromise(null, mock(EventExecutor.class)); webSessionResources = new WebSessionResources(mock(BufferAllocator.class), mock(SocketAddress.class), mock (UserSession.class), closeFuture); webSessionResources.close(); verify(webSessionResources.getAllocator()).close(); verify(webSessionResources.getSession()).close(); assertTrue(webSessionResources.getCloseFuture() == null); webSessionResources.close(); } catch (Exception e) { fail(); } }
@Test public void itClosesTheUnderlyingChannel() { DefaultChannelPromise channelPromise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); when(channel.close()).thenReturn(channelPromise); CompletableFuture<Void> f = session.close(); channelPromise.setSuccess(); assertThat(f.isDone()); }
private void assertExceptionsFiredOnFailure() throws Exception { // get the listener added when the channel was written to ArgumentCaptor<ChannelFutureListener> captor = ArgumentCaptor.forClass(ChannelFutureListener.class); verify(writeFuture, atLeast(1)).addListener(captor.capture()); ChannelFutureListener addedListener = captor.getValue(); // tell the listener the write failed DefaultChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); promise.setFailure(new Exception()); addedListener.operationComplete(promise); verify(pipeline).fireExceptionCaught(promise.cause()); }
/** Reset the channel mock and set basic method call expectations */ void resetChannel() { reset(channel); expect(channel.newPromise()).andAnswer(new IAnswer<ChannelPromise>() { @Override public ChannelPromise answer() throws Throwable { return new DefaultChannelPromise(channel); } }).anyTimes(); eventLoop = new TestEventLoop(); expect(channel.eventLoop()).andReturn(eventLoop).anyTimes(); expect(channel.pipeline()).andReturn(pipeline).anyTimes(); expect(channel.remoteAddress()).andReturn(null).anyTimes(); }
/** Reset the channel mock and set basic method call expectations */ void resetChannel() { reset(channel); expect(channel.newPromise()).andAnswer(new IAnswer<ChannelPromise>() { @Override public ChannelPromise answer() throws Throwable { return new DefaultChannelPromise(channel); } }).anyTimes(); eventLoop = new TestEventLoop(); expect(channel.eventLoop()).andReturn(eventLoop).anyTimes(); expect(channel.pipeline()).andReturn(pipeline).anyTimes(); expect(channel.remoteAddress()).andReturn(InetSocketAddress.createUnresolved("1.1.1.1", 80)).anyTimes(); }
@Test public void testSendAck() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); Ack ack = mock(Ack.class); assertSame(promise, clientSession.sendAck(ack)); verify(channel).writeAndFlush(ack); }
@Test(expected = IllegalStateException.class) public void testIdentifyWhenCommandIsNotIdentifyThrows() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); Admin admin = new Admin(); admin.setBoxId("test"); admin.setAdminCommand(AdminCommand.RESTART); clientSession.identify(admin); }
@Test public void testCloseWhenChannelIsActiveClosesChannel() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.isActive()).thenReturn(true); when(channel.close()).thenReturn(promise); clientSession.close(); verify(channel).close(); }
@Test public void testCloseWhenChannelIsInactiveClosesChannel() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.isActive()).thenReturn(false); when(channel.close()).thenReturn(promise); clientSession.close(); verify(channel, times(0)).close(); }
@Test public void testSendSmsSetsUUIDAndBoxIdWhenNull() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms("from", "to", "date", SmsType.MOBILE_TERMINATED_PUSH, DataCoding.DC_8BIT); clientSession.sendSms(sms, 5000); assertNotNull(sms.getId()); assertSame(clientSessionConfiguration.getClientId(), sms.getBoxId()); verify(channel).writeAndFlush(sms); }
@Test(expected = IOException.class) public void testSendSmsReturnsFailedFutureWhenWriteFails() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setFailure(new IOException()); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); WindowFuture<Sms, Ack> future = clientSession.sendSms(sms, 5000); Futures.getChecked(future, IOException.class); }
@Test(expected = CancellationException.class) public void testSendSmsReturnsFailedFutureWhenWriteIsCancelled() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.cancel(true); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); WindowFuture<Sms, Ack> future = clientSession.sendSms(sms, 5000); Futures.getUnchecked(future); }
@Test public void testSendHeartBeat() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.setSuccess(); when(channel.writeAndFlush(any())).thenReturn(promise); HeartBeat heartBeat = new HeartBeat(); assertSame(promise, clientSession.sendHeartBeat(heartBeat)); verify(channel).writeAndFlush(heartBeat); }
@Test(expected = CancellationException.class) public void testSendSmsAndWaitThrowsWhenWriteIsCancelled() throws Exception { DefaultChannelPromise promise = new DefaultChannelPromise(channel, eventExecutors.next()); promise.cancel(true); when(channel.writeAndFlush(any())).thenReturn(promise); Sms sms = new Sms(); sms.setId(UUID.randomUUID()); sms.setBoxId("test box"); clientSession.sendSmsAndWait(sms, 5000); }
/** * Validates {@link WebSessionResources#close()} throws NPE when closefuture passed to WebSessionResources doesn't * have a valid channel and EventExecutor associated with it. * @throws Exception */ @Test public void testChannelPromiseWithNullExecutor() throws Exception { try { ChannelPromise closeFuture = new DefaultChannelPromise(null); webSessionResources = new WebSessionResources(mock(BufferAllocator.class), mock(SocketAddress.class), mock (UserSession.class), closeFuture); webSessionResources.close(); fail(); } catch (Exception e) { assertTrue(e instanceof NullPointerException); verify(webSessionResources.getAllocator()).close(); verify(webSessionResources.getSession()).close(); } }
/** * Validates successful {@link WebSessionResources#close()} with valid CloseFuture and {@link TestClosedListener} * getting invoked which is added to the close future. * @throws Exception */ @Test public void testCloseWithListener() throws Exception { try { // Assign latch, executor and closeListener for this test case GenericFutureListener<Future<Void>> closeListener = new TestClosedListener(); latch = new CountDownLatch(1); executor = TransportCheck.createEventLoopGroup(1, "Test-Thread").next(); ChannelPromise closeFuture = new DefaultChannelPromise(null, executor); // create WebSessionResources with above ChannelPromise to notify listener webSessionResources = new WebSessionResources(mock(BufferAllocator.class), mock(SocketAddress.class), mock(UserSession.class), closeFuture); // Add the Test Listener to close future assertTrue(!listenerComplete); closeFuture.addListener(closeListener); // Close the WebSessionResources webSessionResources.close(); // Verify the states verify(webSessionResources.getAllocator()).close(); verify(webSessionResources.getSession()).close(); assertTrue(webSessionResources.getCloseFuture() == null); // Since listener will be invoked so test should not wait forever latch.await(); assertTrue(listenerComplete); } catch (Exception e) { fail(); } finally { listenerComplete = false; executor.shutdownGracefully(); } }
final ChannelFuture initAndRegister() { final Channel channel = channelFactory().newChannel(); try { init(channel); } catch (Throwable t) { channel.unsafe().closeForcibly(); // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); } ChannelFuture regFuture = group().register(channel); if (regFuture.cause() != null) { if (channel.isRegistered()) { channel.close(); } else { channel.unsafe().closeForcibly(); } } // If we are here and the promise is not failed, it's one of the following cases: // 1) If we attempted registration from the event loop, the registration has been completed at this point. // i.e. It's safe to attempt bind() or connect() now because the channel has been registered. // 2) If we attempted registration from the other thread, the registration request has been successfully // added to the event loop's task queue for later execution. // i.e. It's safe to attempt bind() or connect() now: // because bind() or connect() will be executed *after* the scheduled registration task is executed // because register(), bind(), and connect() are all bound to the same thread. return regFuture; }
@Test @SuppressWarnings("deprecation") public void makeContextAwareChannelFutureListener() { RequestContext context = createContext(); ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); promise.addListener(context.makeContextAware((ChannelFutureListener) f -> { assertCurrentContext(context); assertDepth(1); assertThat(f.getNow()).isNull(); })); promise.setSuccess(null); }
@Before public final void setUp() { MockitoAnnotations.initMocks(this); final ChannelFuture future = new DefaultChannelPromise(this.channel); doAnswer(invocation -> { final Object[] args = invocation.getArguments(); AbstractPCEPSessionTest.this.msgsSend.add((Notification) args[0]); return future; }).when(this.channel).writeAndFlush(any(Notification.class)); doReturn(this.channelFuture).when(this.channel).closeFuture(); doReturn(this.channelFuture).when(this.channelFuture).addListener(any(GenericFutureListener.class)); doReturn("TestingChannel").when(this.channel).toString(); doReturn(this.pipeline).when(this.channel).pipeline(); doReturn(this.address).when(this.channel).localAddress(); doReturn(this.address).when(this.channel).remoteAddress(); doReturn(this.eventLoop).when(this.channel).eventLoop(); doReturn(true).when(this.future).cancel(false); doReturn(this.future).when(this.eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class)); doReturn(this.pipeline).when(this.pipeline).replace(any(ChannelHandler.class), any(String.class), any(ChannelHandler.class)); doReturn(this.pipeline).when(this.pipeline).addFirst(any(ChannelHandler.class)); doReturn(true).when(this.channel).isActive(); doReturn(mock(ChannelFuture.class)).when(this.channel).close(); doReturn(new InetSocketAddress(this.ipAddress, this.port)).when(this.channel).remoteAddress(); doReturn(new InetSocketAddress(this.ipAddress, this.port)).when(this.channel).localAddress(); this.openMsg = new OpenBuilder().setOpenMessage( new OpenMessageBuilder().setOpen( new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder().setDeadTimer( DEADTIMER).setKeepalive(KEEP_ALIVE).setSessionId((short) 0).build()).build()).build(); this.kaMsg = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build(); this.startTlsMsg = new StarttlsBuilder().setStartTlsMessage(new StartTlsMessageBuilder().build()).build(); this.closeMsg = new CloseBuilder().setCCloseMessage( new CCloseMessageBuilder().setCClose(new CCloseBuilder().setReason((short) 6).build()).build()).build(); this.listener = new SimpleSessionListener(); }
private void mockSession() { final EventLoop eventLoop = Mockito.mock(EventLoop.class); final Channel channel = Mockito.mock(Channel.class); final ChannelPipeline pipeline = Mockito.mock(ChannelPipeline.class); doReturn(null).when(eventLoop).schedule(any(Runnable.class), any(long.class), any(TimeUnit.class)); doReturn(eventLoop).when(channel).eventLoop(); doReturn(Boolean.TRUE).when(channel).isWritable(); doReturn(null).when(channel).close(); doReturn(pipeline).when(channel).pipeline(); Mockito.doCallRealMethod().when(channel).toString(); doReturn(pipeline).when(pipeline).addLast(any(ChannelHandler.class)); doReturn(new DefaultChannelPromise(channel)).when(channel).writeAndFlush(any(Notification.class)); doReturn(new InetSocketAddress("localhost", 12345)).when(channel).remoteAddress(); doReturn(new InetSocketAddress("localhost", 12345)).when(channel).localAddress(); final List<BgpParameters> params = Lists.newArrayList(new BgpParametersBuilder().setOptionalCapabilities( Lists.newArrayList(new OptionalCapabilitiesBuilder().setCParameters( new CParametersBuilder().addAugmentation( CParameters1.class, new CParameters1Builder().setMultiprotocolCapability( new MultiprotocolCapabilityBuilder() .setAfi(Ipv4AddressFamily.class) .setSafi(UnicastSubsequentAddressFamily.class) .build()).build()).build()).build())).build()); final Open openObj = new OpenBuilder() .setBgpIdentifier(new Ipv4Address("1.1.1.1")) .setHoldTimer(50) .setMyAsNumber(72) .setBgpParameters(params).build(); this.session = new BGPSessionImpl(this.classic, channel, openObj, 30, null); this.session.setChannelExtMsgCoder(openObj); }
/** Set up for test. */ @Before public void setUp() { MockitoAnnotations.initMocks(this); mockFuture(true); when(channel.write(any())).thenReturn(future); when(channel.writeAndFlush(any())).thenReturn(future); when(channel.alloc()).thenReturn(UnpooledByteBufAllocator.DEFAULT); when(channel.pipeline()).thenReturn(pipeline); when(channel.eventLoop()).thenReturn(eventLoop); when(channel.newPromise()).thenReturn(new DefaultChannelPromise(channel)); when(channel.voidPromise()).thenReturn(new DefaultChannelPromise(channel)); when(pipeline.firstContext()).thenReturn(ctx); when(eventLoop.inEventLoop()).thenReturn(true); when(http2Stream.id()).thenReturn(STREAM_ID); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { Runnable runnable = (Runnable) invocation.getArguments()[0]; runnable.run(); return null; } }).when(eventLoop).execute(any(Runnable.class)); stream = createStream(); }
@Test public void testEncodeMethodCallFailure() throws InvalidProtocolBufferException, InterruptedException { Channel channel = Mockito.mock(Channel.class); ArgumentCaptor<Object> captor = ArgumentCaptor.forClass(Object.class); DefaultChannelPromise failure = new DefaultChannelPromise( channel, ImmediateEventExecutor.INSTANCE); failure.setFailure(new Exception("OMGWTF")); Mockito.when(channel.writeAndFlush(captor.capture())).thenReturn(failure); RpcClientHandler handler = new RpcClientHandler(); RpcClient client = new RpcClient(channel, handler, new NullClientLogger()); ClientMethod<TimeResponse> method = Mockito.mock(ClientMethod.class); Mockito.when(method.serviceName()).thenReturn("TimeService"); Mockito.when(method.name()).thenReturn("GetTime"); Mockito.when(method.outputParser()).thenReturn(TimeResponse.PARSER); final CountDownLatch latch = new CountDownLatch(1); FutureCallback<TimeResponse> callback = new FutureCallback<TimeResponse>() { @Override public void onSuccess(@Nullable TimeResponse result) { } @Override public void onFailure(Throwable t) { Assert.assertEquals("OMGWTF", t.getMessage()); latch.countDown(); } }; ListenableFuture<TimeResponse> future = client.encodeMethodCall( method, TimeRequest.newBuilder().setTimezone("UTC").build()); Futures.addCallback(future, callback); latch.await(5, TimeUnit.SECONDS); Assert.assertEquals(0, handler.inFlightRequests().size()); }