package cabana import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" "git.golem15.com/golem15/summercms/modules/bouncer" ) // previewRequest builds a POST /markdown/preview request with a raw body and // an optional principal in the context. func previewRequest(body string, principal *bouncer.Principal) *http.Request { req := httptest.NewRequest(http.MethodPost, adminAPI("/markdown/preview"), strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") if principal != nil { req = req.WithContext(bouncer.WithUser(req.Context(), principal)) } return req } func previewJSON(t *testing.T, markdown string) string { t.Helper() raw, err := json.Marshal(AdminMarkdownPreviewRequest{Markdown: markdown}) if err != nil { t.Fatal(err) } return string(raw) } func previewBackend() *bouncer.Principal { return &bouncer.Principal{ID: 1, Backend: true} } // decodePreview decodes a 200 answer strictly into the documented envelope. func decodePreview(t *testing.T, raw []byte) AdminMarkdownPreviewResult { t.Helper() dec := json.NewDecoder(bytes.NewReader(raw)) dec.DisallowUnknownFields() var out Envelope[AdminMarkdownPreviewResult] if err := dec.Decode(&out); err != nil { t.Fatalf("decode %s: %v", raw, err) } return out.Data } // previewDetails returns the error code and details of an error answer. func previewDetails(t *testing.T, raw []byte) (string, map[string][]string) { t.Helper() var body struct { Error struct { Code string `json:"code"` Details map[string][]string `json:"details"` } `json:"error"` } if err := json.Unmarshal(raw, &body); err != nil { t.Fatalf("decode %s: %v", raw, err) } return body.Error.Code, body.Error.Details } func TestMarkdownPreviewRequiresBackendPrincipal(t *testing.T) { for name, principal := range map[string]*bouncer.Principal{ "none": nil, "frontend": {ID: 7, Backend: false}, } { t.Run(name, func(t *testing.T) { rec := httptest.NewRecorder() (&service{}).markdownPreview(rec, previewRequest(previewJSON(t, "# Hello"), principal)) if rec.Code != http.StatusUnauthorized { t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) } assertErrorCode(t, rec.Body.Bytes(), "unauthenticated") }) } } func TestMarkdownPreviewRendersHTML(t *testing.T) { rec := httptest.NewRecorder() (&service{}).markdownPreview(rec, previewRequest(`{"markdown":"# Hello"}`, previewBackend())) if rec.Code != http.StatusOK { t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) } if got := decodePreview(t, rec.Body.Bytes()); !strings.Contains(got.HTML, "