You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
Go
75 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/cookiejar"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.runcible.io/learning/ratchet/internal/model/mock"
|
|
"git.runcible.io/learning/ratchet/internal/server"
|
|
"github.com/alexedwards/scs/v2"
|
|
)
|
|
|
|
// Create a newTestApplication helper which returns an instance of our
|
|
// application struct containing mocked dependencies.
|
|
func newTestApplication(t *testing.T) *server.RatchetApp {
|
|
|
|
//tc, err := server.InitTemplateCache()
|
|
tc, err := server.InitFSTemplateCache()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
sessionManager := scs.New()
|
|
sessionManager.Lifetime = 12 * time.Hour
|
|
sessionManager.Cookie.Secure = true
|
|
|
|
rs := server.NewRatchetApp(slog.New(slog.NewTextHandler(io.Discard, nil)), tc, &mock.SnippetService{}, &mock.UserService{}, sessionManager)
|
|
return rs
|
|
}
|
|
|
|
// create out own test server with additional receiver functions for ease of testing
|
|
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)
|
|
}
|
|
|
|
// Any response cookies will be stored and sent on subsequent requests
|
|
ts.Client().Jar = jar
|
|
|
|
// Disable redirect-following for test server client by setting custom
|
|
// CheckRedirect function. Called whenever 3xx response. By returning a
|
|
// http.ErrUseLastResponse error it forces the client to immediately return
|
|
// the received response
|
|
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) {
|
|
resp, err := ts.Client().Get(ts.URL + urlPath)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return resp.StatusCode, resp.Header, string(body)
|
|
}
|