Files
summercms/examples/hello/plugins/greeter/plugin_test.go
Jakub Zych 86969739ae feat(01-02): add optional plugin services and HasPlugin
- App-scoped typed Publish/Lookup with duplicate-provider errors
- Set plugin IDs before Register so HasPlugin sees the full set
- Greeter uses pact.OptionalMessage without importing optional
2026-09-16 13:24:30 +02:00

87 lines
2.2 KiB
Go

package greeter
import (
"bytes"
"context"
"fmt"
"io"
"os"
"strings"
"testing"
"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 testOut struct{ bytes.Buffer }
func (o *testOut) Write(p []byte) (int, error) { return o.Buffer.Write(p) }
func (o *testOut) Println(a ...any) { fmt.Fprintln(&o.Buffer, a...) }
func (o *testOut) Printf(format string, a ...any) {
fmt.Fprintf(&o.Buffer, format, a...)
}
var _ bonfire.Output = (*testOut)(nil)
var _ io.Writer = (*testOut)(nil)
type extraMsg struct{ msg string }
func (e extraMsg) Message() string { return e.msg }
func TestBootSkipsAbsentOptionalPlugin(t *testing.T) {
app := backpack.New(&compass.Config{})
app.SetPlugins([]string{"golem15.hello", "golem15.greeter"})
p := &Plugin{}
if err := p.Boot(app); err != nil {
t.Fatalf("Boot: %v", err)
}
out := runHelloCmd(t, p)
if strings.Contains(out, "hello-from-optional") {
t.Fatalf("absent optional leaked into output: %q", out)
}
if !strings.Contains(out, "extra=") {
t.Fatalf("output %q should include extra=", out)
}
}
func TestBootUsesPublishedOptionalService(t *testing.T) {
app := backpack.New(&compass.Config{})
app.SetPlugins([]string{"golem15.hello", "golem15.greeter", "golem15.optional"})
if err := app.Publish[pact.OptionalMessage](extraMsg{msg: "hello-from-optional"}); err != nil {
t.Fatalf("Publish: %v", err)
}
p := &Plugin{}
if err := p.Boot(app); err != nil {
t.Fatalf("Boot: %v", err)
}
out := runHelloCmd(t, p)
if !strings.Contains(out, "extra=hello-from-optional") {
t.Fatalf("output = %q, want extra=hello-from-optional", out)
}
}
func TestGreeterSourceDoesNotImportOptional(t *testing.T) {
body, err := os.ReadFile("plugin.go")
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), "plugins/optional") {
t.Fatal("greeter must not import the optional plugin module")
}
}
func runHelloCmd(t *testing.T, p *Plugin) string {
t.Helper()
cmds := p.Commands()
if len(cmds) == 0 {
t.Fatal("no commands")
}
var out testOut
if err := cmds[0].Run(context.Background(), nil, &out); err != nil {
t.Fatalf("Run: %v", err)
}
return strings.TrimSpace(out.String())
}