Java Code Examples for reactor.test.publisher.TestPublisher#complete()

The following examples show how to use reactor.test.publisher.TestPublisher#complete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotHangWhenOneElementUpstream() {
    TestPublisher<Long> publisher = TestPublisher.createCold();

    Flux<String> switchTransformed = publisher.flux()
                                              .switchOnFirst((first, innerFlux) ->
                                                  innerFlux.map(String::valueOf)
                                                           .subscriberContext(Context.of("a", "b"))
                                              )
                                              .subscriberContext(Context.of("a", "c"))
                                              .subscriberContext(Context.of("c", "d"));

    publisher.next(1L);
    publisher.complete();

    StepVerifier.create(switchTransformed, 0)
                .thenRequest(1)
                .expectNext("1")
                .expectComplete()
                .verify(Duration.ofSeconds(10));

    publisher.assertWasRequested();
    publisher.assertNoRequestOverflow();
}
 
Example 2
Source File: ReactiveCompositeDiscoveryClientTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFluxOfServices() {
	TestPublisher<String> discoveryClient1Publisher = TestPublisher.createCold();
	discoveryClient1Publisher.emit("serviceAFromClient1");
	discoveryClient1Publisher.emit("serviceBFromClient1");
	discoveryClient1Publisher.complete();

	TestPublisher<String> discoveryClient2Publisher = TestPublisher.createCold();
	discoveryClient2Publisher.emit("serviceCFromClient2");
	discoveryClient2Publisher.complete();

	when(discoveryClient1.getServices()).thenReturn(discoveryClient1Publisher.flux());
	when(discoveryClient2.getServices()).thenReturn(discoveryClient2Publisher.flux());

	ReactiveCompositeDiscoveryClient client = new ReactiveCompositeDiscoveryClient(
			asList(discoveryClient1, discoveryClient2));

	assertThat(client.description()).isEqualTo("Composite Reactive Discovery Client");

	Flux<String> services = client.getServices();

	StepVerifier.create(services).expectNext("serviceAFromClient1")
			.expectNext("serviceBFromClient1").expectNext("serviceCFromClient2")
			.expectComplete().verify();
}
 
Example 3
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeRequestedExactlyOneAndThenLongMaxValueConditional() throws InterruptedException {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    ArrayList<Long> capture = new ArrayList<>();
    ArrayList<Long> requested = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flux<Long> switchTransformed = publisher.flux()
                                            .doOnRequest(requested::add)
                                            .switchOnFirst((first, innerFlux) -> innerFlux);

    publisher.next(1L);
    publisher.complete();

    switchTransformed.subscribe(capture::add, __ -> {}, latch::countDown);

    latch.await(5, TimeUnit.SECONDS);

    Assertions.assertThat(capture).containsExactly(1L);
    Assertions.assertThat(requested).containsExactly(1L, Long.MAX_VALUE);
}
 
Example 4
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeRequestedExactlyOneAndThenLongMaxValue() throws InterruptedException {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    ArrayList<Long> capture = new ArrayList<>();
    ArrayList<Long> requested = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flux<Long> switchTransformed = publisher.flux()
                                            .doOnRequest(requested::add)
                                            .switchOnFirst((first, innerFlux) -> innerFlux);

    publisher.next(1L);
    publisher.complete();

    switchTransformed.subscribe(capture::add, __ -> {}, latch::countDown);

    latch.await(5, TimeUnit.SECONDS);

    Assertions.assertThat(capture).containsExactly(1L);
    Assertions.assertThat(requested).containsExactly(1L, Long.MAX_VALUE);
}
 
Example 5
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeRequestedOneFromUpstreamTwiceInCaseOfConditional() throws InterruptedException {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    ArrayList<Long> capture = new ArrayList<>();
    ArrayList<Long> requested = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flux<Long> switchTransformed = publisher.flux()
                                            .doOnRequest(requested::add)
                                            .switchOnFirst((first, innerFlux) -> innerFlux)
                                            .filter(e -> false);

    publisher.next(1L);
    publisher.complete();

    switchTransformed.subscribeWith(new LambdaSubscriber<>(capture::add, __ -> {}, latch::countDown, s -> s.request(1)));

    latch.await(5, TimeUnit.SECONDS);

    Assertions.assertThat(capture).isEmpty();
    Assertions.assertThat(requested).containsExactly(1L, 1L);
}
 
Example 6
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNeverSendIncorrectRequestSizeToUpstreamConditional() throws InterruptedException {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    AtomicLong capture = new AtomicLong();
    ArrayList<Long> requested = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flux<Long> switchTransformed = publisher.flux()
                                            .doOnRequest(requested::add)
                                            .switchOnFirst((first, innerFlux) -> innerFlux)
                                            .filter(e -> true);

    publisher.next(1L);
    publisher.complete();

    switchTransformed.subscribeWith(new LambdaSubscriber<>(capture::set, __ -> {}, latch::countDown, s -> s.request(1)));

    latch.await(5, TimeUnit.SECONDS);

    Assertions.assertThat(capture.get()).isEqualTo(1L);
    Assertions.assertThat(requested).containsExactly(1L);
}
 
Example 7
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNeverSendIncorrectRequestSizeToUpstream() throws InterruptedException {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    AtomicLong capture = new AtomicLong();
    ArrayList<Long> requested = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flux<Long> switchTransformed = publisher.flux()
                                            .doOnRequest(requested::add)
                                            .switchOnFirst((first, innerFlux) -> innerFlux);

    publisher.next(1L);
    publisher.complete();

    switchTransformed.subscribeWith(new LambdaSubscriber<>(capture::set, __ -> {}, latch::countDown, s -> s.request(1)));

    latch.await(5, TimeUnit.SECONDS);

    Assertions.assertThat(capture.get()).isEqualTo(1L);
    Assertions.assertThat(requested).containsExactly(1L);
}
 
Example 8
Source File: ReactorProbe.java    From Hands-On-Reactive-Programming-with-Reactor with MIT License 5 votes vote down vote up
@Test
public void testPublisherStub() throws Exception {
    Hooks.onOperatorDebug();
    TestPublisher<Long> numberGenerator= TestPublisher.<Long>create();
    StringWriter out = new StringWriter();
    new PrintService().printEventNumbers(numberGenerator.flux(),new PrintWriter(out));
    numberGenerator.next(1L,2L,3L,4L);
    numberGenerator.complete();
    assertTrue(out.getBuffer().length() >0);
}
 
Example 9
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleComplete() {
    TestPublisher<String> publisher = TestPublisher.create();
    publisher.subscribe(subscriber);

    publisher.complete();

    verify(mockMonoSink).success();
}
 
Example 10
Source File: FluxBufferPredicateTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void requestRaceWithOnNext() {
	AtomicLong requested = new AtomicLong();
	TestPublisher<Integer> testPublisher = TestPublisher.create();
	FluxBufferPredicate<Integer, List<Integer>> bufferPredicate = new FluxBufferPredicate<>(
			testPublisher.flux().doOnRequest(requested::addAndGet),
			i -> true, ArrayList::new, FluxBufferPredicate.Mode.UNTIL);

	BaseSubscriber<List<Integer>> subscriber = new BaseSubscriber<List<Integer>>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			request(1);
		}
	};
	bufferPredicate.subscribe(subscriber);
	@SuppressWarnings("unchecked")
	final FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>> bufferPredicateSubscriber =
			(FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>>) subscriber.subscription;

	for (int i = 0; i < 10; i++) {
		final int value = i;
		RaceTestUtils.race(() -> subscriber.request(1), () -> testPublisher.next(value));
	}
	for (int i = 0; i < bufferPredicateSubscriber.requestedFromSource; i++) {
		testPublisher.next(100 + i);
	}
	testPublisher.complete();

	assertThat(requested).as("total upstream request").hasValue(10 + 1);
}
 
Example 11
Source File: FluxBufferPredicateTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void onNextRaceWithRequest() {
	AtomicLong requested = new AtomicLong();
	TestPublisher<Integer> testPublisher = TestPublisher.create();
	FluxBufferPredicate<Integer, List<Integer>> bufferPredicate = new FluxBufferPredicate<>(
			testPublisher.flux().doOnRequest(requested::addAndGet),
			i -> true, ArrayList::new, FluxBufferPredicate.Mode.UNTIL);

	BaseSubscriber<List<Integer>> subscriber = new BaseSubscriber<List<Integer>>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			request(1);
		}
	};
	bufferPredicate.subscribe(subscriber);
	@SuppressWarnings("unchecked")
	final FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>> bufferPredicateSubscriber =
			(FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>>) subscriber.subscription;

	for (int i = 0; i < 10; i++) {
		final int value = i;
		RaceTestUtils.race(() -> testPublisher.next(value), () -> subscriber.request(1));
	}
	for (int i = 0; i < bufferPredicateSubscriber.requestedFromSource; i++) {
		testPublisher.next(100 + i);
	}
	testPublisher.complete();

	assertThat(requested).as("total upstream request").hasValue(10 + 1);
}
 
Example 12
Source File: FluxBufferPredicateTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void onNextRaceWithRequestOfTwo() {
	AtomicLong requested = new AtomicLong();
	TestPublisher<Integer> testPublisher = TestPublisher.create();
	FluxBufferPredicate<Integer, List<Integer>> bufferPredicate = new FluxBufferPredicate<>(
			testPublisher.flux().doOnRequest(requested::addAndGet),
			i -> true, ArrayList::new, FluxBufferPredicate.Mode.UNTIL);

	BaseSubscriber<List<Integer>> subscriber = new BaseSubscriber<List<Integer>>() {
		@Override
		protected void hookOnSubscribe(Subscription subscription) {
			request(1);
		}
	};
	bufferPredicate.subscribe(subscriber);
	@SuppressWarnings("unchecked")
	final FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>> bufferPredicateSubscriber =
			(FluxBufferPredicate.BufferPredicateSubscriber<Integer, List<Integer>>) subscriber.subscription;

	for (int i = 0; i < 10; i++) {
		final int value = i;
		RaceTestUtils.race(() -> testPublisher.next(value), () -> subscriber.request(2));
	}
	for (int i = 0; i < bufferPredicateSubscriber.requestedFromSource; i++) {
		testPublisher.next(100 + i);
	}
	testPublisher.complete();

	assertThat(requested).as("total upstream request").hasValue(2 * 10 + 1);
}
 
Example 13
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotExpiredIfNotCompleted() {
  final TestPublisher<String> publisher =
      TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW);

  final ReconnectMono<String> reconnectMono =
      publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

  MonoProcessor<String> processor = MonoProcessor.create();

  reconnectMono.subscribe(processor);

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  publisher.next("test");

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  reconnectMono.invalidate();

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();
  publisher.assertSubscribers(1);
  Assertions.assertThat(publisher.subscribeCount()).isEqualTo(1);

  publisher.complete();

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).hasSize(1);
  Assertions.assertThat(processor.isTerminated()).isTrue();

  publisher.assertSubscribers(0);
  Assertions.assertThat(publisher.subscribeCount()).isEqualTo(1);
}
 
Example 14
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotEmitUntilCompletion() {
  final TestPublisher<String> publisher =
      TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW);

  final ReconnectMono<String> reconnectMono =
      publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

  MonoProcessor<String> processor = MonoProcessor.create();

  reconnectMono.subscribe(processor);

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  publisher.next("test");

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  publisher.complete();

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).hasSize(1);
  Assertions.assertThat(processor.isTerminated()).isTrue();
  Assertions.assertThat(processor.peek()).isEqualTo("test");
}
 
Example 15
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBePossibleToRemoveThemSelvesFromTheList_CancellationTest() {
  final TestPublisher<String> publisher =
      TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW);

  final ReconnectMono<String> reconnectMono =
      publisher.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

  MonoProcessor<String> processor = MonoProcessor.create();

  reconnectMono.subscribe(processor);

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  publisher.next("test");

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).isEmpty();
  Assertions.assertThat(processor.isTerminated()).isFalse();

  processor.cancel();

  Assertions.assertThat(reconnectMono.resolvingInner.subscribers)
      .isEqualTo(ResolvingOperator.EMPTY_SUBSCRIBED);

  publisher.complete();

  Assertions.assertThat(expired).isEmpty();
  Assertions.assertThat(received).hasSize(1);
  Assertions.assertThat(processor.isTerminated()).isFalse();
  Assertions.assertThat(processor.peek()).isNull();
}
 
Example 16
Source File: RSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
void completeFromRequesterPublisher(
    TestPublisher<Payload> requesterPublisher, AssertSubscriber<Payload> responderSubscriber) {
  // ensures that after sending complete upstream part is closed
  requesterPublisher.complete();
  responderSubscriber.assertTerminated();
  requesterPublisher.assertNoSubscribers();
}
 
Example 17
Source File: RSocketTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
void completeFromResponderPublisher(
    TestPublisher<Payload> responderPublisher, AssertSubscriber<Payload> requesterSubscriber) {
  // ensures that after sending complete inner upstream is closed
  responderPublisher.complete();
  requesterSubscriber.assertTerminated();
  responderPublisher.assertNoSubscribers();
}
 
Example 18
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyCompleteFlow() {
    TestWriteStream<String> writeStream = new TestWriteStream<>();
    TestPublisher<String> publisher = TestPublisher.create();

    Subscriber<String> subscriber = new WriteStreamSubscriber.Builder<WriteStream<String>, String>()
        .writeStream(writeStream)
        .nextHandler(WriteStream::write)
        .endHook(mockMonoSink)
        .build();

    writeStream.setWriteQueueMaxSize(2);

    publisher.subscribe(subscriber);
    publisher.assertMinRequested(1);

    publisher.next("first");
    publisher.assertMinRequested(1);

    publisher.next("second");
    publisher.assertMinRequested(0);
    assertThat(writeStream.getReceived()).containsOnly("first", "second");

    writeStream.clearReceived();
    publisher.assertMinRequested(1);

    publisher.next("third");
    assertThat(writeStream.getReceived()).containsOnly("third");

    publisher.complete();
    verify(mockMonoSink).success();
}
 
Example 19
Source File: FluxRefCountGraceTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void doesDisconnectAfterRefCountZeroAndSlowResubscribe()
		throws InterruptedException {
	AtomicLong subscriptionCount = new AtomicLong();
	AtomicReference<SignalType> termination = new AtomicReference<>();

	TestPublisher<Integer> publisher = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE);

	Flux<Integer> source = publisher.flux()
	                                .doFinally(termination::set)
	                                .doOnSubscribe(s -> subscriptionCount.incrementAndGet());

	Flux<Integer> refCounted = source.publish().refCount(2, Duration.ofMillis(500));

	Disposable sub1 = refCounted.subscribe();
	//initial subscribe doesn't reach the count
	assertThat(subscriptionCount.get()).isZero();
	assertThat(termination.get()).isNull();

	Disposable sub2 = refCounted.subscribe();
	//second subscribe does reaches the count
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub1.dispose();
	//all subscribers are not disposed so source isn't terminated
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub2.dispose();
	//all subscribers are now disposed, but grace period kicks in
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	//we wait for grace period to elapse
	Thread.sleep(600);
	assertThat(termination.get()).isEqualTo(SignalType.CANCEL);
	termination.set(null);

	//we then resubscribe
	sub1 = refCounted.subscribe();
	sub2 = refCounted.subscribe();
	assertThat(subscriptionCount.get()).isEqualTo(2);

	//since the TestPublisher doesn't cleanup on termination, we can re-evaluate the doFinally
	publisher.complete();
	assertThat(termination.get()).isEqualTo(SignalType.ON_COMPLETE);
}
 
Example 20
Source File: FluxRefCountGraceTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void doesntDisconnectAfterRefCountZeroAndQuickResubscribe()
		throws InterruptedException {
	AtomicLong subscriptionCount = new AtomicLong();
	AtomicReference<SignalType> termination = new AtomicReference<>();

	TestPublisher<Integer> publisher = TestPublisher.create();

	Flux<Integer> source = publisher.flux()
	                                .doFinally(termination::set)
	                                .doOnSubscribe(s -> subscriptionCount.incrementAndGet());

	Flux<Integer> refCounted = source.publish().refCount(2, Duration.ofMillis(800));

	Disposable sub1 = refCounted.subscribe();
	//initial subscribe doesn't reach the count
	assertThat(subscriptionCount.get()).isZero();
	assertThat(termination.get()).isNull();

	Disposable sub2 = refCounted.subscribe();
	//second subscribe does reaches the count
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub1.dispose();
	//all subscribers are not disposed so source isn't terminated
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	sub2.dispose();
	//all subscribers are now disposed, but grace period kicks in
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	//we re-subscribe quickly before grace period elapses
	sub1 = refCounted.subscribe();
	sub2 = refCounted.subscribe();

	//we sleep until sure the initial grace period is over
	Thread.sleep(500);

	//we expect the subscription to be still active
	assertThat(subscriptionCount.get()).isEqualTo(1);
	assertThat(termination.get()).isNull();

	publisher.complete();
	assertThat(termination.get()).isEqualTo(SignalType.ON_COMPLETE);
}