github.com/companieshouse/insolvency-api@v0.0.0-20231024103413-440c973d9e9b/handlers/recovery_test.go (about)

     1  package handlers
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"testing"
     9  
    10  	. "github.com/smartystreets/goconvey/convey"
    11  )
    12  
    13  // panickingHandler is an http handler for test use, that just panics
    14  func panickingHandler() http.Handler {
    15  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    16  		panic("Message from runtime panic")
    17  	})
    18  }
    19  
    20  // notPanickingHandler is an http handler for test use, that does not panic
    21  func notPanickingHandler() http.Handler {
    22  	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    23  		fmt.Fprintln(w, "Everything is OK")
    24  	})
    25  }
    26  
    27  func TestUnitRecoveryHandler(t *testing.T) {
    28  	Convey("Recovery handler should catch runtime panics", t, func() {
    29  		handler := RecoveryHandler(panickingHandler())
    30  		req := httptest.NewRequest(http.MethodGet, "/test", bytes.NewReader(nil))
    31  		res := httptest.NewRecorder()
    32  		handler.ServeHTTP(res, req)
    33  		So(res.Code, ShouldEqual, http.StatusInternalServerError)
    34  		So(res.Body.String(), ShouldContainSubstring, "there was a problem handling your request")
    35  	})
    36  
    37  	Convey("Recovery handler should silently wrap successful handlers", t, func() {
    38  		handler := RecoveryHandler(notPanickingHandler())
    39  		req := httptest.NewRequest(http.MethodGet, "/test", bytes.NewReader(nil))
    40  		res := httptest.NewRecorder()
    41  		handler.ServeHTTP(res, req)
    42  		So(res.Code, ShouldEqual, http.StatusOK)
    43  		So(res.Body.String(), ShouldEqual, "Everything is OK\n")
    44  	})
    45  }