Files
summercms/modules/postcard/locale_postgres_test.go
Jakub Zych a0dde086d2 test(postcard): locale fallback, built-in layouts, partials and CSS inlining
- TestTemplateBase, TestTemplateFor and TestSendLocaleFallback pin the
  <template>-<locale> resolution and the order the override source is asked
- TestEnsureLocaleRows (Postgres): rows only for non-default locales without
  files, idempotent, customized content kept while file_hash follows the
  base, base_code from SyncIndex, reset of a fallback row, migrations roll back
- TestBuiltinLayoutsLogo, TestHeaderFooterPartials, TestButtonPartial and
  TestSiteName cover the finished default, system and minimal layouts
- TestInlineCSS, TestInlineCSSOptOut and TestInlineFailure cover inlining,
  the per-layout opt-out and the fallback when the inliner fails
- check-phase35.sh requires the new names (GO_TESTS, DOCKER_TESTS)
2026-11-13 21:31:44 +01:00

194 lines
7.1 KiB
Go

package postcard
import (
"context"
"testing"
"testing/fstest"
"time"
"github.com/go-gormigrate/gormigrate/v2"
"gorm.io/gorm"
)
// ensureCatalog is a catalog holding welcome (body welcomeBody) and
// welcome-en, the shape EnsureLocaleRows works on.
func ensureCatalog(t *testing.T, welcomeBody string) *Catalog {
t.Helper()
fsys := fstest.MapFS{
"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome, {{ .name }}\"\ndescription = \"Sent after registration\"\n==\n" + welcomeBody + "\n")},
"views/mail/welcome-en.htm": {Data: []byte("subject = \"Welcome (en)\"\n==\nHello.\n")},
}
cat := NewCatalog()
if err := cat.Register("acme.blog", fsys, []string{localeWelcome, localeWelcome + "-en"}, nil); err != nil {
t.Fatal(err)
}
return cat
}
// templateRow is the part of a template index row TestEnsureLocaleRows reads.
type templateRow struct {
Code string
Locale *string
BaseCode *string
Description string
Subject string
Body string
LayoutID *int64
IsCustom bool
FileHash *string
BaseHash *string
CustomizedAt *time.Time
UpdatedAt time.Time
}
func templateRows(t *testing.T, gdb *gorm.DB) map[string]templateRow {
t.Helper()
var rows []templateRow
if err := gdb.Raw(`SELECT code, locale, base_code, description, subject, body, layout_id, is_custom, file_hash, base_hash, customized_at, updated_at
FROM ` + TemplatesTable + ` ORDER BY code`).Scan(&rows).Error; err != nil {
t.Fatal(err)
}
out := make(map[string]templateRow, len(rows))
for _, r := range rows {
out[r.Code] = r
}
return out
}
func derefOrNil(p *string) string {
if p == nil {
return "<nil>"
}
return *p
}
func TestEnsureLocaleRows(t *testing.T) {
gdb := mailPostgres(t)
ctx := context.Background()
locales := []string{"pl", "en", "de"}
de := localeWelcome + "-de"
cat := ensureCatalog(t, "Hi **{{ .name }}**.")
base, _ := cat.Template(localeWelcome)
// Only de gets a row: pl is the default locale (the base file is its
// version) and en ships a file.
if err := EnsureLocaleRows(ctx, gdb, cat, "pl", locales); err != nil {
t.Fatal(err)
}
rows := templateRows(t, gdb)
if len(rows) != 1 {
t.Fatalf("rows after EnsureLocaleRows = %v, want only %s", rows, de)
}
row, ok := rows[de]
if !ok {
t.Fatalf("no %s row: %v", de, rows)
}
if derefOrNil(row.Locale) != "de" || derefOrNil(row.BaseCode) != localeWelcome || derefOrNil(row.FileHash) != base.Hash ||
row.Subject != base.Subject || row.Body != base.Body || row.Description != base.Description || row.IsCustom || row.BaseHash != nil {
t.Errorf("%s row = %+v, want the base file's content and hash, locale de, base_code %s, not customized", de, row, localeWelcome)
}
var defaultLayout int64
if err := gdb.Raw(`SELECT COUNT(*) FROM `+LayoutsTable+` WHERE code = ?`, defaultLayoutName).Scan(&defaultLayout).Error; err != nil {
t.Fatal(err)
}
if defaultLayout == 0 && row.LayoutID != nil {
t.Errorf("layout_id = %d without a layout row", *row.LayoutID)
}
// A second run writes nothing.
time.Sleep(20 * time.Millisecond)
if err := EnsureLocaleRows(ctx, gdb, cat, "pl", locales); err != nil {
t.Fatal(err)
}
if again := templateRows(t, gdb)[de]; !again.UpdatedAt.Equal(row.UpdatedAt) {
t.Errorf("a second run rewrote %s: updated_at %v, was %v", de, again.UpdatedAt, row.UpdatedAt)
}
// bases limits the run to the listed templates.
if err := EnsureLocaleRows(ctx, gdb, cat, "pl", []string{"pl", "fr"}, "acme.blog::mail.other"); err != nil {
t.Fatal(err)
}
if _, ok := templateRows(t, gdb)[localeWelcome+"-fr"]; ok {
t.Error("a base outside bases got a fr row")
}
// SyncIndex writes base_code for the file-backed rows, and its layout
// rows give the fallback row a layout_id on the next run.
if err := SyncIndex(ctx, gdb, cat, locales); err != nil {
t.Fatal(err)
}
rows = templateRows(t, gdb)
if r := rows[localeWelcome+"-en"]; derefOrNil(r.BaseCode) != localeWelcome || derefOrNil(r.Locale) != "en" {
t.Errorf("welcome-en after SyncIndex = %+v, want base_code %s and locale en", r, localeWelcome)
}
if r := rows[localeWelcome]; derefOrNil(r.BaseCode) != localeWelcome || r.Locale != nil {
t.Errorf("welcome after SyncIndex = %+v, want base_code %s and no locale", r, localeWelcome)
}
// A customized fallback row keeps its content when the base file
// changes; file_hash follows the base, so the row shows as outdated.
if err := gdb.Exec(`UPDATE `+TemplatesTable+` SET subject = 'Willkommen', body = 'Hallo.', is_custom = TRUE, base_hash = file_hash, customized_at = NOW() WHERE code = ?`, de).Error; err != nil {
t.Fatal(err)
}
changed := ensureCatalog(t, "Hi **{{ .name }}**, the file changed.")
newBase, _ := changed.Template(localeWelcome)
if newBase.Hash == base.Hash {
t.Fatal("the changed base file has the same hash")
}
if err := EnsureLocaleRows(ctx, gdb, changed, "pl", locales); err != nil {
t.Fatal(err)
}
row = templateRows(t, gdb)[de]
if row.Subject != "Willkommen" || row.Body != "Hallo." || !row.IsCustom {
t.Errorf("customized %s lost its content: %+v", de, row)
}
if derefOrNil(row.FileHash) != newBase.Hash || derefOrNil(row.BaseHash) != base.Hash {
t.Errorf("%s file_hash = %s, base_hash = %s, want %s (the changed base) and %s", de, derefOrNil(row.FileHash), derefOrNil(row.BaseHash), newBase.Hash, base.Hash)
}
// Reset returns the fallback row to the base file's version.
if err := ResetOverride(ctx, gdb, changed, KindTemplate, de); err != nil {
t.Fatal(err)
}
row = templateRows(t, gdb)[de]
if row.Subject != newBase.Subject || row.Body != newBase.Body || row.IsCustom || row.BaseHash != nil || row.CustomizedAt != nil || derefOrNil(row.FileHash) != newBase.Hash {
t.Errorf("%s after reset = %+v, want the base file's version, not customized", de, row)
}
if err := ResetOverride(ctx, gdb, changed, KindTemplate, "acme.blog::mail.missing-de"); err == nil {
t.Error("reset of a code with no file version succeeded")
}
// Every migration rolls back and applies again, the 35 gap-closure ones
// (base_code, site_name, disable_auto_inline_css) included.
ids := make(map[string]bool, len(Migrations))
for _, m := range Migrations {
ids[m.ID] = true
}
for _, id := range []string{"202611130001_mail_template_base_code", "202611130002_mail_brand_site_name", "202611130003_mail_layout_disable_auto_inline_css"} {
if !ids[id] {
t.Errorf("migration %s is missing", id)
}
}
mig := gormigrate.New(gdb, gormigrate.DefaultOptions, Migrations)
for range Migrations {
if err := mig.RollbackLast(); err != nil {
t.Fatalf("rollback: %v", err)
}
}
var n int64
if err := gdb.Raw(`SELECT COUNT(*) FROM information_schema.tables WHERE table_name LIKE 'system_mail_%'`).Scan(&n).Error; err != nil {
t.Fatal(err)
}
if n != 0 {
t.Errorf("%d mail tables left after the rollback", n)
}
if err := mig.Migrate(); err != nil {
t.Fatalf("migrate again: %v", err)
}
if err := EnsureLocaleRows(ctx, gdb, cat, "pl", locales); err != nil {
t.Fatalf("EnsureLocaleRows after migrating again: %v", err)
}
if rows := templateRows(t, gdb); len(rows) != 1 || derefOrNil(rows[de].BaseCode) != localeWelcome {
t.Errorf("rows after migrating again = %v", rows)
}
}