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

The following examples show how to use reactor.test.publisher.TestPublisher#create() . 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: FluxBufferWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void openCloseOpenCompletesNoBuffers() {
	TestPublisher<Integer> source = TestPublisher.create();
	TestPublisher<Integer> open = TestPublisher.create();
	TestPublisher<Integer> close = TestPublisher.create();

	StepVerifier.create(source.flux()
	                          .bufferWhen(open, o -> close))
	            .then(() -> {
		            open.next(1);
		            close.assertSubscribers();
	            })
	            .then(() -> {
		            close.complete();
		            source.assertSubscribers();
		            open.assertSubscribers();
	            })
	            .then(() -> {
		            open.complete();
		            source.assertNoSubscribers();
	            })
	            .expectNextMatches(List::isEmpty)
	            .verifyComplete();
}
 
Example 2
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleOnDiscardRequestChannelTest2() {
  ByteBufAllocator allocator = rule.alloc();
  AssertSubscriber<Payload> assertSubscriber = AssertSubscriber.create(1);
  TestPublisher<Payload> testPublisher = TestPublisher.create();

  Flux<Payload> payloadFlux = rule.socket.requestChannel(testPublisher);

  payloadFlux.subscribe(assertSubscriber);

  testPublisher.next(ByteBufPayload.create("d", "m"));

  int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL);
  testPublisher.next(ByteBufPayload.create("d1", "m1"), ByteBufPayload.create("d2", "m2"));

  rule.connection.addToReceivedBuffer(
      ErrorFrameCodec.encode(
          allocator, streamId, new CustomRSocketException(0x00000404, "test")));

  Assertions.assertThat(rule.connection.getSent()).allMatch(ByteBuf::release);

  rule.assertHasNoLeaks();
}
 
Example 3
Source File: AbstractEventHandlerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_resubscribe_after_error() {
    TestPublisher<InstanceEvent> testPublisher = TestPublisher.create();

    TestEventHandler eventHandler = new TestEventHandler(testPublisher.flux());
    eventHandler.start();

    StepVerifier.create(eventHandler.getFlux())
            .expectSubscription()
            .then(() -> testPublisher.next(event))
            .expectNext(event)
            .then(() -> testPublisher.next(errorEvent))
            .expectNoEvent(Duration.ofMillis(100L))
            .then(() -> testPublisher.next(event))
            .expectNext(event)
            .thenCancel()
            .verify(Duration.ofSeconds(5));

}
 
Example 4
Source File: ParallelFluxTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void parallelSubscribeAndDispose() throws InterruptedException {
	AtomicInteger nextCount = new AtomicInteger();
	CountDownLatch cancelLatch = new CountDownLatch(1);
	TestPublisher<Integer> source = TestPublisher.create();

	Disposable d = source
			.flux()
			.parallel(3)
			.doOnCancel(cancelLatch::countDown)
			.subscribe(i -> nextCount.incrementAndGet());

	source.next(1, 2, 3);
	d.dispose();

	source.emit(4, 5, 6);

	boolean finished = cancelLatch.await(300, TimeUnit.MILLISECONDS);

	assertThat(finished).as("cancelled latch").isTrue();
	assertThat(d.isDisposed()).as("disposed").isTrue();
	assertThat(nextCount.get()).as("received count").isEqualTo(3);
}
 
Example 5
Source File: MonoCacheTimeTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void coordinatorCacheInnerDisposedOrNoReferenceNoLeak() throws InterruptedException {
	TestPublisher<Integer> source = TestPublisher.create();

	MonoCacheTime<Integer> cached = new MonoCacheTime<>(source.mono(),
			Duration.ofMillis(100), //short cache TTL should trigger state change if source is not never
			Schedulers.parallel());

	Disposable d1 = cached.subscribe();
	cached.subscribe();

	WeakReference<Signal<Integer>> refCoordinator = new WeakReference<>(cached.state);

	assertThat(refCoordinator.get()).isInstanceOf(MonoCacheTime.CoordinatorSubscriber.class);

	Thread.sleep(150);
	source = null;
	cached = null;
	d1.dispose();
	System.gc();

	assertThat(refCoordinator.get()).isNull();
}
 
Example 6
Source File: FluxOnBackpressureBufferTimeoutTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void evictThrows() {

	TestPublisher<Integer> tp = TestPublisher.create();
	StepVerifier.withVirtualTime(() -> tp.flux()
	                                     .onBackpressureBuffer(Duration.ofSeconds(1), 10, i -> {
		                                     throw new IllegalStateException(i.toString());
	                                     }),
			0)
	            .then(() -> tp.emit(1, 2, 3, 4, 5))
	            .thenAwait(Duration.ofMinutes(1))
	            .thenRequest(1)
	            .expectComplete()
	            .verifyThenAssertThat()
	            .hasDroppedErrors(5)
	            .hasDroppedErrorsSatisfying(c -> {
		            Iterator<Throwable> it = c.iterator();
		            for (int i = 1; it.hasNext(); i++) {
		            	assertThat(it.next())
					            .isInstanceOf(IllegalStateException.class)
					            .hasMessage("" + i);
		            }
	            });
}
 
Example 7
Source File: FluxBufferWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void openCloseEmptyBackpressure() {
		TestPublisher<Integer> source = TestPublisher.create();
		TestPublisher<Integer> open = TestPublisher.create();
		TestPublisher<Integer> close = TestPublisher.create();

		StepVerifier.create(source.flux()
				.bufferWhen(open, o -> close), 0)
		            .then(() -> {
		            	source.complete();
		            	open.assertNoSubscribers();
		            	close.assertNoSubscribers();
		            })
		            .verifyComplete();
//		ts.assertResult();
	}
 
Example 8
Source File: VertxClientHttpRequestTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldWriteFromPublisherAndFlush() {
    Buffer firstChunk = Buffer.buffer("chunk 1");
    Buffer secondChunk = Buffer.buffer("chunk 2");

    TestPublisher<DataBuffer> source = TestPublisher.create();
    Mono<Void> result = request.writeAndFlushWith(Flux.just(source));

    StepVerifier.create(result)
        .expectSubscription()
        .then(() -> source.assertMinRequested(1))
        .then(() -> source.next(bufferConverter.toDataBuffer(firstChunk)))
        .then(() -> source.assertMinRequested(1))
        .then(() -> source.next(bufferConverter.toDataBuffer(secondChunk)))
        .then(() -> source.assertMinRequested(1))
        .then(source::complete)
        .verifyComplete();

    verify(mockHttpClientRequest).write(firstChunk);
    verify(mockHttpClientRequest).write(secondChunk);
    verify(mockHttpClientRequest).end();
}
 
Example 9
Source File: FluxWindowWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void endDoneThenNext() {
	TestPublisher<Integer> source = TestPublisher.create();
	TestPublisher<Integer> start = TestPublisher.create();
	TestPublisher<Integer> end = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE);

	StepVerifier.create(source.flux()
	                          .windowWhen(start, v -> end)
	                          .flatMap(Flux.identityFunction())
	)
	            .then(() -> start.next(1))
	            .then(() -> end.error(new IllegalStateException("boom"))
	                           .next(1))
	            .expectErrorMessage("boom")
	            .verifyThenAssertThat()
	            .hasNotDroppedErrors()
	            .hasNotDroppedElements();

	source.assertNoSubscribers();
	start.assertNoSubscribers();
	//end doesn't cleanup and as such still has a subscriber
}
 
Example 10
Source File: WriteStreamSubscriberTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleOnSubscribe() {
    TestPublisher<String> publisher = TestPublisher.create();

    publisher.subscribe(subscriber);

    publisher.assertMinRequested(1);
    verify(mockWriteStream).drainHandler(any(Handler.class));
}
 
Example 11
Source File: FluxLimitRequestTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void completeUnderCap() {
	TestPublisher<Integer> tp = TestPublisher.create();

	StepVerifier.create(tp.flux().limitRequest(4))
	            .then(() -> tp.emit(1, 2, 3))
	            .expectNext(1, 2, 3)
	            .verifyComplete();
}
 
Example 12
Source File: MonoTakeUntilOtherTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void apiTakeUntilOtherErrorBeforeOther() {
	TestPublisher<String> other = TestPublisher.create();

	StepVerifier.withVirtualTime(() ->
			Mono.delay(Duration.ofMillis(100))
			    .then(Mono.error(new IllegalStateException("boom")))
			    .takeUntilOther(other)
	)
	            .thenAwait(Duration.ofMillis(200))
	            .then(() -> other.next("go"))
	            .verifyErrorMessage("boom");

	other.assertCancelled();
}
 
Example 13
Source File: MonoElementAtTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void cancel() {
	TestPublisher<String> cancelTester = TestPublisher.create();

	MonoProcessor<String> processor = cancelTester.flux()
	                                              .elementAt(1000)
	                                              .toProcessor();
	processor.subscribe();
	processor.cancel();

	cancelTester.assertCancelled();
}
 
Example 14
Source File: MonoProcessorTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoToProcessorConnects() {
	TestPublisher<String> tp = TestPublisher.create();
	MonoProcessor<String> connectedProcessor = tp.mono().toProcessor();

	assertThat(connectedProcessor.subscription).isNotNull();
}
 
Example 15
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void thenCancel_cancelsAfterFirst2() {
	TestPublisher<Long> publisher = TestPublisher.create();
	AtomicBoolean downStreamCancelled = new AtomicBoolean();
	AtomicBoolean asserted = new AtomicBoolean();
	Flux<Long> source = publisher
			.flux()
			.doOnCancel(() -> downStreamCancelled.set(true));

	Duration took = StepVerifier.create(source)
	                            .then(() -> Schedulers.boundedElastic().schedule(() -> publisher.next(0L)))
	                            .assertNext(next -> {
		                            asserted.set(true);
		                            assertThat(next).isEqualTo(0L);
	                            })
	                            .then(() -> Schedulers.boundedElastic().schedule(() ->
			                            publisher.next(1L)))
	                            .thenCancel()
	                            .verify(Duration.ofSeconds(5));

	publisher.assertCancelled();

	assertThat(asserted.get())
			.as("expectation processed")
			.isTrue();
	assertThat(downStreamCancelled.get())
			.as("is cancelled by awaitThenCancel")
			.isTrue();
}
 
Example 16
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCancelSourceOnUnrelatedPublisherCancel() {
    TestPublisher<Long> testPublisher = TestPublisher.create();

    StepVerifier.create(testPublisher.flux().switchOnFirst((s, f) -> Flux.error(new RuntimeException("test"))))
                .expectSubscription()
                .thenCancel()
                .verify(Duration.ofSeconds(5));

    Assertions.assertThat(testPublisher.wasCancelled()).isTrue();
}
 
Example 17
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCancelInnerSubscriptionImmediatelyUpOnReceivingIfDownstreamIsAlreadyCancelled() {
    VirtualTimeScheduler virtualTimeScheduler = VirtualTimeScheduler.getOrSet();
    TestPublisher<Long> testPublisher = TestPublisher.create();
    TestPublisher<Long> testPublisherInner = TestPublisher.create();

    try {
        StepVerifier
                .create(
                        testPublisher
                                .flux()
                                .switchOnFirst((s, f) ->
                                                testPublisherInner
                                                        .flux()
                                                        .transform(Operators.lift((__, cs) -> new BaseSubscriber<Long>() {
                                                            @Override
                                                            protected void hookOnSubscribe(Subscription subscription) {
                                                                Schedulers.parallel().schedule(() -> cs.onSubscribe(this), 1, TimeUnit.SECONDS);
                                                            }
                                                        })),
                                        false
                                )
                )
                .expectSubscription()
                .then(() -> testPublisher.next(1L))
                .thenCancel()
                .verify(Duration.ofSeconds(5));

        Assertions.assertThat(testPublisher.wasCancelled()).isTrue();
        Assertions.assertThat(testPublisherInner.wasCancelled()).isFalse();
        virtualTimeScheduler.advanceTimeBy(Duration.ofMillis(1000));
        Assertions.assertThat(testPublisherInner.wasCancelled()).isTrue();
    } finally {
        VirtualTimeScheduler.reset();
    }
}
 
Example 18
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 19
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("lifoPools")
void smokeTestInScopeLifo(Function<PoolBuilder<PoolableTest, ?>, AbstractPool<PoolableTest>> configAdjuster) {
	AtomicInteger newCount = new AtomicInteger();
	PoolBuilder<PoolableTest, ?> builder =
			//default maxUse is 5, but this test relies on it being 2
			PoolBuilder.from(Mono.defer(() -> Mono.just(new PoolableTest(newCount.incrementAndGet(), 2))))
			           .sizeBetween(2, 3)
			           .releaseHandler(pt -> Mono.fromRunnable(pt::clean))
			           .evictionPredicate((value, metadata) -> !value.isHealthy());
	AbstractPool<PoolableTest> pool = configAdjuster.apply(builder);
	pool.warmup().block();

	TestPublisher<Integer> trigger1 = TestPublisher.create();
	TestPublisher<Integer> trigger2 = TestPublisher.create();
	TestPublisher<Integer> cleanupTrigger = TestPublisher.create();

	List<PoolableTest> acquired1 = new ArrayList<>();

	Mono.when(
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired1::add).delayUntil(__ -> trigger1)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired1::add).delayUntil(__ -> trigger1)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired1::add).delayUntil(__ -> trigger1))
	).subscribe();

	List<PoolableTest> acquired2 = new ArrayList<>();
	Mono.when(
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired2::add).delayUntil(__ -> cleanupTrigger)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired2::add).delayUntil(__ -> cleanupTrigger)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired2::add).delayUntil(__ -> cleanupTrigger))
	).subscribe();

	List<PoolableTest> acquired3 = new ArrayList<>();
	Mono.when(
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired3::add).delayUntil(__ -> trigger2)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired3::add).delayUntil(__ -> trigger2)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired3::add).delayUntil(__ -> trigger2))
	).subscribe();

	assertThat(acquired1).as("first batch not pending").hasSize(3);
	assertThat(acquired2).as("second and third pending").hasSameSizeAs(acquired3).isEmpty();

	trigger1.emit(1);

	assertThat(acquired3).as("batch3 after trigger1").hasSize(3);
	assertThat(acquired2).as("batch2 after trigger1").isEmpty();

	trigger2.emit(1);
	assertThat(acquired2).as("batch2 after trigger2").hasSize(3);

	assertThat(newCount).as("allocated total").hasValue(6);

	cleanupTrigger.emit(1); //release the objects

	assertThat(acquired1)
			.as("acquired1/3 all used up")
			.hasSameElementsAs(acquired3)
			.allSatisfy(elem -> assertThat(elem.usedUp).isEqualTo(2));

	assertThat(acquired2)
			.as("acquired2 all new (released once)")
			.allSatisfy(elem -> assertThat(elem.usedUp).isOne());
}
 
Example 20
Source File: FluxWindowPredicateTest.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void prefetchIntegerMaxIsRequestUnboundedWhile() {
	TestPublisher<?> tp = TestPublisher.create();
	tp.flux().windowWhile(s -> true, Integer.MAX_VALUE).subscribe();
	tp.assertMinRequested(Long.MAX_VALUE);
}