|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "io" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | +) |
| 11 | + |
| 12 | +func Test_sendErrorMsg(t *testing.T) { |
| 13 | + testCases := []struct { |
| 14 | + name string |
| 15 | + errorMsg string |
| 16 | + body io.Reader |
| 17 | + expectedStatus int |
| 18 | + expectedBody string |
| 19 | + }{ |
| 20 | + { |
| 21 | + name: "invalid request", |
| 22 | + body: nil, |
| 23 | + errorMsg: "MSG", |
| 24 | + expectedStatus: http.StatusBadRequest, |
| 25 | + expectedBody: `<div class="error-msg" role="alert"><strong>Error: </strong> <span>MSG</span></div>`, |
| 26 | + }, |
| 27 | + } |
| 28 | + |
| 29 | + for _, tc := range testCases { |
| 30 | + t.Run(tc.name, func(t *testing.T) { |
| 31 | + w := httptest.NewRecorder() |
| 32 | + r := httptest.NewRequest(http.MethodGet, "/", tc.body) |
| 33 | + |
| 34 | + sendErrorMsg(w, r, tc.errorMsg) |
| 35 | + |
| 36 | + assert.Equal(t, tc.expectedStatus, w.Result().StatusCode, |
| 37 | + "unexpected status code. Expected :%d, got: %d", tc.expectedStatus, w.Result().StatusCode) |
| 38 | + |
| 39 | + body, _ := io.ReadAll(w.Result().Body) |
| 40 | + assert.Equal(t, tc.expectedBody, string(body), "expected response body") |
| 41 | + }) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +func Test_Page404(t *testing.T) { |
| 46 | + testCases := []struct { |
| 47 | + name string |
| 48 | + body io.Reader |
| 49 | + expectedStatus int |
| 50 | + }{ |
| 51 | + { |
| 52 | + name: "not found page", |
| 53 | + body: nil, |
| 54 | + expectedStatus: http.StatusNotFound, |
| 55 | + }, |
| 56 | + } |
| 57 | + |
| 58 | + for _, tc := range testCases { |
| 59 | + t.Run(tc.name, func(t *testing.T) { |
| 60 | + w := httptest.NewRecorder() |
| 61 | + r := httptest.NewRequest(http.MethodGet, "/", tc.body) |
| 62 | + |
| 63 | + handler := &Handlers{} |
| 64 | + handler.Page404(w, r) |
| 65 | + |
| 66 | + assert.Equal(t, tc.expectedStatus, w.Result().StatusCode, |
| 67 | + "unexpected status code. Expected :%d, got: %d", tc.expectedStatus, w.Result().StatusCode) |
| 68 | + }) |
| 69 | + } |
| 70 | +} |
0 commit comments