Search in sources :

Example 1 with TestPublisher

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

the class HttpLifecycleObserverTest method testClientCancelsRequestAfterResponse.

@ParameterizedTest(name = "{displayName} [{index}] protocol={0}")
@EnumSource(HttpProtocol.class)
void testClientCancelsRequestAfterResponse(HttpProtocol protocol) throws Exception {
    TestPublisher<Buffer> serverResponsePayload = new TestPublisher<>();
    serviceFilterFactory(service -> new StreamingHttpServiceFilter(service) {

        @Override
        public Single<StreamingHttpResponse> handle(HttpServiceContext ctx, StreamingHttpRequest request, StreamingHttpResponseFactory responseFactory) {
            return request.payloadBody().ignoreElements().concat(succeeded(responseFactory.ok().payloadBody(serverResponsePayload)));
        }
    });
    setUp(protocol);
    StreamingHttpConnection connection = streamingHttpConnection();
    StreamingHttpRequest request = connection.post("/").payloadBody(Publisher.from(CONTENT.duplicate())).transform(// adds empty trailers
    new StatelessTrailersTransformer<>());
    StreamingHttpResponse response = connection.request(request).toFuture().get();
    assertResponse(response, protocol.version, OK);
    Future<Collection<Buffer>> payload = response.payloadBody().toFuture();
    payload.cancel(true);
    if (protocol == HttpProtocol.HTTP_1) {
        // wait for cancellation to close the connection:
        connection.onClose().toFuture().get();
    }
    // try to write server content to trigger write failure and close the server-side connection:
    serverResponsePayload.onNext(CONTENT.duplicate());
    bothTerminate.await();
    clientInOrder.verify(clientLifecycleObserver).onNewExchange();
    clientInOrder.verify(clientExchangeObserver).onConnectionSelected(any(ConnectionInfo.class));
    clientInOrder.verify(clientExchangeObserver).onRequest(any(StreamingHttpRequest.class));
    clientInOrder.verify(clientExchangeObserver).onResponse(any(StreamingHttpResponse.class));
    clientInOrder.verify(clientResponseObserver).onResponseCancel();
    clientRequestInOrder.verify(clientRequestObserver).onRequestData(any(Buffer.class));
    clientRequestInOrder.verify(clientRequestObserver).onRequestTrailers(any(HttpHeaders.class));
    clientRequestInOrder.verify(clientRequestObserver).onRequestComplete();
    clientInOrder.verify(clientExchangeObserver).onExchangeFinally();
    verifyNoMoreInteractions(clientLifecycleObserver, clientExchangeObserver, clientRequestObserver, clientResponseObserver);
    serverInOrder.verify(serverLifecycleObserver).onNewExchange();
    serverInOrder.verify(serverExchangeObserver).onConnectionSelected(any(ConnectionInfo.class));
    serverInOrder.verify(serverExchangeObserver).onRequest(any(StreamingHttpRequest.class));
    serverInOrder.verify(serverExchangeObserver).onResponse(any(StreamingHttpResponse.class));
    verify(serverResponseObserver, atMostOnce()).onResponseData(any(Buffer.class));
    serverInOrder.verify(serverResponseObserver).onResponseCancel();
    serverRequestInOrder.verify(serverRequestObserver).onRequestData(any(Buffer.class));
    serverRequestInOrder.verify(serverRequestObserver).onRequestComplete();
    serverInOrder.verify(serverExchangeObserver).onExchangeFinally();
    verifyNoMoreInteractions(serverLifecycleObserver, serverExchangeObserver, serverRequestObserver, serverResponseObserver);
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) HttpHeaders(io.servicetalk.http.api.HttpHeaders) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) StreamingHttpResponseFactory(io.servicetalk.http.api.StreamingHttpResponseFactory) StreamingHttpServiceFilter(io.servicetalk.http.api.StreamingHttpServiceFilter) Single(io.servicetalk.concurrent.api.Single) HttpServiceContext(io.servicetalk.http.api.HttpServiceContext) Collection(java.util.Collection) StreamingHttpRequest(io.servicetalk.http.api.StreamingHttpRequest) ConnectionInfo(io.servicetalk.transport.api.ConnectionInfo) StreamingHttpConnection(io.servicetalk.http.api.StreamingHttpConnection) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) EnumSource(org.junit.jupiter.params.provider.EnumSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 2 with TestPublisher

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

the class DefaultSerializerSerializationTest method applySerializationForPublisherWithTypeAndEstimator.

@Test
void applySerializationForPublisherWithTypeAndEstimator() {
    TestPublisher<String> source = new TestPublisher<>();
    final Publisher<Buffer> serialized = factory.serialize(source, allocator, String.class, sizeEstimator);
    TestPublisherSubscriber<Buffer> subscriber = new TestPublisherSubscriber<>();
    toSource(serialized).subscribe(subscriber);
    subscriber.awaitSubscription().request(2);
    verify(provider).getSerializer(String.class);
    Buffer expected1 = verifySerializedBufferWithSizes(source, "Hello", 1);
    assertThat(subscriber.takeOnNext(), is(expected1));
    Buffer expected2 = verifySerializedBufferWithSizes(source, "Hello", 2);
    assertThat(subscriber.takeOnNext(), is(expected2));
    source.onComplete();
    subscriber.awaitOnComplete();
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) TestPublisherSubscriber(io.servicetalk.concurrent.test.internal.TestPublisherSubscriber) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) Test(org.junit.jupiter.api.Test)

Example 3 with TestPublisher

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

the class NettyPipelinedConnectionTest method writeThrowsClosesConnection.

@Test
void writeThrowsClosesConnection() {
    TestPublisher<Integer> mockReadPublisher2 = new TestPublisher<>();
    @SuppressWarnings("unchecked") NettyConnection<Integer, Integer> mockConnection = mock(NettyConnection.class);
    doAnswer((Answer<Publisher<Integer>>) invocation -> mockReadPublisher2).when(mockConnection).read();
    doAnswer((Answer<Completable>) invocation -> {
        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());
    when(mockConnection.closeAsync()).thenReturn(completed());
    requester = new NettyPipelinedConnection<>(mockConnection, 2);
    toSource(requester.write(writePublisher1)).subscribe(readSubscriber);
    toSource(requester.write(writePublisher2)).subscribe(readSubscriber2);
    Subscription readSubscription = readSubscriber.awaitSubscription();
    readSubscription.request(1);
    assertThat(readSubscriber.awaitOnError(), is(DELIBERATE_EXCEPTION));
    assertFalse(writePublisher1.isSubscribed());
    verify(mockConnection).closeAsync();
}
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) Completable(io.servicetalk.concurrent.api.Completable) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) 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)

Example 4 with TestPublisher

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

the class JdkFlowAdaptersTest method toFlowCancel.

@Test
void toFlowCancel() {
    TestPublisher<Integer> stPublisher = new TestPublisher<>();
    Subscriber<Integer> subscriber = toFlowPublisherAndSubscribe(stPublisher);
    TestSubscription subscription = new TestSubscription();
    stPublisher.onSubscribe(subscription);
    assertThat("Source not subscribed.", stPublisher.isSubscribed(), is(true));
    ArgumentCaptor<Subscription> subscriptionCaptor = ArgumentCaptor.forClass(Subscription.class);
    verify(subscriber).onSubscribe(subscriptionCaptor.capture());
    subscriptionCaptor.getValue().cancel();
    assertThat("Subscription not cancelled.", subscription.isCancelled(), is(true));
}
Also used : TestSubscription(io.servicetalk.concurrent.api.TestSubscription) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) Subscription(java.util.concurrent.Flow.Subscription) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) ScalarValueSubscription(io.servicetalk.concurrent.internal.ScalarValueSubscription) Test(org.junit.jupiter.api.Test)

Example 5 with TestPublisher

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

the class AbstractTimeoutHttpFilterTest method subscribeToPayloadBodyAfterTimeout.

@Test
void subscribeToPayloadBodyAfterTimeout() {
    Duration timeout = ofMillis(100L);
    TestPublisher<Buffer> payloadBody = new TestPublisher<>();
    AtomicReference<StreamingHttpResponse> response = new AtomicReference<>();
    StepVerifiers.create(applyFilter(timeout, true, defaultStrategy(), responseWith(payloadBody))).expectSuccessConsumed(response::set).verify();
    // Subscribe to payload body after timeout
    StepVerifiers.create(immediate().timer(timeout.plusMillis(5L)).concat(response.get().payloadBody())).expectError(TimeoutException.class).verify();
    assertThat("No subscribe for payload body", payloadBody.isSubscribed(), is(true));
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) TestPublisher(io.servicetalk.concurrent.api.TestPublisher) Duration(java.time.Duration) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

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