-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathapp_test.go
More file actions
595 lines (548 loc) · 19.1 KB
/
app_test.go
File metadata and controls
595 lines (548 loc) · 19.1 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// 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 api
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/slackapi/slack-cli/internal/config"
"github.com/slackapi/slack-cli/internal/iostreams"
"github.com/slackapi/slack-cli/internal/shared/types"
"github.com/slackapi/slack-cli/internal/slackcontext"
"github.com/slackapi/slack-cli/internal/slackdeps"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestClient_CreateApp_Ok(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appManifestCreateMethod,
ExpectedRequest: `{"manifest":{"display_information":{"name":"TestApp"}},"enable_distribution":true}`,
Response: `{"ok":true,"app_id":"A123"}`,
})
defer teardown()
result, err := c.CreateApp(ctx, "token", types.AppManifest{
DisplayInformation: types.DisplayInformation{
Name: "TestApp",
},
}, /* enableDistribution= */ true)
require.NoError(t, err)
require.Equal(t, "A123", result.AppID)
}
func TestClient_CreateApp_CommonErrors(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
verifyCommonErrorCases(t, appManifestCreateMethod, func(c *Client) error {
_, err := c.CreateApp(ctx, "token", types.AppManifest{}, false)
return err
})
}
func TestClient_ExportAppManifest_Ok(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appManifestExportMethod,
ExpectedRequest: `{"app_id":"A0123456789"}`,
Response: `{"ok":true,"manifest":{"display_information":{"name":"example"}}}`,
})
defer teardown()
result, err := c.ExportAppManifest(ctx, "token", "A0123456789")
require.NoError(t, err)
require.Equal(t, "example", result.Manifest.DisplayInformation.Name)
}
func TestClient_ExportAppManifest_CommonErrors(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
verifyCommonErrorCases(t, appManifestExportMethod, func(c *Client) error {
_, err := c.ExportAppManifest(ctx, "token", "A0000000001")
return err
})
}
func TestClient_UpdateApp_OK(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appManifestUpdateMethod,
ExpectedRequest: `{"manifest":{"display_information":{"name":"TestApp"},"outgoing_domains":[]},"app_id":"A123","force_update":true,"consent_breaking_changes":true}`,
Response: `{"ok":true,"app_id":"A123"}`,
})
defer teardown()
result, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{
DisplayInformation: types.DisplayInformation{
Name: "TestApp",
},
OutgoingDomains: &[]string{},
},
/* forceUpdate= */ true,
/* continueWithBreakingChanges= */ true)
require.NoError(t, err)
require.Equal(t, "A123", result.AppID)
}
func TestClient_UpdateApp_CommonErrors(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
verifyCommonErrorCases(t, appManifestUpdateMethod, func(c *Client) error {
_, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{},
/* forceUpdate= */ true,
/* continueWithBreakingChanges= */ true)
return err
})
}
func TestClient_UpdateApp_SchemaCompatibilityError(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appManifestUpdateMethod,
Response: `{"ok": false, "error": "err", "errors": [{"message": "schema_compatibility_error: Following datatstore(s) will be deleted after the deploy: tasks"}]}`,
})
defer teardown()
_, err := c.UpdateApp(ctx, "token", "A123", types.AppManifest{},
/* forceUpdate= */ true,
/* continueWithBreakingChanges= */ true)
require.Error(t, err)
require.Contains(t, err.Error(), "schema_compatibility_error")
}
func TestClient_ValidateAppManifest(t *testing.T) {
// Error Fixtures
var errInvalidManifestCode = "invalid_manifest"
var errInvalidManifestDesc = "Illegal bot scopes found"
// Error detail illegal_bot_scopes
var errInvalidManifestDetailIllegalBotScopes = slackerror.ErrorDetail{
Code: "illegal_bot_scopes",
Message: "Illegal bot scopes found 'thisisnotascope'",
Pointer: "/oauth_config/scopes/bot",
}
var errorDetails slackerror.ErrorDetails
errorDetails = append(errorDetails, errInvalidManifestDetailIllegalBotScopes)
// Error detail connector_not_installed
var errInvalidManifestDetailConnectorNotInstalled = slackerror.ErrorDetail{
Code: slackerror.ErrConnectorNotInstalled,
Message: "Function `post_random_gif` from `Giphy` found in step `0` of the Workflow references Workflow Steps that are not installed in the Workspace.",
Pointer: "/workflows/post_random_gif/steps/0",
}
var errorDetails2 slackerror.ErrorDetails
errorDetails2 = append(errorDetails2, errInvalidManifestDetailConnectorNotInstalled)
// Warning Fixtures
var breakingChangeWarning = slackerror.Warning{
Code: "breaking_change",
Message: "Required properties removed: ['id'].",
Pointer: "/events/incident_created",
}
var warnings slackerror.Warnings
warnings = append(warnings, breakingChangeWarning)
// Setup tests
type args struct {
token string
appID string
manifest types.AppManifest
}
tests := map[string]struct {
httpResponseJSON string
args args
want ValidateAppManifestResult
wantErr bool
wantErrVal error
}{
"handles an ok error ": {
httpResponseJSON: `{"ok": true, "errors":[]}`,
want: ValidateAppManifestResult{nil},
},
"returns an error and error details on invalid_manifest": {
httpResponseJSON: fmt.Sprintf(
`{"ok":false,"error":"%s","slack_cli_error_description":"%s","errors":[{"code":"%s","message":"%s","pointer":"%s"}]}`,
errInvalidManifestCode,
errInvalidManifestDesc,
errInvalidManifestDetailIllegalBotScopes.Code,
errInvalidManifestDetailIllegalBotScopes.Message,
errInvalidManifestDetailIllegalBotScopes.Pointer,
),
want: ValidateAppManifestResult{nil},
wantErr: true,
wantErrVal: slackerror.NewAPIError(errInvalidManifestCode, errInvalidManifestDesc, errorDetails, appManifestValidateMethod),
},
"returns warning with breaking_change": {
httpResponseJSON: fmt.Sprintf(
`{"ok":true,"errors":[],"warnings":[{"code":"%s","message":"%s","pointer":"%s"}]}`,
breakingChangeWarning.Code,
breakingChangeWarning.Message,
breakingChangeWarning.Pointer,
),
want: ValidateAppManifestResult{warnings},
},
// This shouldn't happen right now, but adding a test to make sure that if we start sending back warnings AND
// errors nothing breaks and nothing unexpected happens - we should still return JUST the error and no warning
"returns error on invalid_manifest and warnings with breaking_change": {
httpResponseJSON: fmt.Sprintf(
`{"ok":true,"error":"%s","slack_cli_error_description":"%s","errors":[{"code":"%s","message":"%s","pointer":"%s"}],"warnings":[{"code":"%s","message":"%s","pointer":"%s"}]}`,
errInvalidManifestCode,
errInvalidManifestDesc,
errInvalidManifestDetailIllegalBotScopes.Code,
errInvalidManifestDetailIllegalBotScopes.Message,
errInvalidManifestDetailIllegalBotScopes.Pointer,
breakingChangeWarning.Code,
breakingChangeWarning.Message,
breakingChangeWarning.Pointer,
),
want: ValidateAppManifestResult{nil},
wantErr: true,
wantErrVal: slackerror.NewAPIError(errInvalidManifestCode, errInvalidManifestDesc, errorDetails, appManifestValidateMethod),
},
"returns an error invalid_manifest when error detail is due to connector not being installed": {
httpResponseJSON: fmt.Sprintf(
`{"ok":false,"error":"%s","errors":[{"code":"%s","message":"%s","pointer":"%s"}]}`,
errInvalidManifestCode,
errInvalidManifestDetailConnectorNotInstalled.Code,
errInvalidManifestDetailConnectorNotInstalled.Message,
errInvalidManifestDetailConnectorNotInstalled.Pointer,
),
want: ValidateAppManifestResult{nil},
wantErr: true,
wantErrVal: slackerror.NewAPIError(errInvalidManifestCode, "", errorDetails2, appManifestValidateMethod),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appManifestValidateMethod,
Response: tc.httpResponseJSON,
})
defer teardown()
got, err := c.ValidateAppManifest(ctx, tc.args.token, tc.args.manifest, tc.args.appID)
if tc.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.wantErrVal.Error())
return
}
require.Equal(t, tc.want, got)
})
}
}
func TestClient_GetPresignedS3PostParams_Ok(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appGeneratePresignedPostMethod,
ExpectedRequest: `{"app_id":"A123"}`,
Response: `{"ok":true,"url":"example.com/upload","file_name":"foo.tar.gz","fields":{"X-Amz-Credential":"cred"}}`,
})
defer teardown()
result, err := c.GetPresignedS3PostParams(ctx, "token", "A123")
require.NoError(t, err)
require.Equal(t, "foo.tar.gz", result.FileName)
require.Equal(t, "example.com/upload", result.URL)
require.Equal(t, "cred", result.Fields.AmzCredentials)
}
func TestClient_GetPresignedS3PostParams_CommonErrors(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
verifyCommonErrorCases(t, appGeneratePresignedPostMethod, func(c *Client) error {
_, err := c.GetPresignedS3PostParams(ctx, "token", "A123")
return err
})
}
func TestClient_CertifiedAppInstall(t *testing.T) {
tests := map[string]struct {
mockAppID string
httpResponseJSON string
}{
"OK result": {
mockAppID: "A123",
httpResponseJSON: `{"ok":true}`,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appCertifiedInstallMethod,
ExpectedRequest: fmt.Sprintf(`{"app_id":"%s"}`, tc.mockAppID),
Response: tc.httpResponseJSON,
})
defer teardown()
// execute
_, err := c.CertifiedAppInstall(ctx, "token", tc.mockAppID)
// check
require.NoError(t, err)
})
}
}
func TestClient_InstallApp(t *testing.T) {
var setup = func(t *testing.T) (context.Context, *iostreams.IOStreamsMock) {
// Mocks
ctx := slackcontext.MockContext(t.Context())
fsMock := slackdeps.NewFsMock()
osMock := slackdeps.NewOsMock()
osMock.AddDefaultMocks()
config := config.NewConfig(fsMock, osMock)
ioMock := iostreams.NewIOStreamsMock(config, fsMock, osMock)
return ctx, ioMock
}
tests := map[string]struct {
mockAppID string
httpResponseJSON string
expectedErr *slackerror.Error
}{
"OK result": {
mockAppID: "A123",
httpResponseJSON: `{"ok":true}`,
},
"Error result": {
mockAppID: "A123",
httpResponseJSON: `{"ok":false,"error":"invalid_app_id"}`,
expectedErr: slackerror.New(slackerror.ErrInvalidAppID),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx, ioMock := setup(t)
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appDeveloperInstallMethod,
ExpectedRequest: fmt.Sprintf(`{"app_id":"%s"}`, tc.mockAppID),
Response: tc.httpResponseJSON,
})
defer teardown()
mockApp := types.App{
AppID: tc.mockAppID,
TeamID: "T123",
TeamDomain: "mock",
}
// execute
_, _, err := c.DeveloperAppInstall(ctx, ioMock, "token", mockApp, []string{}, []string{}, "", false)
// check
if tc.expectedErr != nil {
assert.Equal(t, slackerror.ToSlackError(err).Code, tc.expectedErr.Code)
} else {
assert.NoError(t, err)
}
})
}
}
func TestClient_UninstallApp(t *testing.T) {
tests := map[string]struct {
httpResponseJSON string
wantErr bool
errMessage string
}{
"OK result": {
httpResponseJSON: `{"ok":true}`,
},
"Error result": {
httpResponseJSON: `{"ok":false,"error":"invalid_app_id"}`,
wantErr: true,
errMessage: "invalid_app_id",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appDeveloperUninstallMethod,
ExpectedRequest: `{"app_id":"A123","team_id":"T123"}`,
Response: tc.httpResponseJSON,
})
defer teardown()
// execute
err := c.UninstallApp(ctx, "token", "A123", "T123")
// check
if (err != nil) != tc.wantErr {
t.Errorf("%s test error = %v, wantErr %v", name, err, tc.wantErr)
return
}
if tc.wantErr {
require.Contains(
t,
err.Error(),
tc.errMessage,
"test error contains invalid message",
)
}
})
}
}
func TestClient_DeleteApp(t *testing.T) {
tests := map[string]struct {
httpResponseJSON string
wantErr bool
errMessage string
}{
"OK result": {
httpResponseJSON: `{"ok":true}`,
},
"Error result": {
httpResponseJSON: `{"ok":false,"error":"invalid_app_id"}`,
wantErr: true,
errMessage: "invalid_app_id",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appDeleteMethod,
ExpectedRequest: `{"app_id":"A123"}`,
Response: tc.httpResponseJSON,
})
defer teardown()
// execute
err := c.DeleteApp(ctx, "token", "A123")
// check
if (err != nil) != tc.wantErr {
t.Errorf("%s test error = %v, wantErr %v", name, err, tc.wantErr)
return
}
if tc.wantErr {
require.Contains(
t,
err.Error(),
tc.errMessage,
"test error contains invalid message",
)
}
})
}
}
func TestClient_DeveloperAppInstall_RequestAppApproval(t *testing.T) {
tests := map[string]struct {
app types.App
orgGrantWorkspaceID string
teamID string
requestJSON string
wantErr bool
errMessage string
}{
`Standalone workspace, AAA is requested \
(workspace ID passed into apps.approvals.requests.create)`: {
app: types.App{AppID: "A1234", TeamID: "T1234"},
orgGrantWorkspaceID: "",
teamID: "T1234",
requestJSON: `{"app":"A1234","reason":"This request has been automatically generated according to project environment settings.","team_id":"T1234"}`,
},
`User tried to install to a single workspace in an org, AAA is requested \
(workspace ID passed into apps.approvals.requests.create)`: {
app: types.App{AppID: "A1234", EnterpriseID: "E1234", TeamID: "E1234"},
orgGrantWorkspaceID: "T1234",
teamID: "T1234",
requestJSON: `{"app":"A1234","reason":"This request has been automatically generated according to project environment settings.","team_id":"T1234"}`,
},
`User tried to install to all workspaces in an org, AAA is requested \
(no team_id passed into apps.approvals.requests.create so it will default to creating a request for the auth team ie. the org)`: {
app: types.App{AppID: "A1234", EnterpriseID: "E1234", TeamID: "E1234"},
orgGrantWorkspaceID: "all",
teamID: "E1234",
requestJSON: `{"app":"A1234","reason":"This request has been automatically generated according to project environment settings."}`,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
// prepare
handlerFunc := func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, appDeveloperInstallMethod) {
result := fmt.Sprintf(
`{"ok":false,"error":"%s","team_id":"%s"}`,
slackerror.ErrAppApprovalRequestEligible,
tc.teamID,
)
_, err := fmt.Fprintln(w, result)
require.NoError(t, err)
}
if strings.Contains(r.URL.Path, appApprovalRequestCreateMethod) {
expectedJSON := tc.requestJSON
payload, err := io.ReadAll(r.Body)
require.NoError(t, err)
require.Equal(t, expectedJSON, string(payload))
_, err = fmt.Fprintln(w, `{"ok":true}`)
require.NoError(t, err)
}
}
ts := httptest.NewServer(http.HandlerFunc(handlerFunc))
defer ts.Close()
c := NewClient(&http.Client{}, ts.URL, nil)
iostreamMock := iostreams.NewIOStreamsMock(&config.Config{}, &slackdeps.FsMock{}, &slackdeps.OsMock{})
iostreamMock.On("PrintTrace", mock.Anything, mock.Anything, mock.Anything).Return()
// execute
_, _, err := c.DeveloperAppInstall(ctx, iostreamMock, "token", tc.app, []string{}, []string{}, tc.orgGrantWorkspaceID, true)
require.NoError(t, err)
})
}
}
func Test_Client_GetAppStatus(t *testing.T) {
tests := map[string]struct {
httpResponseJSON string
wantErr bool
errMessage string
}{
"OK result": {
httpResponseJSON: `{"ok":true,"apps":[{"app_id":"A123","status":"installed"}]}`,
},
"Error result": {
httpResponseJSON: `{"ok":false,"error":"invalid_app"}`,
wantErr: true,
errMessage: "invalid_app",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appStatusMethod,
Response: tc.httpResponseJSON,
})
defer teardown()
result, err := c.GetAppStatus(ctx, "token", []string{"A123"}, "T123")
if tc.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.errMessage)
} else {
require.NoError(t, err)
require.NotNil(t, result)
}
})
}
}
func Test_Client_ConnectionsOpen(t *testing.T) {
tests := map[string]struct {
httpResponseJSON string
wantErr bool
errMessage string
expectedURL string
}{
"OK result": {
httpResponseJSON: `{"ok":true,"url":"wss://example.com/ws"}`,
expectedURL: "wss://example.com/ws",
},
"Error result": {
httpResponseJSON: `{"ok":false,"error":"token_revoked"}`,
wantErr: true,
errMessage: "token_revoked",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := slackcontext.MockContext(t.Context())
c, teardown := NewFakeClient(t, FakeClientParams{
ExpectedMethod: appConnectionsOpenMethod,
Response: tc.httpResponseJSON,
})
defer teardown()
result, err := c.ConnectionsOpen(ctx, "token")
if tc.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.errMessage)
} else {
require.NoError(t, err)
require.Equal(t, tc.expectedURL, result.URL)
}
})
}
}