-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugins_test.go
More file actions
264 lines (211 loc) · 7.76 KB
/
Copy pathplugins_test.go
File metadata and controls
264 lines (211 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package cmd
import (
"bytes"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// writeScript writes a shell script executable at dir/name with the given body.
// Returns the absolute path. Skips the test on Windows — shell scripts and 0o755
// aren't a useful way to exercise plugin discovery there.
func writeScript(t *testing.T, dir, name, body string) string {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("plugin discovery tests use shell scripts; skip on Windows")
}
path := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(path, []byte(body), 0o755))
return path
}
func TestDiscoverPlugins_FindsExecutableStackctlBinaries(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-hello", "#!/bin/sh\necho hi\n")
// Also place a non-plugin binary that shouldn't match.
_ = writeScript(t, dir, "notaplugin", "#!/bin/sh\necho nope\n")
// And a bare "stackctl-" which is the empty-name case — must be ignored.
_ = writeScript(t, dir, "stackctl-", "#!/bin/sh\necho empty\n")
got := discoverPlugins(dir)
require.Contains(t, got, "hello")
assert.Len(t, got, 1)
assert.True(t, filepath.IsAbs(got["hello"]))
}
func TestDiscoverPlugins_SkipsNonExecutable(t *testing.T) {
dir := t.TempDir()
nonExec := filepath.Join(dir, "stackctl-readonly")
require.NoError(t, os.WriteFile(nonExec, []byte("#!/bin/sh\necho hi\n"), 0o644))
got := discoverPlugins(dir)
assert.NotContains(t, got, "readonly", "non-executable files must be ignored")
}
func TestDiscoverPlugins_FirstPathEntryWins(t *testing.T) {
dir1 := t.TempDir()
dir2 := t.TempDir()
_ = writeScript(t, dir1, "stackctl-same", "#!/bin/sh\necho first\n")
_ = writeScript(t, dir2, "stackctl-same", "#!/bin/sh\necho second\n")
got := discoverPlugins(dir1 + string(os.PathListSeparator) + dir2)
require.Contains(t, got, "same")
assert.Equal(t, filepath.Join(dir1, "stackctl-same"), got["same"])
}
func TestDiscoverPlugins_IgnoresMissingAndEmptyPATHEntries(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-ok", "#!/bin/sh\necho ok\n")
got := discoverPlugins(string(os.PathListSeparator) + "/nonexistent/path" + string(os.PathListSeparator) + dir)
assert.Contains(t, got, "ok")
}
func TestRegisterPlugins_AddsPluginAsSubcommand(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-greet", "#!/bin/sh\necho hello-from-plugin\n")
root := &cobra.Command{Use: "stackctl"}
builtin := &cobra.Command{Use: "config", Short: "builtin"}
root.AddCommand(builtin)
registerPlugins(root, dir)
var greet *cobra.Command
for _, c := range root.Commands() {
if c.Name() == "greet" {
greet = c
break
}
}
require.NotNil(t, greet, "plugin subcommand must be registered")
assert.Contains(t, greet.Short, "Plugin:")
}
func TestRegisterPlugins_BuiltinWinsOnCollision(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-config", "#!/bin/sh\necho shadow\n")
root := &cobra.Command{Use: "stackctl"}
builtin := &cobra.Command{Use: "config", Short: "builtin"}
root.AddCommand(builtin)
registerPlugins(root, dir)
// Verify exactly one command named "config" exists (not two, with Cobra
// silently accepting the duplicate) and that it's the built-in.
named := 0
var found *cobra.Command
for _, c := range root.Commands() {
if c.Name() == "config" {
named++
found = c
}
}
assert.Equal(t, 1, named, "exactly one command should be named 'config'")
require.NotNil(t, found)
assert.Equal(t, "builtin", found.Short, "built-in must not be replaced by a colliding plugin")
}
func TestRegisterPlugins_PluginInvocationPassesThroughArgsAndStdout(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-echo",
"#!/bin/sh\nprintf '%s|' \"$@\"\n")
root := &cobra.Command{Use: "stackctl"}
registerPlugins(root, dir)
var pluginCmd *cobra.Command
for _, c := range root.Commands() {
if c.Name() == "echo" {
pluginCmd = c
break
}
}
require.NotNil(t, pluginCmd)
// The plugin uses os.Exit on error; on success we get its stdout.
// Cobra's Execute path would os.Exit; drive the wrapped binary directly via
// exec for a clean, assertable invocation.
bin := filepath.Join(dir, "stackctl-echo")
out, err := exec.Command(bin, "alpha", "--flag=beta", "gamma").CombinedOutput()
require.NoError(t, err)
assert.Equal(t, "alpha|--flag=beta|gamma|", string(out))
}
func TestRegisterPlugins_NoOpOnEmptyPath(t *testing.T) {
root := &cobra.Command{Use: "stackctl"}
before := len(root.Commands())
registerPlugins(root, "")
assert.Equal(t, before, len(root.Commands()))
}
// TestRegisterPlugins_StdinPassthrough proves stdin is routed to the plugin.
// Uses a `cat` style shell script that copies stdin to stdout; the plugin
// subcommand reads stdin via cmd.InOrStdin() which Cobra resolves to the
// buffer we set via root.SetIn.
func TestRegisterPlugins_StdinPassthrough(t *testing.T) {
dir := t.TempDir()
_ = writeScript(t, dir, "stackctl-cat", "#!/bin/sh\ncat\n")
root := &cobra.Command{Use: "stackctl", SilenceUsage: true, SilenceErrors: true}
registerPlugins(root, dir)
var catCmd *cobra.Command
for _, c := range root.Commands() {
if c.Name() == "cat" {
catCmd = c
break
}
}
require.NotNil(t, catCmd)
var outBuf bytes.Buffer
root.SetIn(strings.NewReader("payload-from-stdin"))
root.SetOut(&outBuf)
root.SetErr(&outBuf)
require.NoError(t, catCmd.RunE(catCmd, nil))
assert.Equal(t, "payload-from-stdin", outBuf.String(),
"plugin must receive stdin and its stdout must reach root's writer")
}
// TestRegisterPlugins_RunViaCobraRouting wires a plugin through Cobra's
// Execute path to verify the command is actually routed by name. The plugin
// exits 0, so the parent survives; args are captured via a sentinel file
// the plugin writes.
func TestRegisterPlugins_RunViaCobraRouting(t *testing.T) {
dir := t.TempDir()
sentinel := filepath.Join(t.TempDir(), "args.txt")
script := "#!/bin/sh\nprintf '%s ' \"$@\" > " + sentinel + "\n"
_ = writeScript(t, dir, "stackctl-touch", script)
root := &cobra.Command{Use: "stackctl", SilenceUsage: true, SilenceErrors: true}
registerPlugins(root, dir)
var buf bytes.Buffer
root.SetOut(&buf)
root.SetErr(&buf)
root.SetArgs([]string{"touch", "--hello=world", "posarg"})
// Run the plugin directly via the command's RunE rather than via Execute —
// Execute may call os.Exit(0) on failure paths via our plugin wrapper and
// that would terminate the test process.
var touchCmd *cobra.Command
for _, c := range root.Commands() {
if c.Name() == "touch" {
touchCmd = c
break
}
}
require.NotNil(t, touchCmd)
require.NoError(t, touchCmd.RunE(touchCmd, []string{"--hello=world", "posarg"}))
contents, err := os.ReadFile(sentinel)
require.NoError(t, err)
assert.Contains(t, string(contents), "--hello=world")
assert.Contains(t, string(contents), "posarg")
}
// ---------- pluginEnv ----------
func TestPluginEnv_PassesDebugFlag(t *testing.T) {
root := &cobra.Command{Use: "stackctl"}
root.PersistentFlags().Bool("debug", false, "")
require.NoError(t, root.PersistentFlags().Set("debug", "true"))
env := pluginEnv(root)
found := false
for _, kv := range env {
if strings.HasPrefix(kv, "STACKCTL_DEBUG=") {
assert.Equal(t, "STACKCTL_DEBUG=1", kv)
found = true
}
}
assert.True(t, found, "STACKCTL_DEBUG should be set when --debug flag is changed")
}
func TestPluginEnv_OmitsDebugWhenNotChanged(t *testing.T) {
root := &cobra.Command{Use: "stackctl"}
root.PersistentFlags().Bool("debug", false, "")
env := pluginEnv(root)
for _, kv := range env {
if strings.HasPrefix(kv, "STACKCTL_DEBUG=") {
t.Fatal("STACKCTL_DEBUG should not be set when --debug flag is not changed")
}
}
}
func TestPluginEnv_NilCommand(t *testing.T) {
env := pluginEnv(nil)
assert.NotEmpty(t, env)
}