Files
summercms/modules/cabana/companions_smoke_test.go
Jakub Zych 0cdff4c258 feat(17-01): menu item type registry and dependent dropdown binding
- pact: HasMenuItemTypes, MenuItemType, MenuItemReference, MenuItemResolve,
  ResolvedMenuItem, MenuItemAlternate, DependentOptionsProvider,
  DependentOptionSet; Option gains Depth (omitempty)
- signpost (new module): boot-time registry with fail-loud key and pattern
  checks, layered URL patterns incl. PatternFrom for list types, host
  overrides at menu_items.patterns, Resolve and ReferenceOptions
- party: signpost.Activate after postcard, before Boot
- cabana: dependsOn on dropdowns (boot checks, controller-only), GET
  fields/{field}/dependent-options with swag, inventories, conformance case
- companions fixture, TestSignpostSmoke, TestCompanionsDependentSmoke, docs
2026-10-12 15:09:14 +02:00

226 lines
9.0 KiB
Go

package cabana_test
import (
"context"
"encoding/json"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/cabana"
"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/phrasebook"
"git.golem15.com/golem15/summercms/modules/signpost"
"git.golem15.com/golem15/summercms/modules/surf"
"gorm.io/gorm"
)
// companionsDir is the neutral acme.companions fixture plugin tree of the
// Phase 17 cabana features: a dependent reference dropdown fed by the menu
// item type registry.
const companionsDir = "testdata/companions"
// companionsLink is the fixture model of the links controller.
type companionsLink struct {
ID uint `gorm:"column:id;primaryKey"`
Title string `gorm:"column:title"`
Type *string `gorm:"column:type"`
Reference *string `gorm:"column:reference"`
}
func (companionsLink) TableName() string { return "cabana_companions_links" }
func (companionsLink) Fillable() []string { return []string{"title", "type", "reference"} }
func (companionsLink) Rules() map[string]string { return map[string]string{"title": "required"} }
// companionsModels are the fixture tables, dropped and recreated per env.
func companionsModels() []any { return []any{&companionsLink{}} }
// companionsEcho resolves an item to its layered pattern.
func companionsEcho(_ context.Context, in pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
return &pact.ResolvedMenuItem{Title: in.Type, URL: in.Pattern, Alternates: []pact.MenuItemAlternate{{Locale: "en", URL: in.Pattern}}}, nil
}
// companionsPlugin registers two menu item types (acme-page with a two-level
// reference tree, acme-list without references) and the links controller.
type companionsPlugin struct{ app *backpack.App }
func (companionsPlugin) ID() string { return "acme.companions" }
func (companionsPlugin) Requires() []string { return nil }
func (companionsPlugin) Register(*backpack.App) error { return nil }
func (companionsPlugin) Boot(*backpack.App) error { return nil }
func (companionsPlugin) AdminFS() fs.FS { return os.DirFS(companionsDir) }
func (p companionsPlugin) AdminControllers() []pact.AdminController {
return []pact.AdminController{companionsLinks{app: p.app}}
}
func (companionsPlugin) Permissions() []pact.Permission {
return []pact.Permission{{Code: "acme.companions.access", Roles: []string{"developer"}}}
}
func (companionsPlugin) MenuItemTypes() []pact.MenuItemType {
return []pact.MenuItemType{
{Key: "acme-page", Label: "Page", DefaultPattern: "/:slug", Resolve: companionsEcho,
References: func(context.Context) ([]pact.MenuItemReference, error) {
return []pact.MenuItemReference{{Value: "1", Label: "Home", Items: []pact.MenuItemReference{{Value: "2", Label: "About"}}}}, nil
}},
{Key: "acme-list", Label: "All pages", DefaultPattern: "/:slug", PatternFrom: "acme-page", Resolve: companionsEcho},
}
}
var (
_ pact.HasMenuItemTypes = companionsPlugin{}
_ pact.DependentOptionsProvider = companionsLinks{}
_ pact.DropdownOptionsProvider = companionsLinks{}
)
// companionsLinks is the links controller: its type dropdown offers the
// built-in url plus every registered menu item type, and its reference
// dropdown depends on type through signpost.ReferenceOptions.
type companionsLinks struct{ app *backpack.App }
func (companionsLinks) ID() string { return "acme.companions.links" }
func (companionsLinks) ModelName() string { return "Link" }
func (companionsLinks) ConfigDir() string { return "controllers/links" }
func (companionsLinks) RequiredPermissions() []string { return []string{"acme.companions.access"} }
func (companionsLinks) NewRecord() any { return &companionsLink{} }
func (c companionsLinks) registry() *signpost.Registry {
if c.app == nil {
return nil
}
reg, _ := c.app.Lookup[*signpost.Registry]()
return reg
}
func (c companionsLinks) DropdownOptions(string) []pact.Option {
out := []pact.Option{{Value: "url", Label: "URL"}}
for _, t := range c.registry().Types() {
out = append(out, pact.Option{Value: t.Key, Label: t.Label})
}
return out
}
func (c companionsLinks) DependentOptions(ctx context.Context, _ string, values map[string]any) (pact.DependentOptionSet, error) {
typ, _ := values["type"].(string)
return signpost.ReferenceOptions(ctx, c.registry(), typ)
}
// newCompanionsEnv boots the acme.companions fixture alone on Postgres, with
// the menu item type registry activated, and signs an administrator in.
func newCompanionsEnv(t *testing.T) *conformEnv {
t.Helper()
gdb := adminGorm(t)
resetCompanions(t, gdb)
login := "companions-" + filepath.Base(t.TempDir())
insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false)
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: cabana-companions\nlocale: en\nfallback_locale: en\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=" + adminTestSecret}})
if err != nil {
t.Fatal(err)
}
for key, value := range map[string]any{"http.body_limits.default_bytes": 1048576, "http.body_limits.upload_bytes": 1048576} {
if err := cfg.Set(key, value); err != nil {
t.Fatal(err)
}
}
app := backpack.New(cfg)
if err := lagoon.Publish(app, adminSQL, gdb); err != nil {
t.Fatal(err)
}
plugins := []party.Plugin{companionsPlugin{app: app}}
if err := phrasebook.Activate(app, plugins); err != nil {
t.Fatal(err)
}
if err := signpost.Activate(app, plugins); err != nil {
t.Fatal(err)
}
h, err := surf.Assemble(app, plugins)
if err != nil {
t.Fatal(err)
}
env := &conformEnv{h: h, db: gdb, login: login}
if rec := env.send(t, http.MethodPost, "/auth/login", map[string]string{"login": login, "password": adminTestPassword}, false); rec.Code != http.StatusOK {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
return env
}
// resetCompanions drops and recreates the fixture tables.
func resetCompanions(t *testing.T, gdb *gorm.DB) {
t.Helper()
if err := gdb.Migrator().DropTable(companionsModels()...); err != nil {
t.Fatal(err)
}
if err := gdb.AutoMigrate(companionsModels()...); err != nil {
t.Fatal(err)
}
}
// dependentOptionsPath is the dependent-options route of a links field for
// one value of its type sibling.
func dependentOptionsPath(field, typ string) string {
path := "/acme/companions/links/fields/" + field + "/dependent-options"
if typ != "" {
path += "?" + url.Values{"values[type]": {typ}}.Encode()
}
return path
}
// TestCompanionsDependentSmoke checks the D-08 binding end to end: the
// reference dropdown of the links form lists the references of the menu item
// type chosen in its type sibling, served from the registry with depths.
func TestCompanionsDependentSmoke(t *testing.T) {
e := newCompanionsEnv(t)
decode := func(t *testing.T, field, typ string) cabana.AdminDependentOptionsResult {
t.Helper()
rec := e.send(t, http.MethodGet, dependentOptionsPath(field, typ), nil, true)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var body cabana.Envelope[cabana.AdminDependentOptionsResult]
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
return body.Data
}
page := decode(t, "reference", "acme-page")
if !page.Applies || len(page.Options) != 2 || page.Options[0] != (cabana.AdminDependentOption{Value: "1", Label: "Home", Depth: 0}) || page.Options[1] != (cabana.AdminDependentOption{Value: "2", Label: "About", Depth: 1}) {
t.Fatalf("acme-page options = %+v", page)
}
list := decode(t, "reference", "acme-list")
if list.Applies || list.Options == nil || len(list.Options) != 0 {
t.Fatalf("acme-list options = %+v", list)
}
if none := decode(t, "reference", ""); none.Applies {
t.Fatalf("no type options = %+v", none)
}
if rec := e.send(t, http.MethodGet, dependentOptionsPath("title", "acme-page"), nil, true); rec.Code != http.StatusNotFound {
t.Fatalf("non-dependent field status=%d body=%s", rec.Code, rec.Body.String())
}
if rec := e.send(t, http.MethodGet, dependentOptionsPath("reference", "acme-page"), nil, false); rec.Code != http.StatusUnauthorized {
t.Fatalf("anonymous status=%d body=%s", rec.Code, rec.Body.String())
}
schema := e.send(t, http.MethodGet, "/acme/companions/links/schema/form", nil, true)
var form cabana.Envelope[cabana.FormView]
if err := json.Unmarshal(schema.Body.Bytes(), &form); err != nil {
t.Fatal(err)
}
found := false
for _, field := range form.Data.Fields {
if field.Name == "reference" {
found = field.DependsOn == "type" && len(field.Options) == 0
}
}
if !found {
t.Fatalf("form schema does not carry dependsOn: %s", schema.Body.String())
}
}