(t *testing.T)
| 15 | var testContent = []byte("Hello world!") |
| 16 | |
| 17 | func TestThrottleBacklog(t *testing.T) { |
| 18 | r := chi.NewRouter() |
| 19 | |
| 20 | r.Use(ThrottleBacklog(10, 50, time.Second*10)) |
| 21 | |
| 22 | r.Get("/", func(w http.ResponseWriter, r *http.Request) { |
| 23 | w.WriteHeader(http.StatusOK) |
| 24 | time.Sleep(time.Second * 1) // Expensive operation. |
| 25 | w.Write(testContent) |
| 26 | }) |
| 27 | |
| 28 | server := httptest.NewServer(r) |
| 29 | defer server.Close() |
| 30 | |
| 31 | client := http.Client{ |
| 32 | Timeout: time.Second * 5, // Maximum waiting time. |
| 33 | } |
| 34 | |
| 35 | var wg sync.WaitGroup |
| 36 | |
| 37 | // The throttler processes 10 consecutive requests, each one of those |
| 38 | // requests lasts 1s. The maximum number of requests this can possible serve |
| 39 | // before the clients time out (5s) is 40. |
| 40 | for i := range 40 { |
| 41 | wg.Add(1) |
| 42 | go func(i int) { |
| 43 | defer wg.Done() |
| 44 | |
| 45 | res, err := client.Get(server.URL) |
| 46 | assertNoError(t, err) |
| 47 | |
| 48 | assertEqual(t, http.StatusOK, res.StatusCode) |
| 49 | buf, err := io.ReadAll(res.Body) |
| 50 | assertNoError(t, err) |
| 51 | assertEqual(t, testContent, buf) |
| 52 | }(i) |
| 53 | } |
| 54 | |
| 55 | wg.Wait() |
| 56 | } |
| 57 | |
| 58 | func TestThrottleClientTimeout(t *testing.T) { |
| 59 | r := chi.NewRouter() |
nothing calls this directly
no test coverage detected