Search in sources :

Example 96 with StepVerifier

use of reactor.test.StepVerifier in project spring-cloud-gcp by spring-cloud.

the class ReactiveFirestoreTransactionManagerTest method writeTransaction.

@Test
public void writeTransaction() {
    FirestoreTemplate template = getFirestoreTemplate();
    ReactiveFirestoreTransactionManager txManager = new ReactiveFirestoreTransactionManager(this.firestoreStub, this.parent);
    TransactionalOperator operator = TransactionalOperator.create(txManager);
    doAnswer(invocation -> {
        CommitRequest commitRequest = invocation.getArgument(0);
        StreamObserver<CommitResponse> streamObserver = invocation.getArgument(1);
        assertThat(commitRequest.getTransaction()).isEqualTo(ByteString.copyFromUtf8("transaction1"));
        assertThat(commitRequest.getWritesList().get(0).getUpdate().getName()).isEqualTo(this.parent + "/testEntities/" + "e2");
        assertThat(commitRequest.getWritesList().get(1).getUpdate().getName()).isEqualTo(this.parent + "/testEntities/" + "e3");
        assertThat(commitRequest.getWritesList().get(2).getDelete()).isEqualTo(this.parent + "/testEntities/" + "e3");
        streamObserver.onNext(CommitResponse.newBuilder().build());
        streamObserver.onCompleted();
        return null;
    }).when(this.firestoreStub).commit(any(), any());
    template.findById(Mono.just("e1"), FirestoreTemplateTests.TestEntity.class).flatMap(testEntity -> template.save(new FirestoreTemplateTests.TestEntity("e2", 100L))).flatMap(testEntity -> template.save(new FirestoreTemplateTests.TestEntity("e3", 100L))).flatMap(testEntity -> template.delete(Mono.just(testEntity))).then().as(operator::transactional).as(StepVerifier::create).verifyComplete();
    verify(this.firestoreStub).beginTransaction(any(), any());
    verify(this.firestoreStub).commit(any(), any());
    GetDocumentRequest request1 = GetDocumentRequest.newBuilder().setName(this.parent + "/testEntities/" + "e1").setTransaction(ByteString.copyFromUtf8("transaction1")).build();
    verify(this.firestoreStub, times(1)).getDocument(eq(request1), any());
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) CommitRequest(com.google.firestore.v1.CommitRequest) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) CommitResponse(com.google.firestore.v1.CommitResponse) StepVerifier(reactor.test.StepVerifier) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) FirestoreTemplate(org.springframework.cloud.gcp.data.firestore.FirestoreTemplate) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BeginTransactionResponse(com.google.firestore.v1.BeginTransactionResponse) Empty(com.google.protobuf.Empty) StreamObserver(io.grpc.stub.StreamObserver) CommitRequest(com.google.firestore.v1.CommitRequest) Duration(java.time.Duration) Mockito.doAnswer(org.mockito.Mockito.doAnswer) RollbackRequest(com.google.firestore.v1.RollbackRequest) FirestoreDefaultClassMapper(org.springframework.cloud.gcp.data.firestore.mapping.FirestoreDefaultClassMapper) GetDocumentRequest(com.google.firestore.v1.GetDocumentRequest) FirestoreGrpc(com.google.firestore.v1.FirestoreGrpc) FirestoreTemplateTests(org.springframework.cloud.gcp.data.firestore.FirestoreTemplateTests) Document(com.google.firestore.v1.Document) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) Mockito.verify(org.mockito.Mockito.verify) ByteString(com.google.protobuf.ByteString) VerificationModeFactory.times(org.mockito.internal.verification.VerificationModeFactory.times) FirestoreDataException(org.springframework.cloud.gcp.data.firestore.FirestoreDataException) FirestoreMappingContext(org.springframework.cloud.gcp.data.firestore.mapping.FirestoreMappingContext) Mockito.mock(org.mockito.Mockito.mock) CommitResponse(com.google.firestore.v1.CommitResponse) FirestoreTemplateTests(org.springframework.cloud.gcp.data.firestore.FirestoreTemplateTests) GetDocumentRequest(com.google.firestore.v1.GetDocumentRequest) FirestoreTemplate(org.springframework.cloud.gcp.data.firestore.FirestoreTemplate) Test(org.junit.Test)

Example 97 with StepVerifier

use of reactor.test.StepVerifier in project reactor-core by reactor.

the class FluxPublishTest method prematureOnComplete.

@Test
public void prematureOnComplete() {
    Sinks.Many<Flux<String>> sink = Sinks.unsafe().many().multicast().onBackpressureBuffer(Queues.SMALL_BUFFER_SIZE, false);
    Flux.just("ALPHA", "BRAVO", "CHARLIE", "DELTA", "ALPHA", "BRAVO", "CHARLIE", "DELTA", "ALPHA", "BRAVO", "CHARLIE", "DELTA").log("stream.incoming").windowWhile(s -> !"DELTA".equals(s), 1).subscribe(v -> sink.emitNext(v, FAIL_FAST), e -> sink.emitError(e, FAIL_FAST), () -> sink.emitComplete(FAIL_FAST));
    AtomicInteger windowIndex = new AtomicInteger(0);
    AtomicInteger nextIndex = new AtomicInteger(0);
    sink.asFlux().next().flatMapMany(flux -> flux.takeWhile(s -> !"CHARLIE".equals(s)).log(String.format("stream.window.%d", windowIndex.getAndIncrement()))).log(String.format("stream.next.%d", nextIndex.getAndIncrement())).as(StepVerifier::create).expectNextCount(2).verifyComplete();
    sink.asFlux().next().flatMapMany(flux -> flux.takeWhile(s -> !"CHARLIE".equals(s)).log(String.format("stream.window.%d", windowIndex.getAndIncrement()))).log(String.format("stream.next.%d", nextIndex.getAndIncrement())).as(StepVerifier::create).expectNextCount(2).verifyComplete();
    sink.asFlux().next().flatMapMany(flux -> flux.takeWhile(s -> !"CHARLIE".equals(s)).log(String.format("stream.window.%d", windowIndex.getAndIncrement()))).log(String.format("stream.next.%d", nextIndex.getAndIncrement())).as(StepVerifier::create).expectNextCount(2).verifyComplete();
}
Also used : TestPublisher(reactor.test.publisher.TestPublisher) Arrays(java.util.Arrays) Disposable(reactor.core.Disposable) StepVerifier(reactor.test.StepVerifier) CancellationException(java.util.concurrent.CancellationException) Scannable(reactor.core.Scannable) ContextView(reactor.util.context.ContextView) Context(reactor.util.context.Context) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) FluxOperatorTest(reactor.test.publisher.FluxOperatorTest) AtomicReference(java.util.concurrent.atomic.AtomicReference) Queues(reactor.util.concurrent.Queues) Test(org.junit.jupiter.api.Test) List(java.util.List) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FAIL_FAST(reactor.core.publisher.Sinks.EmitFailureHandler.FAIL_FAST) Duration(java.time.Duration) Subscription(org.reactivestreams.Subscription) AssertSubscriber(reactor.test.subscriber.AssertSubscriber) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Schedulers(reactor.core.scheduler.Schedulers) Timeout(org.junit.jupiter.api.Timeout) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StepVerifier(reactor.test.StepVerifier) FluxOperatorTest(reactor.test.publisher.FluxOperatorTest) Test(org.junit.jupiter.api.Test)

Example 98 with StepVerifier

use of reactor.test.StepVerifier in project reactor-core by reactor.

the class ParallelMergeOrderedTest method dealsWithPrefetchLargerThanSmallBufferSize.

// see https://github.com/reactor/reactor-core/issues/1958
@Test
void dealsWithPrefetchLargerThanSmallBufferSize() {
    // parallelism must be > 1 to expose issue
    int parallelism = 2;
    int bufferS = Queues.SMALL_BUFFER_SIZE;
    // if orderedPrefetch > bufferS then operator used to drop elements and eventually hang
    int orderedPrefetch = bufferS + 128;
    final AtomicInteger prev = new AtomicInteger(-1);
    Flux.range(0, 200_000).subscribeOn(Schedulers.newSingle("init", true)).parallel(parallelism, bufferS).runOn(Schedulers.newParallel("process", parallelism, true), bufferS).map(i -> i).ordered(Comparator.comparing(i -> i), orderedPrefetch).as(StepVerifier::create).thenConsumeWhile(current -> {
        int previous = prev.getAndSet(current);
        try {
            assertThat(current).withFailMessage("elements dropped: prev: %d, next: %d, lost: %d\n", previous, current, current - previous).isEqualTo(previous + 1);
        } catch (AssertionError ae) {
            ae.printStackTrace();
        }
        return true;
    }).expectComplete().verify(// should run in 3s
    Duration.ofSeconds(5));
}
Also used : Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) Scannable(reactor.core.Scannable) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Tuple2(reactor.util.function.Tuple2) Scheduler(reactor.core.scheduler.Scheduler) ArrayList(java.util.ArrayList) Queues(reactor.util.concurrent.Queues) Test(org.junit.jupiter.api.Test) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) Schedulers(reactor.core.scheduler.Schedulers) Comparator(java.util.Comparator) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.jupiter.api.Test)

Example 99 with StepVerifier

use of reactor.test.StepVerifier in project reactor-core by reactor.

the class BoundedElasticSchedulerTest method testGh1973.

// gh-1973 smoke test
@Test
@Tag("slow")
public void testGh1973() throws InterruptedException {
    Scheduler scheduler = afterTest.autoDispose(Schedulers.newBoundedElastic(3, 100000, "subscriberElastic", 600, true));
    LinkedList<MonoSink<String>> listeners = new LinkedList<>();
    List<Disposable> scheduled = new LinkedList<>();
    ExecutorService producer = startProducer(listeners);
    Consumer<MonoSink<String>> addListener = sink -> {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            LOGGER.trace("listener cancelled");
        }
        listeners.add(sink);
        sink.onDispose(() -> listeners.remove(sink));
    };
    for (int i = 0; i < 50; i++) {
        scheduled.add(Mono.create(addListener).subscribeOn(scheduler).subscribe(LOGGER::info));
    }
    Thread.sleep(1000);
    scheduled.forEach(Disposable::dispose);
    Thread.sleep(1000);
    Mono.<String>create(sink -> {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            LOGGER.warn("last listener improperly cancelled");
        }
        listeners.add(sink);
        sink.onDispose(() -> listeners.remove(sink));
    }).subscribeOn(scheduler).map(res -> res + " the end").doOnNext(LOGGER::info).as(StepVerifier::create).assertNext(n -> assertThat(n).endsWith(" the end")).expectComplete().verify(Duration.ofSeconds(5));
}
Also used : MonoSink(reactor.core.publisher.MonoSink) Disposable(reactor.core.Disposable) Offset(org.assertj.core.data.Offset) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) AfterAll(org.junit.jupiter.api.AfterAll) BoundedServices(reactor.core.scheduler.BoundedElasticScheduler.BoundedServices) Loggers(reactor.util.Loggers) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Logger(reactor.util.Logger) BoundedState(reactor.core.scheduler.BoundedElasticScheduler.BoundedState) Assertions(org.assertj.core.api.Assertions) Tag(org.junit.jupiter.api.Tag) Disposables(reactor.core.Disposables) AtomicIntegerArray(java.util.concurrent.atomic.AtomicIntegerArray) Set(java.util.Set) Worker(reactor.core.scheduler.Scheduler.Worker) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) ThrowingSupplier(com.pivovarit.function.ThrowingSupplier) Awaitility(org.awaitility.Awaitility) CsvSource(org.junit.jupiter.params.provider.CsvSource) Disposable(reactor.core.Disposable) Scannable(reactor.core.Scannable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MonoSink(reactor.core.publisher.MonoSink) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ThrowingRunnable(com.pivovarit.function.ThrowingRunnable) MockUtils(reactor.test.MockUtils) LinkedList(java.util.LinkedList) RaceTestUtils(reactor.test.util.RaceTestUtils) ExecutorService(java.util.concurrent.ExecutorService) BoundedScheduledExecutorService(reactor.core.scheduler.BoundedElasticScheduler.BoundedScheduledExecutorService) ParameterizedTestWithName(reactor.test.ParameterizedTestWithName) Mono(reactor.core.publisher.Mono) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Flux(reactor.core.publisher.Flux) Clock(java.time.Clock) Comparator(java.util.Comparator) ExecutorService(java.util.concurrent.ExecutorService) BoundedScheduledExecutorService(reactor.core.scheduler.BoundedElasticScheduler.BoundedScheduledExecutorService) LinkedList(java.util.LinkedList) Test(org.junit.jupiter.api.Test) Tag(org.junit.jupiter.api.Tag)

Example 100 with StepVerifier

use of reactor.test.StepVerifier in project reactor-core by reactor.

the class SchedulersTest method handleErrorWithJvmFatalForwardsToUncaughtHandlerFusedCallable.

@Test
public void handleErrorWithJvmFatalForwardsToUncaughtHandlerFusedCallable() {
    AtomicBoolean handlerCaught = new AtomicBoolean();
    Scheduler scheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(r -> {
        Thread thread = new Thread(r);
        thread.setUncaughtExceptionHandler((t, ex) -> {
            handlerCaught.set(true);
            System.err.println("from uncaught handler: " + ex.toString());
        });
        return thread;
    }));
    final StepVerifier stepVerifier = StepVerifier.create(Mono.<String>fromCallable(() -> {
        throw new StackOverflowError("boom");
    }).subscribeOn(scheduler)).expectFusion().expectErrorMessage("boom");
    // the exception is still fatal, so the StepVerifier should time out.
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> stepVerifier.verify(Duration.ofMillis(100))).withMessageStartingWith("VerifySubscriber timed out on ");
    // nonetheless, the uncaught exception handler should have been invoked
    assertThat(handlerCaught).as("uncaughtExceptionHandler used").isTrue();
}
Also used : Sinks(reactor.core.publisher.Sinks) Disposable(reactor.core.Disposable) StepVerifier(reactor.test.StepVerifier) Scannable(reactor.core.Scannable) BiFunction(java.util.function.BiFunction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) AtomicReference(java.util.concurrent.atomic.AtomicReference) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) RunnableScheduledFuture(java.util.concurrent.RunnableScheduledFuture) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Assertions(org.assertj.core.api.Assertions) Tag(org.junit.jupiter.api.Tag) Disposables(reactor.core.Disposables) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) Awaitility.await(org.awaitility.Awaitility.await) Executor(java.util.concurrent.Executor) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) Mono(reactor.core.publisher.Mono) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) List(java.util.List) AfterEach(org.junit.jupiter.api.AfterEach) Assertions.fail(org.assertj.core.api.Assertions.fail) FAIL_FAST(reactor.core.publisher.Sinks.EmitFailureHandler.FAIL_FAST) Condition(org.assertj.core.api.Condition) Exceptions(reactor.core.Exceptions) Timeout(org.junit.jupiter.api.Timeout) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Aggregations

StepVerifier (reactor.test.StepVerifier)234 Test (org.junit.jupiter.api.Test)176 Mono (reactor.core.publisher.Mono)111 Flux (reactor.core.publisher.Flux)92 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)77 Duration (java.time.Duration)76 BeforeEach (org.junit.jupiter.api.BeforeEach)60 Test (org.junit.Test)55 Query (org.springframework.data.mongodb.core.query.Query)54 Assertions (org.assertj.core.api.Assertions)53 Document (org.bson.Document)49 Arrays (java.util.Arrays)46 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)44 Criteria (org.springframework.data.mongodb.core.query.Criteria)44 TimeUnit (java.util.concurrent.TimeUnit)42 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)42 Disposable (reactor.core.Disposable)39 List (java.util.List)38 ClassPathResource (org.springframework.core.io.ClassPathResource)38 AtomicReference (java.util.concurrent.atomic.AtomicReference)37