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

The following examples show how to use reactor.test.publisher.TestPublisher#createCold() . 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: 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 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: 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 4
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldErrorOnOverflowTest() {
    TestPublisher<Long> publisher = TestPublisher.createCold();

    Flux<String> switchTransformed = publisher.flux()
                                              .switchOnFirst((first, innerFlux) -> innerFlux.map(String::valueOf));

    publisher.next(1L);

    StepVerifier.create(switchTransformed, 0)
                .thenRequest(1)
                .expectNext("1")
                .then(() -> publisher.next(2L))
                .expectErrorSatisfies(t -> Assertions
                    .assertThat(t)
                    .isInstanceOf(IllegalStateException.class)
                    .hasMessage("Can't deliver value due to lack of requests")
                )
                .verify(Duration.ofSeconds(10));

    publisher.assertWasRequested();
    publisher.assertNoRequestOverflow();
}
 
Example 5
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void backpressureTest() {
    TestPublisher<Long> publisher = TestPublisher.createCold();
    AtomicLong requested = new AtomicLong();

    Flux<String> switchTransformed = publisher.flux()
                                              .doOnRequest(requested::addAndGet)
                                              .switchOnFirst((first, innerFlux) -> innerFlux.map(String::valueOf));

    publisher.next(1L);

    StepVerifier.create(switchTransformed, 0)
                .thenRequest(1)
                .expectNext("1")
                .thenRequest(1)
                .then(() -> publisher.next(2L))
                .expectNext("2")
                .then(publisher::complete)
                .expectComplete()
                .verify(Duration.ofSeconds(10));

    publisher.assertWasRequested();
    publisher.assertNoRequestOverflow();

    Assertions.assertThat(requested.get()).isEqualTo(2L);
}
 
Example 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: MonoUsingWhenTest.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");

	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))
	            .hasDropped("boom")
	            .hasNotDroppedErrors();

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

	testPublisher.assertCancelled();
}
 
Example 14
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExpireValueExactlyOnceOnRacingBetweenInvalidateAndDispose() {
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold = TestPublisher.createCold();
    cold.next("value");
    final int timeout = 10000;

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

    StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic()))
        .expectSubscription()
        .expectNext("value")
        .expectComplete()
        .verify(Duration.ofSeconds(timeout));

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono));

    RaceTestUtils.race(reconnectMono::invalidate, reconnectMono::dispose);

    Assertions.assertThat(expired).hasSize(1).containsOnly("value");
    Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono));

    StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic()))
        .expectSubscription()
        .expectError(CancellationException.class)
        .verify(Duration.ofSeconds(timeout));

    Assertions.assertThat(expired).hasSize(1).containsOnly("value");
    Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono));

    Assertions.assertThat(cold.subscribeCount()).isEqualTo(1);

    expired.clear();
    received.clear();
  }
}
 
Example 15
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
// Since context is immutable, with switchOnFirst it should not be mutable as well. Upstream should observe downstream
// Inner should be able to access downstreamContext but should not modify upstream context after the first element
public void shouldNotBeAbleToAccessUpstreamContext() {
    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);

    StepVerifier.create(switchTransformed, 0)
                .thenRequest(1)
                .expectNext("1")
                .thenRequest(1)
                .then(() -> publisher.next(2L))
                .expectNext("2")
                .expectAccessibleContext()
                .contains("a", "c")
                .contains("c", "d")
                .then()
                .then(publisher::complete)
                .expectComplete()
                .verify(Duration.ofSeconds(10));

    publisher.assertWasRequested();
    publisher.assertNoRequestOverflow();
}
 
Example 16
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 17
Source File: ReactiveCompositeDiscoveryClientTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServiceInstances() {
	DefaultServiceInstance serviceInstance1 = new DefaultServiceInstance("instance",
			"service", "localhost", 8080, false);
	DefaultServiceInstance serviceInstance2 = new DefaultServiceInstance("instance2",
			"service", "localhost", 8080, false);
	TestPublisher<ServiceInstance> discoveryClient1Publisher = TestPublisher
			.createCold();
	discoveryClient1Publisher.emit(serviceInstance1);
	discoveryClient1Publisher.emit(serviceInstance2);
	discoveryClient1Publisher.complete();

	TestPublisher<ServiceInstance> discoveryClient2Publisher = TestPublisher
			.createCold();
	discoveryClient2Publisher.complete();

	when(discoveryClient1.getInstances("service"))
			.thenReturn(discoveryClient1Publisher.flux());
	when(discoveryClient2.getInstances("service"))
			.thenReturn(discoveryClient2Publisher.flux());

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

	Flux<ServiceInstance> instances = client.getInstances("service");

	StepVerifier.create(instances).expectNext(serviceInstance1)
			.expectNext(serviceInstance2).expectComplete().verify();
}
 
Example 18
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldExpireValueExactlyOnceOnRacingBetweenInvalidates() {
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold = TestPublisher.createCold();
    cold.next("value");
    final int timeout = 10;

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

    StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic()))
        .expectSubscription()
        .expectNext("value")
        .expectComplete()
        .verify(Duration.ofSeconds(timeout));

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono));

    RaceTestUtils.race(reconnectMono::invalidate, reconnectMono::invalidate);

    Assertions.assertThat(expired).hasSize(1).containsOnly("value");
    Assertions.assertThat(received).hasSize(1).containsOnly(Tuples.of("value", reconnectMono));

    StepVerifier.create(reconnectMono.subscribeOn(Schedulers.elastic()))
        .expectSubscription()
        .expectNext("value")
        .expectComplete()
        .verify(Duration.ofSeconds(timeout));

    Assertions.assertThat(expired).hasSize(1).containsOnly("value");
    Assertions.assertThat(received)
        .hasSize(2)
        .containsOnly(Tuples.of("value", reconnectMono), Tuples.of("value", reconnectMono));

    Assertions.assertThat(cold.subscribeCount()).isEqualTo(2);

    expired.clear();
    received.clear();
  }
}
 
Example 19
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEstablishValueOnceInCaseOfRacingBetweenSubscribers() {
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold = TestPublisher.createCold();
    cold.next("value" + i);

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

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

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).isEmpty();

    Assertions.assertThat(cold.subscribeCount()).isZero();

    RaceTestUtils.race(
        () -> reconnectMono.subscribe(processor), () -> reconnectMono.subscribe(racerProcessor));

    Assertions.assertThat(processor.isTerminated()).isTrue();
    Assertions.assertThat(racerProcessor.isTerminated()).isTrue();

    Assertions.assertThat(processor.peek()).isEqualTo("value" + i);
    Assertions.assertThat(racerProcessor.peek()).isEqualTo("value" + i);

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

    Assertions.assertThat(cold.subscribeCount()).isOne();

    Assertions.assertThat(
            reconnectMono.resolvingInner.add(
                new ResolvingOperator.MonoDeferredResolutionOperator<>(
                    reconnectMono.resolvingInner, processor)))
        .isEqualTo(ResolvingOperator.READY_STATE);

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received)
        .hasSize(1)
        .containsOnly(Tuples.of("value" + i, reconnectMono));

    received.clear();
  }
}
 
Example 20
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEstablishValueOnceInCaseOfRacingBetweenBlocks() {
  Duration timeout = Duration.ofMillis(100);
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold = TestPublisher.createCold();
    cold.next("value" + i);

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

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).isEmpty();

    Assertions.assertThat(cold.subscribeCount()).isZero();

    String[] values1 = new String[1];
    String[] values2 = new String[1];

    RaceTestUtils.race(
        () -> values1[0] = reconnectMono.block(timeout),
        () -> values2[0] = reconnectMono.block(timeout));

    Assertions.assertThat(values2).containsExactly("value" + i);
    Assertions.assertThat(values1).containsExactly("value" + i);

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

    Assertions.assertThat(cold.subscribeCount()).isOne();

    Assertions.assertThat(
            reconnectMono.resolvingInner.add(
                new ResolvingOperator.MonoDeferredResolutionOperator<>(
                    reconnectMono.resolvingInner, MonoProcessor.create())))
        .isEqualTo(ResolvingOperator.READY_STATE);

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received)
        .hasSize(1)
        .containsOnly(Tuples.of("value" + i, reconnectMono));

    received.clear();
  }
}