MCPcopy
hub / github.com/go-chi/chi / TestThrottleMaximum

Function TestThrottleMaximum

middleware/throttle_test.go:144–200  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

142}
143
144func TestThrottleMaximum(t *testing.T) {
145 r := chi.NewRouter()
146
147 r.Use(ThrottleBacklog(10, 10, time.Second*5))
148
149 r.Get("/", func(w http.ResponseWriter, r *http.Request) {
150 w.WriteHeader(http.StatusOK)
151 time.Sleep(time.Second * 3) // Expensive operation.
152 w.Write(testContent)
153 })
154
155 server := httptest.NewServer(r)
156 defer server.Close()
157
158 client := http.Client{
159 Timeout: time.Second * 60, // Maximum waiting time.
160 }
161
162 var wg sync.WaitGroup
163
164 for i := range 20 {
165 wg.Add(1)
166 go func(i int) {
167 defer wg.Done()
168
169 res, err := client.Get(server.URL)
170 assertNoError(t, err)
171 assertEqual(t, http.StatusOK, res.StatusCode)
172
173 buf, err := io.ReadAll(res.Body)
174 assertNoError(t, err)
175 assertEqual(t, testContent, buf)
176 }(i)
177 }
178
179 // Wait less time than what the server takes to reply.
180 time.Sleep(time.Second * 2)
181
182 // At this point the server is still processing, all the following request
183 // will be beyond the server capacity.
184 for i := range 20 {
185 wg.Add(1)
186 go func(i int) {
187 defer wg.Done()
188
189 res, err := client.Get(server.URL)
190 assertNoError(t, err)
191
192 buf, err := io.ReadAll(res.Body)
193 assertNoError(t, err)
194 assertEqual(t, http.StatusTooManyRequests, res.StatusCode)
195 assertEqual(t, errCapacityExceeded, strings.TrimSpace(string(buf)))
196 }(i)
197 }
198
199 wg.Wait()
200}
201

Callers

nothing calls this directly

Calls 9

UseMethod · 0.95
GetMethod · 0.95
ThrottleBacklogFunction · 0.85
assertNoErrorFunction · 0.85
assertEqualFunction · 0.85
CloseMethod · 0.80
AddMethod · 0.80
WriteMethod · 0.65
WriteHeaderMethod · 0.45

Tested by

no test coverage detected