Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.stablecoin.payments.orchestrator;

import jakarta.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
Expand Down Expand Up @@ -34,6 +36,21 @@ public abstract class AbstractIntegrationTest {
@Autowired
private JdbcTemplate jdbcTemplate;

@Autowired
private EntityManager entityManager;

@BeforeEach
void cleanDatabase() {
jdbcTemplate.execute("""
TRUNCATE TABLE
payment_audit_log,
payments,
orchestrator_outbox_record
CASCADE
""");
entityManager.clear();
Comment on lines +39 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | πŸ”΅ Trivial

entityManager.clear() here likely is not clearing what this test expects.

Spring's shared EntityManager proxy delegates to the current transactional EntityManager and otherwise creates a new one per operation, so calling clear() in @BeforeEach is unlikely to evict the persistence context later used by repository calls unless the test itself is transactional. If the goal is to invalidate cached entities after the TRUNCATE, either do the clear inside the same active transaction or drop this line to avoid a false sense of isolation. That's an inference from Spring's shared EntityManager contract. (docs.spring.io)

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@payment-orchestrator/payment-orchestrator/src/integration-test/java/com/stablecoin/payments/orchestrator/AbstractIntegrationTest.java`
around lines 39 - 51, The call to entityManager.clear() in the `@BeforeEach`
cleanDatabase() is ineffective because Spring injects a shared EntityManager
proxy; either remove the entityManager.clear() line to avoid a false sense of
clearing the persistence context, or ensure it runs inside the same
transaction/persistence-context used by the repositories (e.g., make
cleanDatabase() `@Transactional` and call entityManager.clear() after the
TRUNCATE). Update the cleanDatabase() method accordingly and keep references to
the existing method name cleanDatabase(), the `@BeforeEach` annotated setup, and
the entityManager.clear() invocation when making the change.

}

@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.stablecoin.payments.orchestrator.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.JsonSerializer;

import java.util.Map;

@Configuration
public class TestKafkaConfig {

@Bean
@Primary
public ProducerFactory<String, Object> producerFactory(
@Value("${spring.kafka.bootstrap-servers}") String bootstrapServers) {
return new DefaultKafkaProducerFactory<>(Map.of(
ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers,
ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class,
ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class));
}

@Bean
@Primary
public KafkaTemplate<String, Object> kafkaTemplate(
ProducerFactory<String, Object> producerFactory) {
return new KafkaTemplate<>(producerFactory);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
package com.stablecoin.payments.orchestrator.infrastructure.persistence;

import com.stablecoin.payments.orchestrator.AbstractIntegrationTest;
import com.stablecoin.payments.orchestrator.infrastructure.persistence.entity.PaymentAuditLogEntity;
import com.stablecoin.payments.orchestrator.infrastructure.persistence.entity.PaymentAuditLogJpaRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Instant;
import java.util.Map;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

@DisplayName("PaymentAuditLogRepository IT")
class PaymentAuditLogRepositoryIT extends AbstractIntegrationTest {

@Autowired
private PaymentAuditLogJpaRepository auditLogRepository;

// ── Append-only insert ──────────────────────────────────────────────

@Test
@DisplayName("should insert audit log entry and retrieve by id")
void shouldInsertAuditLogEntryAndRetrieveById() {
var paymentId = UUID.randomUUID();
var logEntry = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState(null)
.toState("INITIATED")
.triggeredBy("SYSTEM")
.actor("payment-orchestrator")
.metadata(Map.of("source", "api"))
.occurredAt(Instant.now())
.build();

var saved = auditLogRepository.save(logEntry);

var expected = PaymentAuditLogEntity.builder()
.logId(saved.getLogId())
.paymentId(paymentId)
.fromState(null)
.toState("INITIATED")
.triggeredBy("SYSTEM")
.actor("payment-orchestrator")
.metadata(Map.of("source", "api"))
.occurredAt(saved.getOccurredAt())
.build();

assertThat(auditLogRepository.findById(saved.getLogId())).isPresent().get()
.usingRecursiveComparison()
.ignoringFieldsOfTypes(Instant.class)
.isEqualTo(expected);
Comment on lines +52 to +55

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟑 Minor

Don’t exclude occurredAt from the repository round-trip assertion.

This still passes if occurredAt is truncated, defaulted, or mapped back incorrectly because every Instant is ignored. Compare it at database precision instead of dropping the type from the assertion.

As per coding guidelines, "Assert on meaningful values β€” avoid assertTrue(result != null)".

πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@payment-orchestrator/payment-orchestrator/src/integration-test/java/com/stablecoin/payments/orchestrator/infrastructure/persistence/PaymentAuditLogRepositoryIT.java`
around lines 52 - 55, The test currently ignores all Instant fields which hides
mismatches for occurredAt; remove the .ignoringFieldsOfTypes(Instant.class) call
in the assertion chain in PaymentAuditLogRepositoryIT and instead add a
type-specific comparator for Instant that compares the persisted and expected
Instants at the database precision (e.g., truncating both to the DB precision
such as ChronoUnit.MILLIS) via AssertJ's usingComparatorForType for
Instant.class applied on the existing .usingRecursiveComparison() so that
occurredAt is asserted at DB precision rather than being completely ignored.

}

@Test
@DisplayName("should insert multiple audit log entries for same payment")
void shouldInsertMultipleAuditLogEntriesForSamePayment() {
var paymentId = UUID.randomUUID();
var now = Instant.now();

var entry1 = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState(null)
.toState("INITIATED")
.triggeredBy("INITIATE")
.actor("system")
.metadata(Map.of())
.occurredAt(now.minusSeconds(30))
.build();

var entry2 = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState("INITIATED")
.toState("COMPLIANCE_CHECK")
.triggeredBy("START_COMPLIANCE")
.actor("system")
.metadata(Map.of())
.occurredAt(now.minusSeconds(20))
.build();

var entry3 = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState("COMPLIANCE_CHECK")
.toState("FX_LOCKED")
.triggeredBy("COMPLIANCE_PASSED")
.actor("compliance-service")
.metadata(Map.of("provider", "ecb"))
.occurredAt(now.minusSeconds(10))
.build();

auditLogRepository.save(entry1);
auditLogRepository.save(entry2);
auditLogRepository.save(entry3);

var results = auditLogRepository.findByPaymentIdOrderByOccurredAtDesc(paymentId);
assertThat(results).hasSize(3);
}

// ── Query by payment_id ordered by occurred_at desc ─────────────────

@Test
@DisplayName("should return audit log entries ordered by occurred_at descending")
void shouldReturnAuditLogEntriesOrderedByOccurredAtDesc() {
var paymentId = UUID.randomUUID();
var now = Instant.now();

var earliest = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState(null)
.toState("INITIATED")
.triggeredBy("INITIATE")
.actor("system")
.metadata(Map.of())
.occurredAt(now.minusSeconds(60))
.build();

var middle = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState("INITIATED")
.toState("COMPLIANCE_CHECK")
.triggeredBy("START_COMPLIANCE")
.actor("system")
.metadata(Map.of())
.occurredAt(now.minusSeconds(30))
.build();

var latest = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState("COMPLIANCE_CHECK")
.toState("FX_LOCKED")
.triggeredBy("COMPLIANCE_PASSED")
.actor("compliance-service")
.metadata(Map.of())
.occurredAt(now)
.build();

// Insert in non-chronological order to verify sorting
auditLogRepository.save(middle);
auditLogRepository.save(latest);
auditLogRepository.save(earliest);

var results = auditLogRepository.findByPaymentIdOrderByOccurredAtDesc(paymentId);
assertThat(results).hasSize(3);
assertThat(results.get(0).getToState()).isEqualTo("FX_LOCKED");
assertThat(results.get(1).getToState()).isEqualTo("COMPLIANCE_CHECK");
assertThat(results.get(2).getToState()).isEqualTo("INITIATED");
}

@Test
@DisplayName("should return empty list when no audit logs exist for payment")
void shouldReturnEmptyListWhenNoAuditLogsExistForPayment() {
var results = auditLogRepository.findByPaymentIdOrderByOccurredAtDesc(UUID.randomUUID());
assertThat(results).isEmpty();
}

@Test
@DisplayName("should not return audit logs for different payment id")
void shouldNotReturnAuditLogsForDifferentPaymentId() {
var paymentId1 = UUID.randomUUID();
var paymentId2 = UUID.randomUUID();

var entry1 = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId1)
.fromState(null)
.toState("INITIATED")
.triggeredBy("INITIATE")
.actor("system")
.metadata(Map.of())
.occurredAt(Instant.now())
.build();

var entry2 = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId2)
.fromState(null)
.toState("INITIATED")
.triggeredBy("INITIATE")
.actor("system")
.metadata(Map.of())
.occurredAt(Instant.now())
.build();

auditLogRepository.save(entry1);
auditLogRepository.save(entry2);

var results = auditLogRepository.findByPaymentIdOrderByOccurredAtDesc(paymentId1);
assertThat(results).hasSize(1);
assertThat(results.get(0).getPaymentId()).isEqualTo(paymentId1);
}

// ── JSONB metadata round-trip ───────────────────────────────────────

@Test
@DisplayName("should persist and retrieve JSONB metadata in audit log")
void shouldPersistAndRetrieveJsonbMetadataInAuditLog() {
var paymentId = UUID.randomUUID();
var metadata = Map.of(
"reason", "compliance_passed",
"riskScore", "25",
"provider", "chainalysis"
);

var entry = PaymentAuditLogEntity.builder()
.logId(UUID.randomUUID())
.paymentId(paymentId)
.fromState("COMPLIANCE_CHECK")
.toState("FX_LOCKED")
.triggeredBy("COMPLIANCE_PASSED")
.actor("compliance-service")
.metadata(metadata)
.occurredAt(Instant.now())
.build();

auditLogRepository.save(entry);

var results = auditLogRepository.findByPaymentIdOrderByOccurredAtDesc(paymentId);
assertThat(results).hasSize(1);
assertThat(results.get(0).getMetadata()).containsEntry("reason", "compliance_passed");
assertThat(results.get(0).getMetadata()).containsEntry("riskScore", "25");
assertThat(results.get(0).getMetadata()).containsEntry("provider", "chainalysis");
}
}
Loading
Loading