-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcommand_test.go
More file actions
596 lines (474 loc) · 14.3 KB
/
Copy pathcommand_test.go
File metadata and controls
596 lines (474 loc) · 14.3 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
596
// Copyright (c) Liam Stanley <liam@liam.sh>. All rights reserved. Use of
// this source code is governed by the MIT license that can be found in
// the LICENSE file.
//nolint:forbidigo
package ytdlp
import (
"context"
"fmt"
"os"
"path/filepath"
"slices"
"sync"
"testing"
"time"
)
func TestMain(m *testing.M) {
os.Setenv("YTDLP_DEBUG", "true")
MustInstallAll(context.TODO())
os.Exit(m.Run())
}
type testSampleFile struct {
url string
name string
ext string
extractor string
}
var sampleFiles = []testSampleFile{
{url: "https://cdn.liam.sh/github/go-ytdlp/sample-1.mp4", name: "sample-1", ext: "mp4", extractor: "generic"},
{url: "https://cdn.liam.sh/github/go-ytdlp/sample-2.mp4", name: "sample-2", ext: "mp4", extractor: "generic"},
{url: "https://cdn.liam.sh/github/go-ytdlp/sample-3.mp4", name: "sample-3", ext: "mp4", extractor: "generic"},
{url: "https://cdn.liam.sh/github/go-ytdlp/sample-4.mpg", name: "sample-4", ext: "mpg", extractor: "generic"},
}
func TestCommand_hasJSONFlag(t *testing.T) {
t.Parallel()
tests := []struct {
name string
cmd *Command
want bool
}{
{name: "none", cmd: New(), want: false},
{name: "DumpJSON", cmd: New().DumpJSON(), want: true},
{name: "DumpSingleJSON", cmd: New().DumpSingleJSON(), want: true},
{name: "PrintJSON", cmd: New().PrintJSON(), want: true},
{name: "Print %(j)", cmd: New().Print("%(j)"), want: true},
{name: "Print %(title)s", cmd: New().Print("%(title)s"), want: false},
{name: "Print %(j) with extra template", cmd: New().Print("%(j)").Print("%(title)s"), want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if got := tt.cmd.hasJSONFlag(); got != tt.want {
t.Fatalf("hasJSONFlag() = %v, want %v", got, tt.want)
}
})
}
}
func TestCommand_BuildCommand_BunCache(t *testing.T) {
bunResolveCache.Store(&ResolvedInstall{Executable: "bun"})
t.Cleanup(func() {
bunResolveCache.Store(nil)
})
cmd := New().
SetExecutable("/bin/true").
BuildCommand(context.Background())
if !slices.Contains(cmd.Args, "--no-js-runtimes") {
t.Fatal("expected --no-js-runtimes flag to be set")
}
if !slices.Contains(cmd.Args, "--js-runtimes") {
t.Fatal("expected --js-runtimes flag to be set")
}
if !slices.Contains(cmd.Args, "bun") {
t.Fatal("expected bun runtime to be enabled")
}
}
func TestCommand_CloneExecutionSettings(t *testing.T) {
t.Parallel()
original := New().
SetCancelMaxWait(2 * time.Second).
SetEnvVarInherit(false)
clone := original.Clone()
if clone.cancelMaxWait != 2*time.Second {
t.Fatalf("expected cancel max wait to be cloned, got %s", clone.cancelMaxWait)
}
if !clone.disableEnvVarInherit {
t.Fatal("expected environment inheritance setting to be cloned")
}
}
func TestFlagConfigToFlagsDeduplicatesLastFlag(t *testing.T) {
t.Parallel()
config := &FlagConfig{}
config.General.IgnoreErrors = new(true)
config.General.NoAbortOnError = new(true)
config.General.AbortOnError = new(true)
flags := config.ToFlags().FindByID("ignoreerrors")
if len(flags) != 1 {
t.Fatalf("expected one ignoreerrors flag, got %d: %#v", len(flags), flags)
}
if flags[0].Flag != "--abort-on-error" {
t.Fatalf("expected the last ignoreerrors flag, got %q", flags[0].Flag)
}
}
func TestCommand_Simple(t *testing.T) {
t.Parallel()
dir := t.TempDir()
var urls []string
for _, f := range sampleFiles {
urls = append(urls, f.url)
}
progressUpdates := map[string]ProgressUpdate{}
res, rerr := New().
NoUpdate().
Verbose().
PrintJSON().
NoProgress().
NoOverwrites().
Output(filepath.Join(dir, "%(extractor)s - %(title)s.%(ext)s")).
ProgressFunc(100*time.Millisecond, func(prog ProgressUpdate) {
progressUpdates[prog.Filename] = prog
}).
Run(context.Background(), urls...)
if rerr != nil {
t.Fatal(rerr)
}
if res == nil {
t.Fatal("res is nil")
}
if res.ExitCode != 0 {
t.Fatalf("expected exit code 0, got %d", res.ExitCode)
}
if !slices.Contains(res.Args, "--verbose") {
t.Fatal("expected --verbose flag to be set")
}
var hasJSON bool
for _, l := range res.OutputLogs {
if l.JSON != nil {
hasJSON = true
break
}
}
if !hasJSON {
t.Fatal("expected at least one log line to be valid JSON due to one of --print-json/--dump-json/--print '%()j'")
}
for _, f := range sampleFiles {
t.Run(f.name, func(t *testing.T) {
t.Parallel()
fn := filepath.Join(dir, fmt.Sprintf("%s - %s.%s", f.extractor, f.name, f.ext))
stat, err := os.Stat(fn)
if err != nil {
t.Fatal(err)
}
if stat.Size() == 0 {
t.Fatal("file is empty")
}
prog, ok := progressUpdates[fn]
if !ok {
t.Fatalf("expected progress updates for %s", fn)
}
if prog.Finished.IsZero() || prog.Started.IsZero() {
t.Fatal("expected progress start and finish times to be set")
}
if prog.TotalBytes == 0 {
t.Fatal("expected progress total bytes to be set")
}
if prog.DownloadedBytes == 0 {
t.Fatal("expected progress downloaded bytes to be set")
}
if prog.Percent() < 100.0 {
t.Fatalf("expected progress to be 100%%, got %.2f%%", prog.Percent())
}
if prog.Info.URL == nil {
t.Fatal("expected progress info URL to be set")
}
})
}
}
func TestCommand_Version(t *testing.T) {
t.Parallel()
res, err := New().NoUpdate().Version(context.Background())
if err != nil {
t.Fatal(err)
}
if res == nil {
t.Fatal("res is nil")
}
if res.ExitCode != 0 {
t.Fatalf("expected exit code 0, got %d", res.ExitCode)
}
_, err = time.Parse("2006.01.02", res.Stdout)
if err != nil {
t.Fatalf("failed to parse version: %v", err)
}
}
func TestCommand_Unset(t *testing.T) {
t.Parallel()
builder := New().NoUpdate().Progress().NoProgress().Output("test.mp4")
bunResolveCache.Store(nil) // Explicitly clear the resolve cache for bun, so it doesn't inject itself into the command.
cmd := builder.BuildCommand(context.TODO(), sampleFiles[0].url)
// Make sure --no-progress is set.
if !slices.Contains(cmd.Args, "--no-progress") {
t.Fatal("expected --no-progress flag to be set")
}
_ = builder.UnsetProgress()
bunResolveCache.Store(nil) // Explicitly clear the resolve cache for bun, so it doesn't inject itself into the command.
cmd = builder.BuildCommand(context.TODO(), sampleFiles[0].url)
// Make sure --no-progress is not set.
if slices.Contains(cmd.Args, "--no-progress") {
t.Fatal("expected --no-progress flag to not be set")
}
// Progress and NoProgress should conflict, so arg length should be 5 (no-update, executable, output, output value, and url).
if len(cmd.Args) != 5 {
t.Fatalf("expected arg length to be 4, got %d: %#v", len(cmd.Args), cmd.Args)
}
}
func TestCommand_Clone(t *testing.T) {
t.Parallel()
builder1 := New().NoUpdate().NoProgress().Output("test.mp4")
builder2 := builder1.Clone()
cmd := builder2.BuildCommand(context.TODO(), sampleFiles[0].url)
// Make sure --no-progress is set.
if !slices.Contains(cmd.Args, "--no-progress") {
t.Fatal("expected --no-progress flag to be set")
}
}
func TestCommand_SetExecutable(t *testing.T) {
t.Parallel()
cmd := New().NoUpdate().SetExecutable("/usr/bin/test").BuildCommand(context.Background(), sampleFiles[0].url)
if cmd.Path != "/usr/bin/test" {
t.Fatalf("expected executable to be /usr/bin/test, got %s", cmd.Path)
}
}
func TestCommand_SetWorkDir(t *testing.T) {
t.Parallel()
cmd := New().NoUpdate().SetWorkDir("/tmp").BuildCommand(context.Background(), sampleFiles[0].url)
if cmd.Dir != "/tmp" {
t.Fatalf("expected workdir to be /tmp, got %s", cmd.Dir)
}
}
func TestCommand_SetEnvVar(t *testing.T) {
t.Parallel()
cmd := New().NoUpdate().SetEnvVar("TEST", "1").BuildCommand(context.Background(), sampleFiles[0].url)
if !slices.Contains(cmd.Env, "TEST=1") {
t.Fatalf("expected env var to be TEST=1, got %v", cmd.Env)
}
}
func TestCommand_SetFlagConfig_DuplicateFlags(t *testing.T) {
t.Parallel()
flagConfig := &FlagConfig{}
flagConfig.General.IgnoreErrors = new(true)
flagConfig.General.AbortOnError = new(true)
builder := New().NoUpdate().SetFlagConfig(flagConfig)
err := builder.flagConfig.General.Validate()
if err == nil {
t.Fatal("expected validation error, got nil")
}
if _, ok := IsMultipleJSONParsingFlagsError(err); !ok {
t.Fatalf("expected validation error to be a multiple JSON parsing flags error, got %v", err)
}
}
func TestCommand_JSONClone(t *testing.T) {
t.Parallel()
builder := New().NoUpdate().IgnoreErrors().Output("test.mp4")
cloned := builder.GetFlagConfig().Clone()
if cloned.General.IgnoreErrors == nil {
t.Fatal("expected ignore errors to be set")
}
if v := cloned.Filesystem.Output; v == nil {
t.Fatal("expected output to be set")
}
if *cloned.Filesystem.Output != "test.mp4" {
t.Fatalf("expected output to be %q, got %q", "test.mp4", *cloned.Filesystem.Output)
}
}
func TestCommand_StderrFunc(t *testing.T) {
t.Parallel()
server := newMockServer(t, "testdata/sample-1.mp4")
dir := t.TempDir()
var mu sync.Mutex
var stderrLines []string
result, err := New().
Verbose().
ForceOverwrites().
Output(filepath.Join(dir, "%(extractor)s - %(title)s.%(ext)s")).
StderrFunc(func(line string) { //nolint:staticcheck // testing deprecated alias
mu.Lock()
stderrLines = append(stderrLines, line)
mu.Unlock()
}).
Run(context.TODO(), server.fileURL)
if err != nil {
t.Fatal(err)
}
if result.ExitCode != 0 {
t.Fatalf("expected exit code 0, got %d", result.ExitCode)
}
mu.Lock()
count := len(stderrLines)
mu.Unlock()
if count == 0 {
t.Fatal("expected at least one stderr line from the callback")
}
if result.Stderr == "" {
t.Fatal("expected result.Stderr to be non-empty with --verbose")
}
}
func TestCommand_StderrFuncFiltersStdout(t *testing.T) {
t.Parallel()
var got []string
cmd := New().LogFunc(func(log *ResultLog) {
if log.Pipe == "stderr" {
StderrCallbackFunc(func(line string) { got = append(got, line) })(log.Line)
}
})
cmd.log(&ResultLog{Pipe: PipeStdout, Line: "out"})
cmd.log(&ResultLog{Pipe: PipeStderr, Line: "err"})
if len(got) != 1 || got[0] != "err" {
t.Fatalf("got %v, want [err]", got)
}
}
func TestCommand_StderrFunc_Clone(t *testing.T) {
t.Parallel()
called := false
builder := New().NoUpdate().StderrFunc(func(_ string) { //nolint:staticcheck // testing deprecated alias
called = true
})
cloned := builder.Clone()
if cloned.log == nil {
t.Fatal("expected log handler to be copied by Clone()")
}
cloned.log(&ResultLog{Pipe: PipeStderr, Line: "test"})
if !called {
t.Fatal("expected cloned stderr handler to invoke the original callback")
}
called = false
cloned.log(&ResultLog{Pipe: PipeStdout, Line: "test"})
if called {
t.Fatal("stderr handler should ignore stdout")
}
}
func TestCommand_UnsetStderrFunc(t *testing.T) {
t.Parallel()
builder := New().NoUpdate().LogFunc(func(log *ResultLog) {
if log.Pipe == "stderr" {
StderrCallbackFunc(func(_ string) {})(log.Line)
}
}).UnsetStderrFunc() //nolint:staticcheck // testing deprecated alias
if builder.log != nil {
t.Fatal("expected log handler to be nil after UnsetStderrFunc()")
}
}
func TestCommand_LogFunc_Clone(t *testing.T) {
t.Parallel()
called := false
builder := New().NoUpdate().LogFunc(func(_ *ResultLog) {
called = true
})
cloned := builder.Clone()
if cloned.log == nil {
t.Fatal("expected log handler to be copied by Clone()")
}
cloned.log(&ResultLog{Line: "test"})
if !called {
t.Fatal("expected cloned log handler to invoke the original callback")
}
}
func TestCommand_UnsetLogFunc(t *testing.T) {
t.Parallel()
builder := New().NoUpdate().LogFunc(func(_ *ResultLog) {}).UnsetLogFunc()
if builder.log != nil {
t.Fatal("expected log handler to be nil after UnsetLogFunc()")
}
}
func TestCommand_ExtractInfoDoesNotMutate(t *testing.T) {
t.Parallel()
cmd := New().NoUpdate().SetExecutable("/nonexistent-ytdlp")
_, _, _ = cmd.ExtractInfo(t.Context(), "https://example.com/video")
cfg := cmd.GetFlagConfig()
if cfg.VerbositySimulation.SkipDownload != nil {
t.Fatal("ExtractInfo mutated SkipDownload")
}
if cfg.VerbositySimulation.DumpJSON != nil {
t.Fatal("ExtractInfo mutated DumpJSON")
}
}
func TestCommand_RunWithInfoDoesNotMutate(t *testing.T) {
t.Parallel()
cmd := New().NoUpdate().SetExecutable("/nonexistent-ytdlp")
_, _ = cmd.RunWithInfo(t.Context(), []*ExtractedInfo{{
ID: "sample-1",
Type: ExtractedTypeVideo,
Title: new("sample-1"),
}})
if cmd.GetFlagConfig().Filesystem.LoadInfoJSON != nil {
t.Fatal("RunWithInfo mutated LoadInfoJSON")
}
}
func TestCommand_RunWithInfoEmpty(t *testing.T) {
t.Parallel()
_, err := New().RunWithInfo(t.Context(), nil)
if err == nil {
t.Fatal("expected error")
}
}
func TestCommand_LogFunc(t *testing.T) {
t.Parallel()
server := newMockServer(t, "testdata/sample-1.mp4")
dir := t.TempDir()
var mu sync.Mutex
var logs []*ResultLog
result, err := New().
Verbose().
ForceOverwrites().
Output(filepath.Join(dir, "%(extractor)s - %(title)s.%(ext)s")).
LogFunc(func(log *ResultLog) {
mu.Lock()
logs = append(logs, log)
mu.Unlock()
}).
Run(t.Context(), server.fileURL)
if err != nil {
t.Fatal(err)
}
if result.ExitCode != 0 {
t.Fatalf("expected exit code 0, got %d", result.ExitCode)
}
mu.Lock()
defer mu.Unlock()
if len(logs) == 0 {
t.Fatal("expected at least one log line from the callback")
}
}
func TestCommand_ExtractInfo(t *testing.T) {
t.Parallel()
server := newMockServer(t, "testdata/sample-1.mp4")
info, result, err := New().NoUpdate().ExtractInfo(t.Context(), server.fileURL)
if err != nil {
t.Fatal(err)
}
if result.ExitCode != 0 {
t.Fatalf("exit code = %d, want 0", result.ExitCode)
}
if len(info) != 1 || info[0].ID != "sample-1" {
t.Fatalf("info = %+v, want sample-1", idsOf(info))
}
if info[0].Type != ExtractedTypeVideo && info[0].Type != ExtractedTypeSingle && info[0].Type != "" {
t.Fatalf("type = %q", info[0].Type)
}
}
func TestCommand_RunWithInfo(t *testing.T) {
t.Parallel()
server := newMockServer(t, "testdata/sample-1.mp4")
info, _, err := New().NoUpdate().ExtractInfo(t.Context(), server.fileURL)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
result, err := New().
NoUpdate().
ForceOverwrites().
Output(filepath.Join(dir, "%(extractor)s - %(title)s.%(ext)s")).
RunWithInfo(t.Context(), info)
if err != nil {
t.Fatal(err)
}
if result.ExitCode != 0 {
t.Fatalf("exit code = %d, want 0", result.ExitCode)
}
matches, err := filepath.Glob(filepath.Join(dir, "*"))
if err != nil {
t.Fatal(err)
}
if len(matches) == 0 {
t.Fatal("expected a downloaded file")
}
}