test(01-04): cover config, lifecycle, services, events and context

- Table-driven compass precedence, malformed YAML, snake_case env and concurrent reads
- Party duplicate/missing/cycle, reordered manifest, HasConfig/HasCommands discovery
- Isolated backpack services, festival panic payload omission, towel nested isolation
This commit is contained in:
Jakub Zych
2026-09-16 14:08:17 +02:00
parent 4093d4230e
commit a43c734546
6 changed files with 840 additions and 0 deletions

View File

@@ -1,9 +1,11 @@
package backpack
import (
"sync"
"testing"
"git.golem15.com/golem15/summercms/compass"
"git.golem15.com/golem15/summercms/pact"
)
type ping interface {
@@ -70,3 +72,90 @@ func TestHasPluginUsesCompleteSet(t *testing.T) {
t.Fatal("HasPlugin(golem15.missing) = true")
}
}
func TestTwoAppsIsolateHasPluginAndServices(t *testing.T) {
a := New(&compass.Config{})
b := New(&compass.Config{})
a.SetPlugins([]string{"golem15.optional"})
b.SetPlugins([]string{"golem15.hello"})
if err := a.Publish[pact.OptionalMessage](msgService{s: "from-a"}); err != nil {
t.Fatalf("Publish A: %v", err)
}
if !a.HasPlugin("golem15.optional") {
t.Fatal("app A should see optional")
}
if a.HasPlugin("golem15.hello") {
t.Fatal("app A should not see hello")
}
if !b.HasPlugin("golem15.hello") {
t.Fatal("app B should see hello")
}
if b.HasPlugin("golem15.optional") {
t.Fatal("app B should not see optional")
}
got, ok := a.Lookup[pact.OptionalMessage]()
if !ok || got.Message() != "from-a" {
t.Fatalf("app A lookup = (%v, %v)", got, ok)
}
if _, ok := b.Lookup[pact.OptionalMessage](); ok {
t.Fatal("app B must not see app A's OptionalMessage")
}
}
func TestPublishNilRejectedAndLookupStaysAbsent(t *testing.T) {
app := New(&compass.Config{})
var nilPing ping
if err := app.Publish[ping](nilPing); err == nil {
t.Fatal("expected nil publish error")
}
if _, ok := app.Lookup[ping](); ok {
t.Fatal("nil publish must not store a value")
}
}
func TestDuplicatePublishKeepsFirstValue(t *testing.T) {
app := New(&compass.Config{})
if err := app.Publish[ping](pingImpl{s: "first"}); err != nil {
t.Fatalf("Publish: %v", err)
}
if err := app.Publish[ping](pingImpl{s: "second"}); err == nil {
t.Fatal("expected duplicate error")
}
got, ok := app.Lookup[ping]()
if !ok || got.Ping() != "first" {
t.Fatalf("Lookup = (%v, %v), want first", got, ok)
}
}
func TestConcurrentLookupAndHasPlugin(t *testing.T) {
app := New(&compass.Config{})
app.SetPlugins([]string{"golem15.hello"})
if err := app.Publish[ping](pingImpl{s: "pong"}); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 80; j++ {
got, ok := app.Lookup[ping]()
if !ok || got.Ping() != "pong" {
t.Errorf("Lookup = (%v, %v)", got, ok)
return
}
if !app.HasPlugin("golem15.hello") || app.HasPlugin("golem15.missing") {
t.Error("HasPlugin concurrent mismatch")
return
}
}
}()
}
wg.Wait()
}
type msgService struct{ s string }
func (m msgService) Message() string { return m.s }

View File

@@ -3,6 +3,8 @@ package compass
import (
"os"
"path/filepath"
"strings"
"sync"
"testing"
"testing/fstest"
)
@@ -241,3 +243,298 @@ func writeConfigTree(t *testing.T, files map[string]string) string {
}
return dir
}
func TestPrecedenceIsolatesEachLayer(t *testing.T) {
pluginFS := fstest.MapFS{
"config/config.yaml": {Data: []byte("name: plugin\n")},
}
tests := []struct {
name string
plugin bool
base bool
overlay bool
env bool
persist bool
set bool
want string
}{
{name: "plugin default", plugin: true, want: "plugin"},
{name: "base over plugin", plugin: true, base: true, want: "base"},
{name: "overlay over base", plugin: true, base: true, overlay: true, want: "overlay"},
{name: "env over overlay", plugin: true, base: true, overlay: true, env: true, want: "env"},
{name: "persist over env", plugin: true, base: true, overlay: true, env: true, persist: true, want: "persist"},
{name: "set over persist", plugin: true, base: true, overlay: true, env: true, persist: true, set: true, want: "set"},
{name: "env over base without overlay", plugin: true, base: true, env: true, want: "env"},
{name: "persist over overlay without env", plugin: true, base: true, overlay: true, persist: true, want: "persist"},
{name: "set only", set: true, want: "set"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
files := map[string]string{}
if tt.base {
files["app.yaml"] = "name: base\n"
} else {
files["app.yaml"] = "other: 1\n"
}
if tt.overlay {
files["env/development/app.yaml"] = "name: overlay\n"
}
if tt.persist {
files["env/development/overrides.yaml"] = "app:\n name: persist\n"
}
dir := writeConfigTree(t, files)
environ := []string{}
if tt.env {
environ = []string{"SUMMER_APP__NAME=env"}
}
cfg, err := Open(Options{Dir: dir, Env: "development", Environ: environ})
if err != nil {
t.Fatalf("Open: %v", err)
}
if tt.plugin {
if err := cfg.MergePlugin("app", pluginFS); err != nil {
t.Fatalf("MergePlugin: %v", err)
}
}
if tt.set {
if err := cfg.Set("app.name", "set"); err != nil {
t.Fatalf("Set: %v", err)
}
}
if got := cfg.String("app.name"); got != tt.want {
t.Fatalf("app.name = %q, want %q", got, tt.want)
}
})
}
}
func TestMalformedYAMLIsRejectedByName(t *testing.T) {
tests := []struct {
name string
file string
body string
want string
}{
{name: "base section", file: "app.yaml", body: "name: [unterminated\n", want: "app.yaml"},
{name: "env overlay", file: "env/development/app.yaml", body: "name: : :\n[", want: "app.yaml"},
{name: "overrides", file: "env/development/overrides.yaml", body: "app: [\n", want: "overrides"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
files := map[string]string{"app.yaml": "name: base\n"}
files[tt.file] = tt.body
dir := writeConfigTree(t, files)
_, err := Open(Options{Dir: dir, Env: "development", Environ: []string{}})
if err == nil {
t.Fatal("expected malformed YAML error")
}
if !strings.Contains(err.Error(), tt.want) {
t.Fatalf("error %q should name %q", err, tt.want)
}
})
}
}
func TestMalformedPluginYAMLIsRejected(t *testing.T) {
dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"})
cfg, err := Open(Options{Dir: dir, Environ: []string{}})
if err != nil {
t.Fatalf("Open: %v", err)
}
fsys := fstest.MapFS{
"config/config.yaml": {Data: []byte("posts_per_page: [\n")},
}
err = cfg.MergePlugin("golem15.hello", fsys)
if err == nil {
t.Fatal("expected plugin YAML parse error")
}
if !strings.Contains(err.Error(), "golem15.hello") {
t.Fatalf("error should name plugin id, got %v", err)
}
}
func TestSnakeCaseEnvKeysStayLiteral(t *testing.T) {
dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"})
cfg, err := Open(Options{
Dir: dir,
Environ: []string{
"SUMMER_APP__FEATURE_FLAG=on",
"SUMMER_GOLEM15__HELLO__POSTS_PER_PAGE=7",
},
})
if err != nil {
t.Fatalf("Open: %v", err)
}
if got := cfg.String("app.feature_flag"); got != "on" {
t.Fatalf("feature_flag = %q, want on", got)
}
if cfg.Has("app.feature.flag") {
t.Fatal("single underscore must not split the leaf")
}
if got := cfg.Int("golem15.hello.posts_per_page"); got != 7 {
t.Fatalf("posts_per_page = %d, want 7", got)
}
if cfg.Has("golem15.hello.posts.per.page") {
t.Fatal("snake_case plugin key must stay one leaf")
}
}
func TestDotEnvDoesNotOverrideRealEnviron(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "config")
if err := os.Mkdir(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: base\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, ".env"), []byte("SUMMER_APP__NAME=from-dotenv\nSUMMER_APP__TITLE=dotenv-title\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := Open(Options{
Dir: dir,
Environ: []string{"SUMMER_APP__NAME=from-real"},
})
if err != nil {
t.Fatalf("Open: %v", err)
}
if got := cfg.String("app.name"); got != "from-real" {
t.Fatalf("name = %q, want from-real", got)
}
if got := cfg.String("app.title"); got != "dotenv-title" {
t.Fatalf("title = %q, want dotenv-title", got)
}
}
func TestDottedPluginNamespaceAndTypedSection(t *testing.T) {
dir := writeConfigTree(t, map[string]string{
"app.yaml": "name: hello-app\n",
"golem15.hello.yaml": "from_app: true\n",
})
cfg, err := Open(Options{Dir: dir, Environ: []string{}})
if err != nil {
t.Fatalf("Open: %v", err)
}
fsys := fstest.MapFS{
"config/config.yaml": {Data: []byte("posts_per_page: 10\nshow_author: true\n")},
"config/settings.yaml": {Data: []byte("theme: dark\n")},
}
if err := cfg.MergePlugin("golem15.hello", fsys); err != nil {
t.Fatalf("MergePlugin: %v", err)
}
if got := cfg.Int("golem15.hello.posts_per_page"); got != 10 {
t.Fatalf("posts_per_page = %d, want 10", got)
}
if got := cfg.String("golem15.hello.settings.theme"); got != "dark" {
t.Fatalf("settings.theme = %q, want dark", got)
}
if !cfg.Bool("golem15.hello.from_app") {
t.Fatal("app-level dotted plugin namespace file should merge at golem15.hello")
}
var section struct {
PostsPerPage int `koanf:"posts_per_page"`
ShowAuthor bool `koanf:"show_author"`
FromApp bool `koanf:"from_app"`
}
if err := cfg.LoadSection("golem15.hello", &section); err != nil {
t.Fatalf("LoadSection: %v", err)
}
if section.PostsPerPage != 10 || !section.ShowAuthor || !section.FromApp {
t.Fatalf("LoadSection = %+v", section)
}
}
func TestSetPersistReloadRoundTrip(t *testing.T) {
dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\n"})
cfg, err := Open(Options{Dir: dir, Env: "development", Environ: []string{}})
if err != nil {
t.Fatalf("Open: %v", err)
}
if err := cfg.Set("app.name", "runtime"); err != nil {
t.Fatalf("Set: %v", err)
}
if err := cfg.Persist(); err != nil {
t.Fatalf("Persist: %v", err)
}
body, err := os.ReadFile(filepath.Join(dir, "env", "development", "overrides.yaml"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), "runtime") {
t.Fatalf("overrides missing runtime value: %s", body)
}
if err := cfg.Set("app.name", "unsaved"); err != nil {
t.Fatalf("Set unsaved: %v", err)
}
if err := cfg.Reload(); err != nil {
t.Fatalf("Reload: %v", err)
}
if got := cfg.String("app.name"); got != "runtime" {
t.Fatalf("after Reload, name = %q, want persisted runtime", got)
}
}
func TestConcurrentReadsWhileSet(t *testing.T) {
dir := writeConfigTree(t, map[string]string{"app.yaml": "name: base\ncount: 1\n"})
cfg, err := Open(Options{Dir: dir, Environ: []string{}})
if err != nil {
t.Fatalf("Open: %v", err)
}
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 80; j++ {
_ = cfg.String("app.name")
_ = cfg.Int("app.count")
_ = cfg.Bool("app.debug")
_ = cfg.Has("app.name")
_, _ = cfg.Lookup("app.name")
var section struct {
Name string `koanf:"name"`
}
_ = cfg.LoadSection("app", &section)
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 80; j++ {
if err := cfg.Set("app.count", j); err != nil {
t.Errorf("Set: %v", err)
return
}
}
}()
wg.Wait()
if !cfg.Has("app.name") {
t.Fatal("app.name missing after concurrent access")
}
}
func TestOpenRejectsEmptyDir(t *testing.T) {
_, err := Open(Options{})
if err == nil {
t.Fatal("expected empty dir error")
}
}
func TestSUMMER_ENVDoesNotEnterConfigTree(t *testing.T) {
dir := writeConfigTree(t, map[string]string{
"app.yaml": "name: base\n",
"env/development/app.yaml": "name: dev\n",
})
cfg, err := Open(Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
if err != nil {
t.Fatalf("Open: %v", err)
}
if cfg.Has("env") || cfg.Has("SUMMER_ENV") {
t.Fatal("SUMMER_ENV must not become a config key")
}
if cfg.String("app.name") != "dev" {
t.Fatalf("name = %q, want dev", cfg.String("app.name"))
}
}

View File

@@ -4,6 +4,8 @@ import (
"context"
"errors"
"strings"
"sync"
"sync/atomic"
"testing"
)
@@ -164,3 +166,109 @@ func TestBusesAreIsolated(t *testing.T) {
t.Fatal("bus B should not invoke bus A's listeners")
}
}
func TestConcurrentIndependentAppBuses(t *testing.T) {
a := New()
b := New()
var aCount, bCount atomic.Int64
a.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error {
aCount.Add(1)
return nil
})
b.Listen[*evt]("golem15.b", func(ctx context.Context, e *evt) error {
bCount.Add(1)
return nil
})
var wg sync.WaitGroup
const n = 40
for i := 0; i < n; i++ {
wg.Add(2)
go func() {
defer wg.Done()
if err := a.Fire(context.Background(), &evt{}); err != nil {
t.Errorf("bus A: %v", err)
}
}()
go func() {
defer wg.Done()
if err := b.Fire(context.Background(), &evt{}); err != nil {
t.Errorf("bus B: %v", err)
}
}()
}
wg.Wait()
if aCount.Load() != n || bCount.Load() != n {
t.Fatalf("counts a=%d b=%d, want %d each", aCount.Load(), bCount.Load(), n)
}
}
func TestPanicRecoveryOmitsEventPayload(t *testing.T) {
bus := New()
bus.Listen[*evt]("golem15.boom", func(ctx context.Context, e *evt) error {
panic("secret-payload-xyz")
})
event := &evt{data: map[string]any{"secret": "classified"}}
err := bus.Fire(context.Background(), event)
if err == nil {
t.Fatal("expected panic error")
}
msg := err.Error()
if !strings.Contains(msg, "golem15.boom") {
t.Fatalf("error should name owner plugin, got %v", err)
}
if strings.Contains(msg, "secret-payload-xyz") || strings.Contains(msg, "classified") {
t.Fatalf("panic recovery leaked payload: %v", err)
}
}
func TestFireWithNoListeners(t *testing.T) {
bus := New()
if err := bus.Fire(context.Background(), &evt{}); err != nil {
t.Fatalf("Fire with no listeners: %v", err)
}
}
func TestCollectWithoutCollectableReturnsEmptyMap(t *testing.T) {
type plain struct{ n int }
bus := New()
bus.Listen[plain]("golem15.a", func(ctx context.Context, e plain) error { return nil })
got, err := bus.Collect(context.Background(), plain{n: 1})
if err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Fatalf("payload = %v, want empty", got)
}
}
func TestUntilHandledNeverHandled(t *testing.T) {
bus := New()
var order []string
bus.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error {
order = append(order, "a")
return nil
})
ok, err := bus.UntilHandled(context.Background(), &evt{})
if err != nil {
t.Fatal(err)
}
if ok {
t.Fatal("expected unhandled")
}
if strings.Join(order, ",") != "a" {
t.Fatalf("order = %v, want a", order)
}
}
func TestListenNilBusOrFnIsNoop(t *testing.T) {
var bus *Bus
bus.Listen[*evt]("golem15.a", func(ctx context.Context, e *evt) error { return errors.New("should not run") })
if err := bus.Fire(context.Background(), &evt{}); err != nil {
t.Fatalf("nil bus Fire: %v", err)
}
live := New()
live.Listen[*evt]("golem15.a", nil)
if err := live.Fire(context.Background(), &evt{}); err != nil {
t.Fatalf("nil fn Fire: %v", err)
}
}

97
pact/capabilities_test.go Normal file
View File

@@ -0,0 +1,97 @@
package pact
import (
"io/fs"
"testing"
"testing/fstest"
"git.golem15.com/golem15/summercms/bonfire"
)
type configOnly struct{}
func (configOnly) ConfigFS() fs.FS {
return fstest.MapFS{"config/config.yaml": {Data: []byte("k: 1\n")}}
}
type commandsOnly struct{}
func (commandsOnly) Commands() []bonfire.Command {
return []bonfire.Command{{Name: "demo:run"}}
}
type bothCaps struct {
configOnly
commandsOnly
}
type neither struct{}
func TestOptionalCapabilitiesDiscoveredByTypeAssertion(t *testing.T) {
plugins := []any{configOnly{}, commandsOnly{}, bothCaps{}, neither{}, extraMessage{}}
var configs, commands, messages, none int
for _, p := range plugins {
_, hasCfg := p.(HasConfig)
_, hasCmd := p.(HasCommands)
_, hasMsg := p.(OptionalMessage)
if hasCfg {
configs++
}
if hasCmd {
commands++
}
if hasMsg {
messages++
}
if !hasCfg && !hasCmd && !hasMsg {
none++
}
}
if configs != 2 {
t.Fatalf("HasConfig count = %d, want 2", configs)
}
if commands != 2 {
t.Fatalf("HasCommands count = %d, want 2", commands)
}
if messages != 1 {
t.Fatalf("OptionalMessage count = %d, want 1", messages)
}
if none != 1 {
t.Fatalf("neither count = %d, want 1", none)
}
}
func TestHasConfigReturnsFilesystem(t *testing.T) {
var p HasConfig = configOnly{}
fsys := p.ConfigFS()
if fsys == nil {
t.Fatal("ConfigFS returned nil")
}
raw, err := fs.ReadFile(fsys, "config/config.yaml")
if err != nil {
t.Fatal(err)
}
if string(raw) != "k: 1\n" {
t.Fatalf("ConfigFS body = %q", raw)
}
}
func TestHasCommandsReturnsNamespacedCommand(t *testing.T) {
var p HasCommands = commandsOnly{}
cmds := p.Commands()
if len(cmds) != 1 || cmds[0].Name != "demo:run" {
t.Fatalf("Commands = %+v", cmds)
}
}
func TestOptionalMessageContract(t *testing.T) {
var msg OptionalMessage = extraMessage{s: "hello-from-optional"}
if msg.Message() != "hello-from-optional" {
t.Fatalf("Message = %q", msg.Message())
}
}
type extraMessage struct{ s string }
func (e extraMessage) Message() string { return e.s }

View File

@@ -9,7 +9,9 @@ import (
"testing/fstest"
"git.golem15.com/golem15/summercms/backpack"
"git.golem15.com/golem15/summercms/bonfire"
"git.golem15.com/golem15/summercms/compass"
"git.golem15.com/golem15/summercms/pact"
)
type tracePlugin struct {
@@ -225,3 +227,170 @@ func TestActivateRunsAllRegisterBeforeAnyBoot(t *testing.T) {
t.Fatalf("lifecycle = %v, want %v", log, want)
}
}
func TestActivateReorderedManifestStillTopoSorts(t *testing.T) {
var log []string
hello := &tracePlugin{id: "golem15.hello", log: &log}
greeter := &tracePlugin{id: "golem15.greeter", req: []string{"golem15.hello"}, log: &log}
extra := &tracePlugin{id: "golem15.extra", req: []string{"golem15.greeter"}, log: &log}
app := backpack.New(&compass.Config{})
got, err := activate(
[]Plugin{extra, greeter, hello},
app,
[]string{"golem15.extra", "golem15.hello", "golem15.greeter"},
)
if err != nil {
t.Fatalf("activate: %v", err)
}
if len(got) != 3 || got[0].ID() != "golem15.hello" || got[1].ID() != "golem15.greeter" || got[2].ID() != "golem15.extra" {
t.Fatalf("order = %v, want hello, greeter, extra", idsOf(got))
}
want := []string{
"golem15.hello:register",
"golem15.greeter:register",
"golem15.extra:register",
"golem15.hello:boot",
"golem15.greeter:boot",
"golem15.extra:boot",
}
if strings.Join(log, ",") != strings.Join(want, ",") {
t.Fatalf("lifecycle = %v, want %v", log, want)
}
}
func TestActivateDuplicateManifestIDRejected(t *testing.T) {
var log []string
p := &tracePlugin{id: "golem15.hello", log: &log}
app := backpack.New(&compass.Config{})
_, err := activate([]Plugin{p}, app, []string{"golem15.hello", "golem15.hello"})
if err == nil {
t.Fatal("expected duplicate manifest id error")
}
if !strings.Contains(err.Error(), "golem15.hello") {
t.Fatalf("error %q should name the duplicate id", err)
}
if len(log) != 0 {
t.Fatalf("lifecycle ran despite duplicate manifest: %v", log)
}
}
func TestActivateUnregisteredPluginNamesID(t *testing.T) {
app := backpack.New(&compass.Config{})
_, err := activate(nil, app, []string{"golem15.missing"})
if err == nil {
t.Fatal("expected missing registered plugin error")
}
if !strings.Contains(err.Error(), "golem15.missing") {
t.Fatalf("error %q should name the missing id", err)
}
}
func TestActivateEmptyManifestIDRejected(t *testing.T) {
var log []string
p := &tracePlugin{id: "golem15.hello", log: &log}
app := backpack.New(&compass.Config{})
_, err := activate([]Plugin{p}, app, []string{""})
if err == nil {
t.Fatal("expected empty plugin id error")
}
}
func TestActivateNilAppRejected(t *testing.T) {
_, err := Activate(nil, []string{"golem15.hello"})
if err == nil {
t.Fatal("expected nil app error")
}
}
func TestRegisterNilIsNoop(t *testing.T) {
Register(nil)
}
func TestActivateHasPluginFalseForUnselected(t *testing.T) {
var log []string
hello := &tracePlugin{id: "golem15.hello", log: &log}
opt := &tracePlugin{id: "golem15.optional", log: &log}
app := backpack.New(&compass.Config{})
if _, err := activate([]Plugin{hello, opt}, app, []string{"golem15.hello"}); err != nil {
t.Fatalf("activate: %v", err)
}
if !app.HasPlugin("golem15.hello") {
t.Fatal("selected plugin must be present")
}
if app.HasPlugin("golem15.optional") {
t.Fatal("unselected registered plugin must not appear in HasPlugin")
}
}
type commandsPlugin struct {
tracePlugin
}
func (p *commandsPlugin) Commands() []bonfire.Command {
return []bonfire.Command{{
Name: "demo:run",
Description: "demo command",
}}
}
func TestActivateDiscoversHasConfigAndHasCommands(t *testing.T) {
var log []string
var got int
cfgPlugin := &configPlugin{
id: "golem15.hello",
got: &got,
fsys: fstest.MapFS{
"config/config.yaml": {Data: []byte("posts_per_page: 4\n")},
},
}
cmdPlugin := &commandsPlugin{tracePlugin: tracePlugin{id: "golem15.demo", log: &log}}
plain := &tracePlugin{id: "golem15.plain", log: &log}
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: app\n"), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := compass.Load(dir)
if err != nil {
t.Fatalf("Load: %v", err)
}
app := backpack.New(cfg)
gotPlugins, err := activate([]Plugin{cfgPlugin, cmdPlugin, plain}, app, []string{"golem15.hello", "golem15.demo", "golem15.plain"})
if err != nil {
t.Fatalf("activate: %v", err)
}
if got != 4 {
t.Fatalf("HasConfig value during Register = %d, want 4", got)
}
var sawConfig, sawCommands, sawPlainCommands bool
for _, p := range gotPlugins {
if _, ok := p.(pact.HasConfig); ok && p.ID() == "golem15.hello" {
sawConfig = true
}
if hc, ok := p.(pact.HasCommands); ok {
if p.ID() == "golem15.demo" {
cmds := hc.Commands()
if len(cmds) != 1 || cmds[0].Name != "demo:run" {
t.Fatalf("HasCommands commands = %+v", cmds)
}
sawCommands = true
}
if p.ID() == "golem15.plain" {
sawPlainCommands = true
}
}
}
if !sawConfig {
t.Fatal("golem15.hello should satisfy HasConfig")
}
if !sawCommands {
t.Fatal("golem15.demo should satisfy HasCommands")
}
if sawPlainCommands {
t.Fatal("plain plugin must not satisfy HasCommands")
}
if _, ok := any(plain).(pact.HasConfig); ok {
t.Fatal("plain plugin must not satisfy HasConfig")
}
}

View File

@@ -4,6 +4,7 @@ import (
"context"
"os"
"strings"
"sync"
"testing"
)
@@ -33,6 +34,85 @@ func TestContextAccessorsRoundTrip(t *testing.T) {
}
}
func TestNestedContextIsolation(t *testing.T) {
parent := WithActor(context.Background(), "parent")
parent = WithOrganization(parent, "org-parent")
child := WithActor(parent, "child")
child = WithCollection(child, "col-child")
child = WithLocale(child, "pl")
if got, ok := Actor(parent); !ok || got != "parent" {
t.Fatalf("parent Actor mutated: (%q, %v)", got, ok)
}
if got, ok := Actor(child); !ok || got != "child" {
t.Fatalf("child Actor = (%q, %v)", got, ok)
}
if got, ok := Organization(child); !ok || got != "org-parent" {
t.Fatalf("child should inherit organization, got (%q, %v)", got, ok)
}
if _, ok := Collection(parent); ok {
t.Fatal("collection leaked to parent")
}
if _, ok := Locale(parent); ok {
t.Fatal("locale leaked to parent")
}
if got, ok := Collection(child); !ok || got != "col-child" {
t.Fatalf("child Collection = (%q, %v)", got, ok)
}
}
func TestNilContextAccessors(t *testing.T) {
if _, ok := Actor(nil); ok {
t.Fatal("Actor(nil) should be absent")
}
if _, ok := Organization(nil); ok {
t.Fatal("Organization(nil) should be absent")
}
if _, ok := Collection(nil); ok {
t.Fatal("Collection(nil) should be absent")
}
if _, ok := Locale(nil); ok {
t.Fatal("Locale(nil) should be absent")
}
ctx := WithActor(nil, "user-1")
if got, ok := Actor(ctx); !ok || got != "user-1" {
t.Fatalf("WithActor(nil) = (%q, %v)", got, ok)
}
}
func TestConcurrentContextAccessors(t *testing.T) {
ctx := WithActor(context.Background(), "user-1")
ctx = WithOrganization(ctx, "org-9")
ctx = WithCollection(ctx, "col-3")
ctx = WithLocale(ctx, "pl")
var wg sync.WaitGroup
for i := 0; i < 16; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < 80; j++ {
if got, ok := Actor(ctx); !ok || got != "user-1" {
t.Errorf("Actor = (%q, %v)", got, ok)
return
}
if got, ok := Organization(ctx); !ok || got != "org-9" {
t.Errorf("Organization = (%q, %v)", got, ok)
return
}
if got, ok := Collection(ctx); !ok || got != "col-3" {
t.Errorf("Collection = (%q, %v)", got, ok)
return
}
if got, ok := Locale(ctx); !ok || got != "pl" {
t.Errorf("Locale = (%q, %v)", got, ok)
return
}
}
}()
}
wg.Wait()
}
func TestNoPackageGlobalRequestState(t *testing.T) {
entries, err := os.ReadDir(".")
if err != nil {