- generator in Definition::addItemToSet order: 50000 URL cap, lastmod from the record or the updates manifest (regular file, 5 MiB cap, fail safe), BeforeAddItem (skip) and AddItem (extra XML) festival events, tier or item priority, per-alternate expansion of list type children - priority tiers from golem15.sitemap.priority_tiers, compiled at boot, defaults equal to the PHP getPriorityForUrl rules - frontend_url rewrite of loc, xhtml:link href and the stylesheet href; GET /sitemap.xsl serves the PHP stylesheet byte for byte - golem15_sitemap_settings singleton and Settings model - sitemap:import (PHP ImportCommand) and sitemap:import-winter with the read-only Winter export SQL - urlto and full goldens generated from PHP; TestSitemapImportSmoke
362 lines
14 KiB
Go
362 lines
14 KiB
Go
package sitemap_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
_ "git.golem15.com/golem15/sm-sitemap-plugin"
|
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
|
"git.golem15.com/golem15/summercms/modules/compass"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
|
"git.golem15.com/golem15/summercms/modules/pact"
|
|
"git.golem15.com/golem15/summercms/modules/party"
|
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
"git.golem15.com/golem15/summercms/modules/surf"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// testTypesPluginID is the fake content plugin that registers menu item
|
|
// types for the sitemap smoke tests. The real Journal and sitemap
|
|
// combination is proven by the host application's tests.
|
|
const testTypesPluginID = "acme.sitemaptypes"
|
|
|
|
// acmeTypes is a content plugin with one menu item type, acme-post, whose
|
|
// reference "7" resolves to a fixed post with two alternates.
|
|
type acmeTypes struct{}
|
|
|
|
func (acmeTypes) ID() string { return testTypesPluginID }
|
|
func (acmeTypes) Requires() []string { return nil }
|
|
func (acmeTypes) Register(*backpack.App) error { return nil }
|
|
func (acmeTypes) Boot(*backpack.App) error { return nil }
|
|
func (acmeTypes) MenuItemTypes() []pact.MenuItemType {
|
|
mtime := time.Date(2026, 3, 4, 10, 0, 0, 0, time.UTC)
|
|
return []pact.MenuItemType{acmeList(), {
|
|
Key: "acme-post",
|
|
Label: "Acme post",
|
|
DefaultPattern: "/news/:slug",
|
|
References: func(context.Context) ([]pact.MenuItemReference, error) {
|
|
return []pact.MenuItemReference{{Value: "7", Label: "Hello"}}, nil
|
|
},
|
|
Resolve: func(_ context.Context, in pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
|
if in.Reference != "7" {
|
|
return nil, nil
|
|
}
|
|
return &pact.ResolvedMenuItem{
|
|
Title: "Hello",
|
|
URL: "/news/hello",
|
|
MTime: &mtime,
|
|
Alternates: []pact.MenuItemAlternate{
|
|
{Locale: "pl", URL: "/news/hello"},
|
|
{Locale: "en", URL: "/en/news/hello"},
|
|
},
|
|
}, nil
|
|
},
|
|
}}
|
|
}
|
|
|
|
// acmeList is a list type of the fake plugin: no URL of its own, one post
|
|
// with two alternates as its item.
|
|
func acmeList() pact.MenuItemType {
|
|
return pact.MenuItemType{
|
|
Key: "acme-list",
|
|
Label: "Acme posts",
|
|
DefaultPattern: "/news/:slug",
|
|
PatternFrom: "acme-post",
|
|
DynamicItems: true,
|
|
Resolve: func(context.Context, pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
|
return &pact.ResolvedMenuItem{Items: []pact.ResolvedMenuItem{{
|
|
Title: "A",
|
|
URL: "/news/a",
|
|
Alternates: []pact.MenuItemAlternate{
|
|
{Locale: "pl", URL: "/news/a"},
|
|
{Locale: "en", URL: "/en/news/a"},
|
|
},
|
|
}}}, nil
|
|
},
|
|
}
|
|
}
|
|
|
|
var _ pact.HasMenuItemTypes = acmeTypes{}
|
|
|
|
func init() {
|
|
party.Register(acmeTypes{})
|
|
}
|
|
|
|
// sitemapEnv is a booted application with the sitemap and the fake types.
|
|
type sitemapEnv struct {
|
|
h http.Handler
|
|
app *backpack.App
|
|
gdb *gorm.DB
|
|
}
|
|
|
|
func bootSitemap(t *testing.T) *sitemapEnv {
|
|
t.Helper()
|
|
sqlDB := freshDB(t)
|
|
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: sitemap-smoke\nlocale: en\nfallback_locale: en\nurl: https://api.example.test\n"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg, err := compass.Open(compass.Options{
|
|
Dir: dir,
|
|
Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=sitemap-smoke-test-only-hs256-secret-key"},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for key, value := range map[string]any{
|
|
"http.body_limits.default_bytes": 1048576,
|
|
"http.body_limits.upload_bytes": 8388608,
|
|
"mail.driver": "log",
|
|
"mail.from": "noreply@example.test",
|
|
} {
|
|
if err := cfg.Set(key, value); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
app := backpack.New(cfg)
|
|
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
plugins, err := party.Activate(app, []string{testTypesPluginID, "golem15.sitemap"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := lagoon.Migrate(gdb, plugins); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h, err := surf.Assemble(app, plugins)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &sitemapEnv{h: h, app: app, gdb: gdb}
|
|
}
|
|
|
|
func (e *sitemapEnv) get(t *testing.T, path string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
req := httptest.NewRequest(http.MethodGet, path, nil)
|
|
req.Host = "api.example.test"
|
|
rec := httptest.NewRecorder()
|
|
e.h.ServeHTTP(rec, req)
|
|
return rec
|
|
}
|
|
|
|
func (e *sitemapEnv) storeDefinition(t *testing.T, items []models.DefinitionItem) models.Definition {
|
|
t.Helper()
|
|
theme := models.DefinitionTheme
|
|
def := models.Definition{Theme: &theme}
|
|
def.SetItems(items)
|
|
if err := e.gdb.Create(&def).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return def
|
|
}
|
|
|
|
func text(s string) *string { return &s }
|
|
|
|
// TestSitemapTracer stores a definition with a url item and a registry
|
|
// item, GETs /sitemap.xml and compares the body with the PHP golden.
|
|
func TestSitemapTracer(t *testing.T) {
|
|
e := bootSitemap(t)
|
|
|
|
if rec := e.get(t, "/sitemap.xml"); rec.Code != http.StatusNotFound {
|
|
t.Fatalf("no definition: %d, want 404", rec.Code)
|
|
}
|
|
|
|
def := e.storeDefinition(t, nil)
|
|
rec := e.get(t, "/sitemap.xml")
|
|
if rec.Code != http.StatusOK || rec.Body.Len() != 0 || rec.Header().Get("Content-Type") != "application/xml" {
|
|
t.Fatalf("empty definition: %d %q %q", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
|
|
}
|
|
|
|
def.SetItems([]models.DefinitionItem{
|
|
{Type: models.ItemTypeURL, URL: text("/"), Changefreq: text("always"), Priority: text("1.0")},
|
|
{Type: "acme-post", Reference: text("7"), URLPattern: text(""), Nesting: true, Changefreq: text("weekly"), Priority: text("0.5")},
|
|
})
|
|
if err := e.gdb.Save(&def).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rec = e.get(t, "/sitemap.xml")
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("GET /sitemap.xml: %d %s", rec.Code, rec.Body.String())
|
|
}
|
|
if ct := rec.Header().Get("Content-Type"); ct != "application/xml" {
|
|
t.Fatalf("Content-Type = %q", ct)
|
|
}
|
|
want, err := os.ReadFile(filepath.Join("classes", "testdata", "tracer.golden"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := rec.Body.String(); got != string(want) {
|
|
t.Fatalf("/sitemap.xml differs from the PHP golden\n got: %q\nwant: %q", got, want)
|
|
}
|
|
|
|
// The stored data keeps the PHP item keys.
|
|
var raw string
|
|
if err := e.gdb.Raw(`SELECT data FROM golem15_sitemap_definitions WHERE id = ?`, def.ID).Scan(&raw).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const wantData = `[{"changefreq":"always","priority":"1.0","nesting":false,"type":"url","url":"/","reference":null,"cmsPage":null,"urlPattern":null},{"changefreq":"weekly","priority":"0.5","nesting":true,"type":"acme-post","url":null,"reference":"7","cmsPage":null,"urlPattern":""}]`
|
|
if raw != wantData {
|
|
t.Fatalf("stored data = %s", raw)
|
|
}
|
|
}
|
|
|
|
func writeFile(t *testing.T, dir, name, body string) string {
|
|
t.Helper()
|
|
path := filepath.Join(dir, name)
|
|
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return path
|
|
}
|
|
|
|
func testOutput() (bonfire.Output, *bytes.Buffer) {
|
|
var buf bytes.Buffer
|
|
return bonfire.NewOutput(strings.NewReader(""), &buf, &buf), &buf
|
|
}
|
|
|
|
// TestSitemapImportSmoke copies a Winter export through sitemap:import-winter,
|
|
// then checks the frontend_url rewrite, the stylesheet route, a
|
|
// BeforeAddItem listener and sitemap:import.
|
|
func TestSitemapImportSmoke(t *testing.T) {
|
|
e := bootSitemap(t)
|
|
ctx := context.Background()
|
|
reg, ok := e.app.Lookup[*signpost.Registry]()
|
|
if !ok {
|
|
t.Fatal("signpost registry is not published")
|
|
}
|
|
dir := t.TempDir()
|
|
data := `[{"changefreq":"always","priority":"1.0","nesting":"0","type":"url","url":"/","code":null,"reference":null,"cmsPage":null,"urlPattern":null,"exists":false,"fillable":["changefreq"]},` +
|
|
`{"changefreq":"monthly","priority":"0.5","nesting":"0","type":"static-page","url":null,"reference":"about","cmsPage":null,"urlPattern":null},` +
|
|
`{"changefreq":"weekly","priority":"0.4","nesting":"1","type":"blog-posts","url":null,"reference":null,"cmsPage":"blog/post","urlPattern":"/news/:slug"},` +
|
|
`{"changefreq":"weekly","priority":"0.4","nesting":"0","type":"acme-post","url":null,"reference":"99","cmsPage":null,"urlPattern":null}]`
|
|
quotedRaw, _ := json.Marshal(data)
|
|
quoted := string(quotedRaw)
|
|
defs := writeFile(t, dir, "definitions.jsonl", `{"id": 3, "theme": "site-theme", "data": `+quoted+`, "created_at": "2026-01-01 10:00:00", "updated_at": "2026-01-02 10:00:00"}`+"\n")
|
|
settings := writeFile(t, dir, "settings.json", `{"frontend_url":"https://www.example.test/","frontend_default_locale":"pl","enable_priority_tiers":"0","priority_homepage":"0.9","legacy_key":"x"}`)
|
|
|
|
out, buf := testOutput()
|
|
report, err := console.ImportWinterFiles(ctx, e.gdb, reg, console.WinterOptions{
|
|
DefinitionsFile: defs, SettingsFile: settings, Maps: map[string]string{"blog-posts": "acme-list"},
|
|
}, out)
|
|
if err != nil {
|
|
t.Fatalf("import-winter: %v\n%s", err, buf.String())
|
|
}
|
|
if report.Kept != 2 || report.Dropped != 2 || report.Remapped != 1 || !report.Settings {
|
|
t.Fatalf("report = %+v\n%s", report, buf.String())
|
|
}
|
|
for _, want := range []string{
|
|
"item 1 (type 'static-page', reference 'about'): dropped (static and CMS page types are not supported)",
|
|
"item 2 (type 'blog-posts'): type 'blog-posts' mapped to 'acme-list'",
|
|
"item 2 (type 'blog-posts'): cmsPage 'blog/post' dropped",
|
|
"item 3 (type 'acme-post', reference '99'): dropped (reference '99' is not among the current references of 'acme-post')",
|
|
"setting 'legacy_key' ignored",
|
|
"theme 'site-theme'",
|
|
} {
|
|
if !strings.Contains(buf.String(), want) {
|
|
t.Errorf("report lacks %q:\n%s", want, buf.String())
|
|
}
|
|
}
|
|
var def models.Definition
|
|
if err := e.gdb.Where("theme = ?", models.DefinitionTheme).First(&def).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if items := def.Items(); len(items) != 2 || items[0].Type != "url" || items[1].Type != "acme-list" || models.Text(items[1].URLPattern) != "/news/:slug" {
|
|
t.Fatalf("copied items = %+v", items)
|
|
}
|
|
var st models.Settings
|
|
if err := e.gdb.First(&st, 1).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if models.Text(st.FrontendURL) != "https://www.example.test/" || st.EnablePriorityTiers || st.Priority(models.PriorityHomepage) != "0.9" || st.Priority(models.PriorityBlog) != "0.6" {
|
|
t.Fatalf("copied settings = %+v", st)
|
|
}
|
|
|
|
// A second copy without --force is refused.
|
|
out, buf = testOutput()
|
|
if _, err := console.ImportWinterFiles(ctx, e.gdb, reg, console.WinterOptions{DefinitionsFile: defs}, out); err == nil || !strings.Contains(err.Error(), "--force") {
|
|
t.Fatalf("second import: %v\n%s", err, buf.String())
|
|
}
|
|
|
|
// The frontend URL replaces the backend URL in loc, hreflang and the
|
|
// stylesheet href; the list type expands per alternate.
|
|
rec := e.get(t, "/sitemap.xml")
|
|
body := rec.Body.String()
|
|
if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != "no-cache, private" {
|
|
t.Fatalf("GET /sitemap.xml: %d %v", rec.Code, rec.Header())
|
|
}
|
|
for _, want := range []string{
|
|
`href="https://www.example.test/sitemap.xsl"`,
|
|
`<loc>https://www.example.test/</loc>`,
|
|
`<loc>https://www.example.test/news/a</loc>`,
|
|
`<loc>https://www.example.test/en/news/a</loc>`,
|
|
`hreflang="en" href="https://www.example.test/en/news/a"/>`,
|
|
} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("sitemap lacks %s:\n%s", want, body)
|
|
}
|
|
}
|
|
if strings.Contains(body, "api.example.test") {
|
|
t.Errorf("the backend URL is left in the sitemap:\n%s", body)
|
|
}
|
|
|
|
// /sitemap.xsl answers the PHP file.
|
|
rec = e.get(t, "/sitemap.xsl")
|
|
want, err := os.ReadFile(filepath.Join("assets", "sitemap.xsl"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "text/xsl; charset=UTF-8" || !bytes.Equal(rec.Body.Bytes(), want) {
|
|
t.Fatalf("GET /sitemap.xsl: %d %q (%d bytes)", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len())
|
|
}
|
|
|
|
// A BeforeAddItem listener that sets Skip drops its URL.
|
|
e.app.Events.Listen("acme.skip", func(_ context.Context, ev *classes.BeforeAddItem) error {
|
|
if ev.Info.URL == "/en/news/a" {
|
|
ev.Skip = true
|
|
}
|
|
return nil
|
|
})
|
|
body = e.get(t, "/sitemap.xml").Body.String()
|
|
if strings.Contains(body, "<loc>https://www.example.test/en/news/a</loc>") || !strings.Contains(body, "<loc>https://www.example.test/news/a</loc>") {
|
|
t.Fatalf("the skipped URL is still written:\n%s", body)
|
|
}
|
|
|
|
// sitemap:import replaces the url items and keeps the dynamic ones first.
|
|
manifest := writeFile(t, dir, "urls.json", `[{"url":"/x","changefreq":"daily"},{"url":"/y","priority":"0.9"}]`)
|
|
out, buf = testOutput()
|
|
if err := console.ImportFile(ctx, e.gdb, manifest, "", false, out); err != nil {
|
|
t.Fatalf("sitemap:import: %v", err)
|
|
}
|
|
if err := e.gdb.Where("theme = ?", models.DefinitionTheme).First(&def).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
items := def.Items()
|
|
if len(items) != 3 || items[0].Type != "acme-list" || models.Text(items[1].URL) != "/x" || models.Text(items[1].Priority) != "0.5" || models.Text(items[2].Changefreq) != "monthly" {
|
|
t.Fatalf("imported items = %+v", items)
|
|
}
|
|
if !strings.Contains(buf.String(), "Imported 2 URLs into sitemap definition for theme 'default'.") || !strings.Contains(buf.String(), "Kept 1 existing non-URL (dynamic) items.") {
|
|
t.Fatalf("sitemap:import output:\n%s", buf.String())
|
|
}
|
|
bad := writeFile(t, dir, "bad.json", `[{"url":"/x"},{"changefreq":"daily"}]`)
|
|
if err := console.ImportFile(ctx, e.gdb, bad, "", true, out); err == nil || err.Error() != "Entry 1 is missing a 'url' field" {
|
|
t.Fatalf("missing url: %v", err)
|
|
}
|
|
}
|