refactor: testing from the beginning. a journey in 150k lines of tests to none

This commit is contained in:
sam committed 2026-10-03 21:16:25 +10:00
1 parent ba37e37e53
commit ff424b70ac
651 files changed
-146443

No files matched your search

-300
View File
@@ -1,300 +0,0 @@
package plugin_test
import (
"go/ast"
"go/parser"
"go/token"
"maps"
"path/filepath"
"slices"
"strings"
"testing"
)
func TestEngineFamilyInspectionRejectsInvalidShapes(t *testing.T) {
t.Parallel()
tests := []struct {
name string
src string
valid bool
}{
{
name: "typed family",
src: `package fixture
type Engine interface { Name() string; Version() string; Resolve(string) (string, error) }
type Registry struct{}
func (*Registry) Register(Engine) {}
func (*Registry) Get(string) (Engine, bool) { return nil, false }
`,
valid: true,
},
{
name: "embedded typed family",
src: `package fixture
type Resolver interface { Resolve(string) (string, error) }
type Engine interface { Resolver }
type Registry struct{}
func (*Registry) Register(Engine) {}
func (*Registry) Get(string) (Engine, bool) { return nil, false }
`,
valid: true,
},
{
name: "metadata only",
src: `package fixture
type Engine interface { Name() string; Version() string }
type Registry struct{}
func (*Registry) Register(Engine) {}
func (*Registry) Get(string) (Engine, bool) { return nil, false }
`,
},
{
name: "lifecycle only",
src: `package fixture
type Engine interface {
Name() string
Version() string
Start() error
Health() string
Stop() error
}
type Registry struct{}
func (*Registry) Register(Engine) {}
func (*Registry) Get(string) (Engine, bool) { return nil, false }
`,
},
{
name: "embedded metadata only",
src: `package fixture
type Metadata interface { Name() string; Version() string }
type Engine interface { Metadata }
type Registry struct{}
func (*Registry) Register(Engine) {}
func (*Registry) Get(string) (Engine, bool) { return nil, false }
`,
},
{
name: "unrelated owner methods",
src: `package fixture
type Engine interface { Resolve(string) (string, error) }
type Registry struct{}
func (*Registry) Register(string) {}
func (*Registry) Get(string) (string, bool) { return "", false }
`,
},
{
name: "split owners",
src: `package fixture
type Engine interface { Resolve(string) (string, error) }
type Registry struct{}
func (*Registry) Register(Engine) {}
type Manager struct{}
func (*Manager) Get(string) (Engine, bool) { return nil, false }
`,
},
{
name: "pointer to engine interface",
src: `package fixture
type Engine interface { Resolve(string) (string, error) }
type Registry struct{}
func (*Registry) Register(*Engine) {}
func (*Registry) Get(string) (*Engine, bool) { return nil, false }
`,
},
{
name: "collection of engine interfaces",
src: `package fixture
type Engine interface { Resolve(string) (string, error) }
type Registry struct{}
func (*Registry) Register([]Engine) {}
func (*Registry) Get(string) ([]Engine, bool) { return nil, false }
`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
file, err := parser.ParseFile(token.NewFileSet(), tt.name+".go", tt.src, 0)
if err != nil {
t.Fatal(err)
}
families := engineFamiliesInPackage(".", ".", []*ast.File{file})
if len(families) != 1 {
t.Fatalf("found %d engine families, want 1", len(families))
}
family := families[0]
got := family.hasDomainMethod && family.hasOwner &&
family.ownerRegisters && family.ownerManages && family.singleOwner
if got != tt.valid {
t.Fatalf("family validity = %t, want %t: %+v", got, tt.valid, family)
}
})
}
}
type engineFamily struct {
packagePath string
engineName string
hasDomainMethod bool
hasOwner bool
ownerRegisters bool
ownerManages bool
singleOwner bool
}
func engineFamiliesInPackage(root, dir string, files []*ast.File) []engineFamily {
engines := make(map[string]bool)
interfaces := make(map[string]*ast.InterfaceType)
owners := make(map[string]bool)
ownerMethods := make(map[string][]*ast.FuncDecl)
for _, file := range files {
for _, decl := range file.Decls {
switch decl := decl.(type) {
case *ast.GenDecl:
for _, spec := range decl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if iface, ok := typeSpec.Type.(*ast.InterfaceType); ok {
interfaces[typeSpec.Name.Name] = iface
}
if typeSpec.Name.Name == "Registry" || typeSpec.Name.Name == "Manager" {
owners[typeSpec.Name.Name] = true
}
}
case *ast.FuncDecl:
receiver := receiverName(decl)
if receiver != "Registry" && receiver != "Manager" {
continue
}
ownerMethods[receiver] = append(ownerMethods[receiver], decl)
}
}
}
for name, iface := range interfaces {
if strings.HasSuffix(name, "Engine") {
engines[name] = hasDomainMethod(iface, interfaces, nil)
}
}
packagePath, err := filepath.Rel(root, dir)
if err != nil {
packagePath = dir
}
out := make([]engineFamily, 0, len(engines))
for name, domainMethod := range engines {
registers := false
manages := false
singleOwner := false
for owner := range owners {
ownerRegisters := ownerRegistersEngine(ownerMethods[owner], name)
ownerManages := ownerReturnsEngine(ownerMethods[owner], name)
registers = registers || ownerRegisters
manages = manages || ownerManages
singleOwner = singleOwner || ownerRegisters && ownerManages
}
out = append(out, engineFamily{
packagePath: filepath.ToSlash(packagePath),
engineName: name,
hasDomainMethod: domainMethod,
hasOwner: len(owners) > 0,
ownerRegisters: registers,
ownerManages: manages,
singleOwner: singleOwner,
})
}
return out
}
func hasDomainMethod(
iface *ast.InterfaceType,
interfaces map[string]*ast.InterfaceType,
visiting map[string]bool,
) bool {
genericMethods := []string{
"Health",
"Manifest",
"Name",
"Start",
"Stop",
"Version",
}
for _, field := range iface.Methods.List {
for _, name := range field.Names {
if _, generic := slices.BinarySearch(genericMethods, name.Name); !generic {
return true
}
}
if len(field.Names) != 0 {
continue
}
embedded, ok := field.Type.(*ast.Ident)
if !ok || visiting[embedded.Name] {
continue
}
embeddedInterface, ok := interfaces[embedded.Name]
if !ok {
continue
}
next := maps.Clone(visiting)
if next == nil {
next = make(map[string]bool)
}
next[embedded.Name] = true
if hasDomainMethod(embeddedInterface, interfaces, next) {
return true
}
}
return false
}
func receiverName(decl *ast.FuncDecl) string {
if decl.Recv == nil || len(decl.Recv.List) == 0 {
return ""
}
switch receiver := decl.Recv.List[0].Type.(type) {
case *ast.Ident:
return receiver.Name
case *ast.StarExpr:
if ident, ok := receiver.X.(*ast.Ident); ok {
return ident.Name
}
}
return ""
}
func ownerRegistersEngine(methods []*ast.FuncDecl, engineName string) bool {
for _, method := range methods {
if method.Name.Name != "Register" || method.Type.Params == nil {
continue
}
for _, field := range method.Type.Params.List {
if expressionNamesType(field.Type, engineName) {
return true
}
}
}
return false
}
func ownerReturnsEngine(methods []*ast.FuncDecl, engineName string) bool {
for _, method := range methods {
if method.Type.Results == nil {
continue
}
for _, field := range method.Type.Results.List {
if expressionNamesType(field.Type, engineName) {
return true
}
}
}
return false
}
func expressionNamesType(expr ast.Expr, typeName string) bool {
ident, ok := expr.(*ast.Ident)
return ok && ident.Name == typeName
}
-180
View File
@@ -1,180 +0,0 @@
package plugin_test
import (
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"slices"
"strings"
"testing"
)
func TestCapabilityHostContractExists(t *testing.T) {
t.Parallel()
pluginDir := filepath.Clean(".")
entries, err := os.ReadDir(pluginDir)
if err != nil {
t.Fatal(err)
}
types := make(map[string]bool)
hostMethods := make(map[string]bool)
functions := make(map[string]bool)
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".go" || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
file, err := parser.ParseFile(token.NewFileSet(), filepath.Join(pluginDir, entry.Name()), nil, 0)
if err != nil {
t.Fatal(err)
}
for _, decl := range file.Decls {
switch decl := decl.(type) {
case *ast.GenDecl:
for _, spec := range decl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if ok {
types[typeSpec.Name.Name] = true
}
}
case *ast.FuncDecl:
if receiverNameForContract(decl) == "Host" {
hostMethods[decl.Name.Name] = true
}
if decl.Recv == nil {
functions[decl.Name.Name] = true
}
}
}
}
for _, name := range []string{"Manifest", "Module", "Host"} {
if !types[name] {
t.Errorf("plugin package does not define %s", name)
}
}
for _, name := range []string{"Register", "Start", "Stop"} {
if !hostMethods[name] {
t.Errorf("plugin.Host does not define %s", name)
}
}
if !functions["AdaptLegacy"] {
t.Error("plugin package does not define AdaptLegacy")
}
}
func TestCapabilityHostContractHasNoGenericCapabilityHooks(t *testing.T) {
t.Parallel()
disallowed := []string{"AddHook", "RegisterHook", "RegisterCapability", "Service", "Services"}
slices.Sort(disallowed)
pluginType := parseNamedInterface(t, "plugin.go", "Plugin")
for _, field := range pluginType.Methods.List {
for _, name := range field.Names {
if _, found := slices.BinarySearch(disallowed, name.Name); found {
t.Errorf("plugin.Plugin contains forbidden generic hook %s", name.Name)
}
}
}
}
func TestArchiedWiresCapabilityHostLifecycle(t *testing.T) {
t.Parallel()
// The daemon composition lives in internal/app/archied, whose wiring is
// split across main.go (driver) and bootstrap.go (phase methods); the
// contract reads the whole package so the enforcement survives that
// split.
archiedDir := filepath.Join("..", "..", "internal", "app", "archied")
var text strings.Builder
entries, err := os.ReadDir(archiedDir)
if err != nil {
t.Fatal(err)
}
for _, entry := range entries {
if entry.IsDir() || filepath.Ext(entry.Name()) != ".go" || strings.HasSuffix(entry.Name(), "_test.go") {
continue
}
source, err := os.ReadFile(filepath.Join(archiedDir, entry.Name()))
if err != nil {
t.Fatal(err)
}
text.Write(source)
text.WriteString("\n")
}
wiring := text.String()
for _, required := range []string{
"plugin.NewHost()",
"plugin.AdaptLegacy(",
"capabilityHost.Register(",
"capabilityHost.Start(",
"capabilityHost.Stop(",
} {
if !strings.Contains(wiring, required) {
t.Errorf("cmd/archied does not contain capability-host wiring %q", required)
}
}
before, _, ok := strings.Cut(wiring, "capabilityHost.Start(")
if !ok {
t.Fatal("capability host Start call not found")
}
if !strings.Contains(before, "capabilityHost.Stop(") {
t.Error("capability host cleanup must be registered before Start so failed rollback cleanup is retried")
}
// The host lifecycle belongs to the composition root, which the control
// plane and gateway consume. A CapabilityHost field on the daemon would be
// assigned there and read nowhere -- the same defect PluginRegistry: had --
// so both spellings are refused.
for _, forbidden := range []string{"PluginRegistry:", "CapabilityHost:"} {
if strings.Contains(wiring, forbidden) {
t.Errorf("daemon composition carries an unread capability handle %q; the composition root owns the host lifecycle", forbidden)
}
}
}
func parseNamedInterface(t *testing.T, filename, typeName string) *ast.InterfaceType {
t.Helper()
file, err := parser.ParseFile(token.NewFileSet(), filename, nil, 0)
if err != nil {
t.Fatal(err)
}
for _, decl := range file.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range gen.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok || typeSpec.Name.Name != typeName {
continue
}
iface, ok := typeSpec.Type.(*ast.InterfaceType)
if !ok {
t.Fatalf("%s is not an interface", typeName)
}
return iface
}
}
t.Fatalf("%s not found in %s", typeName, filename)
return nil
}
func receiverNameForContract(decl *ast.FuncDecl) string {
if decl.Recv == nil || len(decl.Recv.List) == 0 {
return ""
}
switch receiver := decl.Recv.List[0].Type.(type) {
case *ast.Ident:
return receiver.Name
case *ast.StarExpr:
ident, _ := receiver.X.(*ast.Ident)
if ident != nil {
return ident.Name
}
}
return ""
}
-200
View File
@@ -1,200 +0,0 @@
package plugin_test
import (
"context"
"errors"
"slices"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/plugin"
)
// The running-state operations a live plugin load needs: Add puts one new
// module beside the running set, Replace swaps one module's implementation,
// and neither disturbs a module it is not touching.
// docs/prds/plugin-settings-live.md ("The three registries").
func TestHostAddStartsANewModuleWhileRunning(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
base := &fakeModule{manifest: validManifest("base"), events: events}
if err := host.Register(base); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
added := &fakeModule{manifest: validManifest("late", "base"), events: events}
if err := host.Add(context.Background(), added); err != nil {
t.Fatalf("Add() error = %v", err)
}
if !host.Has("late") {
t.Fatal("Add() did not register the module")
}
if got, want := events.snapshot(), []string{"start:base", "start:late"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
// The already-running set is stopped after the added module, since the
// added module came later.
if err := host.Stop(context.Background()); err != nil {
t.Fatal(err)
}
if got, want := events.snapshot(), []string{"start:base", "start:late", "stop:late", "stop:base"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
}
func TestHostAddRefusesDuplicateAndUnknownDependency(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base")}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("base")}); err == nil {
t.Fatal("Add() of a duplicate id succeeded")
}
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("dependent", "missing")}); err == nil {
t.Fatal("Add() with an unregistered dependency succeeded")
}
if host.Has("dependent") {
t.Error("a refused Add() left the module registered")
}
}
func TestHostAddRollsBackItsOwnStartFailure(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
broken := &fakeModule{manifest: validManifest("late"), events: events, startErr: errors.New("boom")}
if err := host.Add(context.Background(), broken); err == nil {
t.Fatal("Add() of a module whose Start fails succeeded")
}
if host.Has("late") {
t.Error("Add() left a module whose Start failed registered")
}
if got, want := events.snapshot(), []string{"start:base", "start:late"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the base module untouched by the failed add: %v", got, want)
}
}
func TestHostReplaceStopsTheOldAndStartsTheNew(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
oldManifest := validManifest("module")
oldManifest.Version = "1.0.0"
if err := host.Register(&fakeModule{manifest: oldManifest, events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
newManifest := validManifest("module")
newManifest.Version = "2.0.0"
if err := host.Replace(context.Background(), &fakeModule{manifest: newManifest, events: events}); err != nil {
t.Fatalf("Replace() error = %v", err)
}
if got, want := events.snapshot(), []string{"start:module", "stop:module", "start:module"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
manifests := host.Manifests()
if len(manifests) != 1 || manifests[0].Version != "2.0.0" {
t.Fatalf("manifests after replace = %+v, want the new 2.0.0", manifests)
}
}
func TestHostReplaceRestartsTheOldWhenTheNewStartFails(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("module"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
broken := &fakeModule{manifest: validManifest("module"), events: events, startErr: errors.New("boom")}
err := host.Replace(context.Background(), broken)
if err == nil {
t.Fatal("Replace() with a failing new module succeeded")
}
if got, want := events.snapshot(), []string{"start:module", "stop:module", "start:module", "start:module"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the old module restarted after the failed start: %v", got, want)
}
if !host.Has("module") {
t.Error("a refused Replace() unregistered the module")
}
}
func TestHostReplaceRefusesAModuleARunningDependentNeeds(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Register(&fakeModule{manifest: validManifest("base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Register(&fakeModule{manifest: validManifest("dependent", "base"), events: events}); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
err := host.Replace(context.Background(), &fakeModule{manifest: validManifest("base"), events: events})
if err == nil || !strings.Contains(err.Error(), "dependent") {
t.Fatalf("Replace() of a depended-on module = %v, want a refusal naming the dependent", err)
}
if got, want := events.snapshot(), []string{"start:base", "start:dependent"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the dependent left running: %v", got, want)
}
}
func TestHostReplaceRefusesAnUnregisteredModule(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Replace(context.Background(), &fakeModule{manifest: validManifest("absent")}); err == nil {
t.Fatal("Replace() of an unregistered module succeeded")
}
}
func TestHostAddBeforeStartBehavesLikeRegister(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
if err := host.Add(context.Background(), &fakeModule{manifest: validManifest("early"), events: events}); err != nil {
t.Fatalf("Add() before Start error = %v", err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if got, want := events.snapshot(), []string{"start:early"}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want the module started by Start(): %v", got, want)
}
}
-481
View File
@@ -1,481 +0,0 @@
package plugin_test
import (
"context"
"errors"
"slices"
"strings"
"sync"
"testing"
"github.com/samcharles93/archie-core/internal/plugin"
)
func TestHostRegisterValidatesManifest(t *testing.T) {
t.Parallel()
tests := []struct {
name string
mutate func(*plugin.Manifest)
wantErr bool
register plugin.Module
}{
{name: "valid", mutate: func(*plugin.Manifest) {}},
{name: "empty id", mutate: func(m *plugin.Manifest) { m.ID = "" }, wantErr: true},
{name: "unstable id", mutate: func(m *plugin.Manifest) { m.ID = "Bad ID" }, wantErr: true},
{name: "empty name", mutate: func(m *plugin.Manifest) { m.Name = "" }, wantErr: true},
{name: "invalid version", mutate: func(m *plugin.Manifest) { m.Version = "v1" }, wantErr: true},
{name: "empty prerelease identifier", mutate: func(m *plugin.Manifest) { m.Version = "1.0.0-alpha..1" }, wantErr: true},
{name: "empty prerelease", mutate: func(m *plugin.Manifest) { m.Version = "1.0.0-." }, wantErr: true},
{name: "leading zero prerelease", mutate: func(m *plugin.Manifest) { m.Version = "1.0.0-01" }, wantErr: true},
{name: "invalid api version", mutate: func(m *plugin.Manifest) { m.APIVersion = "latest" }, wantErr: true},
{name: "incompatible api major", mutate: func(m *plugin.Manifest) { m.APIVersion = "2.0.0" }, wantErr: true},
{name: "newer api minor", mutate: func(m *plugin.Manifest) { m.APIVersion = "1.1.0" }, wantErr: true},
{name: "no capabilities", mutate: func(m *plugin.Manifest) { m.Capabilities = nil }, wantErr: true},
{name: "invalid capability", mutate: func(m *plugin.Manifest) { m.Capabilities = []plugin.CapabilityKind{"Bad Kind"} }, wantErr: true},
{name: "duplicate capability", mutate: func(m *plugin.Manifest) {
m.Capabilities = []plugin.CapabilityKind{"tools", "tools"}
}, wantErr: true},
{name: "self dependency", mutate: func(m *plugin.Manifest) { m.Dependencies = []string{m.ID} }, wantErr: true},
{name: "invalid dependency", mutate: func(m *plugin.Manifest) { m.Dependencies = []string{"Bad ID"} }, wantErr: true},
{name: "duplicate dependency", mutate: func(m *plugin.Manifest) {
m.Dependencies = []string{"dependency", "dependency"}
}, wantErr: true},
{name: "invalid permission", mutate: func(m *plugin.Manifest) { m.Permissions = []plugin.Permission{"Bad Permission"} }, wantErr: true},
{name: "duplicate permission", mutate: func(m *plugin.Manifest) {
m.Permissions = []plugin.Permission{"network", "network"}
}, wantErr: true},
{name: "invalid config schema json", mutate: func(m *plugin.Manifest) { m.ConfigSchema = []byte(`{`) }, wantErr: true},
{name: "non-object config schema", mutate: func(m *plugin.Manifest) { m.ConfigSchema = []byte(`[]`) }, wantErr: true},
{name: "nil module", wantErr: true, register: (*fakeModule)(nil)},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
manifest := validManifest("module")
if tt.mutate != nil {
tt.mutate(&manifest)
}
module := tt.register
if module == nil {
module = &fakeModule{manifest: manifest}
}
err := plugin.NewHost().Register(module)
if (err != nil) != tt.wantErr {
t.Fatalf("Register() error = %v, wantErr %t", err, tt.wantErr)
}
})
}
}
func TestHostRegisterRejectsDuplicateAndMutationAfterStart(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
first := &fakeModule{manifest: validManifest("duplicate")}
if err := host.Register(first); err != nil {
t.Fatal(err)
}
if err := host.Register(&fakeModule{manifest: validManifest("duplicate")}); err == nil {
t.Fatal("duplicate Register() succeeded")
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Register(&fakeModule{manifest: validManifest("late")}); err == nil {
t.Fatal("Register() after Start succeeded")
}
}
func TestHostStartsInDependencyOrderAndStopsInReverse(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
modules := []*fakeModule{
{manifest: validManifest("api", "database"), events: events},
{manifest: validManifest("database"), events: events},
{manifest: validManifest("worker", "api"), events: events},
}
for _, module := range modules {
if err := host.Register(module); err != nil {
t.Fatal(err)
}
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatalf("second Start() error = %v", err)
}
if got, want := events.snapshot(), []string{"start:database", "start:api", "start:worker"}; !slices.Equal(got, want) {
t.Fatalf("start events = %v, want %v", got, want)
}
if err := host.Stop(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Stop(context.Background()); err != nil {
t.Fatalf("second Stop() error = %v", err)
}
if got, want := events.snapshot(), []string{
"start:database", "start:api", "start:worker",
"stop:worker", "stop:api", "stop:database",
}; !slices.Equal(got, want) {
t.Fatalf("lifecycle events = %v, want %v", got, want)
}
}
func TestHostStartRejectsMissingDependenciesAndCycles(t *testing.T) {
t.Parallel()
tests := []struct {
name string
modules []*fakeModule
}{
{
name: "missing dependency",
modules: []*fakeModule{{manifest: validManifest("dependent", "missing")}},
},
{
name: "dependency cycle",
modules: []*fakeModule{
{manifest: validManifest("first", "second")},
{manifest: validManifest("second", "first")},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
events := &eventLog{}
host := plugin.NewHost()
for _, module := range tt.modules {
module.events = events
if err := host.Register(module); err != nil {
t.Fatal(err)
}
}
if err := host.Start(context.Background()); err == nil {
t.Fatal("Start() succeeded")
}
if got := events.snapshot(); len(got) != 0 {
t.Fatalf("lifecycle events = %v, want none", got)
}
})
}
}
func TestHostStartFailureRollsBackAndIsolatesPanics(t *testing.T) {
t.Parallel()
tests := []struct {
name string
failing *fakeModule
errorMatch string
}{
{
name: "returned error",
failing: &fakeModule{
manifest: validManifest("failing"),
startErr: errors.New("start failure"),
stopErr: errors.New("rollback failure"),
},
errorMatch: "start failure",
},
{
name: "panic",
failing: &fakeModule{manifest: validManifest("failing"), startPanic: true},
errorMatch: "panic",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
events := &eventLog{}
host := plugin.NewHost()
started := &fakeModule{manifest: validManifest("started"), events: events}
tt.failing.manifest.Dependencies = []string{"started"}
tt.failing.events = events
never := &fakeModule{manifest: validManifest("never", "failing"), events: events}
for _, module := range []*fakeModule{started, tt.failing, never} {
if err := host.Register(module); err != nil {
t.Fatal(err)
}
}
err := host.Start(context.Background())
if err == nil || !strings.Contains(err.Error(), tt.errorMatch) {
t.Fatalf("Start() error = %v, want containing %q", err, tt.errorMatch)
}
if tt.failing.stopErr != nil && !strings.Contains(err.Error(), tt.failing.stopErr.Error()) {
t.Fatalf("Start() error = %v, want rollback error %q", err, tt.failing.stopErr)
}
if got, want := events.snapshot(), []string{
"start:started", "start:failing", "stop:failing", "stop:started",
}; !slices.Equal(got, want) {
t.Fatalf("rollback events = %v, want %v", got, want)
}
})
}
}
func TestEmptyHostLifecycleIsTerminalAfterStop(t *testing.T) {
t.Parallel()
host := plugin.NewHost()
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Stop(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err == nil {
t.Fatal("Start() after Stop() succeeded")
}
}
func TestHostRegisterContainsManifestPanics(t *testing.T) {
t.Parallel()
module := &fakeModule{manifestPanic: true}
if err := plugin.NewHost().Register(module); err == nil || !strings.Contains(err.Error(), "panic") {
t.Fatalf("Register() error = %v, want contained panic", err)
}
}
func TestHostStopContinuesAfterErrorsAndPanics(t *testing.T) {
t.Parallel()
events := &eventLog{}
host := plugin.NewHost()
modules := []*fakeModule{
{manifest: validManifest("first"), events: events, stopErr: errors.New("stop failure")},
{manifest: validManifest("second"), events: events, stopPanic: true},
{manifest: validManifest("third"), events: events},
}
for _, module := range modules {
if err := host.Register(module); err != nil {
t.Fatal(err)
}
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
err := host.Stop(context.Background())
if err == nil || !strings.Contains(err.Error(), "stop failure") || !strings.Contains(err.Error(), "panic") {
t.Fatalf("Stop() error = %v, want joined error and panic", err)
}
if got, want := events.snapshot(), []string{
"start:first", "start:second", "start:third",
"stop:third", "stop:second", "stop:first",
}; !slices.Equal(got, want) {
t.Fatalf("stop events = %v, want %v", got, want)
}
}
func TestHostRetriesModulesWhoseStopFailed(t *testing.T) {
t.Parallel()
stopFailure := errors.New("transient stop failure")
host := plugin.NewHost()
module := &fakeModule{
manifest: validManifest("retry-stop"),
stopErrors: []error{stopFailure, nil},
}
if err := host.Register(module); err != nil {
t.Fatal(err)
}
if err := host.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := host.Stop(context.Background()); !errors.Is(err, stopFailure) {
t.Fatalf("first Stop() error = %v, want %v", err, stopFailure)
}
if err := host.Stop(context.Background()); err != nil {
t.Fatalf("second Stop() error = %v, want cleanup retry success", err)
}
if module.stopCount != 2 {
t.Fatalf("Stop() calls = %d, want 2", module.stopCount)
}
}
func TestHostStartupRollbackIsBoundedAndRetryable(t *testing.T) {
t.Parallel()
cleanupFailure := errors.New("rollback cleanup failure")
host := plugin.NewHost()
module := &fakeModule{
manifest: validManifest("rollback-retry"),
startErr: errors.New("start failure"),
stopErrors: []error{cleanupFailure, nil},
}
if err := host.Register(module); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := host.Start(ctx)
if !errors.Is(err, cleanupFailure) {
t.Fatalf("Start() error = %v, want cleanup failure", err)
}
if len(module.stopContextDeadlines) != 1 || !module.stopContextDeadlines[0] {
t.Fatalf("rollback Stop() deadline flags = %v, want bounded context", module.stopContextDeadlines)
}
if got := module.stopContextErrors[0]; got != nil {
t.Fatalf("rollback Stop() context error = %v, want original cancellation detached", got)
}
if err := host.Stop(context.Background()); err != nil {
t.Fatalf("Stop() retry error = %v", err)
}
if module.stopCount != 2 {
t.Fatalf("Stop() calls = %d, want rollback plus retry", module.stopCount)
}
}
func TestAdaptLegacyCreatesMetadataOnlyLifecycleModule(t *testing.T) {
t.Parallel()
legacy := &fakeLegacyPlugin{name: "legacy-plugin", version: "1.4.2"}
module, err := plugin.AdaptLegacy(legacy)
if err != nil {
t.Fatal(err)
}
manifest := module.Manifest()
if manifest.ID != legacy.name || manifest.Name != legacy.name || manifest.Version != legacy.version {
t.Fatalf("legacy manifest = %+v", manifest)
}
if got, want := manifest.Capabilities, []plugin.CapabilityKind{"plugin.metadata"}; !slices.Equal(got, want) {
t.Fatalf("legacy capabilities = %v, want %v", got, want)
}
if err := module.Start(context.Background()); err != nil {
t.Fatal(err)
}
if err := module.Stop(context.Background()); err != nil {
t.Fatal(err)
}
}
func TestAdaptLegacyRejectsInvalidOrPanickingMetadata(t *testing.T) {
t.Parallel()
tests := []struct {
name string
plugin plugin.Plugin
}{
{name: "nil", plugin: (*fakeLegacyPlugin)(nil)},
{name: "invalid name", plugin: &fakeLegacyPlugin{name: "Bad Name", version: "1.0.0"}},
{name: "invalid version", plugin: &fakeLegacyPlugin{name: "legacy", version: "latest"}},
{name: "name panic", plugin: &fakeLegacyPlugin{namePanic: true}},
{name: "version panic", plugin: &fakeLegacyPlugin{name: "legacy", versionPanic: true}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if _, err := plugin.AdaptLegacy(tt.plugin); err == nil {
t.Fatal("AdaptLegacy() succeeded")
}
})
}
}
func validManifest(id string, dependencies ...string) plugin.Manifest {
return plugin.Manifest{
ID: id,
Name: id,
Version: "1.2.3",
APIVersion: plugin.HostAPIVersion,
Capabilities: []plugin.CapabilityKind{"tools"},
Dependencies: dependencies,
Permissions: []plugin.Permission{"network"},
ConfigSchema: []byte(`{"type":"object"}`),
}
}
type eventLog struct {
mu sync.Mutex
events []string
}
func (l *eventLog) add(event string) {
if l == nil {
return
}
l.mu.Lock()
defer l.mu.Unlock()
l.events = append(l.events, event)
}
func (l *eventLog) snapshot() []string {
l.mu.Lock()
defer l.mu.Unlock()
return slices.Clone(l.events)
}
type fakeModule struct {
manifest plugin.Manifest
events *eventLog
startErr error
stopErr error
stopErrors []error
stopCount int
stopContextDeadlines []bool
stopContextErrors []error
startPanic bool
stopPanic bool
manifestPanic bool
}
type fakeLegacyPlugin struct {
name string
version string
namePanic bool
versionPanic bool
}
func (p *fakeLegacyPlugin) Name() string {
if p.namePanic {
panic("name panic")
}
return p.name
}
func (p *fakeLegacyPlugin) Version() string {
if p.versionPanic {
panic("version panic")
}
return p.version
}
func (m *fakeModule) Manifest() plugin.Manifest {
if m.manifestPanic {
panic("manifest panic")
}
return m.manifest
}
func (m *fakeModule) Start(context.Context) error {
m.events.add("start:" + m.manifest.ID)
if m.startPanic {
panic("start panic")
}
return m.startErr
}
func (m *fakeModule) Stop(ctx context.Context) error {
m.events.add("stop:" + m.manifest.ID)
m.stopCount++
_, hasDeadline := ctx.Deadline()
m.stopContextDeadlines = append(m.stopContextDeadlines, hasDeadline)
m.stopContextErrors = append(m.stopContextErrors, ctx.Err())
if m.stopPanic {
panic("stop panic")
}
if len(m.stopErrors) >= m.stopCount {
return m.stopErrors[m.stopCount-1]
}
return m.stopErr
}
-585
View File
@@ -1,585 +0,0 @@
package plugin_test
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/plugin/pluginextract"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// ── Plugin interface ─────────────────────────────────────────────────
func TestPluginInterfaceExists(t *testing.T) {
var p plugin.Plugin
_ = p
type nameVersioner interface {
Name() string
Version() string
}
var _ nameVersioner = p
}
func TestPartialImplementationIsRejectedBeforeWrapping(t *testing.T) {
// Why the generated interface wrappers carry no nil-guards: Yaegi
// type-checks the assignment to the interface before it ever builds a
// wrapper, so a type missing a method never reaches Go as a wrapper with
// a nil method field. Guarding the generated wrappers by hand defends a
// state Yaegi cannot produce, and every regeneration silently drops it.
i, err := yaegiutil.New(interp.Options{}, symbols)
if err != nil {
t.Fatal(err)
}
_, err = yaegiutil.Resolve[plugin.Plugin](i, `package main
import "github.com/samcharles93/archie-core/internal/plugin"
type partial struct{}
func (partial) Name() string { return "partial" }
var Plugin plugin.Plugin = partial{}
`, "main.Plugin")
if err == nil {
t.Fatal("want error for a Plugin missing Version(), got nil")
}
if !strings.Contains(err.Error(), "cannot use type") {
t.Errorf("want a Yaegi assignment type error, got: %v", err)
}
}
func TestCompleteImplementationWrapsWithNoNilMethods(t *testing.T) {
i, err := yaegiutil.New(interp.Options{}, symbols)
if err != nil {
t.Fatal(err)
}
p, err := yaegiutil.Resolve[plugin.Plugin](i, `package main
import "github.com/samcharles93/archie-core/internal/plugin"
type complete struct{}
func (complete) Name() string { return "n" }
func (complete) Version() string { return "v" }
var Plugin plugin.Plugin = complete{}
`, "main.Plugin")
if err != nil {
t.Fatal(err)
}
rv := reflect.ValueOf(p)
if rv.Kind() != reflect.Struct {
t.Fatalf("want a Yaegi wrapper struct, got %T", p)
}
for j := range rv.NumField() {
f := rv.Type().Field(j)
if f.Type.Kind() == reflect.Func && rv.Field(j).IsNil() {
t.Errorf("wrapper field %s is nil; Yaegi is expected to populate every method", f.Name)
}
}
}
// ── LoadDir behavioral tests ─────────────────────────────────────────
var symbols = pluginextract.Symbols
func TestLoadDirLoadsValidPlugin(t *testing.T) {
// LoadDir must Yaegi-interpret .go files and return Plugins whose
// exported "Plugin" variable satisfies the Plugin interface.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "hello.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "hello" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatalf("LoadDir returned %d plugins, want 1", len(plugins))
}
if plugins[0].Name() != "hello" {
t.Errorf("plugin.Name() = %q, want hello", plugins[0].Name())
}
if plugins[0].Version() != "1.0.0" {
t.Errorf("plugin.Version() = %q, want 1.0.0", plugins[0].Version())
}
}
func TestLoadDirSkipsInvalidPlugin(t *testing.T) {
// A .go file that doesn't compile must be skipped -- not crash the loader.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "broken.go"), []byte(`package main
this is not valid Go syntax @@@@
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins from broken source, want 0", len(plugins))
}
}
func TestLoadDirSkipsFileWithoutPluginExport(t *testing.T) {
// A valid Go file without a "Plugin" export must be skipped.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "notaplugin.go"), []byte(`package main
func Something() string { return "nope" }
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins from file without Plugin export, want 0", len(plugins))
}
}
func TestLoadDirSkipsNonGoFiles(t *testing.T) {
// Only .go files are loaded. Other files are ignored.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "readme.md"), []byte(`# Not a plugin`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "hello.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "hello" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatalf("LoadDir returned %d plugins, want 1 (only .go files count)", len(plugins))
}
}
func TestLoadDirMultiplePlugins(t *testing.T) {
// Multiple valid plugins must all be loaded, sorted by filename.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "01-alpha.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "alpha" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "02-beta.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "beta" },
WVersion: func() string { return "2.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 2 {
t.Fatalf("LoadDir returned %d plugins, want 2", len(plugins))
}
if plugins[0].Name() != "alpha" {
t.Errorf("plugin[0].Name() = %q, want alpha (sorted by filename)", plugins[0].Name())
}
if plugins[1].Name() != "beta" {
t.Errorf("plugin[1].Name() = %q, want beta", plugins[1].Name())
}
}
func TestLoadDirNonexistentDirReturnsNil(t *testing.T) {
plugins, err := plugin.LoadDir("/nonexistent/path/for/plugins")
if err != nil {
t.Fatal(err)
}
if plugins != nil {
t.Errorf("LoadDir returned %v, want nil for nonexistent directory", plugins)
}
}
// ── Adversarial tests ────────────────────────────────────────────────
//
// These tests try to BREAK LoadDir. A correct implementation must
// degrade gracefully -- skip the bad plugin, load the rest, never panic.
func TestLoadDirRefusesWrapperWithNilFunctionFields(t *testing.T) {
// A _Plugin with nil WName/WVersion must be refused at load. It
// previously loaded and answered "" for both, so the daemon logged a
// nameless plugin as if it were healthy.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "nilfuncs.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: nil,
WVersion: nil,
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Fatalf("LoadDir returned %d plugins, want 0 (a wrapper missing methods must be refused)", len(plugins))
}
}
func TestLoadDirPluginReturningEmptyNameVersion(t *testing.T) {
// Plugins with empty name/version are still valid -- the interface
// doesn't forbid empty strings. LoadDir must not reject them.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "empty.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "" },
WVersion: func() string { return "" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatalf("LoadDir returned %d plugins, want 1 (empty name is still valid)", len(plugins))
}
}
func TestLoadDirSkipsPluginWithWrongExportType(t *testing.T) {
// Plugin var exists but is an int, not a Plugin. Must be skipped.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "wrongtype.go"), []byte(`package main
var Plugin = 42
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins from wrong-type export, want 0", len(plugins))
}
}
func TestLoadDirSkipsPluginWithOnlySomeInterfaceMethods(t *testing.T) {
// A struct that has Name() but not Version() -- doesn't satisfy Plugin.
// type assertion must fail and the plugin must be skipped.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "partial.go"), []byte(`package main
type partial struct{}
func (p partial) Name() string { return "partial" }
// No Version() method -- deliberately incomplete.
var Plugin partial
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins from partial impl, want 0", len(plugins))
}
}
func TestLoadDirSkipsHandBuiltPartialWrapper(t *testing.T) {
// Yaegi type-checks "var Plugin plugin.Plugin = impl{}" and refuses an
// incomplete impl, but interpreted code can also build the generated
// wrapper directly, where struct-literal semantics leave an omitted method
// nil and the call panics at first use. LoadDir must refuse it instead.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "partialwrap.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "halfbuilt" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Fatalf("LoadDir returned %d plugins from a wrapper missing WVersion, want 0", len(plugins))
}
}
func TestLoadDirEmptyDirReturnsEmptySlice(t *testing.T) {
dir := t.TempDir()
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins from empty dir, want 0", len(plugins))
}
if plugins == nil {
t.Error("LoadDir returned nil from empty dir, want empty slice")
}
}
func TestLoadDirSubdirectoriesAreIgnored(t *testing.T) {
// Only top-level .go files are loaded. Subdirectories are not traversed.
dir := t.TempDir()
subDir := filepath.Join(dir, "nested")
if err := os.MkdirAll(subDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(subDir, "nested.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "nested" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins, want 0 -- subdirectories must not be traversed", len(plugins))
}
}
func TestLoadDirPluginWithPanicInNameFunc(t *testing.T) {
// A plugin whose Name() function panics must still be loadable --
// the panic only fires on call, not on load.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "panicky.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { panic("boom") },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Fatalf("LoadDir returned %d plugins, want 1 (panics are deferred to call time)", len(plugins))
}
// Verify calling Name() actually panics -- the plugin loaded, the panic
// is the caller's responsibility.
func() {
defer func() {
if r := recover(); r == nil {
t.Error("Name() did not panic -- expected panic from panicky plugin")
}
}()
plugins[0].Name()
}()
}
func TestLoadDirPluginWithUnusedImport(t *testing.T) {
// Yaegi should still eval a file that imports a package but doesn't
// use it directly (the import is needed for the _Plugin type).
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "unusedimp.go"), []byte(`package main
import "fmt"
var Plugin = struct{}{}
`), 0o644); err != nil {
t.Fatal(err)
}
// This must not crash -- just skip.
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal("LoadDir errored on unused import:", err)
}
_ = plugins
}
// The former TestGeneratedWrapperHasNilGuards was retired. It pinned
// hand-added nil guards in the generated wrapper, which every regeneration
// silently dropped. LoadDir now refuses such a plugin outright; see
// TestLoadDirRefusesWrapperWithNilFunctionFields.
func TestLoadDirPluginWithGoBuildTag(t *testing.T) {
// Build tags in Yaegi-interpreted code are just comments -- they
// don't gate evaluation. The file loads normally.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "tagged.go"), []byte(`//go:build ignore
package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "tagged" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
plugins, err := plugin.LoadDir(dir, symbols)
if err != nil {
t.Fatal(err)
}
if len(plugins) != 1 {
t.Errorf("LoadDir returned %d plugins from tagged file, want 1 (build tags are ignored in Yaegi)", len(plugins))
}
}
// ── Timeout tests (issue #43) ────────────────────────────────────────
//
// LoadDir calls yaegiutil.Resolve which calls i.Eval(src) with no
// context, deadline, or goroutine+select guard. A plugin whose
// package-level init code never returns (e.g. select{} in init())
// hangs the entire daemon startup forever. These tests prove the bug:
// they assert the CORRECT behaviour (timeout → skip the bad plugin)
// and FAIL today because LoadDir hangs before returning.
func TestLoadDirTimeoutOnBlockingPlugin(t *testing.T) {
// A single plugin whose init() blocks forever must be skipped,
// not hang LoadDir indefinitely. The daemon must start with zero
// plugins and no error — the blocking file is logged and skipped.
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "blocking.go"), []byte(`package main
func init() { select {} }
`), 0o644); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
var plugins []plugin.Plugin
var loadErr error
go func() {
plugins, loadErr = plugin.LoadDir(dir, symbols)
close(done)
}()
select {
case <-done:
if loadErr != nil {
t.Errorf("LoadDir returned error: %v", loadErr)
}
if len(plugins) != 0 {
t.Errorf("LoadDir returned %d plugins, want 0 (blocking plugin should be skipped)", len(plugins))
}
case <-time.After(5 * time.Second):
t.Error("LoadDir did not return within 5s — plugin eval has no timeout (issue #43)")
}
}
func TestLoadDirSkipsBlockingPluginButLoadsGoodOnes(t *testing.T) {
// A blocking plugin must not prevent good plugins from loading.
// LoadDir must return within the timeout with only the valid plugin.
dir := t.TempDir()
// Blocking plugin first (sorted first by filename).
if err := os.WriteFile(filepath.Join(dir, "00-blocking.go"), []byte(`package main
func init() { select {} }
`), 0o644); err != nil {
t.Fatal(err)
}
// Good plugin second.
if err := os.WriteFile(filepath.Join(dir, "01-good.go"), []byte(`package main
import "github.com/samcharles93/archie-core/internal/plugin"
var Plugin = plugin._Plugin{
WName: func() string { return "good" },
WVersion: func() string { return "1.0.0" },
}
`), 0o644); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
var plugins []plugin.Plugin
var loadErr error
go func() {
plugins, loadErr = plugin.LoadDir(dir, symbols)
close(done)
}()
select {
case <-done:
if loadErr != nil {
t.Errorf("LoadDir returned error: %v", loadErr)
}
if len(plugins) != 1 {
t.Errorf("LoadDir returned %d plugins, want 1 (blocking plugin should be skipped, good plugin loaded)", len(plugins))
} else if plugins[0].Name() != "good" {
t.Errorf("plugin.Name() = %q, want good", plugins[0].Name())
}
case <-time.After(5 * time.Second):
t.Error("LoadDir did not return within 5s — blocking plugin hang prevents loading good plugins (issue #43)")
}
}
@@ -1,36 +0,0 @@
package pluginextract
import (
"reflect"
"testing"
)
func TestSymbolsContainsExpectedPluginEntries(t *testing.T) {
pkgKey := "github.com/samcharles93/archie-core/internal/plugin/plugin"
pkg, ok := Symbols[pkgKey]
if !ok {
t.Fatalf("Symbols missing key %q", pkgKey)
}
// LoadDir must be a function.
if v, ok := pkg["LoadDir"]; !ok {
t.Error("LoadDir missing from Symbols")
} else if v.Kind() != reflect.Func {
t.Errorf("LoadDir kind = %v, want Func", v.Kind())
}
// Plugin must be a pointer type.
if v, ok := pkg["Plugin"]; !ok {
t.Error("Plugin missing from Symbols")
} else if v.Kind() != reflect.Pointer {
t.Errorf("Plugin kind = %v, want Ptr", v.Kind())
}
}
// The former TestGeneratedWrapperHasNilGuards was retired: it was named for a
// regression Yaegi cannot produce. Yaegi type-checks the assignment to an
// interface before building a wrapper, so a wrapper never reaches Go with a nil
// method field, and the hand-added guards it referred to only survived until the
// next regeneration. That invariant is pinned directly in internal/plugin by
// TestPartialImplementationIsRejectedBeforeWrapping and
// TestCompleteImplementationWrapsWithNoNilMethods.
@@ -1,98 +0,0 @@
package pluginextract
import (
"context"
"testing"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/plugin"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// TestPreviouslyMissingSymbolsReachableFromInterpretedCode is the regression
// test for the stale symbol-table drift (e7bo): the committed generated file
// predated internal/plugin/host.go (f73b2d1) and was never regenerated, so
// the Host/Module/Manifest/Permission/CapabilityKind types and the
// NewHost/AdaptLegacy/HostAPIVersion identifiers that plugin.go's LoadDir
// exposes to interpreted daemon plugins were absent from the table. A daemon
// plugin written against the capability-host API could not resolve them,
// silently.
//
// This test interprets a plugin that references the previously-missing
// symbols, resolves it, and calls it -- proving the symbols are wired.
func TestPreviouslyMissingSymbolsReachableFromInterpretedCode(t *testing.T) {
src := `package main
import (
"context"
"fmt"
"github.com/samcharles93/archie-core/internal/plugin"
)
// BuildHost exercises NewHost and HostAPIVersion -- the module-capability
// registration surface that was missing from the symbol table.
func BuildHost(m plugin.Module) (string, error) {
h := plugin.NewHost()
if h == nil {
return "", fmt.Errorf("NewHost returned nil")
}
if plugin.HostAPIVersion == "" {
return "", fmt.Errorf("HostAPIVersion empty")
}
if err := h.Register(m); err != nil {
return "", err
}
if err := h.Start(context.Background()); err != nil {
return "", err
}
defer h.Stop(context.Background())
return plugin.HostAPIVersion, nil
}
`
i, err := yaegiutil.New(interp.Options{}, Symbols)
if err != nil {
t.Fatalf("New: %v", err)
}
buildHost, err := yaegiutil.Resolve[func(plugin.Module) (string, error)](i, src, "main.BuildHost")
if err != nil {
t.Fatalf("Resolve BuildHost: %v", err)
}
// Call through with a Go-side module implementing the contract. This
// proves the interpreted host API works across the boundary end to end.
mod := testModule{}
version, err := buildHost(mod)
if err != nil {
t.Fatalf("BuildHost: %v", err)
}
if version != plugin.HostAPIVersion {
t.Errorf("BuildHost version = %q, want %q", version, plugin.HostAPIVersion)
}
}
// testModule implements plugin.Module for the Go-side call.
type testModule struct{}
func (testModule) Manifest() plugin.Manifest {
return plugin.Manifest{
ID: "test",
Name: "test",
Version: "1.0.0",
APIVersion: plugin.HostAPIVersion,
Capabilities: []plugin.CapabilityKind{"test.capability"},
}
}
func (testModule) Start(context.Context) error { return nil }
func (testModule) Stop(context.Context) error { return nil }
// The former TestWrapperNilGuardsPreserved was retired. It pinned hand-added
// nil guards that every regeneration silently dropped, and the behaviour it
// protected was a lie: a nil WStop reported a clean shutdown for a module that
// never ran one. Such a wrapper is now refused in yaegiutil.Resolve, before it
// can reach a call site.
var _ plugin.Module = testModule{}