-
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcommand_test.go
More file actions
337 lines (257 loc) · 7.87 KB
/
command_test.go
File metadata and controls
337 lines (257 loc) · 7.87 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
// Copyright (c) Liam Stanley <[email protected]>. 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_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 = ptr(true)
flagConfig.General.AbortOnError = ptr(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) {
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_StderrFunc_Clone(t *testing.T) {
t.Parallel()
called := false
builder := New().NoUpdate().StderrFunc(func(_ string) {
called = true
})
cloned := builder.Clone()
if cloned.stderr == nil {
t.Fatal("expected stderr handler to be copied by Clone()")
}
cloned.stderr.handle("test")
if !called {
t.Fatal("expected cloned stderr handler to invoke the original callback")
}
}
func TestCommand_UnsetStderrFunc(t *testing.T) {
t.Parallel()
builder := New().NoUpdate().StderrFunc(func(_ string) {}).UnsetStderrFunc()
if builder.stderr != nil {
t.Fatal("expected stderr handler to be nil after UnsetStderrFunc()")
}
}