internal/middleware: repeat flaky quota test

Change-Id: Ieacb301f2853c0d68da2c63a0e14c80b853a8c5f
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/276296
Trust: Jonathan Amsterdam <jba@google.com>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
TryBot-Result: kokoro <noreply+kokoro@google.com>
Reviewed-by: Julie Qiu <julie@golang.org>
diff --git a/internal/middleware/quota_test.go b/internal/middleware/quota_test.go
index 88c9b55..a305df1 100644
--- a/internal/middleware/quota_test.go
+++ b/internal/middleware/quota_test.go
@@ -6,6 +6,7 @@
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
 	"testing"
@@ -182,6 +183,8 @@
 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,20 +196,35 @@
 	defer c.Close()
 
 	const qps = 5
-	check := func(n int, ip string, want bool) {
-		t.Helper()
-		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)
+
+	var failReason string
+	for n := 0; n < 10; n++ {
+		failReason = ""
+
+		check := func(n int, ip string, want bool) {
+			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 {
+					failReason = fmt.Sprintf("%d: got %t, want %t (reason=%q)", i, got, want, reason)
+					break
+				}
 			}
 		}
-	}
 
-	check(qps, "1.2.3.4", true) // first qps requests are allowed
-	check(1, "1.2.3.4", false)  // anything after that fails
-	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
+		check(qps, "1.2.3.4", true) // first qps requests are allowed
+		check(1, "1.2.3.4", false)  // anything after that fails
+		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)
 }