test(cabana): unit tests for mail permissions, save validation, drift, reset, layout delete and test send

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-13 14:14:08 +01:00
parent 659969b9ac
commit cd20540f13
7 changed files with 603 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
package cabana_test
import (
"strings"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/modules/cabana"
)
// TestMailFieldSchemaPlacement pins mailImages placement and language values
// through CompileForm (companion to TestMailFieldSchema in mail_unit_test.go).
func TestMailFieldSchemaPlacement(t *testing.T) {
ctl := stubMailFieldController{}
fsys := fstest.MapFS{
"controllers/mail/config_form.yaml": {Data: []byte("name: mail\nform: ~/plugins/acme/mail/models/draft/fields.yaml\nmodelClass: Draft\n")},
"models/draft/fields.yaml": {Data: []byte(`fields:
body:
type: markdown
mailImages: true
note:
type: codeeditor
language: text
`)},
}
schema, err := cabana.CompileForm("acme.mail", ctl, fsys)
if err != nil {
t.Fatal(err)
}
var sawMarkdown, sawText bool
for _, f := range schema.Fields {
if f.Name == "body" && f.Type == "markdown" && f.MailImages != nil && *f.MailImages {
sawMarkdown = true
}
if f.Name == "note" && f.Language == "text" {
sawText = true
}
}
if !sawMarkdown || !sawText {
t.Fatalf("fields = %+v", schema.Fields)
}
_, err = cabana.CompileForm("acme.mail", ctl, fstest.MapFS{
"controllers/mail/config_form.yaml": {Data: []byte("name: mail\nform: ~/plugins/acme/mail/models/draft/fields.yaml\nmodelClass: Draft\n")},
"models/draft/fields.yaml": {Data: []byte(`fields:
body:
type: codeeditor
language: javascript
`)},
})
if err == nil || !strings.Contains(err.Error(), "html, css or text") {
t.Fatalf("err = %v", err)
}
}

View File

@@ -0,0 +1,150 @@
package cabana_test
import (
"fmt"
"net/http"
"strings"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/modules/postcard"
)
func TestMailSave(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, tok := env.admin(t, "mail-save", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, tmplID)
before := env.expect(t, http.StatusOK, http.MethodGet, path, tok, nil)
beforeSub := fmt.Sprint(before["data"].(map[string]any)["subject"])
cases := []struct {
name string
body map[string]any
want string
}{
{"parse", map[string]any{"subject": "Hi", "body": "Hello {{ .name", "layout": layoutID}, "body"},
{"render", map[string]any{"subject": "Hi", "body": "{{ len 5 }}", "layout": layoutID}, "body"},
{"unsafe", map[string]any{"subject": "Hi", "body": "Hi\n\n<script>x</script>", "layout": layoutID}, "body"},
{"subject_line", map[string]any{"subject": "Hi\nthere", "body": "Fine.", "layout": layoutID}, "subject"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := env.call(t, http.MethodPut, path, tok, tc.body)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status=%d want 422 body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), tc.want) {
t.Fatalf("422 body missing field %q: %s", tc.want, rec.Body.String())
}
after := env.expect(t, http.StatusOK, http.MethodGet, path, tok, nil)
if fmt.Sprint(after["data"].(map[string]any)["subject"]) != beforeSub {
t.Fatal("row changed after refused save")
}
})
}
t.Run("brand_colour", func(t *testing.T) {
rec := env.call(t, http.MethodPut, "/settings/mail_brand", tok, map[string]any{"button_primary_bg": "red"})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("brand 422 = %d %s", rec.Code, rec.Body.String())
}
})
t.Run("logo_missing", func(t *testing.T) {
rec := env.call(t, http.MethodPut, "/settings/mail_brand", tok, map[string]any{"logo_file_id": 999999})
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("status=%d want 422", rec.Code)
}
})
}
func TestMailDrift(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, tok := env.admin(t, "mail-drift", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcomeEn)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, tmplID)
env.expect(t, http.StatusOK, http.MethodPut, path, tok, map[string]any{
"subject": "Custom {{ .name }}", "body": "Custom body for {{ .name }}", "layout": layoutID,
})
// A second process boots with a changed file and syncs the index.
files := mailBlogFiles()
files["views/mail/welcome-en.htm"] = &fstest.MapFile{Data: []byte(`subject = "Welcome, {{ .name }}"
description = "Sent after registration (English)"
layout = "blog"
sample.name = "Ada"
==
Hi **{{ .name }}**, thanks for joining the Acme blog.
`)}
next := newMailScreensEnvWith(t, mailEnvOptions{files: files, keep: true})
list := next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath+"?filter[status]=outdated", tok, nil)
rows := listRows(t, list)
if rows[blogWelcomeEn] == nil {
t.Fatalf("outdated filter missing row: %#v", list["data"])
}
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), tmplID)); got != "[customized outdated]" {
t.Fatalf("drifted row states = %s", got)
}
next.expect(t, http.StatusOK, http.MethodPut, path, tok, map[string]any{
"subject": "Custom again {{ .name }}", "body": "Custom body for {{ .name }}", "layout": layoutID,
})
if got := fmt.Sprint(rowStates(next.expect(t, http.StatusOK, http.MethodGet, mailTemplatesPath, tok, nil), tmplID)); got != "[customized]" {
t.Fatalf("reviewed row states = %s", got)
}
}
func TestMailReset(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, tok := env.admin(t, "mail-reset", true, "")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
path := fmt.Sprintf("%s/%d", mailTemplatesPath, tmplID)
env.expect(t, http.StatusOK, http.MethodPut, path, tok, map[string]any{
"subject": "Custom", "body": "Body", "layout": layoutID,
})
env.expect(t, http.StatusOK, http.MethodPost, path+"/actions/reset", tok, map[string]any{})
got := env.expect(t, http.StatusOK, http.MethodGet, path, tok, nil)
if fmt.Sprint(got["data"].(map[string]any)["subject"]) == "Custom" {
t.Fatal("subject still custom after reset")
}
}
func TestMailLayoutDelete(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, tok := env.admin(t, "mail-laydel", true, "")
if err := env.gdb.Exec(`INSERT INTO ` + postcard.LayoutsTable + ` (code, source, name, content_html, content_text, is_custom)
VALUES ('promo-del', NULL, 'Promo Del', '<div>{{ .Content }}</div>', '{{ .Content }}', TRUE)`).Error; err != nil {
t.Fatal(err)
}
id := env.mailRowID(t, postcard.LayoutsTable, "promo-del")
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
if err := env.gdb.Exec(`UPDATE `+postcard.TemplatesTable+` SET layout_id = ?, is_custom = TRUE WHERE id = ?`, id, tmplID).Error; err != nil {
t.Fatal(err)
}
rec := env.call(t, http.MethodDelete, fmt.Sprintf("%s/%d", mailLayoutsPath, id), tok, nil)
if rec.Code != http.StatusForbidden {
t.Fatalf("in-use delete status=%d want 403 body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "Promo Del") && !strings.Contains(rec.Body.String(), "1") {
t.Fatalf("403 missing name/count: %s", rec.Body.String())
}
fileID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
form := env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("%s/%d", mailLayoutsPath, fileID), tok, nil)
meta, _ := form["meta"].(map[string]any)
if deletable, ok := meta["deletable"].(bool); ok && deletable {
t.Fatal("file layout marked deletable")
}
}
func TestMailBrand(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, tok := env.admin(t, "mail-brand-unit", true, "")
env.expect(t, http.StatusOK, http.MethodGet, "/settings/mail_brand", tok, nil)
env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", tok, map[string]any{"button_primary_bg": "#112233"})
env.expect(t, http.StatusUnprocessableEntity, http.MethodPut, "/settings/mail_brand", tok, map[string]any{"button_primary_bg": "nope"})
}

View File

@@ -0,0 +1,96 @@
package cabana_test
import (
"fmt"
"net/http"
"testing"
"git.golem15.com/golem15/summercms/modules/postcard"
)
func TestMailPermissions(t *testing.T) {
env := newMailScreensEnv(t, nil)
_, templatesTok := env.admin(t, "mail-perm-tmpl", false, `{"system.manage_mail_templates":1}`)
_, layoutsTok := env.admin(t, "mail-perm-lay", false, `{"system.manage_mail_layouts":1}`)
_, bothTok := env.admin(t, "mail-perm-both", false, `{"system.manage_mail_templates":1,"system.manage_mail_layouts":1}`)
_, superTok := env.admin(t, "mail-perm-super", true, "")
_, noneTok := env.admin(t, "mail-perm-none", false, `{"acme.demo.access":1}`)
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
type check struct {
name string
token string
method string
path string
body map[string]any
want int
}
checks := []check{
{"templates list templates-only", templatesTok, http.MethodGet, mailTemplatesPath, nil, http.StatusOK},
{"templates list layouts-only", layoutsTok, http.MethodGet, mailTemplatesPath, nil, http.StatusForbidden},
{"templates list none", noneTok, http.MethodGet, mailTemplatesPath, nil, http.StatusForbidden},
{"templates list super", superTok, http.MethodGet, mailTemplatesPath, nil, http.StatusOK},
{"templates list both", bothTok, http.MethodGet, mailTemplatesPath, nil, http.StatusOK},
{"layouts list layouts-only", layoutsTok, http.MethodGet, mailLayoutsPath, nil, http.StatusOK},
{"layouts list templates-only", templatesTok, http.MethodGet, mailLayoutsPath, nil, http.StatusForbidden},
{"partials list layouts-only", layoutsTok, http.MethodGet, mailPartialsPath, nil, http.StatusOK},
{"partials list templates-only", templatesTok, http.MethodGet, mailPartialsPath, nil, http.StatusForbidden},
{"branding get layouts-only", layoutsTok, http.MethodGet, "/settings/mail_brand", nil, http.StatusOK},
{"branding get templates-only", templatesTok, http.MethodGet, "/settings/mail_brand", nil, http.StatusForbidden},
{"images list both", bothTok, http.MethodGet, "/mail/images", nil, http.StatusOK},
{"images list templates-only", templatesTok, http.MethodGet, "/mail/images", nil, http.StatusOK},
{"images list none", noneTok, http.MethodGet, "/mail/images", nil, http.StatusForbidden},
{"preview template templates-only", templatesTok, http.MethodPost, "/mail/preview", map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
}, http.StatusOK},
{"preview layout templates-only", templatesTok, http.MethodPost, "/mail/preview", map[string]any{
"mode": "layout", "id": 0,
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
}, http.StatusForbidden},
{"preview layout layouts-only", layoutsTok, http.MethodPost, "/mail/preview", map[string]any{
"mode": "layout", "id": 0,
"values": map[string]any{"content_html": "{{ .Content }}", "content_text": "{{ .Content }}"},
}, http.StatusOK},
{"test send templates-only", templatesTok, http.MethodPost, "/mail/test-send", map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
}, http.StatusOK},
{"test send layouts-only template", layoutsTok, http.MethodPost, "/mail/test-send", map[string]any{
"mode": "template", "id": tmplID,
"values": map[string]any{"subject": "s", "body": "b", "layout": layoutID},
}, http.StatusForbidden},
}
for _, tc := range checks {
t.Run(tc.name, func(t *testing.T) {
env.expect(t, tc.want, tc.method, tc.path, tc.token, tc.body)
})
}
rec := mailUpload(t, env.h, templatesTok, tinyPNG(), "x.png")
if rec.Code != http.StatusForbidden {
t.Fatalf("templates-only upload status=%d want 403", rec.Code)
}
rec = mailUpload(t, env.h, layoutsTok, tinyPNG(), "y.png")
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
t.Fatalf("layouts-only upload status=%d want 200/201 body=%s", rec.Code, rec.Body.String())
}
var granted int64
if err := env.gdb.Raw(`SELECT COUNT(*) FROM backend_user_roles WHERE permissions LIKE '%system.manage_mail%' AND code NOT LIKE 'code-%'`).Scan(&granted).Error; err != nil || granted != 0 {
t.Fatalf("roles granted a mail code: %d err=%v", granted, err)
}
_ = fmt.Sprintf("%d", tmplID)
}
func tinyPNG() []byte {
return []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
0x42, 0x60, 0x82,
}
}

View File

@@ -0,0 +1,112 @@
package cabana_test
import (
"net/http"
"testing"
"time"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/postcard"
)
type fakeAttempter struct {
max int
hits map[string]int
}
func (f *fakeAttempter) Attempt(key string, max int, _ time.Duration) (bool, int, time.Duration) {
if f.hits == nil {
f.hits = map[string]int{}
}
limit := f.max
if max > 0 {
limit = max
}
f.hits[key]++
if f.hits[key] > limit {
return false, f.hits[key], 42 * time.Second
}
return true, f.hits[key], 0
}
func TestMailTestSend(t *testing.T) {
env := newMailScreensEnv(t, nil)
tmplID := env.mailRowID(t, postcard.TemplatesTable, blogWelcome)
layoutID := env.mailRowID(t, postcard.LayoutsTable, blogLayout)
values := map[string]any{"subject": "s", "body": "Hello {{ .name }}", "layout": layoutID}
t.Run("recipient_is_admin_only", func(t *testing.T) {
user, tok := env.admin(t, "mail-unit-send", true, "")
before := len(env.driver.messages())
got := env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tok, map[string]any{
"mode": "template", "id": tmplID, "values": values,
})
if got["data"].(map[string]any)["email"] != user.Email {
t.Fatalf("email = %#v", got["data"])
}
msgs := env.driver.messages()
last := msgs[len(msgs)-1]
if len(msgs) != before+1 || len(last.To) != 1 || last.To[0] != user.Email || len(last.Cc) != 0 || len(last.Bcc) != 0 {
t.Fatalf("recipients To=%v Cc=%v Bcc=%v count=%d", last.To, last.Cc, last.Bcc, len(msgs)-before)
}
})
t.Run("recipient_keys_refused", func(t *testing.T) {
_, tok := env.admin(t, "mail-unit-recip", true, "")
for _, key := range []string{"to", "email", "recipient"} {
body := map[string]any{"mode": "template", "id": tmplID, "values": values, key: "other@example.test"}
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, body)
if rec.Code != http.StatusUnprocessableEntity {
t.Fatalf("%s status=%d want 422", key, rec.Code)
}
}
})
t.Run("token_principal_refused", func(t *testing.T) {
user, _ := env.admin(t, "mail-unit-token", true, "")
plain, err := cabana.IssueTestAPIToken(env.gdb, user.ID, []string{"*"}, nil)
if err != nil {
t.Fatal(err)
}
rec := env.call(t, http.MethodPost, "/mail/test-send", plain, map[string]any{
"mode": "template", "id": tmplID, "values": values,
})
if rec.Code != http.StatusForbidden {
t.Fatalf("status=%d want 403", rec.Code)
}
})
t.Run("rate_limit_and_independence", func(t *testing.T) {
fake := &fakeAttempter{max: 5}
if err := env.app.Publish[cooler.Attempter](fake); err != nil {
t.Logf("publish Attempter: %v (using in-process fallback)", err)
}
_, tokA := env.admin(t, "mail-unit-lim-a", true, "")
_, tokB := env.admin(t, "mail-unit-lim-b", true, "")
body := map[string]any{"mode": "template", "id": tmplID, "values": values}
for i := 0; i < 5; i++ {
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokA, body)
}
rec := env.call(t, http.MethodPost, "/mail/test-send", tokA, body)
if rec.Code != http.StatusTooManyRequests {
t.Fatalf("sixth status=%d want 429 body=%s", rec.Code, rec.Body.String())
}
if rec.Header().Get("Retry-After") == "" {
t.Fatal("missing Retry-After")
}
env.expect(t, http.StatusOK, http.MethodPost, "/mail/test-send", tokB, body)
})
t.Run("driver_failure_502", func(t *testing.T) {
_, tok := env.admin(t, "mail-unit-fail", true, "")
env.driver.fail.Store(true)
t.Cleanup(func() { env.driver.fail.Store(false) })
rec := env.call(t, http.MethodPost, "/mail/test-send", tok, map[string]any{
"mode": "template", "id": tmplID, "values": values,
})
if rec.Code != http.StatusBadGateway {
t.Fatalf("status=%d want 502", rec.Code)
}
})
}

View File

@@ -0,0 +1,123 @@
package cabana_test
import (
"strings"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/modules/cabana"
"git.golem15.com/golem15/summercms/modules/postcard"
)
func TestMailLocale(t *testing.T) {
got := postcard.TemplateLocale("acme.blog::mail.welcome-en", []string{"en", "pl"})
if got != "en" {
t.Fatalf("welcome-en = %q", got)
}
got = postcard.TemplateLocale("acme.blog::mail.welcome", []string{"en", "pl"})
if got != "" {
t.Fatalf("base = %q", got)
}
got = postcard.TemplateLocale("acme.blog::mail.welcome-de", []string{"en", "pl"})
if got != "" {
t.Fatalf("unknown suffix = %q", got)
}
}
func TestMailDiff(t *testing.T) {
identical := cabana.LineDiffForTest(
[]string{"a", "b", "c"},
[]string{"a", "b", "c"},
3,
)
if identical != "" {
t.Fatalf("identical = %q", identical)
}
got := cabana.LineDiffForTest(
[]string{"a", "b", "c", "d", "e", "f", "g", "h"},
[]string{"a", "b", "c", "d", "X", "f", "g", "h"},
3,
)
if got != " b| c| d|- e|+ X| f| g| h" {
t.Fatalf("context diff = %q", got)
}
long := make([]string, 2001)
for i := range long {
long[i] = "line"
}
if got := cabana.LineDiffForTest(long, []string{"x"}, 3); got != "" {
t.Fatalf("above the cap = %q", got)
}
}
func TestMailFieldSchema(t *testing.T) {
ctl := stubMailFieldController{}
okFS := fstest.MapFS{
"controllers/mail/config_form.yaml": {Data: []byte("name: mail\nform: ~/plugins/acme/mail/models/draft/fields.yaml\nmodelClass: Draft\n")},
"models/draft/fields.yaml": {Data: []byte(`fields:
html:
type: codeeditor
language: html
mailImages: true
css:
type: codeeditor
language: css
preview:
type: mailpreview
mode: template
brand_color:
type: colorpicker
logo:
type: mailimage
`)},
}
schema, err := cabana.CompileForm("acme.mail", ctl, okFS)
if err != nil {
t.Fatal(err)
}
byName := map[string]cabana.FormField{}
for _, f := range schema.Fields {
byName[f.Name] = f
}
if byName["html"].Language != "html" || byName["html"].MailImages == nil || !*byName["html"].MailImages {
t.Fatalf("html field = %+v", byName["html"])
}
if byName["preview"].Mode != "template" {
t.Fatalf("preview mode = %q", byName["preview"].Mode)
}
if byName["brand_color"].Type != "colorpicker" || byName["logo"].Type != "mailimage" {
t.Fatalf("settings types color=%q logo=%q", byName["brand_color"].Type, byName["logo"].Type)
}
cases := []struct {
name string
fields string
want string
}{
{"language_required", "fields:\n body:\n type: codeeditor\n", "language is required"},
{"language_on_text", "fields:\n body:\n type: text\n language: html\n", "language is only valid"},
{"mailImages_on_text", "fields:\n body:\n type: text\n mailImages: true\n", "mailImages is only valid"},
{"mode_required", "fields:\n preview:\n type: mailpreview\n", "mode is required"},
{"bad_mode", "fields:\n preview:\n type: mailpreview\n mode: other\n", "must be template"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fsys := fstest.MapFS{
"controllers/mail/config_form.yaml": {Data: []byte("name: mail\nform: ~/plugins/acme/mail/models/draft/fields.yaml\nmodelClass: Draft\n")},
"models/draft/fields.yaml": {Data: []byte(tc.fields)},
}
_, err := cabana.CompileForm("acme.mail", ctl, fsys)
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("err = %v, want containing %q", err, tc.want)
}
})
}
}
type stubMailFieldController struct{}
func (stubMailFieldController) ID() string { return "acme.mail.drafts" }
func (stubMailFieldController) ModelName() string { return "Draft" }
func (stubMailFieldController) ConfigDir() string { return "controllers/mail" }

View File

@@ -14,7 +14,9 @@ import (
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/cooler"
"git.golem15.com/golem15/summercms/modules/party"
"github.com/alicebob/miniredis/v2"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
@@ -254,3 +256,58 @@ func TestBuildRouterNeverDials(t *testing.T) {
t.Fatalf("Redis was dialled %d times without installCooler", n)
}
}
func TestInstallCoolerPublishesAttempter(t *testing.T) {
t.Run("memory_publishes_neither", func(t *testing.T) {
dir := t.TempDir()
for name, body := range map[string]string{
"app.yaml": "name: cooler-mem\n",
"http.yaml": "body_limits:\n default_bytes: 1048576\n upload_bytes: 1048576\nrate_limit:\n store: memory\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
if err != nil {
t.Fatal(err)
}
app := backpack.New(cfg)
hd, err := installCooler(context.Background(), app)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = hd.Close() })
if _, ok := app.Lookup[Store](); ok {
t.Fatal("memory store must not publish surf.Store")
}
if _, ok := app.Lookup[cooler.Attempter](); ok {
t.Fatal("memory store must not publish cooler.Attempter")
}
})
t.Run("redis_publishes_same_store", func(t *testing.T) {
mr, err := miniredis.Run()
if err != nil {
t.Fatal(err)
}
t.Cleanup(mr.Close)
app := redisStoreApp(t, "redis://"+mr.Addr()+"/0")
hd, err := installCooler(context.Background(), app)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = hd.Close() })
store, ok := app.Lookup[Store]()
if !ok {
t.Fatal("redis path must publish surf.Store")
}
att, ok := app.Lookup[cooler.Attempter]()
if !ok {
t.Fatal("redis path must publish cooler.Attempter")
}
if store != att {
t.Fatalf("Attempter %T is not the published Store %T", att, store)
}
})
}