|
| 1 | +package router |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "github.com/netlify/netlify-commons/tracing" |
| 7 | + "github.com/sirupsen/logrus/hooks/test" |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + "io/ioutil" |
| 11 | + "net/http" |
| 12 | + "net/http/httptest" |
| 13 | + "testing" |
| 14 | +) |
| 15 | + |
| 16 | +func TestHandleError_ErrorIsNil(t *testing.T) { |
| 17 | + logger, loggerOutput := test.NewNullLogger() |
| 18 | + w, r, _ := tracing.NewTracer( |
| 19 | + httptest.NewRecorder(), |
| 20 | + httptest.NewRequest(http.MethodGet, "/", nil), |
| 21 | + logger, |
| 22 | + "test", |
| 23 | + ) |
| 24 | + |
| 25 | + HandleError(nil, w, r) |
| 26 | + |
| 27 | + assert.Empty(t, loggerOutput.AllEntries()) |
| 28 | + assert.Empty(t, w.Header()) |
| 29 | +} |
| 30 | + |
| 31 | +func TestHandleError_StandardError(t *testing.T) { |
| 32 | + logger, loggerOutput := test.NewNullLogger() |
| 33 | + w, r, _ := tracing.NewTracer( |
| 34 | + httptest.NewRecorder(), |
| 35 | + httptest.NewRequest(http.MethodGet, "/", nil), |
| 36 | + logger, |
| 37 | + "test", |
| 38 | + ) |
| 39 | + |
| 40 | + HandleError(errors.New("random error"), w, r) |
| 41 | + |
| 42 | + require.Len(t, loggerOutput.AllEntries(), 1) |
| 43 | + assert.Equal(t, "Unhandled server error: random error", loggerOutput.AllEntries()[0].Message) |
| 44 | + assert.Empty(t, w.Header()) |
| 45 | +} |
| 46 | + |
| 47 | +func TestHandleError_HTTPError(t *testing.T) { |
| 48 | + logger, loggerOutput := test.NewNullLogger() |
| 49 | + recorder := httptest.NewRecorder() |
| 50 | + w, r, _ := tracing.NewTracer( |
| 51 | + recorder, |
| 52 | + httptest.NewRequest(http.MethodGet, "/", nil), |
| 53 | + logger, |
| 54 | + "test", |
| 55 | + ) |
| 56 | + |
| 57 | + httpErr := &HTTPError{ |
| 58 | + Code: http.StatusInternalServerError, |
| 59 | + Message: http.StatusText(http.StatusInternalServerError), |
| 60 | + InternalError: errors.New("random error"), |
| 61 | + InternalMessage: "Something unexpected happened", |
| 62 | + } |
| 63 | + |
| 64 | + HandleError(httpErr, w, r) |
| 65 | + |
| 66 | + resp := recorder.Result() |
| 67 | + b, err := ioutil.ReadAll(resp.Body) |
| 68 | + require.NoError(t, err) |
| 69 | + |
| 70 | + expectedBody := fmt.Sprintf(`{"code":500,"msg":"Internal Server Error","json":null,"error_id":"%s"}`, tracing.RequestID(r)) |
| 71 | + assert.Equal(t, expectedBody, string(b)) |
| 72 | + |
| 73 | + require.Len(t, loggerOutput.AllEntries(), 1) |
| 74 | + assert.Equal(t, httpErr.InternalMessage, loggerOutput.AllEntries()[0].Message) |
| 75 | +} |
| 76 | + |
0 commit comments