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

The following examples show how to use reactor.test.publisher.TestPublisher#assertCancelled() . 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: BodyExtractorsTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void toMonoVoidAsClientShouldConsumeAndCancel() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	TestPublisher<DataBuffer> body = TestPublisher.create();

	BodyExtractor<Mono<Void>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(Void.class);
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.setBody(body.flux());

	StepVerifier.create(extractor.extract(response, this.context))
			.then(() -> {
				body.assertWasSubscribed();
				body.emit(dataBuffer);
			})
			.verifyComplete();

	body.assertCancelled();
}
 
Example 2
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToBeCancelledProperly3() {
    TestPublisher<Integer> publisher = TestPublisher.createCold();
    Flux<String> switchTransformed = publisher.flux()
                                              .switchOnFirst((first, innerFlux) ->
                                                      innerFlux
                                                              .map(String::valueOf)
                                              )
                                              .take(1);

    publisher.next(1);
    publisher.next(2);
    publisher.next(3);
    publisher.next(4);

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

    publisher.assertCancelled();
    publisher.assertWasRequested();
}
 
Example 3
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToBeCancelledProperly2() {
    TestPublisher<Integer> publisher = TestPublisher.createCold();
    Flux<String> switchTransformed = publisher.flux()
                                              .switchOnFirst((first, innerFlux) ->
                                                  innerFlux
                                                      .map(String::valueOf)
                                                      .take(1)
                                              );

    publisher.next(1);
    publisher.next(2);
    publisher.next(3);
    publisher.next(4);

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

    publisher.assertCancelled();
    publisher.assertWasRequested();
}
 
Example 4
Source File: MonoDelayElementTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void cancelUpstreamOnceWhenRejected() {
	VirtualTimeScheduler vts = VirtualTimeScheduler.create();
	vts.dispose();

	TestPublisher<Object> testPublisher = TestPublisher.createCold();
	testPublisher.emit("Hello");

	StepVerifier.create(new MonoDelayElement<>(testPublisher.mono(), 2, TimeUnit.SECONDS, vts))
	            .verifyErrorSatisfies(e -> {
		            assertThat(e)
				            .isInstanceOf(RejectedExecutionException.class)
				            .hasMessage("Scheduler unavailable");
	            });

	testPublisher.assertWasRequested();
	testPublisher.assertCancelled(1);
}
 
Example 5
Source File: FluxUsingWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void secondResourceInPublisherIsDropped() {
	AtomicBoolean commitDone = new AtomicBoolean();
	AtomicBoolean rollbackDone = new AtomicBoolean();

	TestPublisher<String> testPublisher = TestPublisher.createCold();
	testPublisher.emit("Resource", "boom");

	Flux<String> test = Flux.usingWhen(testPublisher,
			Mono::just,
			tr -> Mono.fromRunnable(() -> commitDone.set(true)),
			(tr, err) -> Mono.fromRunnable(() -> rollbackDone.set(true)),
			tr -> Mono.fromRunnable(() -> rollbackDone.set(true)));

	StepVerifier.create(test)
	            .expectNext("Resource")
	            .expectComplete()
	            .verifyThenAssertThat(Duration.ofSeconds(2))
	            .hasDropped("boom")
	            .hasNotDroppedErrors();

	assertThat(commitDone).isTrue();
	assertThat(rollbackDone).isFalse();

	testPublisher.assertCancelled();
}
 
Example 6
Source File: FluxUsingWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void errorResourcePublisherAfterEmitIsDropped() {
	AtomicBoolean commitDone = new AtomicBoolean();
	AtomicBoolean rollbackDone = new AtomicBoolean();

	TestPublisher<String> testPublisher = TestPublisher.createCold();
	testPublisher.next("Resource").error(new IllegalStateException("boom"));

	Flux<String> test = Flux.usingWhen(testPublisher,
			Mono::just,
			tr -> Mono.fromRunnable(() -> commitDone.set(true)),
			(tr, err) -> Mono.fromRunnable(() -> rollbackDone.set(true)),
			tr -> Mono.fromRunnable(() -> rollbackDone.set(true)));

	StepVerifier.create(test)
	            .expectNext("Resource")
	            .expectComplete()
	            .verifyThenAssertThat(Duration.ofSeconds(2))
	            .hasDroppedErrorWithMessage("boom")
	            .hasNotDroppedElements();

	assertThat(commitDone).isTrue();
	assertThat(rollbackDone).isFalse();

	testPublisher.assertCancelled();
}
 
Example 7
Source File: MonoUsingWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void errorResourcePublisherAfterEmitIsDropped() {
	AtomicBoolean commitDone = new AtomicBoolean();
	AtomicBoolean rollbackDone = new AtomicBoolean();

	TestPublisher<String> testPublisher = TestPublisher.createCold();
	testPublisher.next("Resource").error(new IllegalStateException("boom"));

	Mono<String> test = Mono.usingWhen(testPublisher,
			Mono::just,
			tr -> Mono.fromRunnable(() -> commitDone.set(true)),
			(tr, err) -> Mono.fromRunnable(() -> rollbackDone.set(true)),
			tr -> Mono.fromRunnable(() -> rollbackDone.set(true)));

	StepVerifier.create(test)
	            .expectNext("Resource")
	            .expectComplete()
	            .verifyThenAssertThat(Duration.ofSeconds(2))
	            .hasDroppedErrorWithMessage("boom")
	            .hasNotDroppedElements();

	assertThat(commitDone).isTrue();
	assertThat(rollbackDone).isFalse();

	testPublisher.assertCancelled();
}
 
Example 8
Source File: BodyExtractorsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void toMonoVoidAsClientShouldConsumeAndCancel() {
	DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
	DefaultDataBuffer dataBuffer =
			factory.wrap(ByteBuffer.wrap("foo".getBytes(StandardCharsets.UTF_8)));
	TestPublisher<DataBuffer> body = TestPublisher.create();

	BodyExtractor<Mono<Void>, ReactiveHttpInputMessage> extractor = BodyExtractors.toMono(Void.class);
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.setBody(body.flux());

	StepVerifier.create(extractor.extract(response, this.context))
			.then(() -> {
				body.assertWasSubscribed();
				body.emit(dataBuffer);
			})
			.verifyComplete();

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

	StepVerifier.withVirtualTime(() ->
			Mono.delay(Duration.ofMillis(200))
			    .takeUntilOther(other)
	)
	            .thenAwait(Duration.ofMillis(100))
	            .then(() -> other.next("go"))
	            .verifyComplete();

	other.assertCancelled();
}
 
Example 10
Source File: MonoAnyTest.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<Boolean> processor = cancelTester.flux()
	                                               .any(s -> s.length() > 100)
	                                               .toProcessor();
	processor.subscribe();
	processor.cancel();

	cancelTester.assertCancelled();
}
 
Example 11
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 12
Source File: MonoFlatMapTest.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<Integer> processor = cancelTester.mono()
												   .flatMap(s -> Mono.just(s.length()))
												   .toProcessor();
	processor.subscribe();
	processor.cancel();

	cancelTester.assertCancelled();
}
 
Example 13
Source File: ByteStreamAggregatorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void emitsErrors() {
    AtomicReference<Throwable> causeCapture = new AtomicReference<>(null);

    Buffer a = new Buffer("aaabbb", UTF_8);

    TestPublisher<Buffer> upstream = TestPublisher.create();

    ByteStreamAggregator aggregator = new ByteStreamAggregator(upstream, 8);

    CompletableFuture<Buffer> future = aggregator.apply()
            .exceptionally(cause -> {
                causeCapture.set(cause);
                throw new RuntimeException();
            });

    upstream.next(a);
    upstream.error(new RuntimeException("something broke"));

    upstream.assertCancelled();

    assertTrue(future.isCompletedExceptionally());
    assertThat(causeCapture.get(), instanceOf(RuntimeException.class));
    assertThat(causeCapture.get().getMessage(), is("something broke"));

    assertThat(a.delegate().refCnt(), is(0));
}
 
Example 14
Source File: MonoNextTest.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()
	                                              .next()
	                                              .toProcessor();
	processor.subscribe();
	processor.cancel();

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

	StepVerifier.withVirtualTime(() ->
			Mono.delay(Duration.ofMillis(100))
			    .takeUntilOther(other)
	)
	            .thenAwait(Duration.ofMillis(200))
	            .then(() -> other.next("go"))
	            .expectNext(0L)
	            .verifyComplete();

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

	StepVerifier.withVirtualTime(() ->
			Mono.delay(Duration.ofMillis(100))
			    .ignoreElement()
			    .takeUntilOther(other)
	)
	            .thenAwait(Duration.ofMillis(200))
	            .then(() -> other.next("go"))
	            .verifyComplete();

	other.assertCancelled();
}
 
Example 17
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToBeCancelledProperly() throws InterruptedException {
    CountDownLatch latch1 = new CountDownLatch(1);
    CountDownLatch latch2 = new CountDownLatch(1);
    TestPublisher<Integer> publisher = TestPublisher.createCold();
    Flux<String> switchTransformed = publisher.flux()
            .doOnCancel(latch2::countDown)
            .switchOnFirst((first, innerFlux) -> innerFlux.map(String::valueOf))
            .doOnCancel(() -> {
                try {
                    if (!latch1.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("latch didn't complete in 5s");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            })
            .cancelOn(Schedulers.boundedElastic());

    publisher.next(1);

    StepVerifier stepVerifier = StepVerifier.create(switchTransformed, 0)
            .thenCancel()
            .verifyLater();

    latch1.countDown();
    stepVerifier.verify(Duration.ofSeconds(10));

    Assertions.assertThat(latch2.await(1, TimeUnit.SECONDS)).isTrue();

    Instant endTime = Instant.now().plusSeconds(5);
    while (!publisher.wasCancelled()) {
        if (endTime.isBefore(Instant.now())) {
            break;
        }
    }
    publisher.assertCancelled();
    publisher.assertWasRequested();
}
 
Example 18
Source File: ByteStreamAggregatorTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void aggregatesUpToNBytes() {
    AtomicReference<Throwable> causeCapture = new AtomicReference<>(null);

    Buffer a = new Buffer("aaabbb", UTF_8);
    Buffer b = new Buffer("ccc", UTF_8);

    TestPublisher<Buffer> upstream = TestPublisher.create();

    ByteStreamAggregator aggregator = new ByteStreamAggregator(upstream, 8);

    CompletableFuture<Buffer> future = aggregator.apply()
            .exceptionally(cause -> {
                causeCapture.set(cause);
                throw new RuntimeException();
            });

    upstream.next(a);
    upstream.next(b);

    upstream.assertCancelled();

    assertTrue(future.isCompletedExceptionally());
    assertThat(causeCapture.get(), instanceOf(ContentOverflowException.class));

    assertThat(a.delegate().refCnt(), is(0));
    assertThat(b.delegate().refCnt(), is(0));
}
 
Example 19
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 20
Source File: StepVerifierTests.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
@Test
public void thenCancel_cancelsAfterFirst() {
	TestPublisher<Long> publisher = TestPublisher.create();
	AtomicBoolean downStreamCancelled = new AtomicBoolean();
	AtomicBoolean asserted = new AtomicBoolean();
	Flux<Long> source = publisher
			.flux()
			.onBackpressureBuffer()
			.doOnCancel(() -> downStreamCancelled.set(true))
			.log();

	Duration took = StepVerifier.create(source,  1)
	                            .then(() -> Schedulers.boundedElastic().schedule(() -> publisher.next(0L)))
	                            .assertNext(next -> {
		                            LockSupport.parkNanos(Duration.ofMillis(500)
		                                                          .toNanos());
		                            asserted.set(true);
		                            assertThat(next).isEqualTo(0L);
	                            })
	                            .then(() -> Schedulers.boundedElastic().schedule(() ->
			                            publisher.next(1L)))
	                            .then(() -> Schedulers.boundedElastic().schedule(() ->
			                            publisher.next(2L), 50, TimeUnit.MILLISECONDS))
	                            .expectNoEvent(Duration.ofMillis(100))
	                            .thenRequest(1)
	                            .thenRequest(1)
	                            .assertNext(next -> {
		                            LockSupport.parkNanos(Duration.ofMillis(500)
		                                                          .toNanos());
		                            assertThat(next).isEqualTo(1L);
	                            })
	                            .thenAwait(Duration.ofSeconds(2))
	                            .thenCancel()
	                            .verify(Duration.ofSeconds(5));

	publisher.assertCancelled();

	assertThat(asserted.get())
			.as("expectation processed")
			.isTrue();
	assertThat(downStreamCancelled.get())
			.as("is cancelled by awaitThenCancel")
			.isTrue();
	assertThat(took.toMillis())
			.as("blocked on first assertNext")
			.isGreaterThanOrEqualTo(1000L);
}