Search in sources :

Example 1 with TransactionalOperator

use of org.springframework.transaction.reactive.TransactionalOperator in project spring-cloud-gcp by spring-cloud.

the class FirestoreIntegrationTests method transactionTest.

@Test
public void transactionTest() {
    User alice = new User("Alice", 29);
    User bob = new User("Bob", 60);
    User user = new User(null, 40);
    DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
    transactionDefinition.setReadOnly(false);
    TransactionalOperator operator = TransactionalOperator.create(this.txManager, transactionDefinition);
    reset(this.txManager);
    this.firestoreTemplate.save(alice).then(this.firestoreTemplate.save(bob)).then(this.firestoreTemplate.save(user)).as(operator::transactional).block();
    assertThat(this.firestoreTemplate.findAll(User.class).collectList().block()).containsExactlyInAnyOrder(bob, alice, user);
    verify(this.txManager, times(1)).commit(any());
    verify(this.txManager, times(0)).rollback(any());
    verify(this.txManager, times(1)).getReactiveTransaction(any());
    reset(this.txManager);
    // test rollback
    this.firestoreTemplate.saveAll(Mono.defer(() -> {
        throw new FirestoreDataException("BOOM!");
    })).then(this.firestoreTemplate.deleteAll(User.class)).as(operator::transactional).onErrorResume(throwable -> Mono.empty()).block();
    verify(this.txManager, times(0)).commit(any());
    verify(this.txManager, times(1)).rollback(any());
    verify(this.txManager, times(1)).getReactiveTransaction(any());
    assertThat(this.firestoreTemplate.count(User.class).block()).isEqualTo(3);
    this.firestoreTemplate.findAll(User.class).flatMap(a -> {
        a.setAge(a.getAge() - 1);
        return this.firestoreTemplate.save(a);
    }).as(operator::transactional).collectList().block();
    List<User> users = this.firestoreTemplate.findAll(User.class).collectList().block();
    assertThat(users).extracting("age").containsExactlyInAnyOrder(28, 59, 39);
    assertThat(users).extracting("name").doesNotContainNull();
    this.firestoreTemplate.deleteAll(User.class).as(operator::transactional).block();
    assertThat(this.firestoreTemplate.findAll(User.class).collectList().block()).isEmpty();
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assume.assumeThat(org.junit.Assume.assumeThat) BeforeClass(org.junit.BeforeClass) FirestoreTemplate(org.springframework.cloud.gcp.data.firestore.FirestoreTemplate) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) PhoneNumber(org.springframework.cloud.gcp.data.firestore.entities.PhoneNumber) SpringRunner(org.springframework.test.context.junit4.SpringRunner) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Before(org.junit.Before) User(org.springframework.cloud.gcp.data.firestore.entities.User) FirestoreReactiveOperations(org.springframework.cloud.gcp.data.firestore.FirestoreReactiveOperations) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) Test(org.junit.Test) Mono(reactor.core.publisher.Mono) Mockito.times(org.mockito.Mockito.times) UUID(java.util.UUID) Mockito.verify(org.mockito.Mockito.verify) Flux(reactor.core.publisher.Flux) List(java.util.List) Level(ch.qos.logback.classic.Level) ReactiveFirestoreTransactionManager(org.springframework.cloud.gcp.data.firestore.transaction.ReactiveFirestoreTransactionManager) ContextConfiguration(org.springframework.test.context.ContextConfiguration) Matchers.is(org.hamcrest.Matchers.is) FirestoreDataException(org.springframework.cloud.gcp.data.firestore.FirestoreDataException) Mockito.reset(org.mockito.Mockito.reset) User(org.springframework.cloud.gcp.data.firestore.entities.User) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) FirestoreDataException(org.springframework.cloud.gcp.data.firestore.FirestoreDataException) Test(org.junit.Test)

Example 2 with TransactionalOperator

use of org.springframework.transaction.reactive.TransactionalOperator 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 3 with TransactionalOperator

use of org.springframework.transaction.reactive.TransactionalOperator in project spring-data-mongodb by spring-projects.

the class ReactiveMongoDatabaseUtilsUnitTests method shouldParticipateInOngoingMongoTransactionWhenSessionSychronizationIsNative.

// DATAMONGO-2265
@Test
void shouldParticipateInOngoingMongoTransactionWhenSessionSychronizationIsNative() {
    when(session.getServerSession()).thenReturn(serverSession);
    when(databaseFactory.getSession(any())).thenReturn(Mono.just(session));
    ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
    when(session.abortTransaction()).thenReturn(Mono.empty());
    TransactionalOperator operator = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
    operator.execute(tx -> {
        return TransactionSynchronizationManager.forCurrentTransaction().doOnNext(synchronizationManager -> {
            assertThat(synchronizationManager.isSynchronizationActive()).isTrue();
            assertThat(tx.isNewTransaction()).isTrue();
            assertThat(synchronizationManager.hasResource(databaseFactory)).isTrue();
        }).then(Mono.fromRunnable(tx::setRollbackOnly));
    }).as(StepVerifier::create).verifyComplete();
    verify(session).startTransaction();
    verify(session).abortTransaction();
    verify(session).close();
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ArgumentMatchers(org.mockito.ArgumentMatchers) StepVerifier(reactor.test.StepVerifier) Mock(org.mockito.Mock) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) Mono(reactor.core.publisher.Mono) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ServerSession(com.mongodb.session.ServerSession) Test(org.junit.jupiter.api.Test) TransactionSynchronizationManager(org.springframework.transaction.reactive.TransactionSynchronizationManager) Mockito(org.mockito.Mockito) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) MongoDatabase(com.mongodb.reactivestreams.client.MongoDatabase) Assertions(org.assertj.core.api.Assertions) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Test(org.junit.jupiter.api.Test)

Example 4 with TransactionalOperator

use of org.springframework.transaction.reactive.TransactionalOperator in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTransactionManagerUnitTests method suspendTransactionWhilePropagationNotSupported.

// DATAMONGO-2265
@Test
void suspendTransactionWhilePropagationNotSupported() {
    ReactiveMongoTransactionManager txManager = new ReactiveMongoTransactionManager(databaseFactory);
    ReactiveMongoTemplate template = new ReactiveMongoTemplate(databaseFactory);
    when(session.commitTransaction()).thenReturn(Mono.empty());
    TransactionalOperator outer = TransactionalOperator.create(txManager, new DefaultTransactionDefinition());
    DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
    definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
    TransactionalOperator inner = TransactionalOperator.create(txManager, definition);
    outer.execute(tx1 -> {
        return template.execute(db -> {
            db.drop();
            return inner.execute(tx2 -> {
                return template.execute(db2 -> {
                    db2.drop();
                    return Mono.empty();
                });
            });
        });
    }).as(StepVerifier::create).verifyComplete();
    verify(session).startTransaction();
    verify(session2, never()).startTransaction();
    verify(databaseFactory, times(1)).withSession(eq(session));
    verify(databaseFactory, never()).withSession(eq(session2));
    verify(db, times(2)).drop();
    verify(session2, never()).close();
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) ReactiveMongoTemplate(org.springframework.data.mongodb.core.ReactiveMongoTemplate) DefaultTransactionDefinition(org.springframework.transaction.support.DefaultTransactionDefinition) Test(org.junit.jupiter.api.Test)

Example 5 with TransactionalOperator

use of org.springframework.transaction.reactive.TransactionalOperator in project spring-boot by spring-projects.

the class TransactionAutoConfigurationTests method whenThereAreBothReactiveAndPlatformTransactionManagersATemplateAndAnOperatorAreAutoConfigured.

@Test
void whenThereAreBothReactiveAndPlatformTransactionManagersATemplateAndAnOperatorAreAutoConfigured() {
    this.contextRunner.withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)).withUserConfiguration(SinglePlatformTransactionManagerConfiguration.class, SingleReactiveTransactionManagerConfiguration.class).withPropertyValues("spring.datasource.url:jdbc:h2:mem:" + UUID.randomUUID()).run((context) -> {
        PlatformTransactionManager platformTransactionManager = context.getBean(PlatformTransactionManager.class);
        TransactionTemplate transactionTemplate = context.getBean(TransactionTemplate.class);
        assertThat(transactionTemplate.getTransactionManager()).isSameAs(platformTransactionManager);
        ReactiveTransactionManager reactiveTransactionManager = context.getBean(ReactiveTransactionManager.class);
        TransactionalOperator transactionalOperator = context.getBean(TransactionalOperator.class);
        assertThat(transactionalOperator).extracting("transactionManager").isSameAs(reactiveTransactionManager);
    });
}
Also used : TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ReactiveTransactionManager(org.springframework.transaction.ReactiveTransactionManager) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) Test(org.junit.jupiter.api.Test)

Aggregations

TransactionalOperator (org.springframework.transaction.reactive.TransactionalOperator)30 Test (org.junit.jupiter.api.Test)25 DefaultTransactionDefinition (org.springframework.transaction.support.DefaultTransactionDefinition)23 StepVerifier (reactor.test.StepVerifier)20 Mono (reactor.core.publisher.Mono)14 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 BeforeEach (org.junit.jupiter.api.BeforeEach)8 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 TransactionDefinition (org.springframework.transaction.TransactionDefinition)7 TransactionSynchronizationManager (org.springframework.transaction.reactive.TransactionSynchronizationManager)7 Connection (io.r2dbc.spi.Connection)6 ConnectionFactory (io.r2dbc.spi.ConnectionFactory)6 R2dbcBadGrammarException (io.r2dbc.spi.R2dbcBadGrammarException)6 Statement (io.r2dbc.spi.Statement)6 ClientSession (com.mongodb.reactivestreams.client.ClientSession)5 MongoDatabase (com.mongodb.reactivestreams.client.MongoDatabase)5 ServerSession (com.mongodb.session.ServerSession)5 IsolationLevel (io.r2dbc.spi.IsolationLevel)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 Assertions.fail (org.assertj.core.api.Assertions.fail)5