package httphandlers import ( "net/http" "net/http/httptest" "strings" "testing" "fiskerinc.com/modules/testhelper" ) func checkPanic(w http.ResponseWriter, r *http.Request) { panic("Test panic") } func noPanic(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) } func TestPanicHandler(t *testing.T) { type test struct { name string httpHandler http.HandlerFunc status int body string } tests := []test{ {name: "Panic", httpHandler: checkPanic, status: http.StatusInternalServerError, body: `{"message":"PanicHandler Test panic","error":"Internal Server Error"}`}, {name: "No Panic", httpHandler: noPanic, status: http.StatusOK, body: "OK"}, } for _, i := range tests { request, err := http.NewRequest(http.MethodGet, "/", nil) if err != nil { t.Fatal(err) } response := httptest.NewRecorder() handler := http.HandlerFunc(PanicHandler(i.httpHandler)) handler.ServeHTTP(response, request) if response.Result().StatusCode != i.status { t.Errorf(testhelper.TestErrorTemplate, i.name, i.status, response.Result().Status) } if strings.TrimSpace(response.Body.String()) != i.body { t.Errorf(testhelper.TestErrorTemplate, i.name, i.body, response.Body) } } }