Repository navigation
Expand file tree
/
Copy pathTransactionPostgresIntegrationTest.java
More file actions
252 lines (229 loc) · 13.2 KB
/
Copy pathTransactionPostgresIntegrationTest.java
File metadata and controls
252 lines (229 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package com.wallet.secure.transaction.integration;
import com.wallet.secure.audit.repository.AuditLogRepository;
import com.wallet.secure.common.enums.AuditAction;
import com.wallet.secure.common.enums.CurrencyCode;
import com.wallet.secure.common.enums.TransactionStatus;
import com.wallet.secure.common.enums.TransactionType;
import com.wallet.secure.common.enums.UserRole;
import com.wallet.secure.common.exception.InsufficientFundsException;
import com.wallet.secure.transaction.dto.WithdrawRequest;
import com.wallet.secure.transaction.dto.TransferRequest;
import com.wallet.secure.transaction.entity.Transaction;
import com.wallet.secure.transaction.repository.TransactionHistoryRepository;
import com.wallet.secure.transaction.repository.TransactionRepository;
import com.wallet.secure.transaction.service.TransactionService;
import com.wallet.secure.user.entity.User;
import com.wallet.secure.user.repository.UserRepository;
import com.wallet.secure.wallet.entity.Wallet;
import com.wallet.secure.wallet.repository.WalletRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.BindMode;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
/**
* TX-001 integration evidence. The container receives the tracked SQL schema
* and is destroyed after the class; no local/developer database is ever read or changed.
*/
@Testcontainers
@SpringBootTest
class TransactionPostgresIntegrationTest {
@Container
static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("wallet_test")
.withUsername("wallet_test")
.withPassword("wallet_test")
.withFileSystemBind("database", "/docker-entrypoint-initdb.d", BindMode.READ_ONLY);
@DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", POSTGRES::getJdbcUrl);
registry.add("spring.datasource.username", POSTGRES::getUsername);
registry.add("spring.datasource.password", POSTGRES::getPassword);
registry.add("spring.datasource.driver-class-name", () -> "org.postgresql.Driver");
registry.add("spring.jpa.database-platform", () -> "org.hibernate.dialect.PostgreSQLDialect");
registry.add("spring.jpa.properties.hibernate.type.preferred_inet_jdbc_type", () -> "VARCHAR");
registry.add("spring.jpa.hibernate.ddl-auto", () -> "validate");
registry.add("jwt.secret", () -> "test-only-secret-that-is-long-enough-for-hs256-signing-key");
}
@Autowired private TransactionService transactionService;
@Autowired private UserRepository userRepository;
@Autowired private WalletRepository walletRepository;
@Autowired private TransactionRepository transactionRepository;
@Autowired private TransactionHistoryRepository historyRepository;
@Autowired private AuditLogRepository auditLogRepository;
@Autowired private JdbcTemplate jdbcTemplate;
private UUID userId;
private UUID walletId;
@BeforeEach
void setUp() {
User user = userRepository.saveAndFlush(User.builder()
.email("tx-" + UUID.randomUUID() + "@example.test")
.passwordHash("$2a$12$integration-test-password-hash")
.role(UserRole.USER).isActive(true).emailVerified(true).build());
Wallet wallet = walletRepository.saveAndFlush(Wallet.builder()
.user(user).currency(CurrencyCode.USD).balance(new BigDecimal("100.0000")).build());
userId = user.getId();
walletId = wallet.getId();
}
@Test
@Transactional
@DisplayName("general history includes transactions with a missing source or target wallet")
void history_nullableWalletSides_includesAllOwnedTransactions() {
Wallet source = walletRepository.findById(walletId).orElseThrow();
User recipient = userRepository.saveAndFlush(User.builder()
.email("history-recipient-" + UUID.randomUUID() + "@example.test")
.passwordHash("$2a$12$integration-test-password-hash")
.role(UserRole.USER).isActive(true).emailVerified(true).build());
Wallet target = walletRepository.saveAndFlush(Wallet.builder()
.user(recipient).currency(CurrencyCode.USD).balance(BigDecimal.ZERO).build());
Transaction deposit = transactionRepository.saveAndFlush(Transaction.builder()
.targetWallet(source).amount(BigDecimal.TEN).currency(CurrencyCode.USD)
.transactionType(TransactionType.DEPOSIT).build());
Transaction withdrawal = transactionRepository.saveAndFlush(Transaction.builder()
.sourceWallet(source).amount(BigDecimal.TEN).currency(CurrencyCode.USD)
.transactionType(TransactionType.WITHDRAWAL).build());
Transaction transfer = transactionRepository.saveAndFlush(Transaction.builder()
.sourceWallet(source).targetWallet(target).amount(BigDecimal.TEN)
.currency(CurrencyCode.USD).transactionType(TransactionType.TRANSFER).build());
var history = transactionRepository.findAllByUserId(userId, PageRequest.of(0, 20));
assertThat(history.getTotalElements()).isEqualTo(3);
assertThat(history.getContent()).extracting(Transaction::getId)
.containsExactlyInAnyOrder(deposit.getId(), withdrawal.getId(), transfer.getId());
assertThat(transactionRepository.findByIdAndUserId(deposit.getId(), userId)).isPresent();
assertThat(transactionRepository.findByIdAndUserId(withdrawal.getId(), userId)).isPresent();
assertThat(transactionRepository.findByIdAndUserId(deposit.getId(), recipient.getId())).isEmpty();
}
@Test
@DisplayName("concurrent withdrawals serialize balance and preserve success/failure evidence")
void withdraw_concurrentRequests_serializesBalanceAndPreservesEvidence() throws Exception {
CountDownLatch start = new CountDownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Boolean> first = CompletableFuture.supplyAsync(() -> attemptWithdrawal(start, "80.0000"), executor);
CompletableFuture<Boolean> second = CompletableFuture.supplyAsync(() -> attemptWithdrawal(start, "80.0000"), executor);
start.countDown();
boolean firstSucceeded = first.get(20, TimeUnit.SECONDS);
boolean secondSucceeded = second.get(20, TimeUnit.SECONDS);
assertThat(firstSucceeded ^ secondSucceeded).isTrue();
} finally {
executor.shutdownNow();
}
Wallet reloaded = walletRepository.findById(walletId).orElseThrow();
assertThat(reloaded.getBalance()).isEqualByComparingTo("20.0000");
assertThat(transactionRepository.findAll().stream()
.filter(t -> t.getTransactionType() == TransactionType.WITHDRAWAL)
.filter(t -> t.getStatus() == TransactionStatus.COMPLETED)).hasSize(1);
assertThat(historyCount(TransactionStatus.COMPLETED)).isEqualTo(2);
assertThat(historyCount(TransactionStatus.FAILED)).isZero();
assertThat(auditLogRepository.findAll().stream()
.filter(a -> userId.equals(a.getUserId()))
.filter(a -> a.getAction() == AuditAction.TRANSACTION_COMPLETE)).hasSize(1);
assertThat(auditLogRepository.findAll().stream()
.filter(a -> userId.equals(a.getUserId()))
.filter(a -> a.getAction() == AuditAction.TRANSACTION_FAIL)).hasSize(1);
}
@Test
@DisplayName("concurrent transfers allow only one debit and roll back the rejected transfer")
void transfer_concurrentRequests_preservesBothBalancesAndAudit() throws Exception {
User recipient = userRepository.saveAndFlush(User.builder()
.email("recipient-" + UUID.randomUUID() + "@example.test")
.passwordHash("$2a$12$integration-test-password-hash").build());
UUID recipientWalletId = walletRepository.saveAndFlush(Wallet.builder()
.user(recipient).currency(CurrencyCode.USD).balance(new BigDecimal("10.0000")).build()).getId();
CountDownLatch start = new CountDownLatch(1);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Boolean> first = CompletableFuture.supplyAsync(() -> attemptTransfer(start, recipientWalletId), executor);
CompletableFuture<Boolean> second = CompletableFuture.supplyAsync(() -> attemptTransfer(start, recipientWalletId), executor);
start.countDown();
assertThat(first.get(20, TimeUnit.SECONDS) ^ second.get(20, TimeUnit.SECONDS)).isTrue();
} finally {
executor.shutdownNow();
}
assertThat(walletRepository.findById(walletId).orElseThrow().getBalance()).isEqualByComparingTo("20.0000");
assertThat(walletRepository.findById(recipientWalletId).orElseThrow().getBalance()).isEqualByComparingTo("90.0000");
assertThat(transactionRepository.findAll().stream()
.filter(t -> t.getTransactionType() == TransactionType.TRANSFER)).hasSize(1)
.allMatch(t -> t.getStatus() == TransactionStatus.COMPLETED);
assertThat(historyCount(TransactionStatus.COMPLETED)).isEqualTo(2);
assertThat(historyCount(TransactionStatus.FAILED)).isZero();
assertThat(auditLogRepository.findAll().stream()
.filter(a -> userId.equals(a.getUserId()))
.filter(a -> a.getAction() == AuditAction.TRANSACTION_COMPLETE)).hasSize(1);
assertThat(auditLogRepository.findAll().stream()
.filter(a -> userId.equals(a.getUserId()))
.filter(a -> a.getAction() == AuditAction.TRANSACTION_FAIL)).hasSize(1);
}
private boolean attemptTransfer(CountDownLatch start, UUID recipientWalletId) {
try {
if (!start.await(10, TimeUnit.SECONDS)) throw new AssertionError("Concurrent workers did not start");
TransferRequest request = new TransferRequest();
setField(request, "sourceWalletId", walletId);
setField(request, "targetWalletId", recipientWalletId);
setField(request, "amount", new BigDecimal("80.0000"));
transactionService.transfer(userId, request);
return true;
} catch (InsufficientFundsException expected) {
return false;
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new AssertionError(interrupted);
}
}
private int historyCount(TransactionStatus status) {
return jdbcTemplate.queryForObject("""
SELECT count(*) FROM transaction_history h JOIN transactions t ON t.id = h.transaction_id
WHERE t.source_wallet_id = ? AND h.new_status = ?::transaction_status
""", Integer.class, walletId, status.name());
}
private void setField(Object target, String name, Object value) {
try {
var field = target.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(target, value);
} catch (ReflectiveOperationException exception) {
throw new AssertionError(exception);
}
}
private boolean attemptWithdrawal(CountDownLatch start, String amount) {
try {
if (!start.await(10, TimeUnit.SECONDS)) throw new AssertionError("Concurrent workers did not start");
transactionService.withdraw(userId, withdraw(amount));
return true;
} catch (InsufficientFundsException expected) {
return false;
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw new AssertionError(interrupted);
}
}
private WithdrawRequest withdraw(String amount) {
WithdrawRequest request = new WithdrawRequest();
try {
var currency = WithdrawRequest.class.getDeclaredField("currency");
var value = WithdrawRequest.class.getDeclaredField("amount");
currency.setAccessible(true); value.setAccessible(true);
currency.set(request, CurrencyCode.USD); value.set(request, new BigDecimal(amount));
} catch (ReflectiveOperationException exception) {
throw new AssertionError(exception);
}
return request;
}
}