| 1 | package discord_test |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "testing" |
| 9 | "testing/synctest" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/stretchr/testify/assert" |
| 13 | "github.com/stretchr/testify/mock" |
| 14 | "github.com/stretchr/testify/require" |
| 15 | |
| 16 | "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord" |
| 17 | "github.com/nicholas-fedor/shoutrrr/pkg/types" |
| 18 | ) |
| 19 | |
| 20 | // noOpSleeper is a sleeper that does nothing, for testing. |
| 21 | type noOpSleeper struct{} |
| 22 | |
| 23 | type timeoutError struct{} |
| 24 | |
| 25 | var _ net.Error = timeoutError{} |
| 26 | |
| 27 | func (noOpSleeper) Sleep(_ time.Duration) {} |
| 28 | |
| 29 | func (timeoutError) Error() string { return "timeout" } |
| 30 | func (timeoutError) Temporary() bool { return false } |
| 31 | func (timeoutError) Timeout() bool { return true } |
| 32 | |
| 33 | // computeExpectedBatches computes the number of batches for a message based on Discord limits. |
| 34 | func computeExpectedBatches(message string, splitLines bool) int { |
| 35 | const ( |
| 36 | chunkSize = 2000 |
| 37 | totalChunkSize = 6000 |
| 38 | ) |
| 39 | |
| 40 | if splitLines { |
| 41 | // For split lines, each line is a separate item, but simplified for test |
| 42 | return 1 |
| 43 | } |
| 44 | |
| 45 | messageLen := len(message) |
| 46 | if messageLen == 0 { |
| 47 | return 0 |
| 48 | } |
| 49 | |
| 50 | chunks := (messageLen + chunkSize - 1) / chunkSize // Ceiling division |
| 51 | batches := (chunks + (totalChunkSize / chunkSize) - 1) / (totalChunkSize / chunkSize) // Ceiling division |
| 52 | |
| 53 | return batches |
| 54 | } |
| 55 | |
| 56 | func TestSendWithHTTPError(t *testing.T) { |
| 57 | t.Parallel() |
| 58 | synctest.Test(t, func(t *testing.T) { |
| 59 | tests := []struct { |
| 60 | name string |
| 61 | statusCode int |
| 62 | response string |
| 63 | expectedError string |
| 64 | expectedCalls int |
| 65 | expectedHeaders map[string]string |
| 66 | }{ |
| 67 | { |
| 68 | "bad request", |
| 69 | http.StatusBadRequest, |
| 70 | `{"message": "Invalid webhook"}`, |
| 71 | "failed to send discord notification", |
| 72 | 1, |
| 73 | nil, |
| 74 | }, |
| 75 | { |
| 76 | "unauthorized", |
| 77 | http.StatusUnauthorized, |
| 78 | `{"message": "Invalid token"}`, |
| 79 | "failed to send discord notification", |
| 80 | 1, |
| 81 | nil, |
| 82 | }, |
| 83 | { |
| 84 | "forbidden", |
| 85 | http.StatusForbidden, |
| 86 | `{"message": "Missing permissions"}`, |
| 87 | "failed to send discord notification", |
| 88 | 1, |
| 89 | nil, |
| 90 | }, |
| 91 | { |
| 92 | "not found", |
| 93 | http.StatusNotFound, |
| 94 | `{"message": "Webhook not found"}`, |
| 95 | "failed to send discord notification", |
| 96 | 1, |
| 97 | nil, |
| 98 | }, |
| 99 | { |
| 100 | "too many requests", |
| 101 | http.StatusTooManyRequests, |
| 102 | `{"message": "Rate limited"}`, |
| 103 | "failed to send discord notification", |
| 104 | 6, |
| 105 | map[string]string{"Retry-After": "0"}, |
| 106 | }, |
| 107 | { |
| 108 | "internal server error", |
| 109 | http.StatusInternalServerError, |
| 110 | `{"message": "Server error"}`, |
| 111 | "failed to send discord notification", |
| 112 | 6, |
| 113 | nil, |
| 114 | }, |
| 115 | } |
| 116 | |
| 117 | for _, tt := range tests { |
| 118 | t.Logf("Running test case: %s", tt.name) |
| 119 | |
| 120 | mockClient := &MockHTTPClient{} |
| 121 | service := createTestService( |
| 122 | t, |
| 123 | "discord://test-token@test-webhook", |
| 124 | mockClient, |
| 125 | ) |
| 126 | |
| 127 | // Use noOpSleeper to avoid real sleeps in tests |
| 128 | service.Sleeper = &noOpSleeper{} |
| 129 | |
| 130 | resp := createMockResponse(tt.statusCode, tt.response, tt.expectedHeaders) |
| 131 | |
| 132 | mockClient.On("Do", mock.Anything). |
| 133 | Return(resp, nil). |
| 134 | Times(tt.expectedCalls) |
| 135 | |
| 136 | err := service.Send("Test message", nil) |
| 137 | |
| 138 | require.Error(t, err) |
| 139 | assert.Contains(t, err.Error(), tt.expectedError) |
| 140 | mockClient.AssertExpectations(t) |
| 141 | } |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | func TestSendWithNetworkError(t *testing.T) { |
| 146 | t.Parallel() |
| 147 | synctest.Test(t, func(t *testing.T) { |
| 148 | mockClient := &MockHTTPClient{} |
| 149 | service := createTestService( |
| 150 | t, |
| 151 | "discord://test-token@test-webhook", |
| 152 | mockClient, |
| 153 | ) |
| 154 | |
| 155 | // Generic errors are not retried; only transient errors (net.Error with Timeout()/Temporary()) trigger retry logic. |
| 156 | networkError := errors.New("network connection failed") |
| 157 | mockClient.On("Do", mock.Anything).Return((*http.Response)(nil), networkError).Once() |
| 158 | |
| 159 | err := service.Send("Test message", nil) |
| 160 | |
| 161 | require.Error(t, err) |
| 162 | assert.Contains(t, err.Error(), "failed to send discord notification") |
| 163 | |
| 164 | mockClient.AssertExpectations(t) |
| 165 | }) |
| 166 | } |
| 167 | |
| 168 | func TestSendWithMalformedResponse(t *testing.T) { |
| 169 | t.Parallel() |
| 170 | synctest.Test(t, func(t *testing.T) { |
| 171 | mockClient := &MockHTTPClient{} |
| 172 | service := createTestService( |
| 173 | t, |
| 174 | "discord://test-token@test-webhook", |
| 175 | mockClient, |
| 176 | ) |
| 177 | |
| 178 | mockClient.On("Do", mock.Anything). |
| 179 | Return(createMockResponse(http.StatusOK, "invalid json"), nil). |
| 180 | Once() |
| 181 | |
| 182 | err := service.Send("Test message", nil) |
| 183 | |
| 184 | // Should still succeed since non-error status codes (2xx) are accepted |
| 185 | require.NoError(t, err) |
| 186 | |
| 187 | mockClient.AssertExpectations(t) |
| 188 | }) |
| 189 | } |
| 190 | |
| 191 | func TestSendWithRetryOnRateLimit(t *testing.T) { |
| 192 | t.Parallel() |
| 193 | synctest.Test(t, func(t *testing.T) { |
| 194 | mockClient := &MockHTTPClient{} |
| 195 | service := createTestService( |
| 196 | t, |
| 197 | "discord://test-token@test-webhook", |
| 198 | mockClient, |
| 199 | ) |
| 200 | |
| 201 | // Use noOpSleeper to avoid real sleeps in tests |
| 202 | service.Sleeper = &noOpSleeper{} |
| 203 | |
| 204 | // First call returns rate limit, second succeeds |
| 205 | mockClient.On("Do", mock.Anything). |
| 206 | Return(createMockResponse(http.StatusTooManyRequests, `{"retry_after": 1}`), nil). |
| 207 | Once() |
| 208 | mockClient.On("Do", mock.Anything). |
| 209 | Return(createMockResponse(http.StatusNoContent, ""), nil). |
| 210 | Once() |
| 211 | |
| 212 | err := service.Send("Test message", nil) |
| 213 | |
| 214 | require.NoError(t, err) |
| 215 | mockClient.AssertNumberOfCalls(t, "Do", 2) |
| 216 | |
| 217 | mockClient.AssertExpectations(t) |
| 218 | }) |
| 219 | } |
| 220 | |
| 221 | func TestSendWithNonExistentWebhook(t *testing.T) { |
| 222 | t.Parallel() |
| 223 | synctest.Test(t, func(t *testing.T) { |
| 224 | mockClient := &MockHTTPClient{} |
| 225 | invalidService := createTestService(t, "discord://token@invalid", mockClient) |
| 226 | |
| 227 | mockClient.On("Do", mock.Anything). |
| 228 | Return(createMockResponse(http.StatusNotFound, `{"message": "Unknown Webhook"}`), nil). |
| 229 | Once() |
| 230 | |
| 231 | err := invalidService.Send("Test message", nil) |
| 232 | |
| 233 | require.Error(t, err) |
| 234 | assert.Contains(t, err.Error(), "failed to send discord notification") |
| 235 | |
| 236 | mockClient.AssertExpectations(t) |
| 237 | }) |
| 238 | } |
| 239 | |
| 240 | func TestSendWithUnknownWebhook(t *testing.T) { |
| 241 | t.Parallel() |
| 242 | synctest.Test(t, func(t *testing.T) { |
| 243 | mockClient := &MockHTTPClient{} |
| 244 | emptyService := createTestService(t, "discord://token@empty", mockClient) |
| 245 | |
| 246 | mockClient.On("Do", mock.Anything). |
| 247 | Return(createMockResponse(http.StatusNotFound, `{"message": "Unknown Webhook"}`), nil). |
| 248 | Once() |
| 249 | |
| 250 | err := emptyService.Send("Test message", nil) |
| 251 | |
| 252 | require.Error(t, err) |
| 253 | assert.Contains(t, err.Error(), "failed to send discord notification") |
| 254 | |
| 255 | mockClient.AssertExpectations(t) |
| 256 | }) |
| 257 | } |
| 258 | |
| 259 | func TestSendWithInvalidScheme(t *testing.T) { |
| 260 | t.Parallel() |
| 261 | synctest.Test(t, func(t *testing.T) { |
| 262 | service := &discord.Service{} |
| 263 | |
| 264 | parsedURL, _ := url.Parse("http://discord.com/api/webhooks/test/test") |
| 265 | |
| 266 | err := service.Initialize(parsedURL, &mockLogger{}) |
| 267 | |
| 268 | require.Error(t, err) |
| 269 | assert.Contains(t, err.Error(), "setting config URL: illegal argument in config URL") |
| 270 | }) |
| 271 | } |
| 272 | |
| 273 | func TestSendWithInvalidHost(t *testing.T) { |
| 274 | t.Parallel() |
| 275 | synctest.Test(t, func(t *testing.T) { |
| 276 | service := &discord.Service{} |
| 277 | |
| 278 | parsedURL, _ := url.Parse("discord://[email protected]/webhook") |
| 279 | |
| 280 | err := service.Initialize(parsedURL, &mockLogger{}) |
| 281 | |
| 282 | require.Error(t, err) |
| 283 | assert.Contains(t, err.Error(), "setting config URL: illegal argument in config URL") |
| 284 | }) |
| 285 | } |
| 286 | |
| 287 | func TestSendWithInvalidPath(t *testing.T) { |
| 288 | t.Parallel() |
| 289 | synctest.Test(t, func(t *testing.T) { |
| 290 | service := &discord.Service{} |
| 291 | |
| 292 | parsedURL, _ := url.Parse("discord://token@webhook/invalid/path") |
| 293 | |
| 294 | err := service.Initialize(parsedURL, &mockLogger{}) |
| 295 | |
| 296 | require.Error(t, err) |
| 297 | assert.Contains(t, err.Error(), "setting config URL: illegal argument in config URL") |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | func TestSendItemsWithInvalidPayload(t *testing.T) { |
| 302 | t.Parallel() |
| 303 | synctest.Test(t, func(t *testing.T) { |
| 304 | mockClient := &MockHTTPClient{} |
| 305 | service := createTestService( |
| 306 | t, |
| 307 | "discord://test-token@test-webhook", |
| 308 | mockClient, |
| 309 | ) |
| 310 | |
| 311 | // Create an item with invalid UTF-8 that gets sent as invalid JSON |
| 312 | items := []types.MessageItem{ |
| 313 | { |
| 314 | Text: string([]byte{0xff, 0xfe, 0xfd}), // Invalid UTF-8 bytes |
| 315 | }, |
| 316 | } |
| 317 | |
| 318 | mockClient.On("Do", mock.Anything). |
| 319 | Return(createMockResponse(http.StatusBadRequest, `{"message": "Invalid JSON"}`), nil). |
| 320 | Once() |
| 321 | |
| 322 | err := service.SendItems(items, nil) |
| 323 | |
| 324 | // Should fail due to invalid JSON payload |
| 325 | require.Error(t, err) |
| 326 | assert.Contains(t, err.Error(), "unexpected response status code") |
| 327 | |
| 328 | mockClient.AssertExpectations(t) |
| 329 | }) |
| 330 | } |
| 331 | |
| 332 | func TestSendWithTimeout(t *testing.T) { |
| 333 | t.Parallel() |
| 334 | synctest.Test(t, func(t *testing.T) { |
| 335 | mockClient := &MockHTTPClient{} |
| 336 | service := createTestService( |
| 337 | t, |
| 338 | "discord://test-token@test-webhook", |
| 339 | mockClient, |
| 340 | ) |
| 341 | |
| 342 | // Use noOpSleeper to avoid real sleeps in tests |
| 343 | service.Sleeper = &noOpSleeper{} |
| 344 | |
| 345 | // Simulate a network timeout by returning a timeout error |
| 346 | // Timeout errors are transient and will be retried up to maxTransportRetries (3) times |
| 347 | mockClient.On("Do", mock.Anything). |
| 348 | Return(nil, timeoutError{}). |
| 349 | Times(4) // Initial attempt + 3 retries |
| 350 | |
| 351 | err := service.Send("Test message", nil) |
| 352 | |
| 353 | require.Error(t, err) |
| 354 | assert.Contains(t, err.Error(), "failed to send discord notification") |
| 355 | |
| 356 | mockClient.AssertExpectations(t) |
| 357 | }) |
| 358 | } |
| 359 | |
| 360 | func TestSendWithLargePayload(t *testing.T) { |
| 361 | t.Parallel() |
| 362 | synctest.Test(t, func(t *testing.T) { |
| 363 | mockClient := &MockHTTPClient{} |
| 364 | service := createTestService( |
| 365 | t, |
| 366 | "discord://test-token@test-webhook?splitLines=false", |
| 367 | mockClient, |
| 368 | ) |
| 369 | |
| 370 | // Create a very large message that might cause issues |
| 371 | largeMessage := make([]byte, 1000000) // 1MB |
| 372 | for i := range largeMessage { |
| 373 | largeMessage[i] = 'a' |
| 374 | } |
| 375 | |
| 376 | // Compute expected number of calls based on message splitting logic |
| 377 | expectedCalls := computeExpectedBatches(string(largeMessage), false) |
| 378 | |
| 379 | mockClient.On("Do", mock.Anything). |
| 380 | Return(createMockResponse(http.StatusNoContent, ""), nil). |
| 381 | Times(expectedCalls) |
| 382 | |
| 383 | err := service.Send(string(largeMessage), nil) |
| 384 | |
| 385 | require.NoError(t, err) |
| 386 | |
| 387 | mockClient.AssertExpectations(t) |
| 388 | }) |
| 389 | } |
| 390 | |
| 391 | func TestSendWithInvalidJSONMode(t *testing.T) { |
| 392 | t.Parallel() |
| 393 | synctest.Test(t, func(t *testing.T) { |
| 394 | mockClient := &MockHTTPClient{} |
| 395 | // Create service with JSON mode |
| 396 | service := createTestService(t, "discord://test-token@test-webhook?json=true", mockClient) |
| 397 | |
| 398 | // Send invalid JSON |
| 399 | mockClient.On("Do", mock.Anything). |
| 400 | Return(createMockResponse(http.StatusNoContent, ""), nil). |
| 401 | Once() |
| 402 | |
| 403 | err := service.Send(`{"invalid": json}`, nil) |
| 404 | |
| 405 | require.NoError(t, err) // Should succeed as it's passed through as raw content |
| 406 | |
| 407 | mockClient.AssertExpectations(t) |
| 408 | }) |
| 409 | } |
| 410 | |
| 411 | func TestSendWithFileUploadError(t *testing.T) { |
| 412 | t.Parallel() |
| 413 | synctest.Test(t, func(t *testing.T) { |
| 414 | mockClient := &MockHTTPClient{} |
| 415 | service := createTestService( |
| 416 | t, |
| 417 | "discord://test-token@test-webhook", |
| 418 | mockClient, |
| 419 | ) |
| 420 | |
| 421 | mockClient.On("Do", mock.Anything). |
| 422 | Return(createMockResponse(http.StatusBadRequest, `{"message": "File too large"}`), nil). |
| 423 | Once() |
| 424 | |
| 425 | items := []types.MessageItem{ |
| 426 | createTestMessageItemWithFile( |
| 427 | "Test", |
| 428 | "large.txt", |
| 429 | make([]byte, 1024), |
| 430 | ), // 1KB file |
| 431 | } |
| 432 | |
| 433 | err := service.SendItems(items, nil) |
| 434 | |
| 435 | require.Error(t, err) |
| 436 | assert.Contains(t, err.Error(), "unexpected response status code") |
| 437 | |
| 438 | mockClient.AssertExpectations(t) |
| 439 | }) |
| 440 | } |