diff --git a/cmd/web/handlers_test.go b/cmd/web/handlers_test.go index 69c3965..ff090e2 100644 --- a/cmd/web/handlers_test.go +++ b/cmd/web/handlers_test.go @@ -1,33 +1,20 @@ package main import ( - "bytes" - "io" "net/http" - "net/http/httptest" "testing" "gitea.local.lab/Lbenedar/snippetbox/internal/assert" ) func TestPing(t *testing.T) { - rr := httptest.NewRecorder() + app := newTestApplication(t) - r, err := http.NewRequest(http.MethodGet, "/", nil) - if err != nil { - t.Fatal(err) - } + ts := newTestServer(t, app.routes()) + defer ts.Close() - ping(rr, r) + statusCode, _, body := ts.get(t, "/ping") - rs := rr.Result() - - assert.Equal(t, rs.StatusCode, http.StatusOK) - defer rs.Body.Close() - body, err := io.ReadAll(rs.Body) - if err != nil { - t.Fatal(err) - } - bytes.TrimSpace(body) - assert.Equal(t, string(body), "OK") + assert.Equal(t, statusCode, http.StatusOK) + assert.Equal(t, body, "OK") } diff --git a/cmd/web/routes.go b/cmd/web/routes.go index c22b316..a891fae 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -19,6 +19,8 @@ func (app *application) routes() http.Handler { fileServer := http.FileServer(http.FS(ui.Files)) router.Handler(http.MethodGet, "/static/*filepath", fileServer) + router.HandlerFunc(http.MethodGet, "/ping", ping) + dynamic := alice.New(app.sessionManager.LoadAndSave, noSurf, app.authenticate) router.Handler(http.MethodGet, "/", dynamic.ThenFunc(app.home)) diff --git a/cmd/web/testutils_test.go b/cmd/web/testutils_test.go new file mode 100644 index 0000000..5e3c4af --- /dev/null +++ b/cmd/web/testutils_test.go @@ -0,0 +1,53 @@ +package main + +import ( + "bytes" + "io" + "log" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "testing" +) + +func newTestApplication(t *testing.T) *application { + return &application{ + errorLog: log.New(io.Discard, "", 0), + infoLog: log.New(io.Discard, "", 0), + } +} + +type testServer struct { + *httptest.Server +} + +func newTestServer(t *testing.T, h http.Handler) *testServer { + ts := httptest.NewTLSServer(h) + jar, err := cookiejar.New(nil) + if err != nil { + t.Fatal(err) + } + + ts.Client().Jar = jar + + ts.Client().CheckRedirect = func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + } + return &testServer{ts} +} + +func (ts *testServer) get(t *testing.T, urlPath string) (int, http.Header, string) { + rs, err := ts.Client().Get(ts.URL + urlPath) + if err != nil { + t.Fatal(err) + } + + defer rs.Body.Close() + body, err := io.ReadAll(rs.Body) + if err != nil { + t.Fatal(err) + } + bytes.TrimSpace(body) + + return rs.StatusCode, rs.Header, string(body) +}