Skip to content

Commit ad338ba

Browse files
ahmet2mirjeevatkm
authored andcommitted
test(hedding): cover rate limit test (#1103)
Signed-off-by: Ahmet DEMIR <me@ahmet2mir.eu>
1 parent 12eb1c5 commit ad338ba

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

hedging_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"math/rand"
1212
"net/http"
1313
"net/http/httptest"
14+
"sync"
1415
"sync/atomic"
1516
"testing"
1617
"time"
@@ -550,3 +551,55 @@ func TestHedgingWrapAlreadyWrapped(t *testing.T) {
550551
t.Errorf("Expected hedging to still work, got %d request(s)", count)
551552
}
552553
}
554+
555+
func TestHedgingRateDelayBetweenRequests(t *testing.T) {
556+
requestTimes := make([]time.Time, 0, 3)
557+
var mu sync.Mutex
558+
559+
ts := createTestServer(func(w http.ResponseWriter, r *http.Request) {
560+
mu.Lock()
561+
requestTimes = append(requestTimes, time.Now())
562+
mu.Unlock()
563+
564+
// Slow response to ensure multiple hedged requests are sent
565+
time.Sleep(500 * time.Millisecond)
566+
w.WriteHeader(http.StatusOK)
567+
})
568+
defer ts.Close()
569+
570+
c := dcnl()
571+
// delay=10ms, upTo=3, maxPerSecond=5.0 (rateDelay = 200ms)
572+
// Expected timing: req1 at 0, req2 at ~10ms + 200ms = ~210ms, req3 at ~420ms
573+
c.EnableHedging(10*time.Millisecond, 3, 5.0)
574+
575+
_, err := c.R().Get(ts.URL + "/")
576+
assertError(t, err)
577+
578+
// Wait for all requests to be recorded
579+
time.Sleep(600 * time.Millisecond)
580+
581+
mu.Lock()
582+
times := make([]time.Time, len(requestTimes))
583+
copy(times, requestTimes)
584+
mu.Unlock()
585+
586+
if len(times) < 2 {
587+
t.Fatalf("Expected at least 2 hedged requests, got %d", len(times))
588+
}
589+
590+
// Verify rate delay was applied between requests
591+
// With maxPerSecond=5.0, rateDelay should be 200ms
592+
// The gap between requests should be at least rateDelay (200ms)
593+
expectedRateDelay := 200 * time.Millisecond
594+
tolerance := 50 * time.Millisecond
595+
596+
for i := 1; i < len(times); i++ {
597+
gap := times[i].Sub(times[i-1])
598+
// Gap should be >= (delay + rateDelay) - tolerance
599+
minExpectedGap := expectedRateDelay - tolerance
600+
if gap < minExpectedGap {
601+
t.Errorf("Gap between request %d and %d was %v, expected at least %v (rate delay should be ~%v)",
602+
i-1, i, gap, minExpectedGap, expectedRateDelay)
603+
}
604+
}
605+
}

0 commit comments

Comments
 (0)