Search in sources :

Example 11 with TestPublisher

use of io.servicetalk.concurrent.api.TestPublisher in project servicetalk by apple.

the class BeforeFinallyHttpOperatorTest method payloadComplete.

@ParameterizedTest(name = "{displayName} [{index}] discardEventsAfterCancel={0}")
@ValueSource(booleans = { false, true })
void payloadComplete(boolean discardEventsAfterCancel) {
    TestPublisher<Buffer> payload = new TestPublisher<>();
    LegacyTestSingle<StreamingHttpResponse> responseSingle = new LegacyTestSingle<>(true);
    final ResponseSubscriber subscriber = new ResponseSubscriber();
    toSource(responseSingle.liftSync(new BeforeFinallyHttpOperator(beforeFinally, discardEventsAfterCancel))).subscribe(subscriber);
    assertThat("onSubscribe not called.", subscriber.cancellable, is(notNullValue()));
    final StreamingHttpResponse response = reqRespFactory.ok().payloadBody(payload);
    responseSingle.onSuccess(response);
    verifyNoInteractions(beforeFinally);
    responseSingle.verifyNotCancelled();
    subscriber.verifyResponseReceived();
    assert subscriber.response != null;
    subscriber.response.payloadBody().forEach(chunk -> {
    // ignore
    });
    payload.onComplete();
    verify(beforeFinally).onComplete();
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) LegacyTestSingle(io.servicetalk.concurrent.api.LegacyTestSingle) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 12 with TestPublisher

use of io.servicetalk.concurrent.api.TestPublisher in project servicetalk by apple.

the class RetryRequestWithNonRepeatablePayloadTest method setUp.

private void setUp(HttpProtocol protocol, TestPublisher<Buffer> payloadBody, Queue<Throwable> errors, boolean offloading) {
    protocol(protocol.config);
    ChannelOutboundHandler firstWriteHandler = new FailingFirstWriteHandler();
    connectionFactoryFilter(ConnectionFactoryFilter.withStrategy(factory -> new DelegatingConnectionFactory<InetSocketAddress, FilterableStreamingHttpConnection>(factory) {

        @Override
        public Single<FilterableStreamingHttpConnection> newConnection(InetSocketAddress address, @Nullable TransportObserver observer) {
            return delegate().newConnection(address, observer).map(c -> {
                final Channel channel = ((NettyConnectionContext) c.connectionContext()).nettyChannel();
                if (protocol == HTTP_1) {
                    // Insert right before HttpResponseDecoder to avoid seeing failed frames on wire logs
                    channel.pipeline().addBefore(HttpRequestEncoder.class.getSimpleName() + "#0", null, firstWriteHandler);
                } else if (protocol == HTTP_2) {
                    // Insert right before Http2MultiplexHandler to avoid failing connection-level frames and
                    // seeing failed stream frames on frame/wire logs
                    channel.pipeline().addBefore(Http2MultiplexHandler.class.getSimpleName() + "#0", null, firstWriteHandler);
                }
                return new StreamingHttpConnectionFilter(c) {

                    @Override
                    public Single<StreamingHttpResponse> request(StreamingHttpRequest request) {
                        return delegate().request(request).whenOnError(t -> {
                            try {
                                assertThat("Unexpected exception type", t, instanceOf(RetryableException.class));
                                assertThat("Unexpected exception type", t.getCause(), instanceOf(DeliberateException.class));
                                assertThat("Unexpected subscribe to payload body", payloadBody.isSubscribed(), is(false));
                            } catch (Throwable error) {
                                errors.add(error);
                            }
                        });
                    }
                };
            });
        }
    }, ExecutionStrategy.offloadNone()));
    setUp(offloading ? CACHED : IMMEDIATE, offloading ? CACHED_SERVER : IMMEDIATE);
}
Also used : ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) TestUtils.assertNoAsyncErrors(io.servicetalk.test.resources.TestUtils.assertNoAsyncErrors) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Sharable(io.netty.channel.ChannelHandler.Sharable) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) StreamingHttpClient(io.servicetalk.http.api.StreamingHttpClient) ExecutionStrategy(io.servicetalk.transport.api.ExecutionStrategy) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) Nullable(javax.annotation.Nullable) CACHED_SERVER(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED_SERVER) MethodSource(org.junit.jupiter.params.provider.MethodSource) IMMEDIATE(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.IMMEDIATE) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) Single(io.servicetalk.concurrent.api.Single) Collection(java.util.Collection) ConnectionFactoryFilter(io.servicetalk.client.api.ConnectionFactoryFilter) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) Arguments(org.junit.jupiter.params.provider.Arguments) OK(io.servicetalk.http.api.HttpResponseStatus.OK) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) List(java.util.List) Buffer(io.servicetalk.buffer.api.Buffer) CACHED(io.servicetalk.http.netty.AbstractNettyHttpServerTest.ExecutorSupplier.CACHED) RetryableException(io.servicetalk.transport.api.RetryableException) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) TransportObserver(io.servicetalk.transport.api.TransportObserver) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) HTTP_2(io.servicetalk.http.netty.HttpProtocol.HTTP_2) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) HTTP_1(io.servicetalk.http.netty.HttpProtocol.HTTP_1) InetSocketAddress(java.net.InetSocketAddress) FilterableStreamingHttpConnection(io.servicetalk.http.api.FilterableStreamingHttpConnection) Channel(io.netty.channel.Channel) TransportObserver(io.servicetalk.transport.api.TransportObserver) NettyConnectionContext(io.servicetalk.transport.netty.internal.NettyConnectionContext) DelegatingConnectionFactory(io.servicetalk.client.api.DelegatingConnectionFactory) Http2MultiplexHandler(io.netty.handler.codec.http2.Http2MultiplexHandler) StreamingHttpConnectionFilter(io.servicetalk.http.api.StreamingHttpConnectionFilter) RetryableException(io.servicetalk.transport.api.RetryableException) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) DeliberateException(io.servicetalk.concurrent.internal.DeliberateException) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Nullable(javax.annotation.Nullable)

Example 13 with TestPublisher

use of io.servicetalk.concurrent.api.TestPublisher in project servicetalk by apple.

the class PublisherAsInputStreamTest method checkAvailableReturnsCorrectlyWithPrefetch.

@Test
void checkAvailableReturnsCorrectlyWithPrefetch() throws IOException {
    TestPublisher<String> testPublisher = new TestPublisher<>();
    InputStream stream = testPublisher.toInputStream(str -> str.getBytes(US_ASCII));
    assertThat("Unexpected available return type.", stream.available(), is(0));
    testPublisher.onNext("1234");
    assertThat("Unexpected available return type.", stream.available(), is(0));
    byte[] data = new byte[2];
    int read = stream.read(data, 0, 2);
    assertThat("Unexpected number of bytes read.", read, is(2));
    assertThat("Unexpected bytes read.", bytesToCharArray(data, read), equalTo(new Character[] { '1', '2' }));
    assertThat("Unexpected available return type.", stream.available(), is(2));
}
Also used : TestPublisher(io.servicetalk.concurrent.api.TestPublisher) InputStream(java.io.InputStream) Test(org.junit.jupiter.api.Test)

Example 14 with TestPublisher

use of io.servicetalk.concurrent.api.TestPublisher in project servicetalk by apple.

the class NettyPipelinedConnectionTest method writeSubscribeThrowsLetsSubsequentRequestsThrough.

@Test
void writeSubscribeThrowsLetsSubsequentRequestsThrough() {
    AtomicBoolean firstReadOperation = new AtomicBoolean();
    TestPublisher<Integer> mockReadPublisher1 = new TestPublisher<>();
    TestPublisher<Integer> mockReadPublisher2 = new TestPublisher<>();
    @SuppressWarnings("unchecked") NettyConnection<Integer, Integer> mockConnection = mock(NettyConnection.class);
    doAnswer((Answer<Publisher<Integer>>) invocation -> firstReadOperation.compareAndSet(false, true) ? mockReadPublisher1 : mockReadPublisher2).when(mockConnection).read();
    doAnswer((Answer<Completable>) invocation -> new Completable() {

        @Override
        protected void handleSubscribe(final CompletableSource.Subscriber subscriber) {
            throw DELIBERATE_EXCEPTION;
        }
    }).when(mockConnection).write(eq(writePublisher1), any(), any());
    doAnswer((Answer<Completable>) invocation -> {
        Publisher<Integer> writePub = invocation.getArgument(0);
        return writePub.ignoreElements();
    }).when(mockConnection).write(eq(writePublisher2), any(), any());
    requester = new NettyPipelinedConnection<>(mockConnection, 2);
    toSource(requester.write(writePublisher1)).subscribe(readSubscriber);
    toSource(requester.write(writePublisher2)).subscribe(readSubscriber2);
    Subscription readSubscription = readSubscriber.awaitSubscription();
    readSubscription.request(1);
    assertTrue(mockReadPublisher1.isSubscribed());
    mockReadPublisher1.onError(newSecondException());
    assertThat(readSubscriber.awaitOnError(), is(DELIBERATE_EXCEPTION));
    assertFalse(writePublisher1.isSubscribed());
    verifySecondRequestProcessed(mockReadPublisher2, mockConnection);
}
Also used : UNSUPPORTED_PROTOCOL_CLOSE_HANDLER(io.servicetalk.transport.netty.internal.CloseHandler.UNSUPPORTED_PROTOCOL_CLOSE_HANDLER) BeforeEach(org.junit.jupiter.api.BeforeEach) Protocol(io.servicetalk.transport.api.ConnectionInfo.Protocol) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) MAX_VALUE(java.lang.Integer.MAX_VALUE) Future(java.util.concurrent.Future) HttpExecutionStrategies.defaultStrategy(io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Executor(io.servicetalk.concurrent.api.Executor) Executors.immediate(io.servicetalk.concurrent.api.Executors.immediate) TestPublisherSubscriber(io.servicetalk.concurrent.test.internal.TestPublisherSubscriber) CyclicBarrier(java.util.concurrent.CyclicBarrier) SynchronousQueue(java.util.concurrent.SynchronousQueue) PublisherSource(io.servicetalk.concurrent.PublisherSource) Collection(java.util.Collection) DefaultNettyConnection(io.servicetalk.transport.netty.internal.DefaultNettyConnection) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) SubscriberUtils.deliverCompleteFromSource(io.servicetalk.concurrent.internal.SubscriberUtils.deliverCompleteFromSource) RetryableException(io.servicetalk.transport.api.RetryableException) WriteDemandEstimators(io.servicetalk.transport.netty.internal.WriteDemandEstimators) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) FlushStrategies.defaultFlushStrategy(io.servicetalk.transport.netty.internal.FlushStrategies.defaultFlushStrategy) Matchers.is(org.hamcrest.Matchers.is) CloseHandler(io.servicetalk.transport.netty.internal.CloseHandler) NoopConnectionObserver(io.servicetalk.transport.netty.internal.NoopTransportObserver.NoopConnectionObserver) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) FlushStrategy(io.servicetalk.transport.netty.internal.FlushStrategy) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) DEFAULT_ALLOCATOR(io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Publisher(io.servicetalk.concurrent.api.Publisher) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Answer(org.mockito.stubbing.Answer) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) DELIBERATE_EXCEPTION(io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION) ExecutorService(java.util.concurrent.ExecutorService) ClosedChannelException(java.nio.channels.ClosedChannelException) Single(io.servicetalk.concurrent.api.Single) Completable(io.servicetalk.concurrent.api.Completable) EmbeddedDuplexChannel(io.servicetalk.transport.netty.internal.EmbeddedDuplexChannel) Mockito.when(org.mockito.Mockito.when) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) SourceAdapters.toSource(io.servicetalk.concurrent.api.SourceAdapters.toSource) CompletableSource(io.servicetalk.concurrent.CompletableSource) Mockito.verify(org.mockito.Mockito.verify) Mockito.never(org.mockito.Mockito.never) WriteDemandEstimator(io.servicetalk.transport.netty.internal.WriteDemandEstimator) Completable.completed(io.servicetalk.concurrent.api.Completable.completed) Executors(io.servicetalk.concurrent.api.Executors) NettyConnection(io.servicetalk.transport.netty.internal.NettyConnection) SECONDS(java.util.concurrent.TimeUnit.SECONDS) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Completable(io.servicetalk.concurrent.api.Completable) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) TestPublisherSubscriber(io.servicetalk.concurrent.test.internal.TestPublisherSubscriber) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) Publisher(io.servicetalk.concurrent.api.Publisher) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) Test(org.junit.jupiter.api.Test)

Aggregations

TestPublisher (io.servicetalk.concurrent.api.TestPublisher)14 Test (org.junit.jupiter.api.Test)11 Buffer (io.servicetalk.buffer.api.Buffer)9 Single (io.servicetalk.concurrent.api.Single)6 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)6 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)5 DEFAULT_ALLOCATOR (io.servicetalk.buffer.netty.BufferAllocators.DEFAULT_ALLOCATOR)4 Executor (io.servicetalk.concurrent.api.Executor)4 Executors (io.servicetalk.concurrent.api.Executors)4 Executors.immediate (io.servicetalk.concurrent.api.Executors.immediate)4 Publisher (io.servicetalk.concurrent.api.Publisher)4 TestSubscription (io.servicetalk.concurrent.api.TestSubscription)4 TestPublisherSubscriber (io.servicetalk.concurrent.test.internal.TestPublisherSubscriber)4 HttpExecutionStrategies.defaultStrategy (io.servicetalk.http.api.HttpExecutionStrategies.defaultStrategy)4 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)4 Matchers.is (org.hamcrest.Matchers.is)4 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 DELIBERATE_EXCEPTION (io.servicetalk.concurrent.internal.DeliberateException.DELIBERATE_EXCEPTION)3 OK (io.servicetalk.http.api.HttpResponseStatus.OK)3