- TestMailLocaleGroups: one list row per template, customized locales, grouped badges and status filter, localeVariants order, labels, states and current flag, the default version on a fallback row, save then send, reset, drift through the base file, the file version against the base file, out-of-group ids, the permission split and locales enabled at run time - TestMailBrandSiteName: saved trimmed, 255-character limit, preview and send header, no header row without a name or a logo, current handling of a name holding a URL scheme - TestMailLayoutInlineOptOut: the switch on a file layout, reset to the file value, a custom layout created with the switch off - check-phase35.sh requires the three names (DOCKER_TESTS)
314 lines
13 KiB
Go
314 lines
13 KiB
Go
package cabana_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"testing/fstest"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
|
"git.golem15.com/golem15/summercms/modules/postcard"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// mutableLocaleWriter is a TranslationWriter whose enabled locales a test
|
|
// changes while the application runs, as a translate plugin does when a
|
|
// locale is enabled.
|
|
type mutableLocaleWriter struct {
|
|
mu sync.Mutex
|
|
def string
|
|
enabled []string
|
|
}
|
|
|
|
func (w *mutableLocaleWriter) DefaultLocale(context.Context, *gorm.DB) (string, error) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
return w.def, nil
|
|
}
|
|
|
|
func (w *mutableLocaleWriter) EnabledLocales(context.Context, *gorm.DB) ([]string, error) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
return append([]string(nil), w.enabled...), nil
|
|
}
|
|
|
|
func (w *mutableLocaleWriter) enable(code string) {
|
|
w.mu.Lock()
|
|
defer w.mu.Unlock()
|
|
w.enabled = append(w.enabled, code)
|
|
}
|
|
|
|
func (*mutableLocaleWriter) WriteTranslated(context.Context, *gorm.DB, any, string, string, string) error {
|
|
return nil
|
|
}
|
|
|
|
func (*mutableLocaleWriter) TranslatedExact(context.Context, *gorm.DB, any, string, string) (string, bool, error) {
|
|
return "", false, nil
|
|
}
|
|
|
|
// getInLanguage is a GET with Accept-Language lang instead of en.
|
|
func getInLanguage(t *testing.T, env *mailEnv, rel, token, lang string) map[string]any {
|
|
t.Helper()
|
|
req, err := env.request(http.MethodGet, rel, token, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req.Header.Set("Accept-Language", lang)
|
|
rec := httptest.NewRecorder()
|
|
env.h.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("GET %s (%s) status=%d body=%s", rel, lang, rec.Code, rec.Body.String())
|
|
}
|
|
var out map[string]any
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// sendGrace sends name to one reader with name=Grace and returns the message.
|
|
func sendGrace(t *testing.T, env *mailEnv, name string) postcard.RenderedMessage {
|
|
t.Helper()
|
|
if err := env.mailer.Send(context.Background(), postcard.Message{Template: name, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil {
|
|
t.Fatalf("Send %s: %v", name, err)
|
|
}
|
|
msgs := env.driver.messages()
|
|
return msgs[len(msgs)-1]
|
|
}
|
|
|
|
// TestMailLocaleGroups covers G-35-1 on the admin side: one list row per
|
|
// template, the customized locales and grouped states, the locale switcher's
|
|
// variants, a locale without a file (its default version, save then send,
|
|
// reset, drift through the base file, its file version and info), ids
|
|
// outside the group, the permission split and locales enabled at run time.
|
|
func TestMailLocaleGroups(t *testing.T) {
|
|
writer := &mutableLocaleWriter{def: "pl", enabled: []string{"pl", "en", "de"}}
|
|
env := newMailScreensEnvWith(t, mailEnvOptions{writer: writer})
|
|
_, root := env.admin(t, "mail-groups-root", true, "")
|
|
_, templatesTok := env.admin(t, "mail-groups-tmpl", false, `{"system.manage_mail_templates":1}`)
|
|
_, layoutsTok := env.admin(t, "mail-groups-lay", false, `{"system.manage_mail_layouts":1}`)
|
|
|
|
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
|
|
baseID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
|
|
enID := env.mailRowID(t, postcard.TemplatesTable, blogWelcomeEn)
|
|
deID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-de")
|
|
basePath := fmt.Sprintf("%s/%d", mailTemplatesPath, baseID)
|
|
dePath := fmt.Sprintf("%s/%d", mailTemplatesPath, deID)
|
|
file, _ := mailEditor(t, env).Catalog().Template(blogWelcome)
|
|
|
|
// The default locale gets no row: the base file is its version.
|
|
var plRows int64
|
|
env.gdb.Raw(`SELECT COUNT(*) FROM `+postcard.TemplatesTable+` WHERE code = ?`, blogWelcome+"-pl").Scan(&plRows)
|
|
if plRows != 0 {
|
|
t.Fatal("the default locale pl has a row of its own")
|
|
}
|
|
|
|
t.Run("one_row_per_template", func(t *testing.T) {
|
|
row := welcomeListRow(t, env, root, "")
|
|
if row == nil || row["customized_locales"] != "" || row["_states"] != "[]" {
|
|
t.Fatalf("fresh welcome row = %v", row)
|
|
}
|
|
if welcomeListRow(t, env, root, "?filter[status]=not_customized") == nil || welcomeListRow(t, env, root, "?filter[status]=customized") != nil {
|
|
t.Fatal("status filter on a fresh group")
|
|
}
|
|
})
|
|
|
|
t.Run("variants", func(t *testing.T) {
|
|
show := env.expect(t, http.StatusOK, http.MethodGet, basePath, root, nil)
|
|
variants := localeVariants(t, show)
|
|
if got := variantSummary(variants); got != "Default[]* de[] en[]" {
|
|
t.Fatalf("welcome variants = %s", got)
|
|
}
|
|
wantIDs := []uint{baseID, deID, enID}
|
|
wantLocales := []string{"", "de", "en"}
|
|
for i, v := range variants {
|
|
if uint(v["id"].(float64)) != wantIDs[i] || v["locale"] != wantLocales[i] {
|
|
t.Errorf("variant %d = %v, want id %d locale %q", i, v, wantIDs[i], wantLocales[i])
|
|
}
|
|
}
|
|
// Labels and states are translated in the request language.
|
|
pl := localeVariants(t, getInLanguage(t, env, basePath, root, "pl"))
|
|
if pl[0]["label"] != "Domyślny" || pl[1]["label"] != "de" {
|
|
t.Errorf("pl labels = %s", variantSummary(pl))
|
|
}
|
|
// Every version of the group lists the same variants, its own current.
|
|
if got := variantSummary(localeVariants(t, env.expect(t, http.StatusOK, http.MethodGet, dePath, root, nil))); got != "Default[] de[]* en[]" {
|
|
t.Errorf("de variants = %s", got)
|
|
}
|
|
if got := variantSummary(localeVariants(t, env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, enID), root, nil))); got != "Default[] de[] en[]*" {
|
|
t.Errorf("en variants = %s", got)
|
|
}
|
|
})
|
|
|
|
t.Run("fallback_shows_default_version", func(t *testing.T) {
|
|
de := dataOf(env.expect(t, http.StatusOK, http.MethodGet, dePath, root, nil))
|
|
if de["subject"] != file.Subject || de["body"] != file.Body || fmt.Sprint(de["layout"]) != fmt.Sprint(layoutID) {
|
|
t.Fatalf("not customized de = %v, want the base file", de)
|
|
}
|
|
info := partialText(t, env, mailTemplatesPath, "info", root, deID)
|
|
if !strings.Contains(info, "Locale de has no file of its own") || !strings.Contains(info, "views/mail/welcome.htm") {
|
|
t.Errorf("de info = %s", info)
|
|
}
|
|
version := partialText(t, env, mailTemplatesPath, "file_version", root, deID)
|
|
if !strings.Contains(version, "dzięki za rejestrację") || strings.Contains(version, "summer-diff__add") {
|
|
t.Errorf("not customized de file version = %s, want the base file without differences", version)
|
|
}
|
|
})
|
|
|
|
t.Run("save_then_send", func(t *testing.T) {
|
|
env.expect(t, http.StatusOK, http.MethodPut, dePath, root, templateBody("Willkommen, {{ .name }}", "Hallo **{{ .name }}**.", layoutID))
|
|
row := welcomeListRow(t, env, root, "")
|
|
if row["customized_locales"] != "de" || row["_states"] != "[customized]" {
|
|
t.Fatalf("welcome row after the de save = %v", row)
|
|
}
|
|
if welcomeListRow(t, env, root, "?filter[status]=customized") == nil || welcomeListRow(t, env, root, "?filter[status]=not_customized") != nil {
|
|
t.Error("status filter does not follow the de customization")
|
|
}
|
|
if got := sendGrace(t, env, blogWelcome+"-de"); got.Subject != "Willkommen, Grace" || !strings.Contains(got.HTML, "Hallo <strong>Grace</strong>") {
|
|
t.Errorf("welcome-de sent %q / %q", got.Subject, got.HTML)
|
|
}
|
|
if got := sendGrace(t, env, blogWelcome); got.Subject != "Witaj, Grace" {
|
|
t.Errorf("welcome sent %q, want the base file", got.Subject)
|
|
}
|
|
if got := variantSummary(localeVariants(t, env.expect(t, http.StatusOK, http.MethodGet, basePath, root, nil))); got != "Default[]* de[Customized] en[]" {
|
|
t.Errorf("variants after the de save = %s", got)
|
|
}
|
|
version := partialText(t, env, mailTemplatesPath, "file_version", root, deID)
|
|
if !strings.Contains(version, "summer-diff__add") || !strings.Contains(version, "Willkommen") || !strings.Contains(version, "Witaj") {
|
|
t.Errorf("customized de file version does not compare with the base file: %s", version)
|
|
}
|
|
})
|
|
|
|
// The base file changes in a second process on the same database.
|
|
files := mailBlogFiles()
|
|
files["views/mail/welcome.htm"] = &fstest.MapFile{Data: []byte(`subject = "Witaj, {{ .name }}"
|
|
description = "Sent after registration"
|
|
layout = "blog"
|
|
sample.name = "Ada"
|
|
==
|
|
Cześć **{{ .name }}**, dzięki za rejestrację na blogu.
|
|
`)}
|
|
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true, writer: writer})
|
|
|
|
t.Run("drift_through_the_base_file", func(t *testing.T) {
|
|
row := welcomeListRow(t, next, root, "")
|
|
if row["_states"] != "[customized outdated]" {
|
|
t.Fatalf("welcome row after the base file changed = %v", row)
|
|
}
|
|
if welcomeListRow(t, next, root, "?filter[status]=outdated") == nil {
|
|
t.Error("outdated filter misses welcome")
|
|
}
|
|
if got := variantSummary(localeVariants(t, next.expect(t, http.StatusOK, http.MethodGet, dePath, root, nil))); got != "Default[] de[Customized File changed]* en[]" {
|
|
t.Errorf("de variants after the base file changed = %s", got)
|
|
}
|
|
var stored cabana.MailTemplate
|
|
if err := next.gdb.First(&stored, deID).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
newFile, _ := mailEditor(t, next).Catalog().Template(blogWelcome)
|
|
if stored.FileHash == nil || *stored.FileHash != newFile.Hash || stored.BaseHash == nil || *stored.BaseHash != file.Hash {
|
|
t.Errorf("de hashes = %v / %v, want file %s and base %s", stored.FileHash, stored.BaseHash, newFile.Hash, file.Hash)
|
|
}
|
|
if version := partialText(t, next, mailTemplatesPath, "file_version", root, deID); !strings.Contains(version, "na blogu") {
|
|
t.Errorf("de file version is not the changed base file: %s", version)
|
|
}
|
|
})
|
|
|
|
t.Run("reset", func(t *testing.T) {
|
|
next.expect(t, http.StatusOK, http.MethodPut, basePath, root, templateBody("Witamy, {{ .name }}", "Base.", layoutID))
|
|
if row := welcomeListRow(t, next, root, ""); row["customized_locales"] != "Default, de" {
|
|
t.Fatalf("welcome row after the base save = %v", row)
|
|
}
|
|
next.expect(t, http.StatusOK, http.MethodPost, dePath+"/actions/reset", root, map[string]any{})
|
|
var stored cabana.MailTemplate
|
|
if err := next.gdb.First(&stored, deID).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if stored.IsCustom || stored.BaseHash != nil {
|
|
t.Fatalf("reset de row = %+v", stored)
|
|
}
|
|
// Not customized again: de shows and sends the base customization.
|
|
de := dataOf(next.expect(t, http.StatusOK, http.MethodGet, dePath, root, nil))
|
|
if de["subject"] != "Witamy, {{ .name }}" || de["body"] != "Base." {
|
|
t.Errorf("de after reset = %v, want the default version", de)
|
|
}
|
|
if got := sendGrace(t, next, blogWelcome+"-de"); got.Subject != "Witamy, Grace" {
|
|
t.Errorf("welcome-de after reset sent %q", got.Subject)
|
|
}
|
|
if row := welcomeListRow(t, next, root, ""); row["customized_locales"] != "Default" {
|
|
t.Errorf("welcome row after the de reset = %v", row)
|
|
}
|
|
})
|
|
|
|
t.Run("ids_outside_the_group", func(t *testing.T) {
|
|
var orphan uint
|
|
if err := next.gdb.Raw(`INSERT INTO ` + postcard.TemplatesTable + ` (code, source, base_code) VALUES ('acme.gone::mail.x-de', 'acme.gone', 'acme.gone::mail.x') RETURNING id`).Scan(&orphan).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, method := range []string{http.MethodGet, http.MethodPut} {
|
|
var body any
|
|
if method == http.MethodPut {
|
|
body = templateBody("x", "y", layoutID)
|
|
}
|
|
if rec := next.call(t, method, fmt.Sprintf("%s/%d", mailTemplatesPath, orphan), root, body); rec.Code != http.StatusNotFound {
|
|
t.Errorf("%s orphan status = %d", method, rec.Code)
|
|
}
|
|
}
|
|
if rec := next.call(t, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, 99999999), root, nil); rec.Code != http.StatusNotFound {
|
|
t.Errorf("unknown id status = %d", rec.Code)
|
|
}
|
|
})
|
|
|
|
t.Run("permissions_on_fallback_rows", func(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name, token, method string
|
|
want int
|
|
}{
|
|
{"layouts-only show", layoutsTok, http.MethodGet, http.StatusForbidden},
|
|
{"layouts-only save", layoutsTok, http.MethodPut, http.StatusForbidden},
|
|
{"layouts-only reset", layoutsTok, http.MethodPost, http.StatusForbidden},
|
|
{"templates-only show", templatesTok, http.MethodGet, http.StatusOK},
|
|
{"templates-only save", templatesTok, http.MethodPut, http.StatusOK},
|
|
} {
|
|
path, body := dePath, any(nil)
|
|
switch tc.method {
|
|
case http.MethodPut:
|
|
body = templateBody("Guten Tag", "Hallo.", layoutID)
|
|
case http.MethodPost:
|
|
path, body = dePath+"/actions/reset", map[string]any{}
|
|
}
|
|
if rec := next.call(t, tc.method, path, tc.token, body); rec.Code != tc.want {
|
|
t.Errorf("%s: status %d, want %d (%s)", tc.name, rec.Code, tc.want, rec.Body.String())
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("locale_enabled_at_run_time", func(t *testing.T) {
|
|
// fr is enabled while the process runs: the switcher lists it on
|
|
// the next show, without a restart.
|
|
writer.enable("fr")
|
|
variants := localeVariants(t, next.expect(t, http.StatusOK, http.MethodGet, basePath, root, nil))
|
|
if got := variantSummary(variants); got != "Default[Customized]* de[Customized] en[] fr[]" {
|
|
t.Fatalf("variants after fr was enabled = %s", got)
|
|
}
|
|
frID := next.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-fr")
|
|
if fr := dataOf(next.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailTemplatesPath, frID), root, nil)); fr["subject"] != "Witamy, {{ .name }}" {
|
|
t.Errorf("fr = %v, want the base customization", fr)
|
|
}
|
|
// it is enabled and only the list is read: the changed locale set
|
|
// re-syncs the index, and the list keeps one row per template.
|
|
writer.enable("it")
|
|
row := welcomeListRow(t, next, root, "")
|
|
if row == nil || row["customized_locales"] != "Default, de" {
|
|
t.Fatalf("welcome row after it was enabled = %v", row)
|
|
}
|
|
next.mailRowID(t, postcard.TemplatesTable, blogWelcome+"-it")
|
|
next.mailRowID(t, postcard.TemplatesTable, blogWelcomeEn) // untouched file-backed row
|
|
})
|
|
}
|