Files
commandkit/invocation_feature_test.go

154 lines
8.0 KiB
Go
Raw Normal View History

package commandkit
import (
"context"
"errors"
"strings"
"testing"
internalcobra "go.maximumdirect.net/commandkit/internal/cobra"
commandmeta "go.maximumdirect.net/commandkit/internal/commandmeta"
)
func TestInvocationFeatureCaptureAndInstallation(t *testing.T) {
type input struct{ enabled bool }
flags := []Flag[input]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *input, v Supplied[bool]) { i.enabled = v.Value })}
feature := NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }})
flags[0] = BoolFlag(FlagMeta{Name: "changed"}, false, func(*input, Supplied[bool]) {})
original := Group("owner", "", Group("child", ""))
attached := WithInvocationFeature(original, feature)
first, err := New(Identity{Name: "test"}, attached, Group("other", ""), FlagAlias("--watch", "--observe"))
if err != nil {
t.Fatal(err)
}
second, err := New(Identity{Name: "test"}, attached)
if err != nil {
t.Fatal(err)
}
if len(first.features) != 1 || len(second.features) != 1 || first.features[0] != second.features[0] || first.featureFlags[0].Name != "observe" {
t.Fatal("feature capture or reuse failed")
}
if len(original.record.features) != 0 {
t.Fatal("attachment mutated original")
}
if _, ok := first.flagAliases[""].bySpelling[flagSpellingKey(capturedFlagSpelling{name: "watch"})]; !ok {
t.Fatal("feature alias missing")
}
if err := first.Register(WithInvocationFeature(Group("reused", ""), feature)); err != nil || len(first.features) != 1 {
t.Fatalf("deduplication: %v", err)
}
if err := first.Register(Group("collision", "", NewCommand(CommandSpec[struct{}]{Name: "nested", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*struct{}, Supplied[bool]) {})}}))); err == nil {
t.Fatal("expected local collision")
}
if first.commands["collision"] != nil || len(first.features) != 1 {
t.Fatal("failed registration mutated registry")
}
if err := second.Register(WithInvocationFeature(Group("another", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: flags, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err != nil {
t.Fatal(err)
}
if err := second.Register(WithInvocationFeature(Group("duplicate", ""), NewInvocationFeature(InvocationFeatureSpec[input]{Flags: []Flag[input]{BoolFlag(FlagMeta{Name: "observe"}, false, func(*input, Supplied[bool]) {})}, Start: func(inv Invocation, _ input) (context.Context, func() Report) { return inv.Context, nil }}))); err == nil {
t.Fatal("expected feature collision")
}
}
func TestInvocationFeatureInvalidAndAbsent(t *testing.T) {
marker := errors.New("wiring")
invalid := NewInvocationFeature(InvocationFeatureSpec[struct{}]{})
for _, command := range []Command{WithInvocationFeature(NoCommand(), invalid), WithInvocationFeature(Group("x", ""), InvocationFeature{}), WithInvocationFeature(Command{}, NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})), WithError(WithInvocationFeature(NoCommand(), invalid), marker)} {
_, err := New(Identity{Name: "test"}, command)
if err == nil {
t.Fatal("invalid feature accepted")
}
if len(command.record.issues) > 0 && errors.Is(command.record.issues[0], marker) && !errors.Is(err, marker) {
t.Fatalf("lost attached error: %v", err)
}
}
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
app, err := New(Identity{Name: "test"}, WithInvocationFeature(NoCommand(), feature))
if err != nil || len(app.features) != 0 {
t.Fatalf("absent feature: %v", err)
}
bad := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "debug"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
if _, err = New(Identity{Name: "test"}, WithInvocationFeature(Group("x", ""), bad)); err == nil || !strings.Contains(err.Error(), "reserved") {
t.Fatalf("reporting collision: %v", err)
}
}
func TestInvocationFeatureRegistrationOrderAndAliasCollision(t *testing.T) {
feature := NewInvocationFeature(InvocationFeatureSpec[struct{}]{Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}, Start: func(inv Invocation, _ struct{}) (context.Context, func() Report) { return inv.Context, nil }})
owner := WithInvocationFeature(Group("owner", ""), feature)
collision := NewCommand(CommandSpec[struct{}]{Name: "local", Flags: []Flag[struct{}]{BoolFlag(FlagMeta{Name: "other", Short: "o"}, false, func(*struct{}, Supplied[bool]) {})}})
for _, pair := range [][2]Command{{owner, collision}, {collision, owner}} {
app, err := New(Identity{Name: "test"}, pair[0])
if err != nil {
t.Fatal(err)
}
old := app.buildRoutingSnapshot()
if err := app.Register(pair[1]); err == nil {
t.Fatal("expected collision")
}
if app.commands[pair[1].record.name] != nil || len(app.features) != len(old.features) {
t.Fatal("registration was not atomic")
}
}
if _, err := New(Identity{Name: "test"}, owner, FlagAlias("--observe", "--verbose")); err == nil {
t.Fatal("feature spelling accepted as alias source")
}
if _, err := New(Identity{Name: "test"}, owner, FlagAliasFor("owner", "--watch", "--observe")); err != nil {
t.Fatalf("feature alias rejected: %v", err)
}
}
func TestInvocationFeatureFlagsParseAndDiscover(t *testing.T) {
type featureInput struct{ selected Supplied[bool] }
constructed := 0
feature := NewInvocationFeature(InvocationFeatureSpec[featureInput]{
NewInput: func() featureInput { constructed++; return featureInput{} },
Flags: []Flag[featureInput]{BoolFlag(FlagMeta{Name: "observe", Short: "o"}, false, func(i *featureInput, v Supplied[bool]) { i.selected = v })},
Start: func(inv Invocation, _ featureInput) (context.Context, func() Report) {
t.Fatal("unexpected start")
return nil, nil
},
})
type localInput struct{ name string }
var got string
cmd := NewCommand(CommandSpec[localInput]{Name: "run", Flags: []Flag[localInput]{ValueFlag(FlagMeta{Name: "name"}, (*string)(nil), func(s string) (string, error) { return s, nil }, func(i *localInput, v Supplied[string]) { i.name = v.Value })}, Run: func(_ Invocation, i localInput) Outcome { got = i.name; return Success() }})
app, err := New(Identity{Name: "test"}, WithInvocationFeature(cmd, feature), Alias("short path", "run"), FlagAlias("--watch", "--observe"))
if err != nil {
t.Fatal(err)
}
if out := app.Execute(context.Background(), []string{"run", "--watch", "--observe=false", "--name=ok"}, Streams{}); out.Status != 0 || got != "ok" {
t.Fatalf("result=%#v name=%q", out, got)
}
if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--observe=true"}, Streams{}); out.Kind != OutcomeUsage {
t.Fatalf("invalid earlier occurrence: %#v", out)
}
if out := app.Execute(context.Background(), []string{"run", "--observe=bad", "--help"}, Streams{}); out.Kind != OutcomeUsage {
t.Fatalf("help invalid flag: %#v", out)
}
if constructed != 0 {
t.Fatal("input constructed before execution boundary")
}
snapshot := app.routeSnapshot()
for _, path := range [][]string{nil, {"run"}, {"short"}} {
route := resolveEnteredRoute(path, snapshot)
view := app.helpView(route, snapshot)
session := internalcobra.Prepare(snapshot.metadata, commandmeta.ParseOptions{})
content, failure := session.RenderHelpView(view)
if failure != nil || !strings.Contains(content, "--observe") {
t.Fatalf("help %v: %q %#v", path, content, failure)
}
ctx := resolveCompletionContext(snapshot, path, "--obs")
target := completionTargetFor(snapshot, ctx)
found := false
for _, choice := range target.choices {
if choice.Value == "--observe" {
found = true
}
}
if !found {
t.Fatalf("completion %v: %#v", path, target)
}
}
}