1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
15 type testHandler struct {
16 inHandler chan struct{}
17 okToProceed chan struct{}
20 func (h *testHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
21 h.inHandler <- struct{}{}
25 func newTestHandler(maxReqs int) *testHandler {
27 inHandler: make(chan struct{}),
28 okToProceed: make(chan struct{}),
32 func TestRequestLimiter1(t *testing.T) {
33 h := newTestHandler(10)
34 l := NewRequestLimiter(1, h, nil)
36 resps := make([]*httptest.ResponseRecorder, 10)
37 for i := 0; i < 10; i++ {
39 resps[i] = httptest.NewRecorder()
41 l.ServeHTTP(resps[i], &http.Request{})
45 done := make(chan struct{})
47 // Make sure one request has entered the handler
49 // Make sure all unsuccessful requests finish (but don't wait
50 // for the one that's still waiting for okToProceed)
53 // Wait for the last goroutine
55 h.okToProceed <- struct{}{}
61 case <-time.After(10 * time.Second):
62 t.Fatal("test timed out, probably deadlocked")
66 for i := 0; i < 10; i++ {
67 switch resps[i].Code {
73 t.Fatalf("Unexpected response code %d", resps[i].Code)
76 if n200 != 1 || n503 != 9 {
77 t.Fatalf("Got %d 200 responses, %d 503 responses (expected 1, 9)", n200, n503)
79 // Now that all 10 are finished, an 11th request should
83 h.okToProceed <- struct{}{}
85 resp := httptest.NewRecorder()
86 l.ServeHTTP(resp, &http.Request{})
88 t.Errorf("Got status %d on 11th request, want 200", resp.Code)
92 func TestRequestLimiter10(t *testing.T) {
93 h := newTestHandler(10)
94 l := NewRequestLimiter(10, h, nil)
96 for i := 0; i < 10; i++ {
99 l.ServeHTTP(httptest.NewRecorder(), &http.Request{})
102 // Make sure the handler starts before we initiate the
103 // next request, but don't let it finish yet.
106 for i := 0; i < 10; i++ {
107 h.okToProceed <- struct{}{}