-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathroot_test.go
More file actions
292 lines (257 loc) · 8.8 KB
/
root_test.go
File metadata and controls
292 lines (257 loc) · 8.8 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright 2022-2026 Salesforce, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"fmt"
"os"
"strings"
"testing"
"github.com/slackapi/slack-cli/internal/iostreams"
"github.com/slackapi/slack-cli/internal/shared"
"github.com/slackapi/slack-cli/internal/slackcontext"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/slackapi/slack-cli/test/testutil"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestRootCommand(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
tmp, _ := os.MkdirTemp("", "")
_ = os.Chdir(tmp)
defer os.RemoveAll(tmp)
// Get command
cmd, _ := Init(ctx)
// Create mocks
clientsMock := shared.NewClientsMock()
testutil.MockCmdIO(clientsMock.IO, cmd)
err := cmd.ExecuteContext(ctx)
if err != nil {
assert.Fail(t, "cmd.Execute had unexpected error")
}
output := clientsMock.GetCombinedOutput()
for _, topLevelCommand := range cmd.Commands() {
// In our template, we don't print out the parent command's description if it has subcommands
// Hence, in the case where there are subcommands, we should always rather be checking
// for the child command's description in the printout.
if topLevelCommand.HasSubCommands() {
for _, subCommand := range topLevelCommand.Commands() {
// We should also ensure that we are not showing a subcommand if the parent is supposed to be hidden.
if subCommand.Hidden || subCommand.Parent().Hidden {
// Since this subcommand is to be hidden, we should not be relying on the Name() of the command not being present.
// Reason: one command name could be a substring of another. A command's `Short` value is a more reliable value to check.
assert.NotContains(t, output, subCommand.Short, fmt.Sprintf("should contain %s in help output", subCommand.Short))
} else {
assert.Contains(t, output, subCommand.Short, fmt.Sprintf("should contain %s in help output", subCommand.Short))
assert.Contains(t, output, subCommand.Name(), fmt.Sprintf("should contain %s in help output", subCommand.Name()))
}
}
} else {
// Since the command does not have child commands, we should check for the top-level command's description instead
if topLevelCommand.Hidden {
assert.NotContains(t, output, topLevelCommand.Short, fmt.Sprintf("should contain %s in help output", topLevelCommand.Short))
} else {
assert.Contains(t, output, topLevelCommand.Name(), fmt.Sprintf("should contain %s in help output", topLevelCommand.Name()))
assert.Contains(t, output, topLevelCommand.Short, fmt.Sprintf("should contain %s in help output", topLevelCommand.Short))
}
}
}
}
func TestExecuteContext(t *testing.T) {
tests := map[string]struct {
mockErr error
mockRuntime string
expectedExitCode iostreams.ExitCode
expectedOutputs []string
unexpectedOutputs []string
}{
"Command successfully executes": {
mockErr: nil,
expectedExitCode: iostreams.ExitOK,
},
"Command fails execution and returns an error": {
mockErr: fmt.Errorf("command failed"),
expectedExitCode: iostreams.ExitError,
expectedOutputs: []string{
"command failed",
},
},
"Command fails execution with a missing hook and missing runtime": {
mockErr: slackerror.New(slackerror.ErrSDKHookNotFound),
expectedExitCode: iostreams.ExitError,
expectedOutputs: []string{
slackerror.New(slackerror.ErrRuntimeNotFound).
WithRootCause(slackerror.New(slackerror.ErrSDKHookNotFound).WithRemediation("")).
Error(),
},
},
"Command fails execution with a missing hook and existing runtime": {
mockErr: slackerror.New(slackerror.ErrSDKHookNotFound),
mockRuntime: "sh",
expectedExitCode: iostreams.ExitError,
expectedOutputs: []string{
slackerror.New(slackerror.ErrSDKHookNotFound).Error(),
},
unexpectedOutputs: []string{
slackerror.ErrRuntimeNotFound,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
// Mock clients
clientsMock := shared.NewClientsMock()
clientsMock.AddDefaultMocks()
clientsMock.EventTracker.On("FlushToLogstash", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil)
clients := shared.NewClientFactory(clientsMock.MockClientFactory(), func(clients *shared.ClientFactory) {
clients.SDKConfig.Runtime = tc.mockRuntime
})
// Mock command
cmd := &cobra.Command{
Use: "mock [flags]",
RunE: func(cmd *cobra.Command, args []string) error {
return tc.mockErr
},
}
testutil.MockCmdIO(clientsMock.IO, cmd)
// Execute the command
ExecuteContext(ctx, cmd, clients)
output := clientsMock.GetCombinedOutput()
// Assertions
require.Equal(t, tc.expectedExitCode, clients.IO.GetExitCode())
clientsMock.EventTracker.AssertCalled(t, "FlushToLogstash", mock.Anything, mock.Anything, mock.Anything, tc.expectedExitCode)
for _, expectedOutput := range tc.expectedOutputs {
require.Contains(t, output, expectedOutput)
}
for _, unexpectedOutputs := range tc.unexpectedOutputs {
require.NotContains(t, output, unexpectedOutputs)
}
})
}
}
func TestVersionFlags(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
tmp, _ := os.MkdirTemp("", "")
_ = os.Chdir(tmp)
defer os.RemoveAll(tmp)
var output string
// Get command
cmd, _ := Init(ctx)
// Create mocks
clientsMock := shared.NewClientsMock()
testutil.MockCmdIO(clientsMock.IO, cmd)
// Test --version
cmd.SetArgs([]string{"--version"})
err := cmd.ExecuteContext(ctx)
if err != nil {
assert.Fail(t, "cmd.Execute had unexpected error", err.Error())
}
output = clientsMock.GetCombinedOutput()
assert.True(t, testutil.ContainsSemVer(output), `--version should output the version number but yielded "%s"`, output)
// Test -v
cmd.SetArgs([]string{"-v"})
err2 := cmd.ExecuteContext(ctx)
if err2 != nil {
assert.Fail(t, "cmd.Execute had unexpected error", err.Error())
}
output = clientsMock.GetCombinedOutput()
assert.True(t, testutil.ContainsSemVer(output), `-v should output the version number but yielded "%s"`, output)
}
func Test_NewSuggestion(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
tmp, _ := os.MkdirTemp("", "")
_ = os.Chdir(tmp)
defer os.RemoveAll(tmp)
// Get command
cmd, clients := Init(ctx)
// Create mocks
clientsMock := shared.NewClientsMock()
clients.IO = clientsMock.IO
testutil.MockCmdIO(clientsMock.IO, cmd)
// Execute new command
cmd.SetArgs([]string{"new"})
err := cmd.ExecuteContext(ctx)
require.Error(t, err, "should have error because command not found")
require.Regexp(t, `Did you mean this\?\s+create`, err.Error(), "should suggest the create command")
}
func Test_Aliases(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
tmp, _ := os.MkdirTemp("", "")
_ = os.Chdir(tmp)
defer os.RemoveAll(tmp)
Init(ctx)
tests := map[string]struct {
args string
expected string
}{
"List alias": {
args: "list --help",
expected: "auth list",
},
"Login alias": {
args: "login --help",
expected: "auth login",
},
"Logout alias": {
args: "logout --help",
expected: "auth logout",
},
"Activity alias": {
args: "activity --help",
expected: "platform activity",
},
"Deploy alias": {
args: "deploy --help",
expected: "platform deploy",
},
"Run alias": {
args: "run --help",
expected: "platform run",
},
"Install alias": {
args: "install --help",
expected: "app install",
},
"Uninstall alias": {
args: "uninstall --help",
expected: "app uninstall",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
output, err := testExecCmd(ctx, strings.Fields(tc.args))
require.NoError(t, err)
require.Contains(t, output, tc.expected)
})
}
}
// testExecCmd will execute the root cobra command with args and return the output
func testExecCmd(ctx context.Context, args []string) (string, error) {
// Get command
cmd, clients := Init(ctx)
// Create mocks
clientsMock := shared.NewClientsMock()
clientsMock.AddDefaultMocks()
clients.IO = clientsMock.IO
testutil.MockCmdIO(clientsMock.IO, cmd)
cmd.SetArgs(args)
err := cmd.ExecuteContext(ctx)
if err != nil {
return "", err
}
return clientsMock.GetCombinedOutput(), nil
}