Files
CHFS-NG/internal/api/root_handler_test.go
T

56 lines
1.9 KiB
Go

package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"chfs-ng/internal/auth"
"chfs-ng/internal/storage"
)
func TestRootAndAPIDoc(t *testing.T) {
s := &Server{Store: storage.Local{Root: t.TempDir()}, Auth: &auth.Manager{Guest: &auth.Account{Mask: auth.Read}}, HTMLTitle: "My Files", HTMLNotice: "`<strong>Hello</strong>`"}
h := s.Handler()
r := httptest.NewRecorder()
h.ServeHTTP(r, httptest.NewRequest(http.MethodGet, "/", nil))
if r.Code != 200 || !strings.Contains(r.Body.String(), "<title>My Files</title>") || !strings.Contains(r.Body.String(), "<strong>Hello</strong>") {
t.Fatalf("root: %d %s", r.Code, r.Body.String())
}
r = httptest.NewRecorder()
h.ServeHTTP(r, httptest.NewRequest(http.MethodGet, "/asset/api.html", nil))
if r.Code != 200 || !strings.Contains(r.Body.String(), "/chfs/files") {
t.Fatalf("api doc: %d %s", r.Code, r.Body.String())
}
}
func TestRootEscapesPlainNotice(t *testing.T) {
s := &Server{Store: storage.Local{Root: t.TempDir()}, Auth: &auth.Manager{Guest: &auth.Account{Mask: auth.Read}}, HTMLNotice: `<script>alert(1)</script>`}
r := httptest.NewRecorder()
s.Handler().ServeHTTP(r, httptest.NewRequest(http.MethodGet, "/", nil))
if strings.Contains(r.Body.String(), `<script>alert(1)</script>`) {
t.Fatal("plain notice was not escaped")
}
}
func TestHealthz(t *testing.T) {
s := &Server{}
old := Version
Version = "test"
defer func() { Version = old }()
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
s.Handler().ServeHTTP(rr, req)
if rr.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rr.Code, rr.Body.String())
}
if got := rr.Header().Get("Cache-Control"); got != "no-store" {
t.Fatalf("cache-control=%q", got)
}
if !strings.Contains(rr.Body.String(), `"status":"ok"`) || !strings.Contains(rr.Body.String(), `"version":"test"`) {
t.Fatalf("unexpected body=%s", rr.Body.String())
}
}