lets-go:14.3 refactor test server setup
This commit is contained in:
parent
eeca8ca34c
commit
01bfefac13
@ -1,36 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"snippetbox.chaosfem.tw/internal/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPing(t *testing.T) {
|
||||
app := &application{
|
||||
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
}
|
||||
app := newTestApplication(t)
|
||||
|
||||
ts := httptest.NewTLSServer(app.routes())
|
||||
ts := newTestServer(t, app.routes())
|
||||
defer ts.Close()
|
||||
|
||||
rs, err := ts.Client().Get(ts.URL + "/ping")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statusCode, _, body := ts.get(t, "/ping")
|
||||
|
||||
assert.Equal(t, rs.StatusCode, http.StatusOK)
|
||||
|
||||
defer rs.Body.Close()
|
||||
body, err := io.ReadAll(rs.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assert.Equal(t, string(bytes.TrimSpace(body)), "OK")
|
||||
assert.Equal(t, statusCode, http.StatusOK)
|
||||
assert.Equal(t, body, "OK")
|
||||
}
|
||||
|
53
snippetbox/cmd/web/testutils_test.go
Normal file
53
snippetbox/cmd/web/testutils_test.go
Normal file
@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newTestApplication(t *testing.T) *application {
|
||||
return &application{
|
||||
logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
return rs.StatusCode, rs.Header, string(bytes.TrimSpace(body))
|
||||
}
|
Loading…
Reference in New Issue
Block a user