forked from mtusi2026/mtusi2026lab4
51 lines
1.5 KiB
Go
51 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
handler := InstanceID("api-01", mux)
|
|
|
|
for _, test := range []struct {
|
|
path string
|
|
wantStatus int
|
|
}{
|
|
{path: "/ok", wantStatus: http.StatusNoContent},
|
|
{path: "/missing", wantStatus: http.StatusNotFound},
|
|
} {
|
|
recorder := httptest.NewRecorder()
|
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
|
|
|
if recorder.Code != test.wantStatus {
|
|
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
|
|
}
|
|
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
|
|
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
|
|
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
|
panic("test panic")
|
|
})
|
|
handler := InstanceID("api-panic", Recovery(panicking))
|
|
recorder := httptest.NewRecorder()
|
|
|
|
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
|
|
|
if recorder.Code != http.StatusInternalServerError {
|
|
t.Fatalf("got status %d, want 500", recorder.Code)
|
|
}
|
|
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
|
|
t.Fatalf("got instance ID %q, want api-panic", got)
|
|
}
|
|
}
|