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

The following examples show how to use reactor.test.publisher.TestPublisher#emit() . 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 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 2
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 3
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 4
Source File: MonoFilterWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void scanTerminatedOnlyTrueIfFilterTerminated() {
	AtomicReference<Subscriber> subscriber = new AtomicReference<>();
	TestPublisher<Boolean> filter = TestPublisher.create();
	new MonoFilterWhen<>(new Mono<Integer>() {
		@Override
		public void subscribe(CoreSubscriber<? super Integer> actual) {
			subscriber.set(actual);
			//NON-EMPTY SOURCE WILL TRIGGER FILTER SUBSCRIPTION
			actual.onNext(2);
			actual.onComplete();
		}
	}, w -> filter)
        .subscribe();

	assertThat(subscriber.get()).isNotNull()
                                .isInstanceOf(Scannable.class);
	Boolean terminated = ((Scannable) subscriber.get()).scan(Scannable.Attr.TERMINATED);
	assertThat(terminated).isFalse();

	filter.emit(Boolean.TRUE);

	terminated = ((Scannable) subscriber.get()).scan(Scannable.Attr.TERMINATED);
	assertThat(terminated).isTrue();
}
 
Example 5
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 6
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 7
Source File: ReactorDemoTest.java    From reactive-streams-in-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test_TestPublisher() {
    TestPublisher<Object> publisher = TestPublisher.create(); //1
    Flux<Object> stringFlux = publisher.flux(); //2
    List list = new ArrayList(); //3

    stringFlux.subscribe(next -> list.add(next), ex -> ex.printStackTrace()); //4
    publisher.emit("foo", "bar"); //5

    assertEquals(2, list.size()); //6
    assertEquals("foo", list.get(0));
    assertEquals("bar", list.get(1));
}
 
Example 8
Source File: SimpleConnectionPoolTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void tracksConnectionsInEstablishment() {
    TestPublisher<Connection> pub1 = TestPublisher.create();
    TestPublisher<Connection> pub2 = TestPublisher.create();
    TestPublisher<Connection> pub3 = TestPublisher.create();
    TestPublisher<Connection> pub4 = TestPublisher.create();

    when(connectionFactory.createConnection(any(Origin.class), any(ConnectionSettings.class)))
            .thenReturn(pub1.mono())
            .thenReturn(pub2.mono())
            .thenReturn(pub3.mono())
            .thenReturn(pub4.mono());

    SimpleConnectionPool pool = new SimpleConnectionPool(
            origin,
            new ConnectionPoolSettings.Builder(defaultConnectionPoolSettings())
                    .maxConnectionsPerHost(2)
                    .build(),
            connectionFactory);

    CompletableFuture<Connection> f1 = Mono.from(pool.borrowConnection()).toFuture();
    CompletableFuture<Connection> f2 = Mono.from(pool.borrowConnection()).toFuture();
    CompletableFuture<Connection> f3 = Mono.from(pool.borrowConnection()).toFuture();
    CompletableFuture<Connection> f4 = Mono.from(pool.borrowConnection()).toFuture();

    pub1.emit(connection1);
    pub2.emit(connection2);
    pub3.emit(connection3);
    pub4.emit(connection4);

    assertTrue(f1.isDone());
    assertTrue(f2.isDone());
    assertFalse(f3.isDone());
    assertFalse(f4.isDone());
}
 
Example 9
Source File: MonoCacheTimeTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void sourceCachedNoCoordinatorLeak() {
	TestPublisher<Integer> source = TestPublisher.create();
	MonoCacheTime<Integer> cached = new MonoCacheTime<>(source.mono(), Duration.ofSeconds(2),
			Schedulers.parallel());
	cached.subscribe();
	WeakReference<Signal<Integer>> refCoordinator = new WeakReference<>(cached.state);

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

	source.emit(100);
	System.gc();

	assertThat(refCoordinator.get()).isNull();
}
 
Example 10
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 11
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("fifoPools")
void smokeTestInScopeFifo(Function<PoolBuilder<PoolableTest, ?>, Pool<PoolableTest>> configAdjuster) {
	AtomicInteger newCount = new AtomicInteger();

	PoolBuilder<PoolableTest, ?> builder = PoolBuilder
			//default maxUse is 5, but this test relies on it being 2
			.from(Mono.defer(() -> Mono.just(new PoolableTest(newCount.incrementAndGet(), 2))))
			.sizeBetween(2, 3)
			.releaseHandler(pt -> Mono.fromRunnable(pt::clean))
			.evictionPredicate((poolable, metadata) -> !poolable.isHealthy());
	Pool<PoolableTest> pool = configAdjuster.apply(builder);
	pool.warmup().block();

	TestPublisher<Integer> trigger1 = TestPublisher.create();
	TestPublisher<Integer> trigger2 = TestPublisher.create();
	TestPublisher<Integer> trigger3 = 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(__ -> trigger2)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired2::add).delayUntil(__ -> trigger2)),
			pool.withPoolable(poolable -> Mono.just(poolable).doOnNext(acquired2::add).delayUntil(__ -> trigger2))
	).subscribe();

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

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

	trigger1.emit(1);

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

	trigger2.emit(1);

	assertThat(acquired3).as("batch3 after trigger2").hasSize(3);
	assertThat(newCount).as("allocated total").hasValue(6);

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

	assertThat(acquired3)
			.as("acquired3 all new (released once)")
			.allSatisfy(elem -> assertThat(elem.usedUp).isZero());
}
 
Example 12
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());
}