| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "html/template" |
| 7 | "io" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "regexp" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "github.com/a-h/templ" |
| 17 | ) |
| 18 | |
| 19 | var betweenTags = regexp.MustCompile(`>\s+<`) |
| 20 | var spaces = regexp.MustCompile(`\s+`) |
| 21 | |
| 22 | func normalizeHTML(s string) string { |
| 23 | s = betweenTags.ReplaceAllString(s, "><") |
| 24 | s = spaces.ReplaceAllString(s, " ") |
| 25 | s = strings.ReplaceAll(s, "> ", ">") |
| 26 | s = strings.ReplaceAll(s, " <", "<") |
| 27 | return strings.TrimSpace(s) |
| 28 | } |
| 29 | |
| 30 | // The starters prefill the /admin/templates editor, so they must render the |
| 31 | // same markup as the templ defaults they stand in for. |
| 32 | func TestStartersMatchTemplDefaults(t *testing.T) { |
| 33 | defaults := map[string]func(any) templ.Component{ |
| 34 | "index": func(v any) templ.Component { return indexBody(v.(indexView)) }, |
| 35 | "post": func(v any) templ.Component { return postBody(v.(postView)) }, |
| 36 | "page": func(v any) templ.Component { return pageBody(v.(pageView)) }, |
| 37 | "posts": func(v any) templ.Component { return postsBody(v.(postsView)) }, |
| 38 | } |
| 39 | for _, k := range templateKinds { |
| 40 | t.Run(k.Kind, func(t *testing.T) { |
| 41 | v := sampleView(k.Kind) |
| 42 | var want bytes.Buffer |
| 43 | if err := defaults[k.Kind](v).Render(context.Background(), &want); err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | src, err := appFS.ReadFile("starters/" + k.Kind + ".html") |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | tmpl, err := validateOverride(k.Kind, string(src)) |
| 51 | if err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | var got bytes.Buffer |
| 55 | if err := tmpl.Execute(&got, v); err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if g, w := normalizeHTML(got.String()), normalizeHTML(want.String()); g != w { |
| 59 | t.Errorf("starter differs from templ default\nstarter: %s\ndefault: %s", g, w) |
| 60 | } |
| 61 | }) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | func newTestApp(t *testing.T) *App { |
| 66 | t.Helper() |
| 67 | tmpls, err := buildTemplates() |
| 68 | if err != nil { |
| 69 | t.Fatal(err) |
| 70 | } |
| 71 | return &App{ |
| 72 | DB: openPostsTestDB(t), |
| 73 | Log: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| 74 | Templates: tmpls, |
| 75 | Overrides: &overrides{}, |
| 76 | SiteURL: "https://example.com", |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | func get(t *testing.T, h http.Handler, path string) *httptest.ResponseRecorder { |
| 81 | t.Helper() |
| 82 | rec := httptest.NewRecorder() |
| 83 | h.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) |
| 84 | return rec |
| 85 | } |
| 86 | |
| 87 | func TestCustomTemplateOverridesBody(t *testing.T) { |
| 88 | a := newTestApp(t) |
| 89 | defer a.DB.Close() |
| 90 | if _, err := createPost(a.DB, PostInput{Title: strp("Hi"), Slug: "hi", Content: "body", Status: "published", Lang: "en"}); err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | h := a.routes() |
| 94 | |
| 95 | rec := get(t, h, "/posts/hi") |
| 96 | if rec.Code != 200 || !strings.Contains(rec.Body.String(), `<h1>Hi</h1>`) { |
| 97 | t.Fatalf("default render: %d %s", rec.Code, rec.Body.String()) |
| 98 | } |
| 99 | |
| 100 | // Invalid templates are rejected and leave the default in place. |
| 101 | for _, src := range []string{"{{.Post.Nope}}", "{{if}}"} { |
| 102 | rec = httptest.NewRecorder() |
| 103 | req := httptest.NewRequest("POST", "/admin/templates/post", strings.NewReader(url.Values{"template": {src}}.Encode())) |
| 104 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 105 | a.adminPostTemplate(rec, withKind(req, "post")) |
| 106 | if rec.Code != http.StatusUnprocessableEntity { |
| 107 | t.Fatalf("%q: want 422, got %d", src, rec.Code) |
| 108 | } |
| 109 | } |
| 110 | if a.Overrides.get("post") != nil { |
| 111 | t.Fatal("invalid template was cached") |
| 112 | } |
| 113 | |
| 114 | save := func(src string) { |
| 115 | rec := httptest.NewRecorder() |
| 116 | req := httptest.NewRequest("POST", "/admin/templates/post", strings.NewReader(url.Values{"template": {src}}.Encode())) |
| 117 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 118 | a.adminPostTemplate(rec, withKind(req, "post")) |
| 119 | if rec.Code != http.StatusSeeOther { |
| 120 | t.Fatalf("save: %d %s", rec.Code, rec.Body.String()) |
| 121 | } |
| 122 | } |
| 123 | save(`<h2 class="custom">{{.Post.TitleStr}} on {{.BlogTitle}}</h2>{{.RenderedContent}}`) |
| 124 | body := get(t, h, "/posts/hi").Body.String() |
| 125 | if !strings.Contains(body, `<h2 class="custom">Hi on My Blog</h2><p>body</p>`) { |
| 126 | t.Fatalf("override not rendered: %s", body) |
| 127 | } |
| 128 | if !strings.Contains(body, `<meta property="og:title" content="Hi">`) { |
| 129 | t.Fatal("layout meta missing with override") |
| 130 | } |
| 131 | |
| 132 | // Overrides survive a restart. |
| 133 | b := &App{DB: a.DB, Log: a.Log, Overrides: &overrides{}} |
| 134 | b.loadOverrides() |
| 135 | if b.Overrides.get("post") == nil { |
| 136 | t.Fatal("override not loaded from settings") |
| 137 | } |
| 138 | |
| 139 | // A runtime failure falls back to the default body. |
| 140 | a.Overrides.set("post", template.Must(template.New("post").Parse(`{{index .Post.TagList 5}}`))) |
| 141 | rec = get(t, h, "/posts/hi") |
| 142 | if rec.Code != 200 || !strings.Contains(rec.Body.String(), `<h1>Hi</h1>`) { |
| 143 | t.Fatalf("fallback: %d %s", rec.Code, rec.Body.String()) |
| 144 | } |
| 145 | |
| 146 | // Clearing removes the override. |
| 147 | save("") |
| 148 | if a.Overrides.get("post") != nil { |
| 149 | t.Fatal("override not cleared") |
| 150 | } |
| 151 | if v, _ := getSetting(a.DB, templateSettingKey("post")); v != "" { |
| 152 | t.Fatalf("setting not cleared: %q", v) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | func withKind(r *http.Request, kind string) *http.Request { |
| 157 | r.SetPathValue("kind", kind) |
| 158 | return r |
| 159 | } |
| 160 | |
| 161 | func TestPublicPagesRender(t *testing.T) { |
| 162 | a := newTestApp(t) |
| 163 | defer a.DB.Close() |
| 164 | if _, err := createPost(a.DB, PostInput{Title: strp("<b>x</b>"), Slug: "x", Content: "body", Status: "published", Lang: "en", Tags: strp("a")}); err != nil { |
| 165 | t.Fatal(err) |
| 166 | } |
| 167 | if _, err := createPage(a.DB, "About", "about", "about me", true, 0); err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | _ = setSetting(a.DB, "intro_content", "hi\n\n{{latest_posts}}") |
| 171 | h := a.routes() |
| 172 | for path, want := range map[string]string{ |
| 173 | "/": `<span class="tag">a</span>`, |
| 174 | "/posts": `<h1>Posts</h1>`, |
| 175 | "/posts/x": `<h1><b>x</b></h1>`, |
| 176 | "/about": `<h1>About</h1>`, |
| 177 | } { |
| 178 | rec := get(t, h, path) |
| 179 | if rec.Code != 200 || !strings.Contains(rec.Body.String(), want) { |
| 180 | t.Errorf("%s: %d, missing %q in %s", path, rec.Code, want, rec.Body.String()) |
| 181 | } |
| 182 | if strings.Contains(rec.Body.String(), "<b>x</b>") { |
| 183 | t.Errorf("%s: unescaped title", path) |
| 184 | } |
| 185 | } |
| 186 | } |