-
Notifications
You must be signed in to change notification settings - Fork 12
/
balance_test.go
479 lines (395 loc) · 18.5 KB
/
balance_test.go
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/*
Copyright 2024 Blnk Finance Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"context"
"database/sql/driver"
"encoding/json"
"math/big"
"regexp"
"testing"
"time"
"github.com/brianvoe/gofakeit/v6"
"github.com/jerry-enebeli/blnk/model"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
)
type BigIntString struct {
*big.Int
}
// Value implements the driver.Valuer interface
func (b BigIntString) Value() (driver.Value, error) {
if b.Int == nil {
return nil, nil
}
return b.String(), nil
}
func getBalanceMock(credit, debit, balance *big.Int, indicator string) *model.Balance {
return &model.Balance{CreditBalance: credit, DebitBalance: debit, Balance: balance, Indicator: indicator}
}
func getTransactionMock(amount float64, overdraft bool) model.Transaction {
transaction := model.Transaction{TransactionID: gofakeit.UUID(), Amount: amount, AllowOverdraft: overdraft, Reference: gofakeit.UUID()}
return transaction
}
func TestUpdateBalancesWithTransaction(t *testing.T) {
tests := []struct {
name string
sourceBalance *model.Balance
ExpectedError error
destinationBalance *model.Balance
transaction model.Transaction
want struct {
SourceBalance *big.Int
SourceCreditBalance *big.Int
SourceDebitBalance *big.Int
DestinationBalance *big.Int
DestinationCreditBalance *big.Int
DestinationDebitBalance *big.Int
SourceIndicator string
DestinationIndicator string
}
}{
{
name: "Send 1k from destination to source balance.",
ExpectedError: nil,
sourceBalance: getBalanceMock(big.NewInt(2500), big.NewInt(0), big.NewInt(2500), "source-indicator"),
destinationBalance: getBalanceMock(big.NewInt(0), big.NewInt(0), big.NewInt(0), "destination-indicator"),
transaction: getTransactionMock(1000, false),
want: struct {
SourceBalance *big.Int
SourceCreditBalance *big.Int
SourceDebitBalance *big.Int
DestinationBalance *big.Int
DestinationCreditBalance *big.Int
DestinationDebitBalance *big.Int
SourceIndicator string
DestinationIndicator string
}{
SourceBalance: big.NewInt(1500),
SourceDebitBalance: big.NewInt(1000),
SourceCreditBalance: big.NewInt(2500),
DestinationBalance: big.NewInt(1000),
DestinationDebitBalance: big.NewInt(0),
DestinationCreditBalance: big.NewInt(1000),
SourceIndicator: "source-indicator",
DestinationIndicator: "destination-indicator",
},
},
{
name: "Debit 900m from source with start balance of 2.5b and debit balance of 500m. And destination start balance of 5k",
ExpectedError: nil,
sourceBalance: getBalanceMock(big.NewInt(2500000000), big.NewInt(500000000), big.NewInt(2500000000), "source-indicator"),
destinationBalance: getBalanceMock(big.NewInt(5000), big.NewInt(0), big.NewInt(5000), "destination-indicator"),
transaction: getTransactionMock(900000000, false),
want: struct {
SourceBalance *big.Int
SourceCreditBalance *big.Int
SourceDebitBalance *big.Int
DestinationBalance *big.Int
DestinationCreditBalance *big.Int
DestinationDebitBalance *big.Int
SourceIndicator string
DestinationIndicator string
}{
SourceBalance: big.NewInt(1100000000),
SourceDebitBalance: big.NewInt(1400000000),
SourceCreditBalance: big.NewInt(2500000000),
DestinationBalance: big.NewInt(900005000),
DestinationDebitBalance: big.NewInt(0),
DestinationCreditBalance: big.NewInt(900005000),
SourceIndicator: "source-indicator",
DestinationIndicator: "destination-indicator",
},
},
// Add more test cases as needed
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
transaction := tt.transaction
err := model.UpdateBalances(&transaction, tt.sourceBalance, tt.destinationBalance)
assert.Equal(t, tt.ExpectedError, err)
assert.Equal(t, tt.want.SourceBalance, tt.sourceBalance.Balance, "expected source balances to match")
assert.Equal(t, tt.want.SourceDebitBalance, tt.sourceBalance.DebitBalance, "expected source debit balances to match")
assert.Equal(t, tt.want.SourceCreditBalance, tt.sourceBalance.CreditBalance, "expected source credit balances to match")
assert.Equal(t, tt.want.DestinationBalance, tt.destinationBalance.Balance, "expected destination balances to match")
assert.Equal(t, tt.want.DestinationDebitBalance, tt.destinationBalance.DebitBalance, "expected destination debit balances to match")
assert.Equal(t, tt.want.DestinationCreditBalance, tt.destinationBalance.CreditBalance, "expected destination credit balances to match")
assert.Equal(t, tt.want.SourceIndicator, tt.sourceBalance.Indicator, "expected source indicators to match")
assert.Equal(t, tt.want.DestinationIndicator, tt.destinationBalance.Indicator, "expected destination indicators to match")
})
}
}
func TestCreateBalance(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
balance := model.Balance{Balance: big.NewInt(100), CreditBalance: big.NewInt(50), DebitBalance: big.NewInt(50), Currency: "USD", LedgerID: "test-id", IdentityID: "test-id"}
// Convert metadata to JSON for mocking
metaDataJSON, _ := json.Marshal(balance.MetaData)
mock.ExpectExec("INSERT INTO blnk.balances").
WithArgs(sqlmock.AnyArg(), balance.Balance.String(), balance.CreditBalance.String(), balance.DebitBalance.String(), balance.Currency, balance.CurrencyMultiplier, balance.LedgerID, balance.IdentityID, sqlmock.AnyArg(), sqlmock.AnyArg(), metaDataJSON).
WillReturnResult(sqlmock.NewResult(1, 1))
result, err := d.CreateBalance(context.Background(), balance)
assert.NoError(t, err)
assert.NotEmpty(t, result.BalanceID)
assert.Contains(t, result.BalanceID, "bln_")
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestGetBalanceByID(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
balanceID := gofakeit.UUID()
mock.ExpectBegin()
// Adjust the expected SQL to match the actual SQL output.
expectedSQL := `SELECT b\.balance_id, b\.balance, b\.credit_balance, b\.debit_balance, b\.currency, b\.currency_multiplier, b\.ledger_id, COALESCE\(b\.identity_id, ''\) as identity_id, b\.created_at, b\.meta_data, b\.inflight_balance, b\.inflight_credit_balance, b\.inflight_debit_balance, b\.version, b\.indicator FROM \( SELECT \* FROM blnk\.balances WHERE balance_id = \$1 \) AS b`
rows := sqlmock.NewRows([]string{"balance_id", "balance", "credit_balance", "debit_balance", "currency", "currency_multiplier", "ledger_id", "identity_id", "created_at", "meta_data", "inflight_balance", "inflight_credit_balance", "inflight_debit_balance", "version", "indicator"}).
AddRow(balanceID,
BigIntString{big.NewInt(100)},
BigIntString{big.NewInt(50)},
BigIntString{big.NewInt(50)},
"USD", 100, "test-ledger", "test-identity", time.Now(),
`{"key":"value"}`,
BigIntString{big.NewInt(0)},
BigIntString{big.NewInt(0)},
BigIntString{big.NewInt(0)},
0,
"test-indicator")
mock.ExpectQuery(expectedSQL).
WithArgs(balanceID).
WillReturnRows(rows)
mock.ExpectCommit()
result, err := d.GetBalanceByID(context.Background(), balanceID, nil)
assert.NoError(t, err)
assert.NotNil(t, result)
assert.Equal(t, balanceID, result.BalanceID)
assert.Equal(t, big.NewInt(100), result.Balance)
assert.Equal(t, big.NewInt(50), result.CreditBalance)
assert.Equal(t, big.NewInt(50), result.DebitBalance)
assert.Equal(t, "test-indicator", result.Indicator)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestGetAllBalances(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
// The column order must match the actual SQL generated.
rows := sqlmock.NewRows([]string{
"balance_id", "indicator", "balance", "credit_balance", "debit_balance",
"currency", "currency_multiplier", "ledger_id", "created_at", "meta_data",
}).
AddRow(
"test-balance", "test-indicator", 100, 50, 50, "USD", 1.0, "test-ledger",
time.Now(), `{"key":"value"}`,
)
mock.ExpectQuery(`SELECT balance_id, indicator, balance, credit_balance, debit_balance, currency, currency_multiplier, ledger_id, created_at, meta_data FROM blnk.balances ORDER BY created_at DESC LIMIT \$1 OFFSET \$2`).
WithArgs(1, 1).
WillReturnRows(rows)
result, err := d.GetAllBalances(context.Background(), 1, 1)
assert.NoError(t, err)
assert.Len(t, result, 1)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestUpdateBalance(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
balance := &model.Balance{
BalanceID: "test-balance",
Balance: big.NewInt(100),
CreditBalance: big.NewInt(50),
DebitBalance: big.NewInt(50),
Currency: "USD",
CurrencyMultiplier: 1,
LedgerID: gofakeit.UUID(),
CreatedAt: time.Time{}, // Assuming CreatedAt is properly initialized elsewhere
MetaData: map[string]interface{}{}, // Assuming MetaData is initialized, even if empty
}
// Assuming metaDataJSON is what you expect to be passed as the last argument
metaDataJSON, _ := json.Marshal(balance.MetaData)
mock.ExpectExec(regexp.QuoteMeta(`
UPDATE blnk.balances
SET balance = $2, credit_balance = $3, debit_balance = $4, currency = $5, currency_multiplier = $6, ledger_id = $7, created_at = $8, meta_data = $9
WHERE balance_id = $1`)).WithArgs(balance.BalanceID, balance.Balance.String(), balance.CreditBalance.String(), balance.DebitBalance.String(), balance.Currency, balance.CurrencyMultiplier, balance.LedgerID, balance.CreatedAt, metaDataJSON).WillReturnResult(sqlmock.NewResult(1, 1))
err = d.datasource.UpdateBalance(balance)
assert.NoError(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestUpdateBalances(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
sourceBalance := &model.Balance{BalanceID: "source-balance", Balance: big.NewInt(100), CreditBalance: big.NewInt(50), DebitBalance: big.NewInt(50), Currency: "USD"}
destinationBalance := &model.Balance{BalanceID: "destination-balance", Balance: big.NewInt(150), CreditBalance: big.NewInt(75), DebitBalance: big.NewInt(75), Currency: "USD"}
// Expect transaction begin
mock.ExpectBegin()
// Expect the first update (for sourceBalance)
mock.ExpectExec("UPDATE blnk.balances").WithArgs(
sourceBalance.BalanceID, sourceBalance.Balance.String(), sourceBalance.CreditBalance.String(), sourceBalance.DebitBalance.String(), sourceBalance.InflightBalance.String(), sourceBalance.InflightCreditBalance.String(), sourceBalance.InflightDebitBalance.String(), sourceBalance.Currency, sourceBalance.CurrencyMultiplier, sourceBalance.LedgerID, sourceBalance.CreatedAt, sqlmock.AnyArg(), sourceBalance.Version,
).WillReturnResult(sqlmock.NewResult(1, 1))
// Expect the second update (for destinationBalance)
mock.ExpectExec("UPDATE blnk.balances").WithArgs(
destinationBalance.BalanceID, destinationBalance.Balance.String(), destinationBalance.CreditBalance.String(), destinationBalance.DebitBalance.String(), destinationBalance.InflightBalance.String(), destinationBalance.InflightCreditBalance.String(), destinationBalance.InflightDebitBalance.String(), destinationBalance.Currency, destinationBalance.CurrencyMultiplier, destinationBalance.LedgerID, destinationBalance.CreatedAt, sqlmock.AnyArg(), destinationBalance.Version,
).WillReturnResult(sqlmock.NewResult(1, 1))
// Expect transaction commit
mock.ExpectCommit()
err = d.datasource.UpdateBalances(context.Background(), sourceBalance, destinationBalance)
assert.NoError(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestCreateMonitor(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
monitor := model.BalanceMonitor{BalanceID: "test-balance", Description: "Test Monitor", CallBackURL: gofakeit.URL(), Condition: model.AlertCondition{Field: "field", Operator: "operator", Value: 1000, Precision: 100, PreciseValue: big.NewInt(100000)}}
mock.ExpectExec("INSERT INTO blnk.balance_monitors").WithArgs(sqlmock.AnyArg(), monitor.BalanceID, monitor.Condition.Field, monitor.Condition.Operator, monitor.Condition.Value, monitor.Condition.Precision, monitor.Condition.PreciseValue.String(), monitor.Description, monitor.CallBackURL, sqlmock.AnyArg()).WillReturnResult(sqlmock.NewResult(1, 1))
result, err := d.CreateMonitor(context.Background(), monitor)
assert.NoError(t, err)
assert.NotEmpty(t, result.MonitorID)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestGetMonitorByID(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
monitorID := "test-monitor"
rows := sqlmock.NewRows([]string{"monitor_id", "balance_id", "field", "operator", "value", "precision", "precise_value", "description", "call_back_url", "created_at"}).
AddRow(monitorID, gofakeit.UUID(), "field", "operator", 1000, 100, 100000, "Test Monitor", gofakeit.URL(), time.Now())
mock.ExpectQuery("SELECT .* FROM blnk.balance_monitors WHERE monitor_id =").WithArgs(monitorID).WillReturnRows(rows)
result, err := d.GetMonitorByID(context.Background(), monitorID)
assert.NoError(t, err)
assert.Equal(t, monitorID, result.MonitorID)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestGetAllMonitors(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
rows := sqlmock.NewRows([]string{"monitor_id", "balance_id", "field", "operator", "value", "description", "call_back_url", "created_at"}).
AddRow("test-monitor", gofakeit.UUID(), "field", "operator", 100, "Test Monitor", gofakeit.URL(), time.Now())
mock.ExpectQuery("SELECT .* FROM blnk.balance_monitors").WillReturnRows(rows)
result, err := d.GetAllMonitors(context.Background())
assert.NoError(t, err)
assert.Len(t, result, 1)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestGetBalanceMonitors(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
balanceID := gofakeit.UUID()
rows := sqlmock.NewRows([]string{"monitor_id", "balance_id", "field", "operator", "value", "description", "call_back_url", "created_at", "precision", "precise_value"}).
AddRow("test-monitor", balanceID, "field", "operator", 100, "Test Monitor", gofakeit.URL(), time.Now(), 100, 100000)
mock.ExpectQuery("SELECT .* FROM blnk.balance_monitors WHERE balance_id =").WithArgs(balanceID).WillReturnRows(rows)
result, err := d.GetBalanceMonitors(context.Background(), balanceID)
assert.NoError(t, err)
assert.Len(t, result, 1)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestUpdateMonitor(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
monitor := &model.BalanceMonitor{MonitorID: "test-monitor", BalanceID: "test-balance", Description: "Updated Monitor"}
mock.ExpectExec("UPDATE blnk.balance_monitors").WithArgs(monitor.MonitorID, monitor.BalanceID, monitor.Condition.Field, monitor.Condition.Operator, monitor.Condition.Value, monitor.Description, monitor.CallBackURL).WillReturnResult(sqlmock.NewResult(1, 1))
err = d.UpdateMonitor(context.Background(), monitor)
assert.NoError(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestDeleteMonitor(t *testing.T) {
datasource, mock, err := newTestDataSource()
if err != nil {
t.Fatalf("Error creating test data source: %s", err)
}
d, err := NewBlnk(datasource)
if err != nil {
t.Fatalf("Error creating Blnk instance: %s", err)
}
monitorID := "test-monitor"
mock.ExpectExec("DELETE FROM blnk.balance_monitors WHERE monitor_id =").WithArgs(monitorID).WillReturnResult(sqlmock.NewResult(1, 1))
err = d.DeleteMonitor(context.Background(), monitorID)
assert.NoError(t, err)
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}