whois/template/api/api_test.go

90 lines
2.2 KiB
Go
Raw Normal View History

2025-01-05 19:39:13 -05:00
package api_test
import (
"database/sql"
"io"
"net/http/httptest"
"os"
"strings"
"testing"
"git.simponic.xyz/simponic/whois/api"
"git.simponic.xyz/simponic/whois/args"
"git.simponic.xyz/simponic/whois/database"
"git.simponic.xyz/simponic/whois/utils"
)
func setup(t *testing.T) (*sql.DB, *httptest.Server) {
randomDb := utils.RandomId()
testDb := database.MakeConn(&randomDb)
database.Migrate(testDb)
arguments := &args.Arguments{
TemplatePath: "../templates",
StaticPath: "../static",
}
mux := api.MakeMux(arguments, testDb)
testServer := httptest.NewServer(mux)
t.Cleanup(func() {
testServer.Close()
testDb.Close()
os.Remove(randomDb)
})
return testDb, testServer
}
func assertResponseCode(t *testing.T, resp *httptest.ResponseRecorder, statusCode int) {
if resp.Code != statusCode {
t.Errorf("code is unexpected: %d, expected %d", resp.Code, statusCode)
}
}
func assertResponseBody(t *testing.T, resp *httptest.ResponseRecorder, body string) {
buf := new(strings.Builder)
_, err := io.Copy(buf, resp.Body)
if err != nil {
panic("could not read response body")
}
bodyStr := buf.String()
if bodyStr != body {
t.Errorf("body is unexpected: %s, expected %s", bodyStr, body)
}
}
func TestHealthcheck(t *testing.T) {
_, testServer := setup(t)
req := httptest.NewRequest("GET", "/health", nil)
resp := httptest.NewRecorder()
testServer.Config.Handler.ServeHTTP(resp, req)
assertResponseCode(t, resp, 200)
assertResponseBody(t, resp, "healthy")
}
func TestHello(t *testing.T) {
_, testServer := setup(t)
req := httptest.NewRequest("GET", "/", nil)
resp := httptest.NewRecorder()
testServer.Config.Handler.ServeHTTP(resp, req)
assertResponseCode(t, resp, 200)
}
func TestCachingStaticFiles(t *testing.T) {
_, testServer := setup(t)
req := httptest.NewRequest("GET", "/static/css/styles.css", nil)
resp := httptest.NewRecorder()
testServer.Config.Handler.ServeHTTP(resp, req)
assertResponseCode(t, resp, 200)
if resp.Header().Get("Cache-Control") != "public, max-age=3600" {
t.Errorf("client cache will live indefinitely for static files, which is probably not great! %s", resp.Header().Get("Cache-Control"))
}
}