forked from go-cmd/cmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_test.go
1229 lines (1103 loc) · 29.9 KB
/
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build !windows
package cmd_test
import (
"bytes"
"errors"
"io/ioutil"
"os"
"os/exec"
"syscall"
"testing"
"time"
"github.com/go-cmd/cmd"
"github.com/go-test/deep"
)
func TestCmdOK(t *testing.T) {
now := time.Now().Unix()
p := cmd.NewCmd("echo", "foo")
gotStatus := <-p.Start()
expectStatus := cmd.Status{
Cmd: "echo",
PID: gotStatus.PID, // nondeterministic
Complete: true,
Exit: 0,
Error: nil,
Runtime: gotStatus.Runtime, // nondeterministic
Stdout: []string{"foo"},
Stderr: []string{},
}
if gotStatus.StartTs < now {
t.Error("StartTs < now")
}
if gotStatus.StopTs < gotStatus.StartTs {
t.Error("StopTs < StartTs")
}
gotStatus.StartTs = 0
gotStatus.StopTs = 0
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Error(diffs)
}
if gotStatus.PID < 0 {
t.Errorf("got PID %d, expected non-zero", gotStatus.PID)
}
if gotStatus.Runtime < 0 {
t.Errorf("got runtime %f, expected non-zero", gotStatus.Runtime)
}
}
func TestCmdClone(t *testing.T) {
opt := cmd.Options{
Buffered: true,
}
c1 := cmd.NewCmdOptions(opt, "ls")
c1.Dir = "/tmp/"
c1.Env = []string{"YES=please"}
c2 := c1.Clone()
if c1.Name != c2.Name {
t.Errorf("got Name %s, expecting %s", c2.Name, c1.Name)
}
if c1.Dir != c2.Dir {
t.Errorf("got Dir %s, expecting %s", c2.Dir, c1.Dir)
}
if diffs := deep.Equal(c1.Env, c2.Env); diffs != nil {
t.Error(diffs)
}
}
func TestCmdNonzeroExit(t *testing.T) {
p := cmd.NewCmd("false")
gotStatus := <-p.Start()
expectStatus := cmd.Status{
Cmd: "false",
PID: gotStatus.PID, // nondeterministic
Complete: true,
Exit: 1,
Error: nil,
Runtime: gotStatus.Runtime, // nondeterministic
Stdout: []string{},
Stderr: []string{},
}
gotStatus.StartTs = 0
gotStatus.StopTs = 0
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Error(diffs)
}
if gotStatus.PID < 0 {
t.Errorf("got PID %d, expected non-zero", gotStatus.PID)
}
if gotStatus.Runtime < 0 {
t.Errorf("got runtime %f, expected non-zero", gotStatus.Runtime)
}
}
func TestCmdStop(t *testing.T) {
// Count to 3 sleeping 5s between counts. The long sleep is because we want
// to kill the proc right after count "1" to ensure Stdout only contains "1"
// and also to ensure that the proc is really killed instantly because if
// it's not then timeout below will trigger.
p := cmd.NewCmd("./test/count-and-sleep", "3", "5")
// Start process in bg and get chan to receive final Status when done
statusChan := p.Start()
// Give it a second
time.Sleep(1 * time.Second)
// Kill the process
err := p.Stop()
if err != nil {
t.Error(err)
}
// The final status should be returned instantly
timeout := time.After(1 * time.Second)
var gotStatus cmd.Status
select {
case gotStatus = <-statusChan:
case <-timeout:
t.Fatal("timeout waiting for statusChan")
}
start := time.Unix(0, gotStatus.StartTs)
stop := time.Unix(0, gotStatus.StopTs)
d := stop.Sub(start).Seconds()
if d < 0.90 || d > 2 {
t.Errorf("stop - start time not between 0.9s and 2.0s: %s - %s = %f", stop, start, d)
}
gotStatus.StartTs = 0
gotStatus.StopTs = 0
expectStatus := cmd.Status{
Cmd: "./test/count-and-sleep",
PID: gotStatus.PID, // nondeterministic
Complete: false, // signaled by Stop
Exit: -1, // signaled by Stop
Error: errors.New("signal: terminated"), // signaled by Stop
Runtime: gotStatus.Runtime, // nondeterministic
Stdout: []string{"1"},
Stderr: []string{},
}
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Error(diffs)
}
if gotStatus.PID < 0 {
t.Errorf("got PID %d, expected non-zero", gotStatus.PID)
}
if gotStatus.Runtime < 0 {
t.Errorf("got runtime %f, expected non-zero", gotStatus.Runtime)
}
// Stop should be idempotent
err = p.Stop()
if err != nil {
t.Error(err)
}
// Start should be idempotent, too. It just returns the same statusChan again.
c2 := p.Start()
if diffs := deep.Equal(statusChan, c2); diffs != nil {
t.Error(diffs)
}
}
func TestCmdNotStarted(t *testing.T) {
// Call everything _but_ Start.
p := cmd.NewCmd("echo", "foo")
gotStatus := p.Status()
expectStatus := cmd.Status{
Cmd: "echo",
PID: 0,
Complete: false,
Exit: -1,
Error: nil,
Runtime: 0,
Stdout: nil,
Stderr: nil,
}
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Error(diffs)
}
err := p.Stop()
if err != cmd.ErrNotStarted {
t.Error(err)
}
}
func TestCmdOutput(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "cmd.TestCmdOutput")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
t.Logf("temp file: %s", tmpfile.Name())
os.Remove(tmpfile.Name())
p := cmd.NewCmd("./test/touch-file-count", tmpfile.Name())
p.Start()
touchFile := func(file string) {
if err := exec.Command("touch", file).Run(); err != nil {
t.Fatal(err)
}
time.Sleep(600 * time.Millisecond)
}
var s cmd.Status
var stdout []string
touchFile(tmpfile.Name())
s = p.Status()
stdout = []string{"1"}
if diffs := deep.Equal(s.Stdout, stdout); diffs != nil {
t.Log(s.Stdout)
t.Error(diffs)
}
touchFile(tmpfile.Name())
s = p.Status()
stdout = []string{"1", "2"}
if diffs := deep.Equal(s.Stdout, stdout); diffs != nil {
t.Log(s.Stdout)
t.Error(diffs)
}
// No more output yet
s = p.Status()
stdout = []string{"1", "2"}
if diffs := deep.Equal(s.Stdout, stdout); diffs != nil {
t.Log(s.Stdout)
t.Error(diffs)
}
// +2 lines
touchFile(tmpfile.Name())
touchFile(tmpfile.Name())
s = p.Status()
stdout = []string{"1", "2", "3", "4"}
if diffs := deep.Equal(s.Stdout, stdout); diffs != nil {
t.Log(s.Stdout)
t.Error(diffs)
}
// Kill the process
if err := p.Stop(); err != nil {
t.Error(err)
}
}
func TestCmdNotFound(t *testing.T) {
p := cmd.NewCmd("cmd-does-not-exist")
gotStatus := <-p.Start()
gotStatus.StartTs = 0
gotStatus.StopTs = 0
expectStatus := cmd.Status{
Cmd: "cmd-does-not-exist",
PID: 0,
Complete: false,
Exit: -1,
Error: &exec.Error{Name: "cmd-does-not-exist", Err: errors.New(`executable file not found in $PATH`)},
Runtime: 0,
Stdout: nil,
Stderr: nil,
}
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Logf("%+v", gotStatus)
t.Error(diffs)
}
}
func TestCmdLost(t *testing.T) {
// Test something like the kernel OOM killing the proc. So the proc is
// stopped outside our control.
p := cmd.NewCmd("./test/count-and-sleep", "3", "5")
statusChan := p.Start()
// Give it a second
time.Sleep(1 * time.Second)
// Get the PID and kill it
s := p.Status()
if s.PID <= 0 {
t.Fatalf("got PID %d, expected PID > 0", s.PID)
}
pgid, err := syscall.Getpgid(s.PID)
if err != nil {
t.Fatal(err)
}
syscall.Kill(-pgid, syscall.SIGKILL) // -pid = process group of pid
// Even though killed externally, our wait should return instantly
timeout := time.After(1 * time.Second)
var gotStatus cmd.Status
select {
case gotStatus = <-statusChan:
case <-timeout:
t.Fatal("timeout waiting for statusChan")
}
gotStatus.Runtime = 0 // nondeterministic
gotStatus.StartTs = 0
gotStatus.StopTs = 0
expectStatus := cmd.Status{
Cmd: "./test/count-and-sleep",
PID: s.PID,
Complete: false,
Exit: -1,
Error: errors.New("signal: killed"),
Runtime: 0,
Stdout: []string{"1"},
Stderr: []string{},
}
if diffs := deep.Equal(gotStatus, expectStatus); diffs != nil {
t.Logf("%+v\n", gotStatus)
t.Error(diffs)
}
}
func TestCmdBothOutput(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "cmd.TestStreamingOutput")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
if err := os.Remove(tmpfile.Name()); err != nil {
t.Fatal(err)
}
touchFile := func(file string) {
if err := exec.Command("touch", file).Run(); err != nil {
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
}
// Streams a count to stdout and stderr until given file exists
// Output like:
// stdout 1
// stderr 1
// stdout 2
// stderr 2
// Where each is printed on stdout and stderr as indicated.
p := cmd.NewCmdOptions(cmd.Options{Buffered: true, Streaming: true}, "./test/stream", tmpfile.Name())
p.Start()
time.Sleep(250 * time.Millisecond) // give test/stream a moment to print something
timeout := time.After(10 * time.Second) // test timeout
// test/stream is spewing output, so we should be able to read it while
// the cmd is running. Try and fetch 3 lines from stdout and stderr.
i := 0
stdoutPrevLine := ""
stderrPrevLine := ""
readLines := 3
lines := 0
for i < readLines {
i++
// STDOUT
select {
case curLine := <-p.Stdout:
t.Logf("got line: '%s'", curLine)
if curLine == "" {
// Shouldn't happen because test/stream doesn't print empty lines.
// This indicates a bug in the stream buffer handling.
t.Fatal("got empty line")
}
if stdoutPrevLine != "" && curLine == stdoutPrevLine {
t.Fatalf("current line == previous line, expected new output:\ncprev: %s\ncur: %s\n", stdoutPrevLine, curLine)
}
stdoutPrevLine = curLine
lines++
case <-timeout:
t.Fatal("timeout reading streaming output")
default:
}
// STDERR
select {
case curLine := <-p.Stderr:
t.Logf("got line: '%s'", curLine)
if curLine == "" {
// Shouldn't happen because test/stream doesn't print empty lines.
// This indicates a bug in the stream buffer handling.
t.Fatal("got empty line")
}
if stderrPrevLine != "" && curLine == stderrPrevLine {
t.Fatalf("current line == previous line, expected new output:\ncprev: %s\ncur: %s\n", stderrPrevLine, curLine)
}
stderrPrevLine = curLine
lines++
case <-timeout:
t.Fatal("timeout reading streaming output")
default:
}
time.Sleep(200 * time.Millisecond)
}
// readLines * 2 (stdout and stderr)
if lines != readLines*2 {
t.Fatalf("read %d lines from streaming output, expected 6", lines)
}
s := p.Status()
if len(s.Stdout) < readLines {
t.Fatalf("read %d lines from buffered STDOUT, expected %d", len(s.Stdout), readLines)
}
if len(s.Stderr) < readLines {
t.Fatalf("read %d lines from buffered STDERR, expected %d", len(s.Stderr), readLines)
}
// Stop test/stream
touchFile(tmpfile.Name())
s = p.Status()
if s.Exit != 0 {
t.Errorf("got exit %d, expected 0", s.Exit)
}
// Kill the process
if err := p.Stop(); err != nil {
t.Error(err)
}
}
func TestCmdOnlyStreamingOutput(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "cmd.TestStreamingOutput")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
if err := tmpfile.Close(); err != nil {
t.Fatal(err)
}
if err := os.Remove(tmpfile.Name()); err != nil {
t.Fatal(err)
}
touchFile := func(file string) {
if err := exec.Command("touch", file).Run(); err != nil {
t.Fatal(err)
}
time.Sleep(500 * time.Millisecond)
}
// Streams a count to stdout and stderr until given file exists
// Output like:
// stdout 1
// stderr 1
// stdout 2
// stderr 2
// Where each is printed on stdout and stderr as indicated.
p := cmd.NewCmdOptions(cmd.Options{Buffered: false, Streaming: true}, "./test/stream", tmpfile.Name())
p.Start()
time.Sleep(250 * time.Millisecond) // give test/stream a moment to print something
timeout := time.After(10 * time.Second) // test timeout
// test/stream is spewing output, so we should be able to read it while
// the cmd is running. Try and fetch 3 lines from stdout and stderr.
i := 0
stdoutPrevLine := ""
stderrPrevLine := ""
readLines := 3
lines := 0
for i < readLines {
i++
t.Log(i)
// STDOUT
select {
case curLine := <-p.Stdout:
t.Logf("got line: '%s'", curLine)
if curLine == "" {
// Shouldn't happen because test/stream doesn't print empty lines.
// This indicates a bug in the stream buffer handling.
t.Fatal("got empty line")
}
if stdoutPrevLine != "" && curLine == stdoutPrevLine {
t.Fatalf("current line == previous line, expected new output:\ncprev: %s\ncur: %s\n", stdoutPrevLine, curLine)
}
stdoutPrevLine = curLine
lines++
case <-timeout:
t.Fatal("timeout reading streaming output")
default:
}
// STDERR
select {
case curLine := <-p.Stderr:
t.Logf("got line: '%s'", curLine)
if curLine == "" {
// Shouldn't happen because test/stream doesn't print empty lines.
// This indicates a bug in the stream buffer handling.
t.Fatal("got empty line")
}
if stderrPrevLine != "" && curLine == stderrPrevLine {
t.Fatalf("current line == previous line, expected new output:\ncprev: %s\ncur: %s\n", stderrPrevLine, curLine)
}
stderrPrevLine = curLine
lines++
case <-timeout:
t.Fatal("timeout reading streaming output")
default:
}
time.Sleep(200 * time.Millisecond)
}
// readLines * 2 (stdout and stderr)
if lines != readLines*2 {
t.Fatalf("read %d lines from streaming output, expected 6", lines)
}
s := p.Status()
if len(s.Stdout) != 0 {
t.Fatalf("read %d lines from buffered STDOUT, expected 0", len(s.Stdout))
}
if len(s.Stderr) != 0 {
t.Fatalf("read %d lines from buffered STDERR, expected 0", len(s.Stderr))
}
// Stop test/stream
touchFile(tmpfile.Name())
s = p.Status()
if s.Exit != 0 {
t.Errorf("got exit %d, expected 0", s.Exit)
}
// Kill the process
if err := p.Stop(); err != nil {
t.Error(err)
}
}
func TestStreamingMultipleLines(t *testing.T) {
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
// Quick side test: Lines() chan string should be the same chan string
// we created the object with
if out.Lines() != lines {
t.Errorf("Lines() does not return the given string chan")
}
// Write two short lines
input := "foo\nbar\n"
n, err := out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
// Get one line
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
// "foo" should be sent before "bar" because that was the input
if gotLine != "foo" {
t.Errorf("got line: '%s', expected 'foo'", gotLine)
}
// Get next line
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "bar" {
t.Errorf("got line: '%s', expected 'bar'", gotLine)
}
}
func TestStreamingMultipleLinesLastNotTerminated(t *testing.T) {
// If last line isn't \n terminated, go-cmd should flush it anyway
// https://github.com/go-cmd/cmd/pull/48
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
// Quick side test: Lines() chan string should be the same chan string
// we created the object with
if out.Lines() != lines {
t.Errorf("Lines() does not return the given string chan")
}
// Write two short lines
input := "foo\nbar" // <- last line doesn't have \n
n, err := out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
// Get one line
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
// "foo" should be sent before "bar" because that was the input
if gotLine != "foo" {
t.Errorf("got line: '%s', expected 'foo'", gotLine)
}
out.Flush() // flush our output so go-cmd receives it
// Get next line
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "bar" {
t.Errorf("got line: '%s', expected 'bar'", gotLine)
}
}
func TestStreamingBlankLines(t *testing.T) {
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
// Blank line in the middle
input := "foo\n\nbar\n"
expectLines := []string{"foo", "", "bar"}
gotLines := []string{}
n, err := out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
LINES1:
for {
select {
case line := <-lines:
gotLines = append(gotLines, line)
default:
break LINES1
}
}
if diffs := deep.Equal(gotLines, expectLines); diffs != nil {
t.Error(diffs)
}
// All blank lines
input = "\n\n\n"
expectLines = []string{"", "", ""}
gotLines = []string{}
n, err = out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
LINES2:
for {
select {
case line := <-lines:
gotLines = append(gotLines, line)
default:
break LINES2
}
}
if diffs := deep.Equal(gotLines, expectLines); diffs != nil {
t.Error(diffs)
}
// Blank lines at end
input = "foo\n\n\n"
expectLines = []string{"foo", "", ""}
gotLines = []string{}
n, err = out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
LINES3:
for {
select {
case line := <-lines:
gotLines = append(gotLines, line)
default:
break LINES3
}
}
if diffs := deep.Equal(gotLines, expectLines); diffs != nil {
t.Error(diffs)
}
}
func TestStreamingCarriageReturn(t *testing.T) {
// Carriage return should be stripped
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
input := "foo\r\nbar\r\n"
expectLines := []string{"foo", "bar"}
gotLines := []string{}
n, err := out.Write([]byte(input))
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
LINES1:
for {
select {
case line := <-lines:
gotLines = append(gotLines, line)
default:
break LINES1
}
}
if diffs := deep.Equal(gotLines, expectLines); diffs != nil {
t.Error(diffs)
}
}
func TestStreamingLineBuffering(t *testing.T) {
// Lines not terminated with newline are held in the line buffer until next
// write. When line is later terminated with newline, we prepend the buffered
// line and send the complete line.
lines := make(chan string, 1)
out := cmd.NewOutputStream(lines)
// Write 3 unterminated lines. Without a newline, they'll be buffered until...
for i := 0; i < 3; i++ {
input := "foo"
n, err := out.Write([]byte(input))
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
// Should not get a line yet because it's not newline terminated
var gotLine string
select {
case gotLine = <-lines:
t.Errorf("got line '%s', expected no line yet", gotLine)
default:
}
}
// Write a line with newline that terminate the previous input
input := "bar\n"
n, err := out.Write([]byte(input))
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
// Now we get the previously buffered part of the line "foofoofoo" plus
// the newline terminated part "bar"
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked receiving line")
}
expectLine := "foofoofoobar"
if gotLine != expectLine {
t.Errorf("got line '%s', expected '%s'", gotLine, expectLine)
}
}
func TestStreamingErrLineBufferOverflow1(t *testing.T) {
// Overflow the line buffer in 1 write. The first line "bc" is sent,
// but the remaining line can't be buffered because it's +2 bytes larger
// than the line buffer.
longLine := make([]byte, 3+cmd.DEFAULT_LINE_BUFFER_SIZE+2) // "bc\nAAA...zz"
longLine[0] = 'b'
longLine[1] = 'c'
longLine[2] = '\n'
for i := 3; i < cmd.DEFAULT_LINE_BUFFER_SIZE; i++ {
longLine[i] = 'A'
}
// These 2 chars cause ErrLineBufferOverflow:
longLine[cmd.DEFAULT_LINE_BUFFER_SIZE] = 'z'
longLine[cmd.DEFAULT_LINE_BUFFER_SIZE+1] = 'z'
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
// Write the long line, it should only write (n) 3 bytes for "bc\n"
n, err := out.Write(longLine)
if n != 3 { // "bc\n"
t.Errorf("Write n = %d, expected 3", n)
}
switch err.(type) {
case cmd.ErrLineBufferOverflow:
lbo := err.(cmd.ErrLineBufferOverflow)
if lbo.BufferSize != cmd.DEFAULT_LINE_BUFFER_SIZE {
t.Errorf("ErrLineBufferOverflow.BufferSize = %d, expected %d", lbo.BufferSize, cmd.DEFAULT_LINE_BUFFER_SIZE)
}
if lbo.BufferFree != cmd.DEFAULT_LINE_BUFFER_SIZE {
t.Errorf("ErrLineBufferOverflow.BufferFree = %d, expected %d", lbo.BufferFree, cmd.DEFAULT_LINE_BUFFER_SIZE)
}
if lbo.Line != string(longLine[3:]) {
t.Errorf("ErrLineBufferOverflow.Line = '%s', expected '%s'", lbo.Line, string(longLine[3:]))
}
if lbo.Error() == "" {
t.Errorf("ErrLineBufferOverflow.Error() string is empty, expected something")
}
default:
t.Errorf("got err '%v', expected cmd.ErrLineBufferOverflow", err)
}
// "bc" should be sent before the overflow error
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "bc" {
t.Errorf("got line '%s', expected 'bc'", gotLine)
}
// Streaming should still work after an overflow. However, Go is going to
// stop any time Write() returns an error.
n, err = out.Write([]byte("foo\n"))
if n != 4 {
t.Errorf("got n %d, expected 4", n)
}
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "foo" {
t.Errorf("got line: '%s', expected 'foo'", gotLine)
}
}
func TestStreamingErrLineBufferOverflow2(t *testing.T) {
// Overflow line buffer on 2nd write. So first write puts something in the
// buffer, and then 2nd overflows it instead of completing the line.
lines := make(chan string, 1)
out := cmd.NewOutputStream(lines)
// Get "bar" into the buffer by omitting its newline
input := "foo\nbar"
n, err := out.Write([]byte(input))
if err != nil {
t.Errorf("got err '%v', expected nil", err)
}
if n != len(input) {
t.Errorf("Write n = %d, expected %d", n, len(input))
}
// Only "foo" sent, not "bar" yet
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "foo" {
t.Errorf("got line '%s', expected 'foo'", gotLine)
}
// Buffer contains "bar", now wverflow it on 2nd write
longLine := make([]byte, cmd.DEFAULT_LINE_BUFFER_SIZE)
for i := 0; i < cmd.DEFAULT_LINE_BUFFER_SIZE; i++ {
longLine[i] = 'X'
}
n, err = out.Write(longLine)
if n != 0 {
t.Errorf("Write n = %d, expected 0", n)
}
switch err.(type) {
case cmd.ErrLineBufferOverflow:
lbo := err.(cmd.ErrLineBufferOverflow)
// Buffer has "bar" so it's free is total - 3
if lbo.BufferFree != cmd.DEFAULT_LINE_BUFFER_SIZE-3 {
t.Errorf("ErrLineBufferOverflow.BufferFree = %d, expected %d", lbo.BufferFree, cmd.DEFAULT_LINE_BUFFER_SIZE)
}
// Up to but not include "bc\n" because it should have been truncated
expectLine := "bar" + string(longLine)
if lbo.Line != expectLine {
t.Errorf("ErrLineBufferOverflow.Line = '%s', expected '%s'", lbo.Line, expectLine)
}
default:
t.Errorf("got err '%v', expected cmd.ErrLineBufferOverflow", err)
}
}
func TestStreamingSetLineBufferSize(t *testing.T) {
// Same overflow as TestStreamingErrLineBufferOverflow1 but before we use
// stream output, we'll increase buffer size by calling SetLineBufferSize
// which should prevent the overflow
longLine := make([]byte, 3+cmd.DEFAULT_LINE_BUFFER_SIZE+2) // "bc\nAAA...z\n"
longLine[0] = 'b'
longLine[1] = 'c'
longLine[2] = '\n'
for i := 3; i < cmd.DEFAULT_LINE_BUFFER_SIZE; i++ {
longLine[i] = 'A'
}
longLine[cmd.DEFAULT_LINE_BUFFER_SIZE] = 'z'
longLine[cmd.DEFAULT_LINE_BUFFER_SIZE+1] = '\n'
lines := make(chan string, 5)
out := cmd.NewOutputStream(lines)
out.SetLineBufferSize(cmd.DEFAULT_LINE_BUFFER_SIZE * 2)
n, err := out.Write(longLine)
if err != nil {
t.Errorf("error '%v', expected nil", err)
}
if n != len(longLine) {
t.Errorf("Write n = %d, expected %d", n, len(longLine))
}
// First we get "bc"
var gotLine string
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
if gotLine != "bc" {
t.Errorf("got line '%s', expected 'bc'", gotLine)
}
// Then we get the long line because the buffer was large enough to hold it
select {
case gotLine = <-lines:
default:
t.Fatal("blocked on <-lines")
}
expectLine := string(longLine[3 : cmd.DEFAULT_LINE_BUFFER_SIZE+1]) // not newline
if gotLine != expectLine {
t.Errorf("got line: '%s', expected '%s'", gotLine, expectLine)
}
}
func TestDone(t *testing.T) {
// Count to 3 sleeping 1s between counts
p := cmd.NewCmd("./test/count-and-sleep", "3", "1")
statusChan := p.Start()
// For 2s while cmd is running, Done() chan should block, which means
// it's still running
runningTimer := time.After(2 * time.Second)
TIMER:
for {
select {
case <-runningTimer:
break TIMER
default:
}
select {
case <-p.Done():
t.Fatal("Done chan is closed before runningTime finished")
default:
// Done chan blocked, cmd is still running
}
time.Sleep(400 * time.Millisecond)