...

Source file src/github.com/gorilla/handlers/recovery_test.go

Documentation: github.com/gorilla/handlers

     1  package handlers
     2  
     3  import (
     4  	"bytes"
     5  	"log"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"strings"
     9  	"testing"
    10  )
    11  
    12  func TestRecoveryLoggerWithDefaultOptions(t *testing.T) {
    13  	var buf bytes.Buffer
    14  	log.SetOutput(&buf)
    15  
    16  	handler := RecoveryHandler()
    17  	handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    18  		panic("Unexpected error!")
    19  	})
    20  
    21  	recovery := handler(handlerFunc)
    22  	recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
    23  
    24  	if !strings.Contains(buf.String(), "Unexpected error!") {
    25  		t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
    26  	}
    27  }
    28  
    29  func TestRecoveryLoggerWithCustomLogger(t *testing.T) {
    30  	var buf bytes.Buffer
    31  	var logger = log.New(&buf, "", log.LstdFlags)
    32  
    33  	handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
    34  		panic("Unexpected error!")
    35  	})
    36  
    37  	t.Run("Without print stack", func(t *testing.T) {
    38  		handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(false))
    39  
    40  		recovery := handler(handlerFunc)
    41  		recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
    42  
    43  		if !strings.Contains(buf.String(), "Unexpected error!") {
    44  			t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!")
    45  		}
    46  	})
    47  
    48  	t.Run("With print stack enabled", func(t *testing.T) {
    49  		handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(true))
    50  
    51  		recovery := handler(handlerFunc)
    52  		recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf"))
    53  
    54  		if !strings.Contains(buf.String(), "runtime/debug.Stack") {
    55  			t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "runtime/debug.Stack")
    56  		}
    57  	})
    58  }
    59  

View as plain text