velocity_test.go77 lines, 2.1 KB
| 1 | package risk_test |
| 2 | |
| 3 | import ( |
| 4 | "slices" |
| 5 | "sync" |
| 6 | "testing" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/platform/redis" |
| 10 | "github.com/fiston-user/payments/internal/transfer/risk" |
| 11 | "github.com/google/uuid" |
| 12 | ) |
| 13 | |
| 14 | // newVelocity counts on the package's Redis. |
| 15 | func newVelocity(t *testing.T, count, amount time.Duration) *risk.Velocity { |
| 16 | t.Helper() |
| 17 | if testing.Short() { |
| 18 | t.Skip("integration test") |
| 19 | } |
| 20 | rdb, err := redis.NewClient(redisURL) |
| 21 | if err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | t.Cleanup(func() { rdb.Close() }) |
| 25 | return risk.NewVelocity(rdb, count, amount) |
| 26 | } |
| 27 | |
| 28 | func TestVelocity(t *testing.T) { |
| 29 | t.Parallel() |
| 30 | v := newVelocity(t, 300*time.Millisecond, time.Hour) |
| 31 | user, retried := uuid.New(), uuid.New() |
| 32 | record := func(id uuid.UUID, amount int64, want risk.Recent) { |
| 33 | t.Helper() |
| 34 | if got, err := v.Record(t.Context(), user, id, amount); err != nil || got != want { |
| 35 | t.Fatalf("Record = %+v, %v; want %+v", got, err, want) |
| 36 | } |
| 37 | } |
| 38 | record(uuid.New(), 1500, risk.Recent{Count: 1, Amount: 1500}) |
| 39 | record(retried, 2500, risk.Recent{Count: 2, Amount: 4000}) |
| 40 | record(retried, 2500, risk.Recent{Count: 2, Amount: 4000}) // a retry counts once |
| 41 | |
| 42 | // Past the count window, inside the amount window. |
| 43 | time.Sleep(400 * time.Millisecond) |
| 44 | record(uuid.New(), 1000, risk.Recent{Count: 1, Amount: 5000}) |
| 45 | |
| 46 | // Someone else starts from zero. |
| 47 | if got, err := v.Record(t.Context(), uuid.New(), uuid.New(), 700); err != nil || got.Count != 1 { |
| 48 | t.Errorf("another user: Record = %+v, %v; want a count of 1", got, err) |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func TestVelocityIsAtomic(t *testing.T) { |
| 53 | t.Parallel() |
| 54 | v := newVelocity(t, time.Hour, time.Hour) |
| 55 | user := uuid.New() |
| 56 | |
| 57 | // Fifty transfers at once, from fifty instances: each sees a count of its |
| 58 | // own, from 1 to 50. With a read, then a write, some would see the same. |
| 59 | counts := make([]int, 50) |
| 60 | var wg sync.WaitGroup |
| 61 | for i := range counts { |
| 62 | wg.Go(func() { |
| 63 | r, err := v.Record(t.Context(), user, uuid.New(), 100) |
| 64 | if err != nil { |
| 65 | t.Error(err) |
| 66 | } |
| 67 | counts[i] = r.Count |
| 68 | }) |
| 69 | } |
| 70 | wg.Wait() |
| 71 | slices.Sort(counts) |
| 72 | for i, n := range counts { |
| 73 | if n != i+1 { |
| 74 | t.Fatalf("counts = %v, want 1 to 50, once each", counts) |
| 75 | } |
| 76 | } |
| 77 | } |