Repository navigation
Expand file tree
/
Copy pathcommands_test.go
More file actions
705 lines (664 loc) · 22.5 KB
/
Copy pathcommands_test.go
File metadata and controls
705 lines (664 loc) · 22.5 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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"testing"
cli "github.com/urfave/cli/v3"
"github.com/bjarneo/cliamp/config"
"github.com/bjarneo/cliamp/ipc"
"github.com/bjarneo/cliamp/resolve"
"github.com/bjarneo/cliamp/theme"
)
func TestInverseBoolFlags(t *testing.T) {
tests := []struct {
flag string
get func(config.Overrides) *bool
want bool
}{
{"--shuffle", func(ov config.Overrides) *bool { return ov.Shuffle }, true},
{"--no-shuffle", func(ov config.Overrides) *bool { return ov.Shuffle }, false},
{"--mono", func(ov config.Overrides) *bool { return ov.Mono }, true},
{"--no-mono", func(ov config.Overrides) *bool { return ov.Mono }, false},
{"--auto-play", func(ov config.Overrides) *bool { return ov.Play }, true},
{"--no-auto-play", func(ov config.Overrides) *bool { return ov.Play }, false},
{"--simplified", func(ov config.Overrides) *bool { return ov.Simplified }, true},
{"--no-simplified", func(ov config.Overrides) *bool { return ov.Simplified }, false},
{"--help-bar", func(ov config.Overrides) *bool { return ov.HideHelpBar }, false},
{"--no-help-bar", func(ov config.Overrides) *bool { return ov.HideHelpBar }, true},
{"--expanded", func(ov config.Overrides) *bool { return ov.Expanded }, true},
{"--no-expanded", func(ov config.Overrides) *bool { return ov.Expanded }, false},
{"--expand-playlist", func(ov config.Overrides) *bool { return ov.ExpandPlaylist }, true},
{"--no-expand-playlist", func(ov config.Overrides) *bool { return ov.ExpandPlaylist }, false},
{"--low-power", func(ov config.Overrides) *bool { return ov.LowPower }, true},
{"--no-low-power", func(ov config.Overrides) *bool { return ov.LowPower }, false},
}
for _, tt := range tests {
t.Run(tt.flag, func(t *testing.T) {
app := buildApp()
var got config.Overrides
app.Action = func(_ context.Context, c *cli.Command) error {
var err error
got, err = overridesFromFlags(c)
return err
}
if err := app.Run(context.Background(), []string{"cliamp", tt.flag}); err != nil {
t.Fatalf("Run: %v", err)
}
value := tt.get(got)
if value == nil || *value != tt.want {
t.Errorf("value = %v, want %t", value, tt.want)
}
})
}
}
// The help of each --[no-] flag shows the default that docs/cli.md names.
// --expand-playlist shows the default of the resolve package.
func TestInverseBoolFlagDefaults(t *testing.T) {
data, err := os.ReadFile(filepath.Join("docs", "cli.md"))
if err != nil {
t.Fatalf("read docs/cli.md: %v", err)
}
code := map[string]bool{"expand-playlist": resolve.ExpandYTPlaylist}
for _, f := range buildApp().Flags {
bf, ok := f.(*cli.BoolWithInverseFlag)
if !ok {
continue
}
t.Run(bf.Name, func(t *testing.T) {
name := regexp.QuoteMeta(bf.Name)
row := regexp.MustCompile("(?m)^\\| `--" + name + "` / `--no-" + name + "` \\| bool \\| (true|false) \\|")
m := row.FindStringSubmatch(string(data))
if m == nil {
t.Fatalf("docs/cli.md has no row for --%s", bf.Name)
}
if got := strconv.FormatBool(bf.Value); got != m[1] {
t.Errorf("--%s help shows default %s, docs/cli.md says %s", bf.Name, got, m[1])
}
if want, ok := code[bf.Name]; ok && bf.Value != want {
t.Errorf("--%s help shows default %t, the code uses %t", bf.Name, bf.Value, want)
}
})
}
}
// Every key and alias in providerKeys parses through --provider in any case,
// and the flag help names each one. An unknown value fails with a message
// that names every key. A key missing from the table would make
// --provider and the provider config key fail for a provider that works.
func TestProviderFlag(t *testing.T) {
parse := func(t *testing.T, value string) (config.Overrides, error) {
t.Helper()
app := buildApp()
var got config.Overrides
var flagErr error
app.Action = func(_ context.Context, c *cli.Command) error {
got, flagErr = overridesFromFlags(c)
return nil
}
if err := app.Run(t.Context(), []string{"cliamp", "--provider", value}); err != nil {
t.Fatalf("Run: %v", err)
}
return got, flagErr
}
type flagCase struct{ value, want string }
var cases []flagCase
for _, pk := range providerKeys {
cases = append(cases, flagCase{pk.key, pk.key}, flagCase{strings.ToUpper(pk.key), pk.key})
if pk.alias != "" {
cases = append(cases, flagCase{pk.alias, pk.key})
}
}
for _, tc := range cases {
t.Run(tc.value, func(t *testing.T) {
got, err := parse(t, tc.value)
if err != nil {
t.Fatalf("--provider %s rejected: %v", tc.value, err)
}
if got.Provider == nil || *got.Provider != tc.want {
t.Fatalf("provider = %v, want %s", got.Provider, tc.want)
}
})
}
t.Run("unknown", func(t *testing.T) {
_, err := parse(t, "winamp")
if err == nil || !strings.HasSuffix(err.Error(), `(got "winamp")`) {
t.Fatalf("error = %v, want a --provider error", err)
}
for _, pk := range providerKeys {
if !strings.Contains(err.Error(), pk.key) {
t.Errorf("error %q does not name %s", err, pk.key)
}
}
})
t.Run("help", func(t *testing.T) {
var usage string
for _, f := range buildApp().Flags {
if sf, ok := f.(*cli.StringFlag); ok && sf.Name == "provider" {
usage = sf.Usage
}
}
for _, pk := range providerKeys {
for _, value := range []string{pk.key, pk.alias} {
if value != "" && !slices.Contains(strings.Split(strings.TrimPrefix(usage, "default provider: "), ", "), value) {
t.Errorf("--provider help %q does not name %s", usage, value)
}
}
}
})
}
func TestRadioCommandFlags(t *testing.T) {
app := buildApp()
radioCmd := app.Command("radio")
if radioCmd == nil {
t.Fatal("radio command not registered")
}
for _, name := range []string{"stats", "globe", "json"} {
if !slices.ContainsFunc(radioCmd.Flags, func(f cli.Flag) bool { return slices.Contains(f.Names(), name) }) {
t.Errorf("radio command lacks --%s", name)
}
}
// --globe --json is contradictory and must fail before any network call.
err := app.Run(context.Background(), []string{"cliamp", "radio", "--globe", "--json"})
if err == nil || !strings.Contains(err.Error(), "cannot be combined") {
t.Errorf("--globe --json error = %v", err)
}
}
// The bookmark commands stay as aliases of the favorite commands so old
// scripts keep working.
func TestPlaylistBookmarkAliases(t *testing.T) {
playlistCmd := buildApp().Command("playlist")
if playlistCmd == nil {
t.Fatal("playlist command not registered")
}
for _, tt := range []struct{ alias, name string }{
{alias: "bookmark", name: "favorite"},
{alias: "bookmarks", name: "favorites"},
} {
t.Run(tt.alias, func(t *testing.T) {
got := playlistCmd.Command(tt.alias)
if got == nil || got.Name != tt.name {
t.Fatalf("playlist %s = %v, want the %s command", tt.alias, got, tt.name)
}
})
}
}
// The ipc package returns a bare sentinel; the CLI wording is added here.
func TestUserIPCErrorRendersNotRunning(t *testing.T) {
rendered := userIPCError(fmt.Errorf("dial: %w", ipc.ErrNotRunning))
want := fmt.Sprintf("cliamp is not running (no socket at %s)", ipc.DefaultSocketPath())
if rendered.Error() != want {
t.Errorf("rendered = %q, want %q", rendered.Error(), want)
}
other := errors.New("connect: permission denied")
if got := userIPCError(other); got != other {
t.Errorf("unrelated error rewritten to %v", got)
}
}
// captureOutput runs fn with stdout and stderr sent to pipes and returns
// what fn wrote to each.
func captureOutput(t *testing.T, fn func()) (stdout, stderr string) {
t.Helper()
read := func(f **os.File) func() string {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
orig := *f
*f = w
done := make(chan string)
go func() {
data, _ := io.ReadAll(r)
done <- string(data)
}()
return func() string {
*f = orig
_ = w.Close()
return <-done
}
}
stopOut := read(&os.Stdout)
stopErr := read(&os.Stderr)
fn()
return stopOut(), stopErr()
}
// cliamp theme list works with no running cliamp. It lists the terminal
// colors first, as the IPC theme list does, and names each theme file that
// it skips on stderr.
func TestThemeListCommand(t *testing.T) {
dir := t.TempDir()
t.Setenv("CLIAMP_CONFIG_DIR", dir)
if err := os.MkdirAll(filepath.Join(dir, "themes"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "themes", "broken.toml"), []byte(`accent = "blue"`), 0o644); err != nil {
t.Fatal(err)
}
var runErr error
stdout, stderr := captureOutput(t, func() {
runErr = buildApp().Run(t.Context(), []string{"cliamp", "theme", "list"})
})
if runErr != nil {
t.Fatal(runErr)
}
lines := strings.Split(strings.TrimRight(stdout, "\n"), "\n")
if len(lines) < 2 || lines[0] != " "+theme.DefaultName {
t.Fatalf("theme list = %q, want %q first", lines, theme.DefaultName)
}
if !strings.Contains(stderr, "skip broken.toml") {
t.Errorf("stderr = %q, want the skipped broken.toml", stderr)
}
}
// cliamp shuffle and cliamp mono toggle by default and pass on, off or
// toggle in lower case.
func TestSwitchCommands(t *testing.T) {
var got []string
var mu sync.Mutex
startTestIPC(t, ipc.RuntimeSnapshot{}, func(jobs *ipc.JobStore, id string, request ipc.V2Request) {
var params ipc.Request
_ = json.Unmarshal(request.Params, ¶ms)
mu.Lock()
got = append(got, request.Operation+" "+params.Name)
mu.Unlock()
_, _ = jobs.Start(id)
_ = jobs.Succeed(id, json.RawMessage(`{"ok":true,"shuffle":true,"mono":false}`))
})
for _, args := range [][]string{{"shuffle"}, {"shuffle", "OFF"}, {"mono"}, {"mono", "on"}} {
stdout, _ := captureOutput(t, func() {
if err := buildApp().Run(t.Context(), append([]string{"cliamp"}, args...)); err != nil {
t.Errorf("cliamp %v: %v", args, err)
}
})
want := "Shuffle: on\n"
if args[0] == "mono" {
want = "Mono: off\n"
}
if stdout != want {
t.Errorf("cliamp %v printed %q, want %q", args, stdout, want)
}
}
want := []string{"shuffle toggle", "shuffle off", "mono toggle", "mono on"}
mu.Lock()
defer mu.Unlock()
if !slices.Equal(got, want) {
t.Fatalf("operations = %q, want %q", got, want)
}
}
// TestVersionFlag checks that --version works with and without the
// version that -ldflags sets. go install and go build set none.
func TestVersionFlag(t *testing.T) {
tests := []struct {
name string
ldflags string
arg string
}{
{"release long", "v1.2.3", "--version"},
{"release short", "v1.2.3", "-v"},
{"plain build long", "", "--version"},
{"plain build short", "", "-v"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orig := version
version = tt.ldflags
t.Cleanup(func() { version = orig })
want := buildVersion()
if want == "" {
t.Fatal("buildVersion() is empty")
}
if tt.ldflags != "" && want != tt.ldflags {
t.Fatalf("buildVersion() = %q, want %q", want, tt.ldflags)
}
var out strings.Builder
app := buildApp()
app.Writer = &out
if err := app.Run(t.Context(), []string{"cliamp", tt.arg}); err != nil {
t.Fatalf("Run(%s) error = %v", tt.arg, err)
}
if got := out.String(); got != "cliamp version "+want+"\n" {
t.Errorf("Run(%s) printed %q, want version %q", tt.arg, got, want)
}
})
}
}
// cliamp queue sends a local file with an absolute path, because the
// running cliamp has its own working directory. A URL or another URI goes
// as it is. A missing file or a directory is an error and sends nothing.
func TestQueueCommandPath(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "song.mp3"), nil, 0o644); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(filepath.Join(dir, "album"), 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
sent := make(chan string, 16)
startTestIPC(t, ipc.RuntimeSnapshot{}, func(jobs *ipc.JobStore, id string, request ipc.V2Request) {
var params ipc.Request
_ = json.Unmarshal(request.Params, ¶ms)
sent <- params.Path
_, _ = jobs.Start(id)
_ = jobs.Succeed(id, json.RawMessage(`{"ok":true}`))
})
for _, tt := range []struct {
name string
arg string
want string
wantErr string
}{
{name: "relative file", arg: "./song.mp3", want: filepath.Join(dir, "song.mp3")},
{name: "bare file name", arg: "song.mp3", want: filepath.Join(dir, "song.mp3")},
{name: "absolute file", arg: filepath.Join(dir, "song.mp3"), want: filepath.Join(dir, "song.mp3")},
{name: "URL", arg: "https://example.com/a.mp3", want: "https://example.com/a.mp3"},
{name: "search", arg: "ytsearch:aphex twin", want: "ytsearch:aphex twin"},
{name: "SSH", arg: "ssh://host/music/a.flac", want: "ssh://host/music/a.flac"},
{name: "provider URI", arg: "spotify:track:abc", want: "spotify:track:abc"},
{name: "missing file", arg: "nope.mp3", wantErr: "nope.mp3"},
{name: "directory", arg: "album", wantErr: "is a directory"},
} {
t.Run(tt.name, func(t *testing.T) {
err := buildApp().Run(t.Context(), []string{"cliamp", "queue", tt.arg})
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("cliamp queue %s error = %v, want %q", tt.arg, err, tt.wantErr)
}
select {
case got := <-sent:
t.Fatalf("cliamp queue %s sent %q, want nothing", tt.arg, got)
default:
}
return
}
if err != nil {
t.Fatalf("cliamp queue %s: %v", tt.arg, err)
}
if got := <-sent; got != tt.want {
t.Fatalf("cliamp queue %s sent %q, want %q", tt.arg, got, tt.want)
}
})
}
}
// cliamp status --json always prints position, volume and index, because
// 0 is a real value of each. Other fields with no value stay out.
func TestStatusJSONKeepsZeroValues(t *testing.T) {
for _, tt := range []struct {
name string
snapshot ipc.RuntimeSnapshot
want map[string]any
}{
{
name: "zero values",
snapshot: ipc.RuntimeSnapshot{State: "playing", Total: 3},
want: map[string]any{"ok": true, "state": "playing", "total": 3.0, "position": 0.0, "volume": 0.0, "index": 0.0},
},
{
name: "set values",
snapshot: ipc.RuntimeSnapshot{State: "paused", Position: 12.5, Volume: -6, Index: 2, Total: 3},
want: map[string]any{"ok": true, "state": "paused", "total": 3.0, "position": 12.5, "volume": -6.0, "index": 2.0},
},
{
name: "empty playlist",
snapshot: ipc.RuntimeSnapshot{State: "stopped", Index: -1},
want: map[string]any{"ok": true, "state": "stopped", "position": 0.0, "volume": 0.0, "index": -1.0},
},
} {
t.Run(tt.name, func(t *testing.T) {
startTestIPC(t, tt.snapshot, func(*ipc.JobStore, string, ipc.V2Request) {})
var runErr error
stdout, _ := captureOutput(t, func() {
runErr = buildApp().Run(t.Context(), []string{"cliamp", "status", "--json"})
})
if runErr != nil {
t.Fatal(runErr)
}
var got map[string]any
if err := json.Unmarshal([]byte(stdout), &got); err != nil {
t.Fatalf("status --json printed %q: %v", stdout, err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Fatalf("status --json = %v, want %v", got, tt.want)
}
})
}
}
func TestReadRemoteCallParams(t *testing.T) {
tempDir := t.TempDir()
validFile := filepath.Join(tempDir, "valid.json")
if err := os.WriteFile(validFile, []byte(`{"value": 42}`), 0o644); err != nil {
t.Fatal(err)
}
emptyFile := filepath.Join(tempDir, "empty.json")
if err := os.WriteFile(emptyFile, []byte(" \n"), 0o644); err != nil {
t.Fatal(err)
}
invalidFile := filepath.Join(tempDir, "invalid.json")
if err := os.WriteFile(invalidFile, []byte(`{not json}`), 0o644); err != nil {
t.Fatal(err)
}
arrayFile := filepath.Join(tempDir, "array.json")
if err := os.WriteFile(arrayFile, []byte(`[1, 2, 3]`), 0o644); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
args []string
stdin string
want string
wantErr string
}{
{
name: "default when no flags set",
args: []string{"cliamp", "remote", "call", "test.op"},
want: "{}",
},
{
name: "params flag valid",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `{"volume": 5}`},
want: `{"volume": 5}`,
},
{
name: "params flag invalid JSON",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `not-json`},
wantErr: "--params must be a JSON object",
},
{
name: "params flag JSON array",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `[1, 2]`},
wantErr: "parameters must be a JSON object",
},
{
name: "params flag JSON string",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `"text"`},
wantErr: "parameters must be a JSON object",
},
{
name: "params flag JSON null",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `null`},
wantErr: "parameters must be a JSON object",
},
{
name: "params stdin false does not read stdin",
args: []string{"cliamp", "remote", "call", "test.op", "--params-stdin=false"},
want: `{}`,
},
{
name: "params-file valid path",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", validFile},
want: `{"value": 42}`,
},
{
name: "params-file missing path",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", filepath.Join(tempDir, "nonexistent.json")},
wantErr: "opening parameters file",
},
{
name: "params-file empty file",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", emptyFile},
wantErr: "parameters file is empty",
},
{
name: "params-file invalid JSON",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", invalidFile},
wantErr: "parameters must be valid JSON",
},
{
name: "params-file array JSON",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", arrayFile},
wantErr: "parameters must be a JSON object",
},
{
name: "params-file dash reads stdin",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", "-"},
stdin: `{"from": "stdin"}`,
want: `{"from": "stdin"}`,
},
{
name: "params-file dash empty stdin",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", "-"},
stdin: " \n",
wantErr: "parameters input is empty",
},
{
name: "params-stdin flag reads stdin",
args: []string{"cliamp", "remote", "call", "test.op", "--params-stdin"},
stdin: `{"query": "lofi"}`,
want: `{"query": "lofi"}`,
},
{
name: "params-stdin flag empty stdin",
args: []string{"cliamp", "remote", "call", "test.op", "--params-stdin"},
stdin: "",
wantErr: "parameters input is empty",
},
{
name: "params and params-file mutually exclusive",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `{}`, "--params-file", validFile},
wantErr: "--params, --params-file, and --params-stdin are mutually exclusive",
},
{
name: "params and params-stdin mutually exclusive",
args: []string{"cliamp", "remote", "call", "test.op", "--params", `{}`, "--params-stdin"},
wantErr: "--params, --params-file, and --params-stdin are mutually exclusive",
},
{
name: "params-file and params-stdin mutually exclusive",
args: []string{"cliamp", "remote", "call", "test.op", "--params-file", validFile, "--params-stdin"},
wantErr: "--params, --params-file, and --params-stdin are mutually exclusive",
},
{
name: "stdin exceeds size limit",
args: []string{"cliamp", "remote", "call", "test.op", "--params-stdin"},
stdin: strings.Repeat("a", maxRemoteParamsSize+2),
wantErr: "parameters exceed maximum allowed size",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
app := buildApp()
var gotParams json.RawMessage
var gotErr error
// Intercept Action in call subcommand to test readRemoteCallParamsFrom directly.
var callCmd *cli.Command
for _, c := range app.Commands {
if c.Name == "remote" {
for _, sub := range c.Commands {
if sub.Name == "call" {
callCmd = sub
break
}
}
break
}
}
if callCmd == nil {
t.Fatal("remote call command not found")
}
callCmd.Action = func(_ context.Context, c *cli.Command) error {
gotParams, gotErr = readRemoteCallParamsFrom(c, strings.NewReader(tt.stdin))
return gotErr
}
err := app.Run(t.Context(), tt.args)
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("error = %v, want substring %q", err, tt.wantErr)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if strings.ReplaceAll(string(gotParams), " ", "") != strings.ReplaceAll(tt.want, " ", "") {
t.Fatalf("gotParams = %s, want %s", string(gotParams), tt.want)
}
})
}
}
func TestRemoteCallParamsIntegration(t *testing.T) {
tempDir := t.TempDir()
paramsFile := filepath.Join(tempDir, "request.json")
if err := os.WriteFile(paramsFile, []byte(`{"value": 3}`), 0o644); err != nil {
t.Fatal(err)
}
var receivedParams json.RawMessage
var receivedOp string
var mu sync.Mutex
startTestIPC(t, ipc.RuntimeSnapshot{}, func(jobs *ipc.JobStore, id string, request ipc.V2Request) {
mu.Lock()
receivedOp = request.Operation
receivedParams = request.Params
mu.Unlock()
_, _ = jobs.Start(id)
_ = jobs.Succeed(id, json.RawMessage(`{"ok": true, "volume": 3}`))
})
// Test 1: --params-file
stdout, _ := captureOutput(t, func() {
err := buildApp().Run(t.Context(), []string{
"cliamp", "remote", "call", "volume.adjust",
"--params-file", paramsFile,
"--wait",
})
if err != nil {
t.Fatalf("remote call --params-file: %v", err)
}
})
mu.Lock()
if receivedOp != "volume.adjust" || strings.ReplaceAll(string(receivedParams), " ", "") != `{"value":3}` {
t.Fatalf("IPC received op=%q params=%s, want volume.adjust and {\"value\":3}", receivedOp, string(receivedParams))
}
mu.Unlock()
if !strings.Contains(stdout, `"ok":true`) && !strings.Contains(stdout, `"ok": true`) {
t.Errorf("stdout = %q, want response containing ok: true", stdout)
}
// Test 2: --params-stdin
oldStdin := remoteStdin
defer func() { remoteStdin = oldStdin }()
remoteStdin = strings.NewReader(`{"value": -3}`)
stdout, _ = captureOutput(t, func() {
err := buildApp().Run(t.Context(), []string{
"cliamp", "remote", "call", "volume.adjust",
"--params-stdin",
"--wait",
})
if err != nil {
t.Fatalf("remote call --params-stdin: %v", err)
}
})
mu.Lock()
if receivedOp != "volume.adjust" || strings.ReplaceAll(string(receivedParams), " ", "") != `{"value":-3}` {
t.Fatalf("IPC received op=%q params=%s, want volume.adjust and {\"value\":-3}", receivedOp, string(receivedParams))
}
mu.Unlock()
if !strings.Contains(stdout, `"ok":true`) && !strings.Contains(stdout, `"ok": true`) {
t.Errorf("stdout = %q, want response containing ok: true", stdout)
}
}