forked from mtusi2026/mtusi2026lab7
103 lines
2.6 KiB
Go
103 lines
2.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// gatedServer пропускает запросы через gate в обработчик, который держит слот,
|
|
// пока тест не закроет release.
|
|
func gatedServer(t *testing.T, g *gate) (*httptest.Server, chan struct{}, chan struct{}) {
|
|
t.Helper()
|
|
entered, release := make(chan struct{}, 10), make(chan struct{})
|
|
reject := func(w http.ResponseWriter, _ *http.Request, err error) {
|
|
if !errors.Is(err, errOverloaded) {
|
|
t.Errorf("unexpected error %v", err)
|
|
}
|
|
w.Header().Set("Retry-After", "1")
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
}
|
|
h := g.middleware(reject)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
|
entered <- struct{}{}
|
|
<-release
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
srv := httptest.NewServer(h)
|
|
t.Cleanup(srv.Close)
|
|
return srv, entered, release
|
|
}
|
|
|
|
func get(t *testing.T, url string) int {
|
|
t.Helper()
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
t.Error(err)
|
|
return 0
|
|
}
|
|
resp.Body.Close()
|
|
return resp.StatusCode
|
|
}
|
|
|
|
func waitFor(t *testing.T, cond func() bool) {
|
|
t.Helper()
|
|
deadline := time.Now().Add(2 * time.Second)
|
|
for !cond() {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("condition not reached")
|
|
}
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
}
|
|
|
|
func TestGateRejectsBeyondQueueAndRecovers(t *testing.T) {
|
|
t.Parallel()
|
|
g := newGate(1, 1, time.Minute)
|
|
srv, entered, release := gatedServer(t, g)
|
|
|
|
statuses := make(chan int, 2)
|
|
var wg sync.WaitGroup
|
|
wg.Go(func() { statuses <- get(t, srv.URL) }) // занимает слот
|
|
<-entered
|
|
wg.Go(func() { statuses <- get(t, srv.URL) }) // ждёт в очереди
|
|
waitFor(t, func() bool { return g.waiting.Load() == 1 })
|
|
|
|
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
|
t.Fatalf("third request: %d, want 503", code)
|
|
}
|
|
close(release)
|
|
wg.Wait()
|
|
close(statuses)
|
|
for code := range statuses {
|
|
if code != http.StatusOK {
|
|
t.Fatalf("admitted request got %d", code)
|
|
}
|
|
}
|
|
if code := get(t, srv.URL); code != http.StatusOK {
|
|
t.Fatalf("after load: %d, want recovery to 200", code)
|
|
}
|
|
if g.stats().Rejected != 1 {
|
|
t.Fatalf("rejected %d", g.stats().Rejected)
|
|
}
|
|
}
|
|
|
|
func TestGateTimesOutQueuedRequest(t *testing.T) {
|
|
t.Parallel()
|
|
g := newGate(1, 10, 20*time.Millisecond)
|
|
srv, entered, release := gatedServer(t, g)
|
|
defer close(release)
|
|
|
|
go get(t, srv.URL)
|
|
<-entered
|
|
start := time.Now()
|
|
if code := get(t, srv.URL); code != http.StatusServiceUnavailable {
|
|
t.Fatalf("queued request: %d, want 503 after timeout", code)
|
|
}
|
|
if time.Since(start) > time.Second {
|
|
t.Fatal("queue timeout not applied")
|
|
}
|
|
}
|