-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathrun_test.go
More file actions
222 lines (201 loc) · 5.91 KB
/
run_test.go
File metadata and controls
222 lines (201 loc) · 5.91 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
package app_test
import (
"bufio"
"bytes"
"io"
"os"
"strings"
"testing"
"time"
"github.com/fastly/cli/pkg/app"
"github.com/fastly/cli/pkg/errors"
"github.com/fastly/cli/pkg/global"
"github.com/fastly/cli/pkg/testutil"
)
// If you add a Short flag and this test starts failing, it could be due to the same short flag existing at the global level.
func TestShellCompletion(t *testing.T) {
scenarios := []testutil.CLIScenario{
{
Name: "bash shell complete",
Args: "--completion-script-bash",
WantOutput: `
_fastly_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _fastly_bash_autocomplete fastly
`,
},
{
Name: "zsh shell complete",
Args: "--completion-script-zsh",
WantOutput: `
#compdef fastly
autoload -U compinit && compinit
autoload -U bashcompinit && bashcompinit
_fastly_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
opts=$( ${COMP_WORDS[0]} --completion-bash ${COMP_WORDS[@]:1:$COMP_CWORD} )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
[[ $COMPREPLY ]] && return
compgen -f
return 0
}
complete -F _fastly_bash_autocomplete fastly
`,
},
{
Name: "shell evaluate completion options",
Args: "--completion-bash",
WantOutput: `help
auth
apisecurity
compute
config
config-store
config-store-entry
dashboard
domain
install
ip-list
kv-store
kv-store-entry
log-tail
ngwaf
object-storage
pops
products
secret-store
secret-store-entry
service
stats
tls-config
tls-custom
tls-platform
tls-subscription
tools
update
user
version
whoami
`,
},
}
for testcaseIdx := range scenarios {
testcase := &scenarios[testcaseIdx]
t.Run(testcase.Name, func(t *testing.T) {
var (
stdout bytes.Buffer
stderr bytes.Buffer
)
// NOTE: The Kingpin dependency internally overrides our stdout
// variable when doing shell completion to the os.Stdout variable and so
// in order for us to verify it contains the shell completion output, we
// need an os.Pipe so we can copy off anything written to os.Stdout.
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
outC := make(chan string)
go func() {
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
outC <- buf.String()
}()
app.Init = func(_ []string, _ io.Reader) (*global.Data, error) {
return testutil.MockGlobalData(testutil.SplitArgs(testcase.Args), &stdout), nil
}
err := app.Run(testutil.SplitArgs(testcase.Args), nil)
if err != nil {
errors.Deduce(err).Print(&stderr)
}
w.Close()
os.Stdout = old
out := <-outC
testutil.AssertString(t, testcase.WantOutput, stripTrailingSpace(out))
})
}
}
// TestExecQuietSuppressesExpiryWarning exercises the full Exec path to verify
// that --quiet suppresses the expiration warning end-to-end.
func TestExecQuietSuppressesExpiryWarning(t *testing.T) {
var stdout bytes.Buffer
args := testutil.SplitArgs("config -l --quiet")
app.Init = func(_ []string, _ io.Reader) (*global.Data, error) {
data := testutil.MockGlobalData(args, &stdout)
// Set the default token to expire soon so a warning would fire without --quiet.
data.Config.Auth.Tokens["user"].APITokenExpiresAt = time.Now().Add(3 * 24 * time.Hour).Format(time.RFC3339)
return data, nil
}
err := app.Run(args, nil)
if err != nil {
t.Fatalf("app.Run returned unexpected error: %v", err)
}
output := stdout.String()
if strings.Contains(output, "expires in") {
t.Errorf("--quiet should suppress expiry warning, but got: %s", output)
}
}
// TestExecConfigShowsExpiryWarning is a companion test verifying the warning
// does appear for a non-quiet, non-auth command when the token is expiring.
func TestExecConfigShowsExpiryWarning(t *testing.T) {
var stdout bytes.Buffer
args := testutil.SplitArgs("config -l")
app.Init = func(_ []string, _ io.Reader) (*global.Data, error) {
data := testutil.MockGlobalData(args, &stdout)
data.Config.Auth.Tokens["user"].APITokenExpiresAt = time.Now().Add(3 * 24 * time.Hour).Format(time.RFC3339)
return data, nil
}
err := app.Run(args, nil)
if err != nil {
t.Fatalf("app.Run returned unexpected error: %v", err)
}
output := stdout.String()
if !strings.Contains(output, "expires in") {
t.Errorf("expected expiry warning for config command, got: %s", output)
}
}
// TestExecJSONLeavesStdoutCleanAndWritesWarningToStderr verifies that in
// --json mode, the expiry warning is written to stderr (not stdout) so it
// does not corrupt JSON output. Because the config command does not register
// --json as a flag, we simulate the effect by pre-setting Flags.JSON (which
// is what Exec does when it sees --json in the args).
func TestExecJSONLeavesStdoutCleanAndWritesWarningToStderr(t *testing.T) {
var (
stdout bytes.Buffer
stderr bytes.Buffer
)
args := testutil.SplitArgs("config -l")
app.Init = func(_ []string, _ io.Reader) (*global.Data, error) {
data := testutil.MockGlobalData(args, &stdout)
data.ErrOutput = &stderr
data.Flags.JSON = true
data.Config.Auth.Tokens["user"].APITokenExpiresAt = time.Now().Add(3 * 24 * time.Hour).Format(time.RFC3339)
return data, nil
}
err := app.Run(args, nil)
if err != nil {
t.Fatalf("app.Run returned unexpected error: %v", err)
}
if strings.Contains(stdout.String(), "expires in") {
t.Errorf("expected stdout free of expiry warning, got: %s", stdout.String())
}
if !strings.Contains(stderr.String(), "expires in") {
t.Errorf("expected expiry warning on stderr, got: %s", stderr.String())
}
}
// stripTrailingSpace removes any trailing spaces from the multiline str.
func stripTrailingSpace(str string) string {
buf := bytes.NewBuffer(nil)
scan := bufio.NewScanner(strings.NewReader(str))
for scan.Scan() {
_, _ = buf.WriteString(strings.TrimRight(scan.Text(), " \t\r\n"))
_, _ = buf.WriteString("\n")
}
return buf.String()
}