internal/middleware: repeat flaky quota test
Trust: Jonathan Amsterdam
Run-TryBot: Jonathan Amsterdam
TryBot-Result: kokoro
@@ -6,6 +6,7 @@ package middleware
import (
"context"
+ "fmt"
"net/http"
"net/http/httptest"
"testing"
@@ -182,6 +183,8 @@ func TestIPKey(t *testing.T) {
func boolptr(b bool) *bool { return &b }
func TestEnforceQuota(t *testing.T) {
+ // This test is inherently time-dependent, so inherently flaky, especially on CI.
+ // So run it a few times before giving up.
ctx := context.Background()
s, err := miniredis.Run()
if err != nil {
@@ -193,13 +196,21 @@ func TestEnforceQuota(t *testing.T) {
defer c.Close()
const qps = 5
+
+ var failReason string
+ for n := 0; n < 10; n++ {
+ failReason = ""
+
check := func(n int, ip string, want bool) {
- t.Helper()
+ if failReason != "" {
+ return
+ }
for i := 0; i < n; i++ {
blocked, reason := enforceQuota(ctx, c, qps, ip+",x", []byte{1, 2, 3, 4})
got := !blocked
if got != want {
- t.Errorf("%d: got %t, want %t (reason=%q)", i, got, want, reason)
+ failReason = fmt.Sprintf("%d: got %t, want %t (reason=%q)", i, got, want, reason)
+ break
}
}
}
@@ -209,4 +220,11 @@ func TestEnforceQuota(t *testing.T) {
check(1, "1.2.3.5", false) // low-order byte doesn't matter
check(qps, "1.2.4.1", true) // other IP is allowed
check(1, "1.2.4.9", false) // other IP blocked after qps requests
+
+ if failReason == "" {
+ return
+ }
+ time.Sleep(2 * time.Second)
+ }
+ t.Error(failReason)
}
