cache_test.go52 lines, 1.2 KB
| 1 | package notification_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "sync" |
| 6 | "sync/atomic" |
| 7 | "testing" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/notification" |
| 11 | "github.com/google/uuid" |
| 12 | ) |
| 13 | |
| 14 | // countingUsers counts the lookups that get through to it. |
| 15 | type countingUsers struct { |
| 16 | calls atomic.Int32 |
| 17 | } |
| 18 | |
| 19 | func (u *countingUsers) Email(ctx context.Context, id uuid.UUID) (string, error) { |
| 20 | u.calls.Add(1) |
| 21 | return users{}.Email(ctx, id) |
| 22 | } |
| 23 | |
| 24 | func TestCachedUsers(t *testing.T) { |
| 25 | t.Parallel() |
| 26 | auth := &countingUsers{} |
| 27 | cache := notification.NewCachedUsers(auth, time.Minute) |
| 28 | alice, bob := uuid.New(), uuid.New() |
| 29 | |
| 30 | // Like the consumers: lots of lookups at once, for the same two users. |
| 31 | var wg sync.WaitGroup |
| 32 | for i := range 100 { |
| 33 | id := alice |
| 34 | if i%2 == 1 { |
| 35 | id = bob |
| 36 | } |
| 37 | wg.Go(func() { |
| 38 | if got, err := cache.Email(t.Context(), id); err != nil || got != id.String()+"@example.com" { |
| 39 | t.Errorf("Email = %q, %v; want %s@example.com", got, err, id) |
| 40 | } |
| 41 | }) |
| 42 | } |
| 43 | wg.Wait() |
| 44 | |
| 45 | // Both are cached now: nothing else gets through to auth. |
| 46 | before := auth.calls.Load() |
| 47 | cache.Email(t.Context(), alice) |
| 48 | cache.Email(t.Context(), bob) |
| 49 | if after := auth.calls.Load(); after != before { |
| 50 | t.Errorf("%d more lookups reached auth, want none", after-before) |
| 51 | } |
| 52 | } |