| 13 | ) |
| 14 | |
| 15 | func TestNewJSONErrorResponse(t *testing.T) { |
| 16 | t.Parallel() |
| 17 | |
| 18 | tests := []struct { |
| 19 | name string |
| 20 | status int |
| 21 | retryAfter time.Duration |
| 22 | body []byte |
| 23 | // Empty string means the header should be absent. |
| 24 | expectRetryAfter string |
| 25 | }{ |
| 26 | { |
| 27 | // Permanent exhaustion: 502 with no Retry-After. |
| 28 | name: "permanent_no_retry_after", |
| 29 | status: http.StatusBadGateway, |
| 30 | retryAfter: 0, |
| 31 | body: []byte(`{"error":"permanent"}`), |
| 32 | expectRetryAfter: "", |
| 33 | }, |
| 34 | { |
| 35 | // Transient exhaustion with zero retryAfter: no Retry-After. |
| 36 | name: "transient_no_retry_after", |
| 37 | status: http.StatusTooManyRequests, |
| 38 | retryAfter: 0, |
| 39 | body: []byte(`{"error":"rate"}`), |
| 40 | expectRetryAfter: "", |
| 41 | }, |
| 42 | { |
| 43 | // Transient exhaustion: 429 with Retry-After in seconds. |
| 44 | name: "transient_with_retry_after", |
| 45 | status: http.StatusTooManyRequests, |
| 46 | retryAfter: 60 * time.Second, |
| 47 | body: []byte(`{"error":"rate"}`), |
| 48 | expectRetryAfter: "60", |
| 49 | }, |
| 50 | { |
| 51 | // Transient exhaustion with negative retryAfter: Retry-After header omitted. |
| 52 | name: "transient_negative_retry_after", |
| 53 | status: http.StatusTooManyRequests, |
| 54 | retryAfter: -1 * time.Second, |
| 55 | body: []byte(`{"error":"rate"}`), |
| 56 | expectRetryAfter: "", |
| 57 | }, |
| 58 | { |
| 59 | // Transient exhaustion with 500ms retryAfter rounds up to Retry-After: 1. |
| 60 | name: "transient_under_one_second_rounds_up", |
| 61 | status: http.StatusTooManyRequests, |
| 62 | retryAfter: 500 * time.Millisecond, |
| 63 | body: []byte(`{"error":"rate"}`), |
| 64 | expectRetryAfter: "1", |
| 65 | }, |
| 66 | } |
| 67 | |
| 68 | for _, tc := range tests { |
| 69 | t.Run(tc.name, func(t *testing.T) { |
| 70 | t.Parallel() |
| 71 | |
| 72 | resp := utils.NewJSONErrorResponse(tc.status, tc.retryAfter, tc.body) |