80 lines
1.9 KiB
Go
80 lines
1.9 KiB
Go
|
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 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"))
|
||
|
}
|
||
|
}
|