-
Notifications
You must be signed in to change notification settings - Fork 11
/
wgo_cmd_test.go
832 lines (792 loc) · 21 KB
/
wgo_cmd_test.go
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
package main
import (
"bytes"
"context"
"errors"
"flag"
"log"
"math/rand"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/fsnotify/fsnotify"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
)
var WGO_RANDOM_NUMBER string
func init() {
WGO_RANDOM_NUMBER = strconv.Itoa(rand.Intn(5000))
os.Setenv("FOO", "green")
os.Setenv("BAR", "lorem ipsum dolor sit amet")
os.Setenv("WGO_RANDOM_NUMBER", WGO_RANDOM_NUMBER)
}
func Test_compileRegexp(t *testing.T) {
type TestTable struct {
description string
pattern string
pass []string
fail []string
}
tests := []TestTable{{
description: "normal regexp without dot",
pattern: `ab\wd`,
pass: []string{"abcd", "abxd", "abzd"},
fail: []string{"ab@d", "ab.d"},
}, {
description: "dot followed by letter is treated as literal dot",
pattern: `.html`,
pass: []string{"header.html", "footer.html"},
fail: []string{"\\xhtml", "footer.xhtml", "main.go"},
}, {
description: "an escaped dot is not escaped again",
pattern: `\.html`,
pass: []string{"header.html", "footer.html"},
fail: []string{"\\xhtml", "footer.xhtml", "main.go"},
}, {
description: "dot followed by non-dot is treated as normal regexp dot",
pattern: `(.)html`,
pass: []string{"header.html", "footer.html", "\\xhtml", "footer.xhtml"},
fail: []string{"main.go"},
}, {
description: "trim patterns starting with dot slash",
pattern: `./testdata/hello_world/main.go`,
pass: []string{"testdata/hello_world/main.go"},
fail: []string{},
}}
for _, tt := range tests {
tt := tt
t.Run(tt.description, func(t *testing.T) {
t.Parallel()
r, err := compileRegexp(tt.pattern)
if err != nil {
t.Fatal(err)
}
for _, s := range tt.pass {
if !r.MatchString(s) {
t.Errorf("%q failed to match %q", tt.pattern, s)
}
}
for _, s := range tt.fail {
if r.MatchString(s) {
t.Errorf("%q incorrectly matches %q", tt.pattern, s)
}
}
})
}
}
func TestWgoCmd_match(t *testing.T) {
type TestTable struct {
description string
roots []string
args []string
path string
want bool
}
tests := []TestTable{{
description: "-xfile",
args: []string{"-xfile", "_test.go"},
path: "wgo_cmd_test.go",
want: false,
}, {
description: "-xfile with slash",
args: []string{"-xfile", "testdata/"},
path: "testdata/args/main.go",
want: false,
}, {
description: "-file",
args: []string{"-file", "main.go"},
path: "testdata/args/main.go",
want: true,
}, {
description: "-xdir overrides -file",
args: []string{"-file", "main.go", "-xdir", "testdata"},
path: "testdata/args/main.go",
want: false,
}, {
description: "-file matches but -dir does not",
args: []string{"-file", "main.go", "-dir", "src"},
path: "testdata/args/main.go",
want: false,
}, {
description: "both -file and -dir match",
args: []string{"-file", "main.go", "-dir", "testdata"},
path: "testdata/args/main.go",
want: true,
}, {
description: "-file with slash",
args: []string{"-file", "testdata/"},
path: "testdata/args/main.go",
want: true,
}, {
description: "wgo run",
args: []string{"run", "."},
path: "testdata/args/main.go",
want: true,
}, {
description: "wgo run without flags exclude non go files",
args: []string{"run", "main.go"},
path: "testdata/dir/foo/bar.txt",
want: false,
}, {
description: "fallthrough",
args: []string{"-file", ".go", "-file", "test", "-xfile", ".css", "-xfile", "assets"},
path: "index.html",
want: false,
}, {
description: "root is truncated",
roots: []string{"/Documents"},
args: []string{"-file", "Documents"},
path: "/Documents/wgo/main.go",
want: false,
}, {
description: "root is not truncated",
roots: []string{"/lorem_ipsum"},
args: []string{"-file", "Documents"},
path: "/Documents/wgo/main.go",
want: true,
}, {
description: "nothing allows anything",
args: []string{},
path: "/Documents/index.rb",
want: true,
}}
for _, tt := range tests {
tt := tt
t.Run(tt.description, func(t *testing.T) {
t.Parallel()
wgoCmd, err := WgoCommand(context.Background(), tt.args)
if err != nil {
t.Fatal(err)
}
if tt.roots != nil {
wgoCmd.Roots = make([]string, len(tt.roots))
for i := range tt.roots {
wgoCmd.Roots[i], err = filepath.Abs(tt.roots[i])
if err != nil {
t.Fatal(err)
}
}
}
path, err := filepath.Abs(tt.path)
if err != nil {
t.Fatal(err)
}
got := wgoCmd.match("", path)
if !got && tt.want {
t.Errorf("%v failed to match %q", tt.args, tt.path)
} else if got && !tt.want {
t.Errorf("%v incorrectly matches %q", tt.args, tt.path)
}
})
}
}
func TestWgoCmd_addDirsRecursively(t *testing.T) {
type TestTable struct {
description string
roots []string
dir string
args []string
wantWatched []string
}
// NOTE: Don't hardcode absolute paths here, use only relative paths. The
// test scaffolding will convert them to absolute paths for you.
tests := []TestTable{{
description: "-xdir",
roots: []string{"testdata/dir"},
dir: "testdata/dir",
args: []string{"-xdir", "subdir"},
wantWatched: []string{
"testdata/dir",
"testdata/dir/foo",
},
}, {
description: "-xdir with slash",
roots: []string{"testdata/dir"},
dir: "testdata/dir",
args: []string{"-xdir", "/"},
wantWatched: []string{
"testdata/dir",
},
}, {
description: "-xdir excludes non root dir",
args: []string{"-xdir", "testdata/dir"},
dir: "testdata/dir",
wantWatched: []string{},
}, {
description: "-dir",
roots: []string{"testdata/dir"},
dir: "testdata/dir",
args: []string{"-dir", "foo"},
wantWatched: []string{
"testdata/dir",
"testdata/dir/foo",
"testdata/dir/subdir",
"testdata/dir/subdir/foo",
},
}, {
description: "explicitly include node_modules",
roots: []string{"testdata/dir"},
dir: "testdata/dir",
args: []string{"-dir", "node_modules"},
wantWatched: []string{
"testdata/dir",
"testdata/dir/foo",
"testdata/dir/node_modules",
"testdata/dir/node_modules/foo",
"testdata/dir/subdir",
"testdata/dir/subdir/foo",
},
}}
for _, tt := range tests {
tt := tt
t.Run(tt.description, func(t *testing.T) {
t.Parallel()
wgoCmd, err := WgoCommand(context.Background(), tt.args)
if err != nil {
t.Fatal(err)
}
for i := range tt.roots {
root, err := filepath.Abs(tt.roots[i])
if err != nil {
t.Fatal(err)
}
wgoCmd.Roots = append(wgoCmd.Roots, root)
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
t.Fatal(err)
}
dir, err := filepath.Abs(tt.dir)
if err != nil {
t.Fatal(err)
}
for i := range tt.wantWatched {
tt.wantWatched[i], err = filepath.Abs(tt.wantWatched[i])
if err != nil {
t.Fatal(err)
}
}
wgoCmd.addDirsRecursively(watcher, dir)
gotWatched := watcher.WatchList()
sort.Strings(gotWatched)
sort.Strings(tt.wantWatched)
if diff := Diff(gotWatched, tt.wantWatched); diff != "" {
t.Error(diff)
}
})
}
}
func TestWgoCommands(t *testing.T) {
type TestTable struct {
description string
args []string
wantCmds []*WgoCmd
}
tests := []TestTable{{
description: "chained commands",
args: []string{
"wgo", "-file", ".go", "clear",
"::", "echo", "building...",
"::", "go", "build", "-o", "hello_world", "hello_world.go",
"::", "echo", "running...",
"::", "./hello_world",
},
wantCmds: []*WgoCmd{{
Roots: []string{"."},
FileRegexps: []*regexp.Regexp{regexp.MustCompile(`\.go`)},
ArgsList: [][]string{
{"clear"},
{"echo", "building..."},
{"go", "build", "-o", "hello_world", "hello_world.go"},
{"echo", "running..."},
{"./hello_world"},
},
Debounce: 300 * time.Millisecond,
}},
}, {
description: "parallel commands",
args: []string{
"wgo", "run", "-tags", "fts5", "main.go", "arg1", "arg2",
"::", "wgo", "-file", ".css", "-dir", "assets", "sass", "assets/styles.scss", "assets/styles.css",
"::", "wgo", "-file", ".js", "-dir", "assets", "tsc", "assets/*.ts", "--outfile", "assets/index.js",
},
wantCmds: []*WgoCmd{{
Roots: []string{"."},
ArgsList: [][]string{
{"go", "build", "-o", "out", "-tags", "fts5", "main.go"},
{"out", "arg1", "arg2"},
},
Debounce: 300 * time.Millisecond,
isRun: true,
binPath: "out",
}, {
Roots: []string{"."},
FileRegexps: []*regexp.Regexp{regexp.MustCompile(`\.css`)},
DirRegexps: []*regexp.Regexp{regexp.MustCompile(`assets`)},
ArgsList: [][]string{
{"sass", "assets/styles.scss", "assets/styles.css"},
},
Debounce: 300 * time.Millisecond,
}, {
Roots: []string{"."},
FileRegexps: []*regexp.Regexp{regexp.MustCompile(`\.js`)},
DirRegexps: []*regexp.Regexp{regexp.MustCompile(`assets`)},
ArgsList: [][]string{
{"tsc", "assets/*.ts", "--outfile", "assets/index.js"},
},
Debounce: 300 * time.Millisecond,
}},
}, {
description: "build flags",
args: []string{
"wgo", "run", "-a", "-n", "-race", "-msan", "-asan", "-v=false",
"-work", "-x", "-buildvcs", "-linkshared=true", "-modcacherw=1",
"-trimpath=t", "-p", "5", ".", "arg1", "arg2",
},
wantCmds: []*WgoCmd{{
Roots: []string{"."},
ArgsList: [][]string{
{"go", "build", "-o", "out", "-p", "5", "-a", "-n", "-race", "-msan", "-asan", "-work", "-x", "-buildvcs", "-linkshared", "-modcacherw", "-trimpath", "."},
{"out", "arg1", "arg2"},
},
Debounce: 300 * time.Millisecond,
isRun: true,
binPath: "out",
}},
}, {
description: "wgo flags",
args: []string{
"wgo", "-root", "/secrets", "-file", ".", "-verbose", "echo", "hello",
},
wantCmds: []*WgoCmd{{
Roots: []string{".", "/secrets"},
FileRegexps: []*regexp.Regexp{regexp.MustCompile(`.`)},
ArgsList: [][]string{
{"echo", "hello"},
},
Debounce: 300 * time.Millisecond,
}},
}, {
description: "escaped ::",
args: []string{
"wgo", "-file", ".", "echo", ":::", "::::", ":::::",
},
wantCmds: []*WgoCmd{{
Roots: []string{"."},
FileRegexps: []*regexp.Regexp{regexp.MustCompile(`.`)},
ArgsList: [][]string{
{"echo", "::", ":::", "::::"},
},
Debounce: 300 * time.Millisecond,
}},
}, {
description: "debounce flag",
args: []string{
"wgo", "-debounce", "10ms", "echo", "test",
},
wantCmds: []*WgoCmd{{
Roots: []string{"."},
ArgsList: [][]string{
{"echo", "test"},
},
Debounce: 10 * time.Millisecond,
}},
}}
for _, tt := range tests {
tt := tt
t.Run(tt.description, func(t *testing.T) {
t.Parallel()
gotCmds, err := WgoCommands(context.Background(), tt.args)
if err != nil {
t.Fatal(err)
}
for _, wgoCmd := range tt.wantCmds {
wgoCmd.ctx = context.Background()
for i := range wgoCmd.Roots {
wgoCmd.Roots[i], err = filepath.Abs(wgoCmd.Roots[i])
if err != nil {
t.Fatal(err)
}
}
}
// This is ugly, but because the binPath is randomly generated we
// have to manually reach into the argslist and overwrite it with a
// well-known string so that we can compare the commands properly.
if tt.description == "parallel commands" || tt.description == "build flags" {
gotCmds[0].binPath = "out"
gotCmds[0].ArgsList[0][3] = "out"
gotCmds[0].ArgsList[1][0] = "out"
}
opts := []cmp.Option{
// Comparing loggers always fails, ignore it.
cmpopts.IgnoreFields(WgoCmd{}, "Logger"),
}
if diff := Diff(gotCmds, tt.wantCmds, opts...); diff != "" {
t.Error(diff)
}
})
}
}
func TestWgoCmd_Run(t *testing.T) {
t.Run("args", func(t *testing.T) {
t.Parallel()
wgoCmd, err := WgoCommand(context.Background(), []string{
"run", "-exit", "-dir", "testdata/args", "./testdata/args", "apple", "banana", "cherry",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "[apple banana cherry]"
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("build flags off", func(t *testing.T) {
t.Parallel()
wgoCmd, err := WgoCommand(context.Background(), []string{
"run", "-exit", "-dir", "testdata/build_flags", "./testdata/build_flags",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "[foo]"
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("build flags on", func(t *testing.T) {
t.Parallel()
wgoCmd, err := WgoCommand(context.Background(), []string{
"run", "-exit", "-dir", "testdata/build_flags", "-tags=bar", "./testdata/build_flags",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "[foo bar]"
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("env", func(t *testing.T) {
t.Parallel()
cmd, err := WgoCommand(context.Background(), []string{
"run", "-exit", "-dir", "testdata/env", "./testdata/env",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
cmd.Stdout = buf
err = cmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "FOO=green\nBAR=lorem ipsum dolor sit amet\nWGO_RANDOM_NUMBER=" + WGO_RANDOM_NUMBER
if got != want {
t.Fatalf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("timeout off", func(t *testing.T) {
t.Parallel()
binPath := "./testdata/hello_world/timeout_off"
if runtime.GOOS == "windows" {
binPath += ".exe"
}
os.RemoveAll(binPath)
defer os.RemoveAll(binPath)
wgoCmd, err := WgoCommand(context.Background(), []string{
"-exit", "-dir", "testdata/hello_world", "-file", ".go", "go", "build", "-o", binPath, "./testdata/hello_world",
"::", binPath,
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "hello world"
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("timeout on", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 0)
defer cancel()
binPath := "./testdata/hello_world/timeout_on"
if runtime.GOOS == "windows" {
binPath += ".exe"
}
os.RemoveAll(binPath)
defer os.RemoveAll(binPath)
wgoCmd, err := WgoCommand(ctx, []string{
"-exit", "-dir", "testdata/hello_world", "-file", ".go", "go", "build", "-o", binPath, "./testdata/hello_world",
"::", binPath,
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := ""
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("signal off", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
wgoCmd, err := WgoCommand(ctx, []string{
"run", "-dir", "testdata/signal", "./testdata/signal",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "Waiting..."
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
t.Run("signal on", func(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows doesn't support sending signals to a running process, skipping.")
}
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
wgoCmd, err := WgoCommand(ctx, []string{
"run", "-dir", "testdata/signal", "./testdata/signal", "-trap-signal",
})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "Waiting...\nInterrupt received, graceful shutdown."
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
})
}
func TestWgoCmd_FileEvent(t *testing.T) {
t.Parallel()
os.RemoveAll("testdata/file_event/foo.txt")
os.RemoveAll("testdata/file_event/internal")
defer os.RemoveAll("testdata/file_event/foo.txt")
defer os.RemoveAll("testdata/file_event/internal")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
wgoCmd, err := WgoCommand(ctx, []string{"run", "-dir", "testdata/file_event", "-file", ".txt", "./testdata/file_event"})
if err != nil {
t.Fatal(err)
}
buf := &Buffer{}
wgoCmd.Stdout = buf
cmdResult := make(chan error)
go func() {
cmdResult <- wgoCmd.Run()
}()
time.Sleep(3 * time.Second)
log.Println("add file")
err = os.WriteFile("testdata/file_event/foo.txt", []byte("foo"), 0666)
if err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Second)
log.Println("edit file")
err = os.WriteFile("testdata/file_event/foo.txt", []byte("foo fighters"), 0666)
if err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Second)
log.Println("create nested directory")
err = os.MkdirAll("testdata/file_event/internal/baz", 0777)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile("testdata/file_event/foo.txt", []byte("foo"), 0666)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile("testdata/file_event/internal/bar.txt", []byte("bar"), 0666)
if err != nil {
t.Fatal(err)
}
err = os.WriteFile("testdata/file_event/internal/baz/baz.txt", []byte("baz"), 0666)
if err != nil {
t.Fatal(err)
}
time.Sleep(3 * time.Second)
cancel()
err = <-cmdResult
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := `---
main.go
run.bat
---
foo.txt: foo
main.go
run.bat
---
foo.txt: foo fighters
main.go
run.bat
---
foo.txt: foo
internal/bar.txt: bar
internal/baz/baz.txt: baz
main.go
run.bat`
if diff := Diff(got, want); diff != "" {
t.Error(diff)
}
}
func TestStdin(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
wgoCmd, err := WgoCommand(ctx, []string{"run", "-exit", "-dir", "testdata/stdin", "-stdin", "./testdata/stdin"})
if err != nil {
t.Fatal(err)
}
wgoCmd.Stdin = strings.NewReader("foo\nbar\nbaz")
buf := &Buffer{}
wgoCmd.Stderr = buf
err = wgoCmd.Run()
if err != nil {
t.Fatal(err)
}
got := strings.TrimSpace(buf.String())
want := "1: foo\n2: bar\n3: baz"
if got != want {
t.Errorf("\ngot: %q\nwant: %q", got, want)
}
}
func TestShellWrapping(t *testing.T) {
t.Parallel()
// builtins are commands that don't exist in PATH, they are manually
// handled by the shell. We can use builtin commands to induce an
// exec.LookPath() error, which will cause WgoCmd to retry by wrapping the
// command in a shell.
builtin := ":"
if runtime.GOOS == "windows" {
builtin = "Get-Location"
}
// Assert that vanilla exec.Command can't find the builtin.
err := exec.Command(builtin).Run()
if !errors.Is(err, exec.ErrNotFound) {
t.Fatalf("expected exec.ErrNotFound, got %#v", err)
}
// Assert that WgoCommand handles the builtin (via shell wrapping).
wgoCmd, err := WgoCommand(context.Background(), []string{"-exit", builtin})
if err != nil {
t.Fatal(err)
}
err = wgoCmd.Run()
if err != nil {
t.Error(err)
}
}
func TestHelp(t *testing.T) {
_, err := WgoCommand(context.Background(), []string{"-h"})
if !errors.Is(err, flag.ErrHelp) {
t.Errorf("expected flag.ErrHelp, got %#v", err)
}
_, err = WgoCommand(context.Background(), []string{"run", "-h"})
if !errors.Is(err, flag.ErrHelp) {
t.Errorf("expected flag.ErrHelp, got %#v", err)
}
}
func Diff(got, want interface{}, opts ...cmp.Option) string {
opts = append(opts,
cmp.Exporter(func(typ reflect.Type) bool { return true }),
cmpopts.EquateEmpty(),
)
diff := cmp.Diff(got, want, opts...)
if diff != "" {
return "\n-got +want\n" + diff
}
return ""
}
// Buffer is a custom buffer type that is guarded by a sync.RWMutex.
//
// Some of the tests (signal on, signal off, timeout on, timeout off) initially
// wrote to a *bytes.Buffer as their Stdout and the *bytes.Buffer was read from
// to assert test results. But these tests occasionally failed with data races
// which caused CI/CD tests to fail and I can't find the cause so I'll just use
// a blunt hammer and use a goroutine-safe buffer for those tests.
type Buffer struct {
rw sync.RWMutex
buf bytes.Buffer
}
func (b *Buffer) Read(p []byte) (n int, err error) {
b.rw.RLock()
defer b.rw.RUnlock()
return b.buf.Read(p)
}
func (b *Buffer) Write(p []byte) (n int, err error) {
b.rw.Lock()
defer b.rw.Unlock()
return b.buf.Write(p)
}
func (b *Buffer) String() string {
b.rw.Lock()
defer b.rw.Unlock()
return b.buf.String()
}