traefik/pkg/middlewares/recovery/recovery_test.go

67 lines
1.3 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package recovery
import (
"context"
"errors"
"io"
2018-11-14 09:18:03 +00:00
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRecoverHandler(t *testing.T) {
tests := []struct {
desc string
panicErr error
headersSent bool
}{
{
desc: "headers sent and custom panic error",
panicErr: errors.New("foo"),
headersSent: true,
},
{
desc: "headers sent and error abort handler",
panicErr: http.ErrAbortHandler,
headersSent: true,
},
{
desc: "custom panic error",
panicErr: errors.New("foo"),
},
{
desc: "error abort handler",
panicErr: http.ErrAbortHandler,
},
2018-11-14 09:18:03 +00:00
}
for _, test := range tests {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
2018-11-14 09:18:03 +00:00
fn := func(rw http.ResponseWriter, req *http.Request) {
if test.headersSent {
rw.WriteHeader(http.StatusTeapot)
}
panic(test.panicErr)
}
recovery, err := New(context.Background(), http.HandlerFunc(fn))
require.NoError(t, err)
2018-11-14 09:18:03 +00:00
server := httptest.NewServer(recovery)
t.Cleanup(server.Close)
2018-11-14 09:18:03 +00:00
res, err := http.Get(server.URL)
if test.headersSent {
require.Nil(t, res)
assert.ErrorIs(t, err, io.EOF)
} else {
require.NoError(t, err)
assert.Equal(t, http.StatusInternalServerError, res.StatusCode)
}
})
}
2018-11-14 09:18:03 +00:00
}