-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathcreate_test.go
More file actions
515 lines (482 loc) · 17.1 KB
/
create_test.go
File metadata and controls
515 lines (482 loc) · 17.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
// 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 create
import (
"fmt"
"net/http"
"path/filepath"
"testing"
"github.com/slackapi/slack-cli/internal/config"
"github.com/slackapi/slack-cli/internal/experiment"
"github.com/slackapi/slack-cli/internal/logger"
"github.com/slackapi/slack-cli/internal/shared"
"github.com/slackapi/slack-cli/internal/slackcontext"
"github.com/slackapi/slack-cli/internal/slackhttp"
"github.com/slackapi/slack-cli/internal/style"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestCreate(t *testing.T) {
assert.True(t, true, "should be true")
}
func TestGetProjectDirectoryName(t *testing.T) {
tests := map[string]struct {
input string
expected string
hasError bool
}{
"empty name returns error": {
input: "",
hasError: true,
},
"simple kebab-case name": {
input: "my-app",
expected: "my-app",
},
"spaces replaced with hyphens": {
input: "my cool app",
expected: "my-cool-app",
},
"leading and trailing spaces trimmed": {
input: " my-app ",
expected: "my-app",
},
"uppercase converted to lowercase": {
input: "My Slack App",
expected: "my-slack-app",
},
"mixed case normalized": {
input: "My-Slack-App",
expected: "my-slack-app",
},
"special characters replaced with dashes": {
input: "my_app!@#test",
expected: "my-app-test",
},
"consecutive special characters collapsed to single dash": {
input: "my---app",
expected: "my-app",
},
"leading and trailing special characters trimmed": {
input: "---my-app---",
expected: "my-app",
},
"dots converted to dashes": {
input: ".my-app",
expected: "my-app",
},
"only special characters returns error": {
input: "!!!",
hasError: true,
},
"numbers preserved": {
input: "app123",
expected: "app123",
},
"complex mixed input": {
input: " My Cool App! (v2) ",
expected: "my-cool-app-v2",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result, err := getAppDirName(tc.input)
if tc.hasError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tc.expected, result)
}
})
}
}
func TestGetAvailableDirectory(t *testing.T) {
var exists bool
var err error
// Current directory should exist
exists, err = parentDirExists("pkg")
assert.True(t, exists, "should exist")
assert.Nil(t, err, "should not return an error")
// Random directory should not exist
exists, err = parentDirExists(`path/to/my-app`)
assert.False(t, exists, "should not exist")
assert.Error(t, err, "should return an error")
// Dot notation for current directory (.) should exist
exists, err = parentDirExists(`.`)
assert.True(t, exists, "should exist")
assert.Nil(t, err, "should not return an error")
// Dot notation for parent directory (..) should exist
exists, err = parentDirExists(`..`)
assert.True(t, exists, "should exist")
assert.Nil(t, err, "should not return an error")
}
func Test_generateGitZipFileURL(t *testing.T) {
tests := map[string]struct {
templateURL string
gitBranch string
expectedURL string
setupHTTPClientMock func(*slackhttp.HTTPClientMock)
}{
"Returns the zip URL using the main branch when no branch is provided": {
templateURL: "https://github.com/slack-samples/deno-starter-template",
gitBranch: "",
expectedURL: "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/main.zip",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusOK, "OK")
httpClientMock.On("Head", mock.Anything).Return(res, nil)
},
},
"Returns the zip URL using the master branch when no branch is provided and main branch doesn't exist": {
templateURL: "https://github.com/slack-samples/deno-starter-template",
gitBranch: "",
expectedURL: "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/master.zip",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusOK, "OK")
httpClientMock.On("Head", "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/main.zip").Return(nil, fmt.Errorf("HttpClient error"))
httpClientMock.On("Head", "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/master.zip").Return(res, nil)
},
},
"Returns the zip URL using the specified branch when a branch is provided": {
templateURL: "https://github.com/slack-samples/deno-starter-template",
gitBranch: "pre-release-0316",
expectedURL: "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/pre-release-0316.zip",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusOK, "OK")
httpClientMock.On("Head", mock.Anything).Return(res, nil)
},
},
"Returns an empty string when the HTTP status code is not 200": {
templateURL: "https://github.com/slack-samples/deno-starter-template",
gitBranch: "",
expectedURL: "",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusNotFound, "Not Found")
httpClientMock.On("Head", mock.Anything).Return(res, nil)
},
},
"Returns an empty string when the HTTPClient has an error": {
templateURL: "https://github.com/slack-samples/deno-starter-template",
gitBranch: "",
expectedURL: "",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
httpClientMock.On("Head", mock.Anything).Return(nil, fmt.Errorf("HTTPClient error"))
},
},
"Returns the zip URL with .git suffix removed": {
templateURL: "https://github.com/slack-samples/deno-starter-template.git",
gitBranch: "",
expectedURL: "https://github.com/slack-samples/deno-starter-template/archive/refs/heads/main.zip",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusOK, "OK")
httpClientMock.On("Head", mock.Anything).Return(res, nil)
},
},
"Returns the zip URL with .git inside URL preserved": {
templateURL: "https://github.com/slack-samples/deno.git-starter-template",
gitBranch: "",
expectedURL: "https://github.com/slack-samples/deno.git-starter-template/archive/refs/heads/main.zip",
setupHTTPClientMock: func(httpClientMock *slackhttp.HTTPClientMock) {
res := slackhttp.MockHTTPResponse(http.StatusOK, "OK")
httpClientMock.On("Head", mock.Anything).Return(res, nil)
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// Create mocks
httpClientMock := &slackhttp.HTTPClientMock{}
tc.setupHTTPClientMock(httpClientMock)
// Execute
url := generateGitZipFileURL(httpClientMock, tc.templateURL, tc.gitBranch)
// Assertions
assert.Equal(t, tc.expectedURL, url)
})
}
}
func TestCreateGitArgs(t *testing.T) {
var testGitArgs, expectedArgs []string
templatePath := "git://github.com:slackapi/bolt-js-getting-started-app"
// TemplateURLFlag
testGitArgs = createGitArgs(templatePath, "./", "")
expectedArgs = []string{"clone", "--depth=1", "git://github.com:slackapi/bolt-js-getting-started-app", "./"}
assert.Equal(t, expectedArgs, testGitArgs)
// GitBranchFlag
testGitArgs = createGitArgs(templatePath, "./", "test-branch")
expectedArgs = []string{"clone", "--depth=1", "git://github.com:slackapi/bolt-js-getting-started-app", "./", "--branch", "test-branch"}
assert.Equal(t, expectedArgs, testGitArgs)
// GitBranchFlag as empty string
testGitArgs = createGitArgs(templatePath, "./", " ")
expectedArgs = []string{"clone", "--depth=1", "git://github.com:slackapi/bolt-js-getting-started-app", "./"}
assert.Equal(t, expectedArgs, testGitArgs)
}
func TestNormalizeSubdir(t *testing.T) {
tests := map[string]struct {
input string
expected string
expectError bool
}{
"empty string returns empty": {
input: "",
expected: "",
},
"dot returns empty": {
input: ".",
expected: "",
},
"slash returns empty": {
input: "/",
expected: "",
},
"simple subdir": {
input: "pydantic-ai/",
expected: "pydantic-ai",
},
"dot-prefixed subdir": {
input: "./my-app",
expected: "my-app",
},
"nested subdir": {
input: "apps/my-app",
expected: "apps/my-app",
},
"parent traversal is rejected": {
input: "../escape",
expectError: true,
},
"nested parent traversal is rejected": {
input: "foo/../../escape",
expectError: true,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
result, err := normalizeSubdir(tc.input)
if tc.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tc.expected, result)
}
})
}
}
func TestCreateAppFromSubdir(t *testing.T) {
tests := map[string]struct {
setupTemplate func(t *testing.T, fs afero.Fs) string
subdir string
expectError bool
errorContains string
expectFiles []string
}{
"extracts subdirectory from local template": {
setupTemplate: func(t *testing.T, fs afero.Fs) string {
tmpDir := t.TempDir()
// Create a subdirectory with a file
subdir := filepath.Join(tmpDir, "apps", "my-app")
require.NoError(t, fs.MkdirAll(subdir, 0755))
require.NoError(t, afero.WriteFile(fs, filepath.Join(subdir, "manifest.json"), []byte(`{}`), 0644))
// Create a file at root that should NOT be copied
require.NoError(t, afero.WriteFile(fs, filepath.Join(tmpDir, "README.md"), []byte("root readme"), 0644))
return tmpDir
},
subdir: "apps/my-app",
expectFiles: []string{"manifest.json"},
},
"returns error for nonexistent subdirectory": {
setupTemplate: func(t *testing.T, fs afero.Fs) string {
return t.TempDir()
},
subdir: "nonexistent",
expectError: true,
errorContains: "was not found in the template",
},
"returns error when subdir path is a file": {
setupTemplate: func(t *testing.T, fs afero.Fs) string {
tmpDir := t.TempDir()
require.NoError(t, afero.WriteFile(fs, filepath.Join(tmpDir, "not-a-dir"), []byte("file"), 0644))
return tmpDir
},
subdir: "not-a-dir",
expectError: true,
errorContains: "is not a directory",
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
fs := afero.NewOsFs()
templateDir := tc.setupTemplate(t, fs)
outputDir := t.TempDir()
// Remove output dir so CopyDirectory can create it
require.NoError(t, fs.Remove(outputDir))
template := Template{path: templateDir, isLocal: true}
log := logger.New(func(event *logger.LogEvent) {})
err := createAppFromSubdir(t.Context(), outputDir, template, "", tc.subdir, log, fs)
if tc.expectError {
assert.Error(t, err)
if tc.errorContains != "" {
assert.Contains(t, err.Error(), tc.errorContains)
}
} else {
assert.NoError(t, err)
for _, f := range tc.expectFiles {
_, statErr := fs.Stat(filepath.Join(outputDir, f))
assert.NoError(t, statErr, "expected file %s to exist", f)
}
}
})
}
}
func Test_Create_installProjectDependencies(t *testing.T) {
tests := map[string]struct {
experiments []string
runtime string
manifestSource config.ManifestSource
existingFiles map[string]string
expectedOutputs []string
unexpectedOutputs []string
expectedVerboseOutputs []string
expectedVerboseArgs []any
}{
"Should output added .slack, hooks.json, .gitignore, and caching": {
expectedOutputs: []string{
"Added project-name/.slack",
"Added project-name/.slack/.gitignore",
"Added project-name/.slack/hooks.json",
"Cached dependencies with deno cache import_map.json",
},
expectedVerboseOutputs: []string{
"Detected a project using %s",
},
expectedVerboseArgs: []any{style.Highlight("Deno")},
},
"When hooks.json exists, should output found .slack and hooks.json": {
existingFiles: map[string]string{
".slack/hooks.json": "{}",
},
expectedOutputs: []string{
"Found project-name/.slack",
"Found project-name/.slack/hooks.json",
"Cached dependencies with deno cache import_map.json",
},
unexpectedOutputs: []string{
"Added project-name/.slack", // Already exists
"Error adding the directory project-name/.slack",
},
expectedVerboseOutputs: []string{
"Detected a project using %s",
},
expectedVerboseArgs: []any{style.Highlight("Deno")},
},
"When slack.json exists, should output added .slack": {
existingFiles: map[string]string{
"slack.json": "{}",
},
expectedOutputs: []string{
"Added project-name/.slack",
"Found project-name/slack.json", // DEPRECATED(semver:major): Now use hooks.json
"Cached dependencies with deno cache import_map.json",
},
expectedVerboseOutputs: []string{
"Detected a project using %s",
},
expectedVerboseArgs: []any{style.Highlight("Deno")},
},
"When no manifest source, default to project (local)": {
expectedOutputs: []string{
`Updated config.json manifest source to "project" (local)`,
},
},
"When manifest source is provided, should set it": {
manifestSource: config.ManifestSourceRemote,
expectedOutputs: []string{
`Updated config.json manifest source to "app settings" (remote)`,
},
},
"When bolt-install experiment and Deno project, should set manifest source to project (local)": {
experiments: []string{"bolt-install"},
expectedOutputs: []string{
`Updated config.json manifest source to "project" (local)`,
},
},
"When bolt-install experiment and non-Deno project, should set manifest source to app settings (remote)": {
experiments: []string{"bolt-install"},
runtime: "node",
expectedOutputs: []string{
`Updated config.json manifest source to "app settings" (remote)`,
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
// Remove any enabled experiments during the test and restore afterward
var _EnabledExperiments = experiment.EnabledExperiments
experiment.EnabledExperiments = []experiment.Experiment{}
defer func() {
// Restore original EnabledExperiments
experiment.EnabledExperiments = _EnabledExperiments
}()
// Setup parameters for test
projectDirPath := "/path/to/project-name"
// Create mocks
ctx := slackcontext.MockContext(t.Context())
clientsMock := shared.NewClientsMock()
clientsMock.Os.On("Getwd").Return(projectDirPath, nil)
clientsMock.HookExecutor.On("Execute", mock.Anything, mock.Anything).Return(`{}`, nil)
clientsMock.AddDefaultMocks()
// Set experiment flag
clientsMock.Config.ExperimentsFlag = append(clientsMock.Config.ExperimentsFlag, tc.experiments...)
clientsMock.Config.LoadExperiments(ctx, clientsMock.IO.PrintDebug)
// Create clients that is mocked for testing
clients := shared.NewClientFactory(clientsMock.MockClientFactory())
// Set runtime to be Deno (or node or whatever)
clients.SDKConfig.Runtime = "deno"
if tc.runtime != "" {
clients.SDKConfig.Runtime = tc.runtime
}
// Create project directory
if err := clients.Fs.MkdirAll(filepath.Dir(projectDirPath), 0755); err != nil {
require.FailNow(t, fmt.Sprintf("Failed to create the directory %s in the memory-based file system", projectDirPath))
}
// Create files
for filePath, fileData := range tc.existingFiles {
filePathAbs := filepath.Join(projectDirPath, filePath)
// Create the directory
if err := clients.Fs.MkdirAll(filepath.Dir(filePathAbs), 0755); err != nil {
require.FailNow(t, fmt.Sprintf("Failed to create the directory %s in the memory-based file system", filePath))
}
// Create the file
if err := afero.WriteFile(clients.Fs, filePathAbs, []byte(fileData), 0644); err != nil {
require.FailNow(t, fmt.Sprintf("Failed to create the file %s in the memory-based file system", filePath))
}
}
// Run the test
outputs := InstallProjectDependencies(ctx, clients, projectDirPath, tc.manifestSource)
// Assertions
for _, expectedOutput := range tc.expectedOutputs {
require.Contains(t, outputs, expectedOutput)
}
for _, unexpectedOutput := range tc.unexpectedOutputs {
require.NotContains(t, outputs, unexpectedOutput)
}
for _, expectedVerboseOutput := range tc.expectedVerboseOutputs {
clientsMock.IO.AssertCalled(t, "PrintDebug", mock.Anything, expectedVerboseOutput, tc.expectedVerboseArgs)
}
assert.NotEmpty(t, clients.Config.ProjectID, "config.project_id")
// output := clientsMock.GetCombinedOutput()
// assert.Contains(t, output, tc.expectedOutputs)
})
}
}