github-bot-sdk 0.2.1

A comprehensive Rust SDK for GitHub App integration with authentication, webhooks, and API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Tests for retry policy and rate limiting.

use super::*;

mod rate_limit_info {
    use super::*;
    use chrono::{DateTime, Duration as ChronoDuration, Utc};

    /// Verify RateLimitInfo::from_headers with valid headers.
    #[test]
    fn test_from_headers_valid() {
        let info = RateLimitInfo::from_headers(Some("5000"), Some("4999"), Some("1640000000"));

        assert!(info.is_some());
        let info = info.unwrap();
        assert_eq!(info.limit, 5000);
        assert_eq!(info.remaining, 4999);
        assert_eq!(
            info.reset_at,
            DateTime::from_timestamp(1640000000, 0).unwrap()
        );
        assert!(!info.is_limited);
    }

    /// Verify from_headers returns None when limit header missing.
    #[test]
    fn test_from_headers_missing() {
        let info = RateLimitInfo::from_headers(None, Some("4999"), Some("1640000000"));
        assert!(info.is_none());

        let info = RateLimitInfo::from_headers(Some("5000"), None, Some("1640000000"));
        assert!(info.is_none());

        let info = RateLimitInfo::from_headers(Some("5000"), Some("4999"), None);
        assert!(info.is_none());
    }

    /// Verify from_headers returns None when headers have invalid values.
    #[test]
    fn test_from_headers_invalid() {
        // Invalid limit
        let info = RateLimitInfo::from_headers(Some("invalid"), Some("4999"), Some("1640000000"));
        assert!(info.is_none());

        // Invalid remaining
        let info = RateLimitInfo::from_headers(Some("5000"), Some("invalid"), Some("1640000000"));
        assert!(info.is_none());

        // Invalid reset timestamp
        let info = RateLimitInfo::from_headers(Some("5000"), Some("4999"), Some("invalid"));
        assert!(info.is_none());
    }

    /// Verify is_limited is true when remaining=0.
    #[test]
    fn test_is_limited() {
        let info = RateLimitInfo::from_headers(Some("5000"), Some("0"), Some("1640000000"));

        assert!(info.is_some());
        let info = info.unwrap();
        assert_eq!(info.remaining, 0);
        assert!(info.is_limited);
    }

    /// Verify is_limited is false when remaining>0.
    #[test]
    fn test_is_not_limited() {
        let info = RateLimitInfo::from_headers(Some("5000"), Some("100"), Some("1640000000"));

        assert!(info.is_some());
        let info = info.unwrap();
        assert_eq!(info.remaining, 100);
        assert!(!info.is_limited);
    }

    /// Verify is_near_limit when below threshold.
    #[test]
    fn test_is_near_limit_true() {
        let info = RateLimitInfo::from_headers(Some("5000"), Some("100"), Some("1640000000"))
            .expect("Valid headers");

        // 100/5000 = 2%, which is below 10% threshold
        assert!(info.is_near_limit(0.10));

        // Also test with 5% threshold
        assert!(info.is_near_limit(0.05));
    }

    /// Verify is_near_limit when above threshold.
    #[test]
    fn test_is_near_limit_false() {
        let info = RateLimitInfo::from_headers(Some("5000"), Some("3000"), Some("1640000000"))
            .expect("Valid headers");

        // 3000/5000 = 60%, which is above 10% threshold
        assert!(!info.is_near_limit(0.10));
    }

    /// Verify time_until_reset when reset is in future.
    #[test]
    fn test_time_until_reset_future() {
        let future_timestamp = (Utc::now() + ChronoDuration::try_hours(1).unwrap()).timestamp();
        let info = RateLimitInfo::from_headers(
            Some("5000"),
            Some("100"),
            Some(&future_timestamp.to_string()),
        )
        .expect("Valid headers");

        let duration = info.time_until_reset();
        // Should be approximately 1 hour (allow some tolerance for test execution time)
        assert!(duration.as_secs() >= 3590);
        assert!(duration.as_secs() <= 3610);
    }

    /// Verify time_until_reset returns 0 when reset is in past.
    #[test]
    fn test_time_until_reset_past() {
        // Use a timestamp from 2021
        let info = RateLimitInfo::from_headers(Some("5000"), Some("100"), Some("1640000000"))
            .expect("Valid headers");

        let duration = info.time_until_reset();
        assert_eq!(duration.as_secs(), 0);
    }
}

mod retry_policy {
    use super::*;

    /// Verify that RetryPolicy::default() has expected values.
    ///
    /// Default policy should have 3 max retries, 100ms initial delay,
    /// 60s max delay, 2.0 multiplier, and jitter enabled.
    #[test]
    fn test_default() {
        let policy = RetryPolicy::default();

        assert_eq!(policy.max_retries, 3);
        assert_eq!(policy.initial_delay, Duration::from_millis(100));
        assert_eq!(policy.max_delay, Duration::from_secs(60));
        assert_eq!(policy.backoff_multiplier, 2.0);
        assert!(policy.use_jitter);
    }

    /// Verify that RetryPolicy::new creates a policy with custom values.
    #[test]
    fn test_new() {
        let policy = RetryPolicy::new(5, Duration::from_millis(500), Duration::from_secs(30));

        assert_eq!(policy.max_retries, 5);
        assert_eq!(policy.initial_delay, Duration::from_millis(500));
        assert_eq!(policy.max_delay, Duration::from_secs(30));
        assert_eq!(policy.backoff_multiplier, 2.0);
        assert!(policy.use_jitter); // Default is enabled
    }

    /// Verify that with_jitter() enables jitter.
    #[test]
    fn test_with_jitter() {
        let policy = RetryPolicy::default().with_jitter();
        assert!(policy.use_jitter);
    }

    /// Verify that without_jitter() disables jitter.
    #[test]
    fn test_without_jitter() {
        let policy = RetryPolicy::default().without_jitter();
        assert!(!policy.use_jitter);
    }

    /// Verify that attempt 0 returns zero delay.
    ///
    /// The first request (attempt 0) should proceed immediately.
    #[test]
    fn test_calculate_delay_attempt_zero() {
        let policy = RetryPolicy::default();
        let delay = policy.calculate_delay(0);
        assert_eq!(delay, Duration::from_secs(0));
    }

    /// Verify that delays grow exponentially without jitter.
    ///
    /// With 100ms initial delay and 2.0 multiplier:
    /// - Attempt 1: 100ms
    /// - Attempt 2: 200ms
    /// - Attempt 3: 400ms
    /// - Attempt 4: 800ms
    #[test]
    fn test_calculate_delay_exponential_backoff() {
        let policy = RetryPolicy::default().without_jitter();

        assert_eq!(policy.calculate_delay(1), Duration::from_millis(100));
        assert_eq!(policy.calculate_delay(2), Duration::from_millis(200));
        assert_eq!(policy.calculate_delay(3), Duration::from_millis(400));
        assert_eq!(policy.calculate_delay(4), Duration::from_millis(800));
    }

    /// Verify that delay is capped at max_delay.
    ///
    /// Even with exponential growth, delays should never exceed max_delay.
    #[test]
    fn test_calculate_delay_max_cap() {
        let policy = RetryPolicy {
            max_retries: 100,
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(5),
            backoff_multiplier: 2.0,
            use_jitter: false,
        };

        // Attempt 20 would be 100ms * 2^19 = ~52 seconds
        // Should be capped at 5 seconds
        let delay = policy.calculate_delay(20);
        assert_eq!(delay, Duration::from_secs(5));
    }

    /// Verify that jitter adds randomization within ±25%.
    ///
    /// With jitter enabled, delays should vary but stay within bounds.
    /// We test by running multiple calculations and verifying the range.
    #[test]
    fn test_calculate_delay_with_jitter() {
        let policy = RetryPolicy::default().with_jitter();

        // For attempt 1, base delay is 100ms
        // With ±25% jitter, range is 75-125ms
        let mut delays = Vec::new();
        for _ in 0..100 {
            let delay = policy.calculate_delay(1);
            delays.push(delay.as_millis());
        }

        // All delays should be within the jitter range
        for delay_ms in &delays {
            assert!(*delay_ms >= 75, "Delay {}ms below minimum 75ms", delay_ms);
            assert!(*delay_ms <= 125, "Delay {}ms above maximum 125ms", delay_ms);
        }

        // With 100 samples, we should see variation (not all the same)
        let min = *delays.iter().min().unwrap();
        let max = *delays.iter().max().unwrap();
        assert!(max > min, "Jitter should produce variation in delays");
    }

    /// Verify that delay is deterministic when use_jitter=false.
    ///
    /// Without jitter, the same attempt should always produce the same delay.
    #[test]
    fn test_calculate_delay_without_jitter() {
        let policy = RetryPolicy::default().without_jitter();

        let delay1 = policy.calculate_delay(1);
        let delay2 = policy.calculate_delay(1);
        let delay3 = policy.calculate_delay(1);

        assert_eq!(delay1, delay2);
        assert_eq!(delay2, delay3);
        assert_eq!(delay1, Duration::from_millis(100));
    }

    /// Verify that jitter stays within bounds for large delays.
    ///
    /// Even for delays near max_delay, jitter should respect bounds.
    #[test]
    fn test_calculate_delay_jitter_respects_bounds() {
        let policy = RetryPolicy {
            max_retries: 10,
            initial_delay: Duration::from_millis(5000),
            max_delay: Duration::from_secs(10),
            backoff_multiplier: 2.0,
            use_jitter: true,
        };

        // This should be capped at 10 seconds, then jitter applied
        // Jitter of ±25% means 7.5-12.5 seconds
        // But max_delay is 10s, so actual range is 7.5-10s
        let mut delays = Vec::new();
        for _ in 0..50 {
            let delay = policy.calculate_delay(5);
            delays.push(delay.as_millis());
        }

        for delay_ms in &delays {
            // With jitter on 10s max, minimum is 7.5s
            assert!(*delay_ms >= 7500, "Delay {}ms below minimum", delay_ms);
            // Jitter can push above max_delay
            assert!(*delay_ms <= 12500, "Delay {}ms above maximum", delay_ms);
        }
    }

    /// Verify that should_retry returns true when attempts < max.
    #[test]
    fn test_should_retry_true() {
        let policy = RetryPolicy::default(); // max_retries = 3

        assert!(policy.should_retry(0));
        assert!(policy.should_retry(1));
        assert!(policy.should_retry(2));
    }

    /// Verify that should_retry returns false when attempts >= max.
    #[test]
    fn test_should_retry_false() {
        let policy = RetryPolicy::default(); // max_retries = 3

        assert!(!policy.should_retry(3));
        assert!(!policy.should_retry(4));
        assert!(!policy.should_retry(100));
    }

    /// Verify that builder pattern works correctly.
    #[test]
    fn test_builder_pattern() {
        let policy = RetryPolicy::new(5, Duration::from_millis(200), Duration::from_secs(30))
            .without_jitter();

        assert_eq!(policy.max_retries, 5);
        assert_eq!(policy.initial_delay, Duration::from_millis(200));
        assert_eq!(policy.max_delay, Duration::from_secs(30));
        assert!(!policy.use_jitter);

        // Chaining should work
        let policy2 = policy.clone().with_jitter();
        assert!(policy2.use_jitter);
    }
}

mod serialization {
    use super::*;

    /// Verify RateLimitInfo can be serialized.
    ///
    /// Tests that RateLimitInfo serializes to JSON with all fields.
    #[test]
    fn test_rate_limit_info_serialize() {
        let reset_time = DateTime::parse_from_rfc3339("2024-01-01T12:00:00Z")
            .unwrap()
            .with_timezone(&Utc);

        let info = RateLimitInfo {
            limit: 5000,
            remaining: 4999,
            reset_at: reset_time,
            is_limited: false,
        };

        let json = serde_json::to_value(&info).unwrap();

        assert_eq!(json["limit"], 5000);
        assert_eq!(json["remaining"], 4999);
        assert_eq!(json["is_limited"], false);
        assert!(json.get("reset_at").is_some());
    }

    /// Verify RateLimitInfo can be deserialized.
    ///
    /// Tests that RateLimitInfo correctly deserializes from JSON.
    #[test]
    fn test_rate_limit_info_deserialize() {
        let json = r#"{
            "limit": 5000,
            "remaining": 4999,
            "reset_at": "2024-01-01T12:00:00Z",
            "is_limited": false
        }"#;

        let info: RateLimitInfo = serde_json::from_str(json).unwrap();

        assert_eq!(info.limit, 5000);
        assert_eq!(info.remaining, 4999);
        assert!(!info.is_limited);
        assert_eq!(
            info.reset_at,
            DateTime::parse_from_rfc3339("2024-01-01T12:00:00Z")
                .unwrap()
                .with_timezone(&Utc)
        );
    }

    /// Verify RetryPolicy can be serialized.
    ///
    /// Tests that RetryPolicy serializes to JSON with all fields,
    /// including Duration types.
    #[test]
    fn test_retry_policy_serialize() {
        let policy = RetryPolicy {
            max_retries: 5,
            initial_delay: Duration::from_secs(2),
            max_delay: Duration::from_secs(60),
            backoff_multiplier: 2.0,
            use_jitter: true,
        };

        let json = serde_json::to_value(&policy).unwrap();

        assert_eq!(json["max_retries"], 5);
        assert_eq!(json["backoff_multiplier"], 2.0);
        assert_eq!(json["use_jitter"], true);
        // Duration serializes as an object with secs and nanos
        assert!(json.get("initial_delay").is_some());
        assert!(json.get("max_delay").is_some());
    }

    /// Verify RetryPolicy can be deserialized.
    ///
    /// Tests that RetryPolicy correctly deserializes from JSON,
    /// including Duration types.
    #[test]
    fn test_retry_policy_deserialize() {
        let json = r#"{
            "max_retries": 5,
            "initial_delay": {"secs": 2, "nanos": 0},
            "max_delay": {"secs": 60, "nanos": 0},
            "backoff_multiplier": 2.0,
            "use_jitter": true
        }"#;

        let policy: RetryPolicy = serde_json::from_str(json).unwrap();

        assert_eq!(policy.max_retries, 5);
        assert_eq!(policy.initial_delay, Duration::from_secs(2));
        assert_eq!(policy.max_delay, Duration::from_secs(60));
        assert_eq!(policy.backoff_multiplier, 2.0);
        assert!(policy.use_jitter);
    }
}

mod retry_after_parsing {
    use super::*;

    /// Verify that parse_retry_after correctly parses delta-seconds format.
    ///
    /// The Retry-After header often uses simple integer seconds.
    #[test]
    fn test_parse_retry_after_delta_seconds() {
        assert_eq!(parse_retry_after("60"), Some(Duration::from_secs(60)));
        assert_eq!(parse_retry_after("120"), Some(Duration::from_secs(120)));
        assert_eq!(parse_retry_after("0"), Some(Duration::from_secs(0)));
    }

    /// Verify that parse_retry_after handles HTTP-date format.
    ///
    /// GitHub may use RFC 2822 date format in Retry-After headers.
    #[test]
    fn test_parse_retry_after_http_date() {
        // Create a future date (60 seconds from now)
        let future = Utc::now() + chrono::Duration::seconds(60);
        let http_date = future.to_rfc2822();

        let delay = parse_retry_after(&http_date);
        assert!(delay.is_some());

        let delay_secs = delay.unwrap().as_secs();
        // Should be approximately 60 seconds (allow 1 second variance for test execution)
        assert!((59..=61).contains(&delay_secs), "Delay was {}s", delay_secs);
    }

    /// Verify that parse_retry_after returns None for invalid formats.
    #[test]
    fn test_parse_retry_after_invalid() {
        assert_eq!(parse_retry_after("invalid"), None);
        assert_eq!(parse_retry_after("not a number"), None);
        assert_eq!(parse_retry_after(""), None);
        assert_eq!(parse_retry_after("-10"), None); // Negative numbers invalid
    }

    /// Verify that parse_retry_after returns None for past HTTP dates.
    #[test]
    fn test_parse_retry_after_past_date() {
        // Create a past date
        let past = Utc::now() - chrono::Duration::seconds(60);
        let http_date = past.to_rfc2822();

        let delay = parse_retry_after(&http_date);
        assert_eq!(delay, None);
    }

    /// Verify that very large delay values are handled correctly.
    #[test]
    fn test_parse_retry_after_large_values() {
        // 1 hour in seconds
        assert_eq!(parse_retry_after("3600"), Some(Duration::from_secs(3600)));

        // 24 hours in seconds
        assert_eq!(parse_retry_after("86400"), Some(Duration::from_secs(86400)));
    }
}

mod rate_limit_delay_calculation {
    use super::*;

    /// Verify that Retry-After header takes priority over rate limit reset.
    #[test]
    fn test_calculate_rate_limit_delay_retry_after_priority() {
        let future_timestamp = (Utc::now().timestamp() + 300).to_string(); // 5 minutes

        let delay = calculate_rate_limit_delay(
            Some("60"),              // 1 minute
            Some(&future_timestamp), // 5 minutes
        );

        // Should use Retry-After (60s), not reset time (300s)
        assert_eq!(delay, Duration::from_secs(60));
    }

    /// Verify that rate limit reset is used when Retry-After is absent.
    #[test]
    fn test_calculate_rate_limit_delay_uses_reset() {
        let future_timestamp = (Utc::now().timestamp() + 120).to_string(); // 2 minutes

        let delay = calculate_rate_limit_delay(None, Some(&future_timestamp));

        // Should be approximately 120 seconds
        let delay_secs = delay.as_secs();
        assert!(
            (119..=121).contains(&delay_secs),
            "Delay was {}s",
            delay_secs
        );
    }

    /// Verify that default delay is used when no headers present.
    #[test]
    fn test_calculate_rate_limit_delay_default() {
        let delay = calculate_rate_limit_delay(None, None);
        assert_eq!(delay, Duration::from_secs(60));
    }

    /// Verify that invalid Retry-After falls back to reset time.
    #[test]
    fn test_calculate_rate_limit_delay_invalid_retry_after() {
        let future_timestamp = (Utc::now().timestamp() + 90).to_string();

        let delay = calculate_rate_limit_delay(Some("invalid"), Some(&future_timestamp));

        // Should fall back to reset time (90s)
        let delay_secs = delay.as_secs();
        assert!((89..=91).contains(&delay_secs), "Delay was {}s", delay_secs);
    }

    /// Verify that invalid reset time falls back to default.
    #[test]
    fn test_calculate_rate_limit_delay_invalid_reset() {
        let delay = calculate_rate_limit_delay(None, Some("not-a-timestamp"));

        // Should use default 60s
        assert_eq!(delay, Duration::from_secs(60));
    }

    /// Verify that past reset time falls back to default.
    #[test]
    fn test_calculate_rate_limit_delay_past_reset() {
        let past_timestamp = (Utc::now().timestamp() - 60).to_string(); // 1 minute ago

        let delay = calculate_rate_limit_delay(None, Some(&past_timestamp));

        // Should use default 60s since reset is in the past
        assert_eq!(delay, Duration::from_secs(60));
    }

    /// Verify handling of edge case: zero delay.
    #[test]
    fn test_calculate_rate_limit_delay_zero() {
        let delay = calculate_rate_limit_delay(Some("0"), None);

        assert_eq!(delay, Duration::from_secs(0));
    }

    /// Verify that Retry-After with HTTP date format works.
    #[test]
    fn test_calculate_rate_limit_delay_http_date() {
        let future = Utc::now() + chrono::Duration::seconds(180); // 3 minutes
        let http_date = future.to_rfc2822();

        let delay = calculate_rate_limit_delay(Some(&http_date), None);

        // Should be approximately 180 seconds
        let delay_secs = delay.as_secs();
        assert!(
            (179..=181).contains(&delay_secs),
            "Delay was {}s",
            delay_secs
        );
    }

    /// Verify handling of very large delays.
    #[test]
    fn test_calculate_rate_limit_delay_large_value() {
        // 1 hour
        let delay = calculate_rate_limit_delay(Some("3600"), None);

        assert_eq!(delay, Duration::from_secs(3600));
    }
}

mod secondary_rate_limit_detection {
    use super::*;

    /// Verify that detect_secondary_rate_limit returns true for 403 with "rate limit" message.
    #[test]
    fn test_detect_secondary_rate_limit_rate_limit_message() {
        let body = r#"{"message":"You have exceeded a secondary rate limit. Please wait a few minutes before you try again."}"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns true for 403 with "rate_limit" underscore format.
    #[test]
    fn test_detect_secondary_rate_limit_rate_limit_underscore() {
        let body = r#"{"message":"API rate_limit exceeded for user"}"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns true for 403 with "abuse" message.
    #[test]
    fn test_detect_secondary_rate_limit_abuse_message() {
        let body = r#"{"message":"You have triggered an abuse detection mechanism. Please retry your request later."}"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns true for 403 with "too many requests" message.
    #[test]
    fn test_detect_secondary_rate_limit_too_many_requests() {
        let body = r#"{"message":"Too many requests. Please slow down."}"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit is case insensitive.
    #[test]
    fn test_detect_secondary_rate_limit_case_insensitive() {
        let body = r#"{"message":"RATE LIMIT exceeded"}"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns false for 403 permission denied.
    #[test]
    fn test_detect_secondary_rate_limit_permission_denied() {
        let body = r#"{"message":"Resource not accessible by integration"}"#;

        assert!(!detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns false for 403 with unrelated message.
    #[test]
    fn test_detect_secondary_rate_limit_unrelated_403() {
        let body = r#"{"message":"This repository has been archived"}"#;

        assert!(!detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit returns false for non-403 status codes.
    #[test]
    fn test_detect_secondary_rate_limit_not_403() {
        let body = r#"{"message":"You have exceeded a secondary rate limit"}"#;

        // Should only detect on 403
        assert!(!detect_secondary_rate_limit(429, body));
        assert!(!detect_secondary_rate_limit(404, body));
        assert!(!detect_secondary_rate_limit(500, body));
        assert!(!detect_secondary_rate_limit(200, body));
    }

    /// Verify that detect_secondary_rate_limit returns false for empty body.
    #[test]
    fn test_detect_secondary_rate_limit_empty_body() {
        assert!(!detect_secondary_rate_limit(403, ""));
    }

    /// Verify that detect_secondary_rate_limit handles non-JSON body.
    #[test]
    fn test_detect_secondary_rate_limit_non_json_body() {
        let body = "Plain text error: rate limit exceeded";

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit matches substring in larger text.
    #[test]
    fn test_detect_secondary_rate_limit_substring_match() {
        let body = r#"
        {
            "message": "Request forbidden by administrative rules. The request has triggered GitHub's abuse detection mechanisms. Please wait before retrying.",
            "documentation_url": "https://docs.github.com"
        }
        "#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit with real GitHub secondary rate limit response.
    #[test]
    fn test_detect_secondary_rate_limit_real_github_response() {
        // Real GitHub secondary rate limit response format
        let body = r#"{
            "message": "You have exceeded a secondary rate limit. Please wait a few minutes before you try again.",
            "documentation_url": "https://docs.github.com/rest/overview/resources-in-the-rest-api#secondary-rate-limits"
        }"#;

        assert!(detect_secondary_rate_limit(403, body));
    }

    /// Verify that detect_secondary_rate_limit does not match partial words.
    #[test]
    fn test_detect_secondary_rate_limit_no_partial_match() {
        // "prelimit" should not match "rate limit"
        let body = r#"{"message":"Preliminary check failed"}"#;

        assert!(!detect_secondary_rate_limit(403, body));
    }
}