-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathapp_test.go
More file actions
509 lines (435 loc) · 14.4 KB
/
Copy pathapp_test.go
File metadata and controls
509 lines (435 loc) · 14.4 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
package main
import (
"bytes"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dgageot/gogo/taskfile"
)
func writeFile(t *testing.T, path, content string) {
t.Helper()
require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
require.NoError(t, os.WriteFile(path, []byte(content), 0o644))
}
// newTestApp builds an App wired to byte buffers, with Getwd pinned to dir.
// Pass an empty dir to fall back to os.Getwd (useful for tests that don't need a task file).
func newTestApp(t *testing.T, dir string, cliArgs ...string) (*App, *bytes.Buffer, *bytes.Buffer) {
t.Helper()
var stdout, stderr bytes.Buffer
getwd := os.Getwd
if dir != "" {
getwd = func() (string, error) { return dir, nil }
}
return &App{
Args: cliArgs,
Stdout: &stdout,
Stderr: &stderr,
Getwd: getwd,
}, &stdout, &stderr
}
func TestIsInternalTask(t *testing.T) {
assert.False(t, taskfile.IsInternalTask("build"))
assert.True(t, taskfile.IsInternalTask("_hidden"))
assert.False(t, taskfile.IsInternalTask("cli:build"))
assert.True(t, taskfile.IsInternalTask("cli:_hidden"))
assert.True(t, taskfile.IsInternalTask("cli:utils:_fmt"))
}
func TestVisibleTaskNames(t *testing.T) {
tf := &taskfile.Config{
Tasks: map[string]taskfile.Task{
"build": {},
"_internal": {},
"cli:test": {},
"cli:_helper": {},
},
}
assert.Equal(t, []string{"build", "cli:test"}, visibleTaskNames(tf))
}
func TestAppHelpWritesUsageToStdout(t *testing.T) {
app, stdout, stderr := newTestApp(t, "", "--help")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stdout.String(), "gogo - a simple task runner")
assert.Contains(t, stdout.String(), "--list")
assert.Empty(t, stderr.String())
}
func TestAppUnknownFlagReturnsError(t *testing.T) {
app, _, _ := newTestApp(t, "", "--no-such-flag")
err := app.Run(t.Context())
require.Error(t, err)
}
func TestAppCompletionBash(t *testing.T) {
app, stdout, _ := newTestApp(t, "", "--completion", "bash")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stdout.String(), "_gogo_completions")
assert.Contains(t, stdout.String(), "complete -F _gogo_completions gogo")
}
func TestAppCompletionZsh(t *testing.T) {
app, stdout, _ := newTestApp(t, "", "--completion", "zsh")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stdout.String(), "#compdef gogo")
assert.Contains(t, stdout.String(), "compdef _gogo gogo")
}
func TestAppCompletionFish(t *testing.T) {
app, stdout, _ := newTestApp(t, "", "--completion", "fish")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stdout.String(), "complete -c gogo")
}
func TestAppCompletionUnsupportedShell(t *testing.T) {
app, _, _ := newTestApp(t, "", "--completion", "pwsh")
err := app.Run(t.Context())
assert.EqualError(t, err, "unsupported shell: pwsh (valid: bash, zsh, fish)")
}
func TestAppYesFlagAutoConfirmsPrompt(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
deploy:
prompt: Deploy to production?
cmd: true
`)
app, _, stderr := newTestApp(t, dir, "--yes", "deploy")
require.NoError(t, app.Run(t.Context()))
assert.NotContains(t, stderr.String(), "[y/N]")
}
func TestAppPromptReadsStdin(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
deploy:
prompt: Deploy to production?
cmd: true
`)
app, _, stderr := newTestApp(t, dir, "deploy")
app.Stdin = strings.NewReader("n\n")
err := app.Run(t.Context())
require.ErrorContains(t, err, `task "deploy": prompt declined`)
assert.Contains(t, stderr.String(), "Deploy to production? [y/N]:")
}
func TestAppListShowsDescriptionsAndAliases(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
# Build the project
build:
cmd: go build
# Run all the tests
test:
aliases: [t]
cmd: go test
no_desc:
cmd: echo hi
`)
app, stdout, _ := newTestApp(t, dir, "--list")
require.NoError(t, app.Run(t.Context()))
out := stdout.String()
assert.Contains(t, out, "build")
assert.Contains(t, out, "Build the project")
assert.Contains(t, out, "test")
assert.Contains(t, out, "Run all the tests")
assert.Contains(t, out, "(aliases: t)")
assert.NotContains(t, out, "no_desc", "tasks without a description are omitted")
// Names render in green, aliases in cyan — the bullet plus ANSI escape
// is the simplest stable shape we can assert without coupling to widths.
assert.Contains(t, out, "* \x1b[32mbuild\x1b[0m")
assert.Contains(t, out, "\x1b[36m(aliases: t)\x1b[0m")
}
func TestAppListShowsOnlyFirstDescriptionLine(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
# Build the project
# using the local Go toolchain
build:
cmd: go build
`)
app, stdout, _ := newTestApp(t, dir, "--list")
require.NoError(t, app.Run(t.Context()))
out := stdout.String()
assert.Contains(t, out, "Build the project")
assert.NotContains(t, out, "using the local Go toolchain")
}
func TestAppListHidesInternalTasks(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
# Public task
build:
cmd: go build
# Hidden helper
_internal:
cmd: echo hidden
`)
app, stdout, _ := newTestApp(t, dir, "--list")
require.NoError(t, app.Run(t.Context()))
out := stdout.String()
assert.Contains(t, out, "build")
assert.NotContains(t, out, "_internal")
assert.NotContains(t, out, "Hidden helper")
}
func TestAppCompleteEmitsVisibleTaskNames(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
build:
cmd: go build
_internal:
cmd: echo hidden
test:
cmd: go test
`)
app, stdout, _ := newTestApp(t, dir, "--complete")
require.NoError(t, app.Run(t.Context()))
assert.Equal(t, "build\ntest\n", stdout.String())
}
func TestAppCompleteSilentOnMissingFile(t *testing.T) {
app, stdout, stderr := newTestApp(t, t.TempDir(), "--complete")
require.NoError(t, app.Run(t.Context()))
assert.Empty(t, stdout.String())
assert.Empty(t, stderr.String())
}
func TestAppListFailsWhenNoFileFound(t *testing.T) {
app, _, _ := newTestApp(t, t.TempDir(), "--list")
err := app.Run(t.Context())
require.Error(t, err)
assert.Contains(t, err.Error(), "no gogo.yaml")
}
func TestAppPropagatesGetwdError(t *testing.T) {
var stdout, stderr bytes.Buffer
app := &App{
Args: []string{"--list"},
Stdout: &stdout,
Stderr: &stderr,
Getwd: func() (string, error) { return "", io.ErrUnexpectedEOF },
}
err := app.Run(t.Context())
assert.ErrorIs(t, err, io.ErrUnexpectedEOF)
}
func TestDefaultTaskNamesUsesTopLevelDefault(t *testing.T) {
tf := &taskfile.Config{Default: "build"}
assert.Equal(t, []string{"build"}, defaultTaskNames(nil, tf))
// Explicit positional args always win over the top-level field, so
// `gogo test` still runs `test` even when default: build is declared.
assert.Equal(t, []string{"test"}, defaultTaskNames([]string{"test"}, tf))
assert.Equal(t, []string{"clean", "install"}, defaultTaskNames([]string{"clean", "install"}, tf))
}
func TestDefaultTaskNamesFallbackWhenUnset(t *testing.T) {
// Backward compatibility: with no top-level default the implicit
// "task literally named default" convention still works.
tf := &taskfile.Config{}
assert.Equal(t, []string{"default"}, defaultTaskNames(nil, tf))
}
func TestAppHelpDoesNotExposeCLIArgsFlag(t *testing.T) {
// Regression: CLIArgs is populated by parseArgs from the tail after
// `--`; it must not be advertised as a `--cliargs` flag.
app, stdout, _ := newTestApp(t, "", "--help")
require.NoError(t, app.Run(t.Context()))
assert.NotContains(t, stdout.String(), "--cliargs")
}
func TestAppRejectsCLIArgsFlag(t *testing.T) {
// Regression: `--cliargs` must not be a recognised flag — args after
// `--` are the only way to feed CLI_ARGS.
app, _, _ := newTestApp(t, "", "--cliargs", "foo")
err := app.Run(t.Context())
require.Error(t, err)
assert.Contains(t, err.Error(), "--cliargs")
}
func TestAppRunsTopLevelDefaultTask(t *testing.T) {
// End-to-end: `gogo` (no positional arg) runs the task named by the
// top-level `default:` field instead of falling back to the implicit
// `default` task. --dry prints the cmd without executing it.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
default: dev
tasks:
dev:
cmd: echo running-dev
`)
app, _, stderr := newTestApp(t, dir, "--dry")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stderr.String(), "echo running-dev")
}
func TestAppRunsMultipleTasksInSequence(t *testing.T) {
// `gogo clean install` must run both, in order, even when one is a
// dep of the other — the user explicitly asked for `clean` to run
// before `install`'s own `clean` dep, so we don't dedupe across tasks.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
clean:
cmd: echo cleaning
install:
deps: [clean]
cmd: echo installing
`)
app, _, stderr := newTestApp(t, dir, "--dry", "clean", "install")
require.NoError(t, app.Run(t.Context()))
log := stderr.String()
// Two `[clean] echo cleaning` lines: the explicit first task and the
// dep of `install`. `ResetRan` between iterations is what allows the
// second one to actually fire instead of being short-circuited.
assert.Equal(t, 2, strings.Count(log, "echo cleaning"), log)
assert.Equal(t, 1, strings.Count(log, "echo installing"), log)
assert.Less(t, strings.Index(log, "echo cleaning"), strings.Index(log, "echo installing"))
}
func TestAppMultipleTasksStopOnFirstError(t *testing.T) {
// If the first task fails, the second one must not run.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
fail:
cmd: false
ok:
cmd: echo should-not-run
`)
app, _, stderr := newTestApp(t, dir, "fail", "ok")
err := app.Run(t.Context())
require.Error(t, err)
assert.NotContains(t, stderr.String(), "should-not-run")
}
func TestAppForwardsCLIArgsAfterDoubleDash(t *testing.T) {
// Args after `--` go to every task in the sequence as `{{.CLI_ARGS}}`.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
test:
cmd: go test {{.CLI_ARGS}}
`)
app, _, stderr := newTestApp(t, dir, "--dry", "test", "--", "-v", "-run", "TestX")
require.NoError(t, app.Run(t.Context()))
assert.Contains(t, stderr.String(), "go test '-v' '-run' 'TestX'")
}
func TestAppWatchRejectsMultipleTasks(t *testing.T) {
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
a:
cmd: true
b:
cmd: true
`)
app, _, _ := newTestApp(t, dir, "--watch", "a", "b")
err := app.Run(t.Context())
require.Error(t, err)
assert.Contains(t, err.Error(), "--watch")
}
func TestAppRejectsUnknownDefault(t *testing.T) {
// A top-level `default:` that names a non-existent task fails fast at
// load time — the user gets a clear error rather than "task not found".
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
default: missing
tasks:
build:
cmd: true
`)
app, _, _ := newTestApp(t, dir)
err := app.Run(t.Context())
require.Error(t, err)
assert.Contains(t, err.Error(), `"missing"`)
}
func TestAppUnknownTaskPrintsListAndSuggestion(t *testing.T) {
// Mistyping a task name should give the user *both* the list of
// available tasks (so they can self-correct) and the closest match
// in red. The CLI returns a sentinel error so main doesn't print the
// message twice.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
# Install the binary
install:
cmd: go install
# Run tests
test:
cmd: go test
`)
app, _, stderr := newTestApp(t, dir, "instll")
err := app.Run(t.Context())
require.Error(t, err)
out := stderr.String()
assert.Contains(t, out, "install", "task list should be printed")
assert.Contains(t, out, "Install the binary")
assert.Contains(t, out, "test")
assert.Contains(t, out, "\x1b[31m", "suggestion line is colored red")
assert.Contains(t, out, `task: task "instll" not found, did you mean: install?`)
}
func TestAppUnknownTaskWithoutSuggestionStillPrintsList(t *testing.T) {
// Even when no near-match exists, the list of available tasks still
// prints so the user can pick one without re-running with --list.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
tasks:
# Build it
build:
cmd: true
`)
app, _, stderr := newTestApp(t, dir, "xyzzy")
err := app.Run(t.Context())
require.Error(t, err)
out := stderr.String()
assert.Contains(t, out, "build")
assert.Contains(t, out, "Build it")
assert.Contains(t, out, `task: task "xyzzy" not found`)
assert.NotContains(t, out, "did you mean")
}
func TestAppUnknownTaskListsNamespacedMatches(t *testing.T) {
// `gogo dev` in a parent of several sub-projects: no root `dev` exists,
// but `frontend:dev` and `backend:dev` do. We narrow the listing to just
// those candidates rather than dumping every task in the index.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
includes: [frontend, backend]
tasks:
# Build everything
build:
cmd: true
`)
writeFile(t, filepath.Join(dir, "frontend", "gogo.yaml"), `version: "1"
tasks:
# Run the frontend dev server
dev:
cmd: true
`)
writeFile(t, filepath.Join(dir, "backend", "gogo.yaml"), `version: "1"
tasks:
# Run the backend dev server
dev:
cmd: true
`)
app, _, stderr := newTestApp(t, dir, "dev")
err := app.Run(t.Context())
require.Error(t, err)
out := stderr.String()
assert.Contains(t, out, "frontend:dev")
assert.Contains(t, out, "backend:dev")
assert.NotContains(t, out, "build", "unrelated tasks are filtered out")
assert.Contains(t, out, `task: task "dev" not found`)
}
func TestAppUnknownTaskWithNoNamespacedMatchPrintsFullList(t *testing.T) {
// When no sub-project provides the requested task, behavior is unchanged:
// the full task list is printed.
dir := t.TempDir()
writeFile(t, filepath.Join(dir, "gogo.yaml"), `version: "1"
includes: [frontend]
tasks:
# Build everything
build:
cmd: true
`)
writeFile(t, filepath.Join(dir, "frontend", "gogo.yaml"), `version: "1"
tasks:
# Run the frontend dev server
dev:
cmd: true
`)
app, _, stderr := newTestApp(t, dir, "nonexistent")
err := app.Run(t.Context())
require.Error(t, err)
out := stderr.String()
assert.Contains(t, out, "build")
assert.Contains(t, out, "frontend:dev")
assert.Contains(t, out, `task: task "nonexistent" not found`)
}