| 1 | package discord |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | "testing/synctest" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/jarcoal/httpmock" |
| 15 | "github.com/onsi/ginkgo/v2" |
| 16 | "github.com/onsi/gomega" |
| 17 | "github.com/stretchr/testify/assert" |
| 18 | "github.com/stretchr/testify/mock" |
| 19 | "github.com/stretchr/testify/require" |
| 20 | |
| 21 | "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord/mocks" |
| 22 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 23 | ) |
| 24 | |
| 25 | // mockTemporaryError implements net.Error for testing. |
| 26 | type mockTemporaryError struct{} |
| 27 | |
| 28 | // mockTimeoutError implements net.Error for testing timeout. |
| 29 | type mockTimeoutError struct{} |
| 30 | |
| 31 | var _ = ginkgo.Describe("Discord Sender", func() { |
| 32 | ginkgo.Describe("NewDefaultHTTPClient", func() { |
| 33 | ginkgo.It("should create a client with proper timeout", func() { |
| 34 | client := NewDefaultHTTPClient() |
| 35 | gomega.Expect(client).NotTo(gomega.BeNil()) |
| 36 | gomega.Expect(client.client).NotTo(gomega.BeNil()) |
| 37 | gomega.Expect(client.client.Timeout).To(gomega.Equal(30 * time.Second)) |
| 38 | }) |
| 39 | }) |
| 40 | |
| 41 | ginkgo.Describe("DefaultHTTPClient.Do", func() { |
| 42 | var client *DefaultHTTPClient |
| 43 | |
| 44 | ginkgo.BeforeEach(func() { |
| 45 | client = NewDefaultHTTPClient() |
| 46 | httpmock.ActivateNonDefault(client.client) |
| 47 | }) |
| 48 | |
| 49 | ginkgo.AfterEach(func() { |
| 50 | httpmock.DeactivateAndReset() |
| 51 | }) |
| 52 | |
| 53 | ginkgo.It("should successfully make HTTP request", func() { |
| 54 | httpmock.RegisterResponder("GET", "http://example.com", |
| 55 | httpmock.NewStringResponder(200, "success")) |
| 56 | |
| 57 | req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) |
| 58 | resp, err := client.Do(req) |
| 59 | |
| 60 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 61 | gomega.Expect(resp.StatusCode).To(gomega.Equal(200)) |
| 62 | body, _ := io.ReadAll(resp.Body) |
| 63 | gomega.Expect(string(body)).To(gomega.Equal("success")) |
| 64 | }) |
| 65 | |
| 66 | ginkgo.It("should handle network errors", func() { |
| 67 | httpmock.RegisterResponder("GET", "http://example.com", |
| 68 | httpmock.NewErrorResponder(errors.New("network error"))) |
| 69 | |
| 70 | req, _ := http.NewRequest(http.MethodGet, "http://example.com", http.NoBody) |
| 71 | _, err := client.Do(req) |
| 72 | |
| 73 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 74 | gomega.Expect(err.Error()).To(gomega.ContainSubstring("performing HTTP request")) |
| 75 | }) |
| 76 | }) |
| 77 | |
| 78 | ginkgo.Describe("JSONRequestPreparer.PrepareRequest", func() { |
| 79 | var ( |
| 80 | preparer *JSONRequestPreparer |
| 81 | payload []byte |
| 82 | ) |
| 83 | |
| 84 | ginkgo.BeforeEach(func() { |
| 85 | payload = []byte(`{"content":"test message"}`) |
| 86 | preparer = &JSONRequestPreparer{payload: payload} |
| 87 | }) |
| 88 | |
| 89 | ginkgo.It("should create a valid JSON POST request", func() { |
| 90 | ctx := context.Background() |
| 91 | url := testWebhookURLAlt |
| 92 | |
| 93 | req, err := preparer.PrepareRequest(ctx, url) |
| 94 | |
| 95 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 96 | gomega.Expect(req.Method).To(gomega.Equal("POST")) |
| 97 | gomega.Expect(req.URL.String()).To(gomega.Equal(url)) |
| 98 | gomega.Expect(req.Header.Get("Content-Type")).To(gomega.Equal("application/json")) |
| 99 | |
| 100 | body, _ := io.ReadAll(req.Body) |
| 101 | gomega.Expect(body).To(gomega.Equal(payload)) |
| 102 | }) |
| 103 | |
| 104 | ginkgo.It("should handle context properly", func() { |
| 105 | ctx, cancel := context.WithCancel(context.Background()) |
| 106 | cancel() // Cancel immediately |
| 107 | |
| 108 | url := testWebhookURLAlt |
| 109 | _, err := preparer.PrepareRequest(ctx, url) |
| 110 | |
| 111 | gomega.Expect(err). |
| 112 | ToNot(gomega.HaveOccurred()) |
| 113 | // http.NewRequestWithContext doesn't fail on canceled context |
| 114 | }) |
| 115 | }) |
| 116 | |
| 117 | ginkgo.Describe("MultipartRequestPreparer.PrepareRequest", func() { |
| 118 | var preparer *MultipartRequestPreparer |
| 119 | |
| 120 | ginkgo.BeforeEach(func() { |
| 121 | payload := &WebhookPayload{ |
| 122 | Content: "test message", |
| 123 | } |
| 124 | files := []types.File{ |
| 125 | {Name: "test.txt", Data: []byte("file content")}, |
| 126 | } |
| 127 | preparer = &MultipartRequestPreparer{ |
| 128 | payload: payload, |
| 129 | files: files, |
| 130 | } |
| 131 | }) |
| 132 | |
| 133 | ginkgo.It("should create a valid multipart POST request", func() { |
| 134 | ctx := context.Background() |
| 135 | url := testWebhookURLAlt |
| 136 | |
| 137 | req, err := preparer.PrepareRequest(ctx, url) |
| 138 | |
| 139 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 140 | gomega.Expect(req.Method).To(gomega.Equal("POST")) |
| 141 | gomega.Expect(req.URL.String()).To(gomega.Equal(url)) |
| 142 | gomega.Expect(req.Header.Get("Content-Type")). |
| 143 | To(gomega.ContainSubstring("multipart/form-data")) |
| 144 | |
| 145 | body, _ := io.ReadAll(req.Body) |
| 146 | gomega.Expect(body).ToNot(gomega.BeEmpty()) |
| 147 | |
| 148 | // Check if payload_json is in the body |
| 149 | bodyStr := string(body) |
| 150 | gomega.Expect(bodyStr).To(gomega.ContainSubstring("payload_json")) |
| 151 | gomega.Expect(bodyStr).To(gomega.ContainSubstring("test message")) |
| 152 | gomega.Expect(bodyStr).To(gomega.ContainSubstring("files[0]")) |
| 153 | gomega.Expect(bodyStr).To(gomega.ContainSubstring("test.txt")) |
| 154 | }) |
| 155 | |
| 156 | ginkgo.It("should handle empty files", func() { |
| 157 | preparer.files = []types.File{} |
| 158 | ctx := context.Background() |
| 159 | url := testWebhookURLAlt |
| 160 | |
| 161 | req, err := preparer.PrepareRequest(ctx, url) |
| 162 | |
| 163 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 164 | |
| 165 | body, _ := io.ReadAll(req.Body) |
| 166 | bodyStr := string(body) |
| 167 | gomega.Expect(bodyStr).To(gomega.ContainSubstring("payload_json")) |
| 168 | gomega.Expect(bodyStr).NotTo(gomega.ContainSubstring("files[")) |
| 169 | }) |
| 170 | }) |
| 171 | |
| 172 | ginkgo.Describe("sendWithRetry", func() { |
| 173 | var preparer *JSONRequestPreparer |
| 174 | |
| 175 | ginkgo.BeforeEach(func() { |
| 176 | payload := []byte(`{"content":"test"}`) |
| 177 | preparer = &JSONRequestPreparer{payload: payload} |
| 178 | }) |
| 179 | |
| 180 | ginkgo.It("should succeed on first attempt", func() { |
| 181 | mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 182 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 183 | |
| 184 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 185 | StatusCode: http.StatusNoContent, |
| 186 | Body: io.NopCloser(strings.NewReader("")), |
| 187 | }, nil).Once() |
| 188 | |
| 189 | ctx := context.Background() |
| 190 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 191 | |
| 192 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 193 | }) |
| 194 | |
| 195 | ginkgo.It("should succeed on first attempt with StatusOK", func() { |
| 196 | mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 197 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 198 | |
| 199 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 200 | StatusCode: http.StatusOK, |
| 201 | Body: io.NopCloser(strings.NewReader("")), |
| 202 | }, nil).Once() |
| 203 | |
| 204 | ctx := context.Background() |
| 205 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 206 | |
| 207 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 208 | }) |
| 209 | |
| 210 | ginkgo.It("should handle unexpected status codes", func() { |
| 211 | mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 212 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 213 | |
| 214 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 215 | StatusCode: http.StatusBadRequest, |
| 216 | Status: "400 Bad Request", |
| 217 | Body: io.NopCloser(strings.NewReader("")), |
| 218 | }, nil).Once() |
| 219 | |
| 220 | ctx := context.Background() |
| 221 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 222 | |
| 223 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 224 | gomega.Expect(err.Error()). |
| 225 | To(gomega.ContainSubstring("unexpected response status code")) |
| 226 | }) |
| 227 | |
| 228 | ginkgo.It("should handle nil response", func() { |
| 229 | mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 230 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 231 | |
| 232 | mockClient.On("Do", mock.Anything).Return((*http.Response)(nil), nil).Once() |
| 233 | |
| 234 | ctx := context.Background() |
| 235 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 236 | |
| 237 | gomega.Expect(err).To(gomega.MatchError(ErrUnknownAPIError)) |
| 238 | }) |
| 239 | |
| 240 | ginkgo.It("should handle HTTP client errors", func() { |
| 241 | mockClient := mocks.NewMockHTTPClient(ginkgo.GinkgoT()) |
| 242 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 243 | |
| 244 | mockClient.On("Do", mock.Anything).Return(nil, http.ErrHandlerTimeout).Once() |
| 245 | |
| 246 | ctx := context.Background() |
| 247 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 248 | |
| 249 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 250 | gomega.Expect(err.Error()).To(gomega.ContainSubstring("making HTTP POST request")) |
| 251 | }) |
| 252 | }) |
| 253 | |
| 254 | ginkgo.Describe("handleRateLimitResponse", func() { |
| 255 | ginkgo.It("should handle retry-after header", func() { |
| 256 | resp := &http.Response{ |
| 257 | StatusCode: http.StatusTooManyRequests, |
| 258 | Header: make(http.Header), |
| 259 | Body: io.NopCloser(strings.NewReader("")), |
| 260 | } |
| 261 | resp.Header.Set("Retry-After", "2") |
| 262 | |
| 263 | startTime := time.Now() |
| 264 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 265 | sleeper.On("Sleep", 2*time.Second).Return().Once() |
| 266 | |
| 267 | err := handleRateLimitResponse(context.Background(), resp, 0, startTime, sleeper) |
| 268 | |
| 269 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 270 | }) |
| 271 | |
| 272 | ginkgo.It("should handle invalid retry-after header", func() { |
| 273 | resp := &http.Response{ |
| 274 | StatusCode: http.StatusTooManyRequests, |
| 275 | Header: make(http.Header), |
| 276 | Body: io.NopCloser(strings.NewReader("")), |
| 277 | } |
| 278 | resp.Header.Set("Retry-After", "invalid") |
| 279 | |
| 280 | startTime := time.Now() |
| 281 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 282 | sleeper.On("Sleep", time.Second).Return().Once() |
| 283 | |
| 284 | err := handleRateLimitResponse(context.Background(), resp, 0, startTime, sleeper) |
| 285 | |
| 286 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 287 | // Should fall back to exponential backoff |
| 288 | }) |
| 289 | |
| 290 | ginkgo.It("should handle retry-after exceeding max timeout", func() { |
| 291 | resp := &http.Response{ |
| 292 | StatusCode: http.StatusTooManyRequests, |
| 293 | Header: make(http.Header), |
| 294 | Body: io.NopCloser(strings.NewReader("")), |
| 295 | } |
| 296 | resp.Header.Set("Retry-After", "400") // Exceeds 5 minutes |
| 297 | |
| 298 | startTime := time.Now() |
| 299 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 300 | |
| 301 | err := handleRateLimitResponse(context.Background(), resp, 0, startTime, sleeper) |
| 302 | |
| 303 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 304 | gomega.Expect(err).To(gomega.MatchError(ErrRateLimited)) |
| 305 | }) |
| 306 | |
| 307 | ginkgo.It("should handle exponential backoff", func() { |
| 308 | resp := &http.Response{ |
| 309 | StatusCode: http.StatusTooManyRequests, |
| 310 | Header: make(http.Header), |
| 311 | Body: io.NopCloser(strings.NewReader("")), |
| 312 | } |
| 313 | // No retry-after header |
| 314 | |
| 315 | startTime := time.Now() |
| 316 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 317 | sleeper.On("Sleep", 4*time.Second).Return().Once() |
| 318 | |
| 319 | err := handleRateLimitResponse( |
| 320 | context.Background(), |
| 321 | resp, |
| 322 | 2, |
| 323 | startTime, |
| 324 | sleeper, |
| 325 | ) |
| 326 | |
| 327 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 328 | }) |
| 329 | |
| 330 | ginkgo.It("should cap exponential backoff", func() { |
| 331 | resp := &http.Response{ |
| 332 | StatusCode: http.StatusTooManyRequests, |
| 333 | Header: make(http.Header), |
| 334 | Body: io.NopCloser(strings.NewReader("")), |
| 335 | } |
| 336 | |
| 337 | startTime := time.Now() |
| 338 | sleeper := mocks.NewMockSleeper(ginkgo.GinkgoT()) |
| 339 | sleeper.On("Sleep", 64*time.Second).Return().Once() |
| 340 | |
| 341 | err := handleRateLimitResponse( |
| 342 | context.Background(), |
| 343 | resp, |
| 344 | 6, |
| 345 | startTime, |
| 346 | sleeper, |
| 347 | ) |
| 348 | |
| 349 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 350 | }) |
| 351 | }) |
| 352 | }) |
| 353 | |
| 354 | func TestSendWithRetryRateLimitRetryAfter(t *testing.T) { |
| 355 | t.Parallel() |
| 356 | synctest.Test(t, func(t *testing.T) { |
| 357 | gomega.RegisterTestingT(t) |
| 358 | |
| 359 | mockClient := mocks.NewMockHTTPClient(t) |
| 360 | payload := []byte(`{"content":"test"}`) |
| 361 | preparer := &JSONRequestPreparer{payload: payload} |
| 362 | sleeper := mocks.NewMockSleeper(t) |
| 363 | |
| 364 | // First call returns 429 with retry-after |
| 365 | resp1 := &http.Response{ |
| 366 | StatusCode: http.StatusTooManyRequests, |
| 367 | Header: make(http.Header), |
| 368 | Body: io.NopCloser(strings.NewReader("")), |
| 369 | } |
| 370 | resp1.Header.Set("Retry-After", "1") |
| 371 | |
| 372 | mockClient.On("Do", mock.Anything).Return(resp1, nil).Once() |
| 373 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 374 | StatusCode: http.StatusNoContent, |
| 375 | Body: io.NopCloser(strings.NewReader("")), |
| 376 | }, nil).Once() |
| 377 | sleeper.On("Sleep", time.Second).Return().Once() |
| 378 | |
| 379 | ctx := context.Background() |
| 380 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 381 | |
| 382 | gomega.Expect(err).ToNot(gomega.HaveOccurred()) |
| 383 | }) |
| 384 | } |
| 385 | |
| 386 | func TestSendWithRetryMaxRetriesExceeded(t *testing.T) { |
| 387 | t.Parallel() |
| 388 | synctest.Test(t, func(t *testing.T) { |
| 389 | gomega.RegisterTestingT(t) |
| 390 | |
| 391 | mockClient := mocks.NewMockHTTPClient(t) |
| 392 | payload := []byte(`{"content":"test"}`) |
| 393 | preparer := &JSONRequestPreparer{payload: payload} |
| 394 | sleeper := mocks.NewMockSleeper(t) |
| 395 | |
| 396 | resp := &http.Response{ |
| 397 | StatusCode: http.StatusInternalServerError, |
| 398 | Status: "500 Internal Server Error", |
| 399 | Body: io.NopCloser(strings.NewReader("")), |
| 400 | } |
| 401 | |
| 402 | // Expect 6 calls (MaxRetries + 1) |
| 403 | mockClient.On("Do", mock.Anything).Return(resp, nil).Times(6) |
| 404 | // Expect 5 sleeps with exponential backoff |
| 405 | sleeper.On("Sleep", time.Second).Return().Once() |
| 406 | sleeper.On("Sleep", 2*time.Second).Return().Once() |
| 407 | sleeper.On("Sleep", 4*time.Second).Return().Once() |
| 408 | sleeper.On("Sleep", 8*time.Second).Return().Once() |
| 409 | sleeper.On("Sleep", 16*time.Second).Return().Once() |
| 410 | |
| 411 | ctx := context.Background() |
| 412 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 413 | |
| 414 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 415 | gomega.Expect(err).To(gomega.MatchError(ErrMaxRetries)) |
| 416 | }) |
| 417 | } |
| 418 | |
| 419 | func TestSendWithRetryMaxRetryTimeout(t *testing.T) { |
| 420 | t.Parallel() |
| 421 | synctest.Test(t, func(t *testing.T) { |
| 422 | gomega.RegisterTestingT(t) |
| 423 | |
| 424 | mockClient := mocks.NewMockHTTPClient(t) |
| 425 | payload := []byte(`{"content":"test"}`) |
| 426 | preparer := &JSONRequestPreparer{payload: payload} |
| 427 | sleeper := mocks.NewMockSleeper(t) |
| 428 | |
| 429 | // Mock a very long retry-after that exceeds MaxRetryTimeout |
| 430 | resp := &http.Response{ |
| 431 | StatusCode: http.StatusTooManyRequests, |
| 432 | Header: make(http.Header), |
| 433 | Body: io.NopCloser(strings.NewReader("")), |
| 434 | } |
| 435 | resp.Header.Set("Retry-After", "400") // Exceeds 5 minutes |
| 436 | |
| 437 | mockClient.On("Do", mock.Anything).Return(resp, nil).Once() |
| 438 | |
| 439 | ctx := context.Background() |
| 440 | err := sendWithRetry(ctx, preparer, "http://example.com", mockClient, sleeper) |
| 441 | |
| 442 | gomega.Expect(err).To(gomega.HaveOccurred()) |
| 443 | gomega.Expect(err.Error()).To(gomega.ContainSubstring("rate limited by Discord")) |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | // TestIsTransientError tests the isTransientError function with table-driven tests. |
| 448 | func TestIsTransientError(t *testing.T) { |
| 449 | t.Parallel() |
| 450 | |
| 451 | tests := []struct { |
| 452 | name string |
| 453 | err error |
| 454 | expected bool |
| 455 | }{ |
| 456 | { |
| 457 | name: "context canceled should not be transient", |
| 458 | err: context.Canceled, |
| 459 | expected: false, |
| 460 | }, |
| 461 | { |
| 462 | name: "context deadline exceeded should be transient", |
| 463 | err: context.DeadlineExceeded, |
| 464 | expected: true, |
| 465 | }, |
| 466 | { |
| 467 | name: "timeout network error should be transient", |
| 468 | err: &mockTimeoutError{}, |
| 469 | expected: true, |
| 470 | }, |
| 471 | { |
| 472 | name: "temporary network error should be transient", |
| 473 | err: &mockTemporaryError{}, |
| 474 | expected: true, |
| 475 | }, |
| 476 | { |
| 477 | name: "connection refused should be transient", |
| 478 | err: errors.New("dial tcp 127.0.0.1:8080: connect: connection refused"), |
| 479 | expected: true, |
| 480 | }, |
| 481 | { |
| 482 | name: "connection reset should be transient", |
| 483 | err: errors.New("read tcp 127.0.0.1:8080: connection reset by peer"), |
| 484 | expected: true, |
| 485 | }, |
| 486 | { |
| 487 | name: "wrapped transient error should be transient", |
| 488 | err: &url.Error{ |
| 489 | Op: "Get", |
| 490 | URL: "http://example.com", |
| 491 | Err: context.DeadlineExceeded, |
| 492 | }, |
| 493 | expected: true, |
| 494 | }, |
| 495 | { |
| 496 | name: "generic error should not be transient", |
| 497 | err: errors.New("some other error"), |
| 498 | expected: false, |
| 499 | }, |
| 500 | { |
| 501 | name: "nil error should not be transient", |
| 502 | err: nil, |
| 503 | expected: false, |
| 504 | }, |
| 505 | } |
| 506 | |
| 507 | for _, tt := range tests { |
| 508 | t.Run(tt.name, func(t *testing.T) { |
| 509 | t.Parallel() |
| 510 | |
| 511 | result := isTransientError(tt.err) |
| 512 | assert.Equal(t, tt.expected, result) |
| 513 | }) |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | func (m *mockTemporaryError) Error() string { return "temporary error" } |
| 518 | func (m *mockTemporaryError) Temporary() bool { return true } |
| 519 | func (m *mockTemporaryError) Timeout() bool { return false } |
| 520 | |
| 521 | func (m *mockTimeoutError) Error() string { return "timeout error" } |
| 522 | func (m *mockTimeoutError) Temporary() bool { return false } |
| 523 | func (m *mockTimeoutError) Timeout() bool { return true } |
| 524 | |
| 525 | // TestExecuteWithTransportRetry tests the executeWithTransportRetry function. |
| 526 | func TestExecuteWithTransportRetry(t *testing.T) { |
| 527 | t.Parallel() |
| 528 | |
| 529 | tests := []struct { |
| 530 | name string |
| 531 | setupClient func(t *testing.T) HTTPClient |
| 532 | setupSleeper func(t *testing.T) *mocks.MockSleeper |
| 533 | expectedError bool |
| 534 | expectedCalls int |
| 535 | expectedSleeps []time.Duration |
| 536 | }{ |
| 537 | { |
| 538 | name: "successful request on first attempt", |
| 539 | setupClient: func(t *testing.T) HTTPClient { |
| 540 | t.Helper() |
| 541 | mockClient := mocks.NewMockHTTPClient(t) |
| 542 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 543 | StatusCode: http.StatusOK, |
| 544 | Body: io.NopCloser(strings.NewReader("")), |
| 545 | }, nil).Once() |
| 546 | |
| 547 | return mockClient |
| 548 | }, |
| 549 | setupSleeper: func(t *testing.T) *mocks.MockSleeper { |
| 550 | t.Helper() |
| 551 | |
| 552 | return mocks.NewMockSleeper(t) |
| 553 | }, |
| 554 | expectedError: false, |
| 555 | expectedCalls: 1, |
| 556 | expectedSleeps: nil, |
| 557 | }, |
| 558 | { |
| 559 | name: "transient error with retry success", |
| 560 | setupClient: func(t *testing.T) HTTPClient { |
| 561 | t.Helper() |
| 562 | mockClient := mocks.NewMockHTTPClient(t) |
| 563 | mockClient.On("Do", mock.Anything).Return(nil, context.DeadlineExceeded).Once() |
| 564 | mockClient.On("Do", mock.Anything).Return(&http.Response{ |
| 565 | StatusCode: http.StatusOK, |
| 566 | Body: io.NopCloser(strings.NewReader("")), |
| 567 | }, nil).Once() |
| 568 | |
| 569 | return mockClient |
| 570 | }, |
| 571 | setupSleeper: func(t *testing.T) *mocks.MockSleeper { |
| 572 | t.Helper() |
| 573 | sleeper := mocks.NewMockSleeper(t) |
| 574 | sleeper.On("Sleep", time.Second).Return().Once() |
| 575 | |
| 576 | return sleeper |
| 577 | }, |
| 578 | expectedError: false, |
| 579 | expectedCalls: 2, |
| 580 | expectedSleeps: []time.Duration{time.Second}, |
| 581 | }, |
| 582 | { |
| 583 | name: "persistent error after max retries", |
| 584 | setupClient: func(t *testing.T) HTTPClient { |
| 585 | t.Helper() |
| 586 | mockClient := mocks.NewMockHTTPClient(t) |
| 587 | // Expect 4 calls (maxTransportRetries + 1) |
| 588 | mockClient.On("Do", mock.Anything).Return(nil, context.DeadlineExceeded).Times(4) |
| 589 | |
| 590 | return mockClient |
| 591 | }, |
| 592 | setupSleeper: func(t *testing.T) *mocks.MockSleeper { |
| 593 | t.Helper() |
| 594 | sleeper := mocks.NewMockSleeper(t) |
| 595 | sleeper.On("Sleep", time.Second).Return().Once() |
| 596 | sleeper.On("Sleep", 2*time.Second).Return().Once() |
| 597 | sleeper.On("Sleep", 4*time.Second).Return().Once() |
| 598 | |
| 599 | return sleeper |
| 600 | }, |
| 601 | expectedError: true, |
| 602 | // Expected calls: maxTransportRetries + 1 = 4 |
| 603 | expectedCalls: 4, |
| 604 | expectedSleeps: []time.Duration{time.Second, 2 * time.Second, 4 * time.Second}, |
| 605 | }, |
| 606 | { |
| 607 | name: "context canceled during retry", |
| 608 | setupClient: func(t *testing.T) HTTPClient { |
| 609 | t.Helper() |
| 610 | mockClient := mocks.NewMockHTTPClient(t) |
| 611 | mockClient.On("Do", mock.Anything).Return(nil, context.DeadlineExceeded).Once() |
| 612 | |
| 613 | return mockClient |
| 614 | }, |
| 615 | setupSleeper: func(t *testing.T) *mocks.MockSleeper { |
| 616 | t.Helper() |
| 617 | |
| 618 | return mocks.NewMockSleeper(t) |
| 619 | }, |
| 620 | expectedError: true, |
| 621 | expectedCalls: 1, |
| 622 | expectedSleeps: nil, |
| 623 | }, |
| 624 | } |
| 625 | |
| 626 | for _, tt := range tests { |
| 627 | t.Run(tt.name, func(t *testing.T) { |
| 628 | t.Parallel() |
| 629 | |
| 630 | client := tt.setupClient(t) |
| 631 | sleeper := tt.setupSleeper(t) |
| 632 | ctx := context.Background() |
| 633 | |
| 634 | if tt.name == "context canceled during retry" { |
| 635 | var cancel context.CancelFunc |
| 636 | |
| 637 | ctx, cancel = context.WithCancel(ctx) |
| 638 | cancel() |
| 639 | } |
| 640 | |
| 641 | req, _ := http.NewRequestWithContext( |
| 642 | ctx, |
| 643 | http.MethodPost, |
| 644 | "http://example.com", |
| 645 | strings.NewReader("test"), |
| 646 | ) |
| 647 | bodyBytes := []byte("test") |
| 648 | |
| 649 | _, err := executeWithTransportRetry(ctx, client, bodyBytes, req, sleeper) |
| 650 | |
| 651 | if tt.expectedError { |
| 652 | require.Error(t, err) |
| 653 | } else { |
| 654 | require.NoError(t, err) |
| 655 | } |
| 656 | }) |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | // TestHandleServerError tests the handleServerError function. |
| 661 | func TestHandleServerError(t *testing.T) { |
| 662 | t.Parallel() |
| 663 | |
| 664 | tests := []struct { |
| 665 | name string |
| 666 | statusCode int |
| 667 | attempt int |
| 668 | expectedError bool |
| 669 | setupSleeper func(t *testing.T) Sleeper |
| 670 | }{ |
| 671 | { |
| 672 | name: "status code below 500 should not wait", |
| 673 | statusCode: 404, |
| 674 | attempt: 0, |
| 675 | expectedError: false, |
| 676 | setupSleeper: func(t *testing.T) Sleeper { |
| 677 | t.Helper() |
| 678 | |
| 679 | return mocks.NewMockSleeper(t) |
| 680 | }, |
| 681 | }, |
| 682 | { |
| 683 | name: "500 status code should wait", |
| 684 | statusCode: 500, |
| 685 | attempt: 0, |
| 686 | expectedError: false, |
| 687 | setupSleeper: func(t *testing.T) Sleeper { |
| 688 | t.Helper() |
| 689 | sleeper := mocks.NewMockSleeper(t) |
| 690 | sleeper.On("Sleep", time.Second).Return().Once() |
| 691 | |
| 692 | return sleeper |
| 693 | }, |
| 694 | }, |
| 695 | { |
| 696 | name: "max retries exceeded should return error", |
| 697 | statusCode: 500, |
| 698 | attempt: maxRetries, |
| 699 | expectedError: true, |
| 700 | setupSleeper: func(t *testing.T) Sleeper { |
| 701 | t.Helper() |
| 702 | |
| 703 | return mocks.NewMockSleeper(t) |
| 704 | }, |
| 705 | }, |
| 706 | { |
| 707 | name: "exponential backoff calculation", |
| 708 | statusCode: 502, |
| 709 | attempt: 2, |
| 710 | expectedError: false, |
| 711 | setupSleeper: func(t *testing.T) Sleeper { |
| 712 | t.Helper() |
| 713 | sleeper := mocks.NewMockSleeper(t) |
| 714 | sleeper.On("Sleep", 4*time.Second).Return().Once() |
| 715 | |
| 716 | return sleeper |
| 717 | }, |
| 718 | }, |
| 719 | { |
| 720 | name: "exponential backoff calculation for higher attempt", |
| 721 | statusCode: 503, |
| 722 | attempt: 4, |
| 723 | expectedError: false, |
| 724 | setupSleeper: func(t *testing.T) Sleeper { |
| 725 | t.Helper() |
| 726 | sleeper := mocks.NewMockSleeper(t) |
| 727 | sleeper.On("Sleep", 16*time.Second).Return().Once() |
| 728 | |
| 729 | return sleeper |
| 730 | }, |
| 731 | }, |
| 732 | } |
| 733 | |
| 734 | for _, tt := range tests { |
| 735 | t.Run(tt.name, func(t *testing.T) { |
| 736 | t.Parallel() |
| 737 | |
| 738 | resp := &http.Response{ |
| 739 | StatusCode: tt.statusCode, |
| 740 | Body: io.NopCloser(strings.NewReader("")), |
| 741 | } |
| 742 | sleeper := tt.setupSleeper(t) |
| 743 | startTime := time.Now() |
| 744 | |
| 745 | err := handleServerError(context.Background(), resp, tt.attempt, startTime, sleeper) |
| 746 | |
| 747 | if tt.expectedError { |
| 748 | require.Error(t, err) |
| 749 | assert.Equal(t, ErrMaxRetries, err) |
| 750 | } else { |
| 751 | require.NoError(t, err) |
| 752 | } |
| 753 | }) |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | // TestWaitWithTimeout tests the waitWithTimeout function. |
| 758 | func TestWaitWithTimeout(t *testing.T) { |
| 759 | t.Parallel() |
| 760 | |
| 761 | tests := []struct { |
| 762 | name string |
| 763 | wait time.Duration |
| 764 | startTime time.Time |
| 765 | cancelContext bool |
| 766 | expectedError bool |
| 767 | setupSleeper func(t *testing.T) Sleeper |
| 768 | }{ |
| 769 | { |
| 770 | name: "normal wait should succeed", |
| 771 | wait: time.Second, |
| 772 | startTime: time.Now(), |
| 773 | cancelContext: false, |
| 774 | expectedError: false, |
| 775 | setupSleeper: func(t *testing.T) Sleeper { |
| 776 | t.Helper() |
| 777 | sleeper := mocks.NewMockSleeper(t) |
| 778 | sleeper.On("Sleep", time.Second).Return().Once() |
| 779 | |
| 780 | return sleeper |
| 781 | }, |
| 782 | }, |
| 783 | { |
| 784 | name: "wait exceeding timeout should fail", |
| 785 | wait: 6 * time.Minute, // Exceeds maxRetryTimeout |
| 786 | startTime: time.Now(), |
| 787 | cancelContext: false, |
| 788 | expectedError: true, |
| 789 | setupSleeper: func(t *testing.T) Sleeper { |
| 790 | t.Helper() |
| 791 | |
| 792 | return mocks.NewMockSleeper(t) |
| 793 | }, |
| 794 | }, |
| 795 | { |
| 796 | name: "context canceled should fail", |
| 797 | wait: time.Second, |
| 798 | startTime: time.Now(), |
| 799 | cancelContext: true, |
| 800 | expectedError: true, |
| 801 | setupSleeper: func(t *testing.T) Sleeper { |
| 802 | t.Helper() |
| 803 | |
| 804 | return mocks.NewMockSleeper(t) |
| 805 | }, |
| 806 | }, |
| 807 | { |
| 808 | name: "zero wait should succeed", |
| 809 | wait: 0, |
| 810 | startTime: time.Now(), |
| 811 | cancelContext: false, |
| 812 | expectedError: false, |
| 813 | setupSleeper: func(t *testing.T) Sleeper { |
| 814 | t.Helper() |
| 815 | sleeper := mocks.NewMockSleeper(t) |
| 816 | sleeper.On("Sleep", time.Duration(0)).Return().Once() |
| 817 | |
| 818 | return sleeper |
| 819 | }, |
| 820 | }, |
| 821 | } |
| 822 | |
| 823 | for _, tt := range tests { |
| 824 | t.Run(tt.name, func(t *testing.T) { |
| 825 | t.Parallel() |
| 826 | |
| 827 | sleeper := tt.setupSleeper(t) |
| 828 | ctx := context.Background() |
| 829 | |
| 830 | if tt.cancelContext { |
| 831 | var cancel context.CancelFunc |
| 832 | |
| 833 | ctx, cancel = context.WithCancel(ctx) |
| 834 | cancel() |
| 835 | } |
| 836 | |
| 837 | err := waitWithTimeout(ctx, tt.wait, tt.startTime, sleeper) |
| 838 | |
| 839 | if tt.expectedError { |
| 840 | require.Error(t, err) |
| 841 | } else { |
| 842 | require.NoError(t, err) |
| 843 | } |
| 844 | }) |
| 845 | } |
| 846 | } |