Files
RenewCMS/test/llms_handler_http_test.go
T

77 lines
2.6 KiB
Go

package test
import (
"RenewCMS/api/handlers/llms"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/go-chi/chi/v5"
)
func llmsRouter(docs fstest.MapFS) http.Handler {
r := chi.NewRouter()
llms.NewHandler(docs, "v9.9.9", "https://cms.example/").Register(r)
return r
}
func llmsGet(handler http.Handler, target string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil))
return rec
}
func TestLlmsServesGeneratedDocsWithVersionAndBaseURL(t *testing.T) {
handler := llmsRouter(fstest.MapFS{
"llms.txt": {Data: []byte("# RenewCMS {{VERSION}}\n{{BASE_URL}}/llms-full.txt")},
"llms-full.txt": {Data: []byte("full {{VERSION}}")},
"openapi.json": {Data: []byte(`{"version":"{{VERSION}}","servers":[{"url":"{{BASE_URL}}"}]}`)},
"llms/gotchas.md": {Data: []byte("# Gotchas {{VERSION}}")},
"llms/private.txt": {Data: []byte("not a page")},
})
cases := []struct {
target string
contentType string
body string
}{
{"/llms.txt", "text/plain; charset=utf-8", "# RenewCMS v9.9.9\nhttps://cms.example/llms-full.txt"},
{"/llms-full.txt", "text/plain; charset=utf-8", "full v9.9.9"},
{"/openapi.json", "application/json", `{"version":"v9.9.9","servers":[{"url":"https://cms.example"}]}`},
{"/llms/gotchas.md", "text/markdown; charset=utf-8", "# Gotchas v9.9.9"},
}
for _, tc := range cases {
rec := llmsGet(handler, tc.target)
if rec.Code != http.StatusOK {
t.Fatalf("%s answered %d", tc.target, rec.Code)
}
if got := rec.Header().Get("Content-Type"); got != tc.contentType {
t.Errorf("%s content type %q, want %q", tc.target, got, tc.contentType)
}
if rec.Body.String() != tc.body {
t.Errorf("%s body %q, want %q", tc.target, rec.Body.String(), tc.body)
}
}
}
func TestLlmsAnswers404WhenNothingWasGenerated(t *testing.T) {
handler := llmsRouter(fstest.MapFS{})
for _, target := range []string{"/llms.txt", "/llms-full.txt", "/openapi.json", "/llms/gotchas.md", "/llms/private.txt", "/llms/..%2Fllms.txt"} {
rec := llmsGet(handler, target)
if rec.Code != http.StatusNotFound {
t.Errorf("%s answered %d, want 404", target, rec.Code)
}
if !strings.Contains(rec.Body.String(), "task build:llms") {
t.Errorf("%s body %q does not name the task", target, rec.Body.String())
}
}
}
func TestLlmsOnlyServesMarkdownPages(t *testing.T) {
handler := llmsRouter(fstest.MapFS{"llms/private.txt": {Data: []byte("not a page")}})
if rec := llmsGet(handler, "/llms/private.txt"); rec.Code != http.StatusNotFound {
t.Fatalf("answered %d, want 404", rec.Code)
}
}