retry_test.go46 lines, 1.2 KB
| 1 | package postgres_test |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "slices" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 10 | "github.com/jackc/pgx/v5/pgconn" |
| 11 | ) |
| 12 | |
| 13 | func TestRetry(t *testing.T) { |
| 14 | t.Parallel() |
| 15 | conflict := &pgconn.PgError{Code: "40001"} // serialization_failure |
| 16 | deadlock := &pgconn.PgError{Code: "40P01"} // deadlock_detected |
| 17 | broken := errors.New("connection refused") |
| 18 | |
| 19 | tests := []struct { |
| 20 | name string |
| 21 | errs []error // what each attempt returns; then nil |
| 22 | calls int |
| 23 | ok bool |
| 24 | }{ |
| 25 | {"works the first time", nil, 1, true}, |
| 26 | {"retries a serialization failure", []error{conflict}, 2, true}, |
| 27 | {"retries a wrapped deadlock", []error{fmt.Errorf("commit: %w", deadlock), deadlock}, 3, true}, |
| 28 | {"gives up eventually", slices.Repeat([]error{conflict}, 10), postgres.MaxAttempts, false}, |
| 29 | {"never retries other errors", []error{broken}, 1, false}, |
| 30 | } |
| 31 | for _, tt := range tests { |
| 32 | t.Run(tt.name, func(t *testing.T) { |
| 33 | calls := 0 |
| 34 | err := postgres.Retry(t.Context(), func() error { |
| 35 | calls++ |
| 36 | if calls <= len(tt.errs) { |
| 37 | return tt.errs[calls-1] |
| 38 | } |
| 39 | return nil |
| 40 | }) |
| 41 | if calls != tt.calls || (err == nil) != tt.ok { |
| 42 | t.Errorf("%d calls, error %v; want %d calls, ok = %t", calls, err, tt.calls, tt.ok) |
| 43 | } |
| 44 | }) |
| 45 | } |
| 46 | } |