reconcile_test.go59 lines, 1.8 KB
| 1 | package wallet_test |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "slices" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/fiston-user/payments/internal/wallet" |
| 9 | "github.com/jackc/pgx/v5" |
| 10 | ) |
| 11 | |
| 12 | // TestReconcileFindsTampering bumps a deposit by ten dollars behind the |
| 13 | // triggers' back, as a hand-written fix might, and expects reconciliation to |
| 14 | // name the transaction. It all happens in a transaction that's rolled back, |
| 15 | // so no other test ever sees it. |
| 16 | func TestReconcileFindsTampering(t *testing.T) { |
| 17 | t.Parallel() |
| 18 | pool := newPool(t) |
| 19 | svc := wallet.NewService(wallet.NewStore(pool)) |
| 20 | deposit, err := svc.Deposit(t.Context(), newWallet(t, svc, 0), usd(5000)) |
| 21 | if err != nil { |
| 22 | t.Fatalf("deposit: %v", err) |
| 23 | } |
| 24 | tx, err := pool.BeginTx(t.Context(), pgx.TxOptions{IsoLevel: pgx.RepeatableRead}) |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | defer tx.Rollback(t.Context()) |
| 29 | store := wallet.NewStore(pool).WithTx(tx) |
| 30 | if r, err := store.Reconcile(t.Context()); err != nil || len(r.Discrepancies) > 0 { |
| 31 | t.Fatalf("before: Reconcile = %+v, %v; want no discrepancies", r, err) |
| 32 | } |
| 33 | |
| 34 | // Replica mode is for replication tools: it fires no triggers, so nothing |
| 35 | // checks this UPDATE. Only a superuser can switch it on. |
| 36 | _, err = tx.Exec(t.Context(), "SET LOCAL session_replication_role = replica") |
| 37 | if err == nil { |
| 38 | _, err = tx.Exec(t.Context(), `UPDATE entries SET amount = amount + 1000 |
| 39 | WHERE transaction_id = $1 AND direction = 'credit'`, deposit.ID) |
| 40 | } |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | r, err := store.Reconcile(t.Context()) |
| 45 | if err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | var got []string |
| 49 | for _, d := range r.Discrepancies { |
| 50 | got = append(got, fmt.Sprintf("%s %s %s %d %d", d.Check, d.Ref, d.Currency, d.Expected, d.Actual)) |
| 51 | } |
| 52 | want := []string{ |
| 53 | "trial_balance all entries USD 0 -1000", |
| 54 | fmt.Sprintf("unbalanced_transaction %s USD 0 -1000", deposit.ID), |
| 55 | } |
| 56 | if !slices.Equal(got, want) { |
| 57 | t.Errorf("Reconcile found\n%q\nwant\n%q", got, want) |
| 58 | } |
| 59 | } |