-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommander_integration_test.go
More file actions
2395 lines (2030 loc) · 65.9 KB
/
Copy pathcommander_integration_test.go
File metadata and controls
2395 lines (2030 loc) · 65.9 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
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
package commander
import (
"context"
"errors"
"fmt"
"os/exec"
"strings"
"sync"
"testing"
"time"
commonerrors "github.com/psyb0t/common-go/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCommander_BasicOperations(t *testing.T) {
tests := []struct {
name string
command string
args []string
operation string
expectError bool
expectOut string
}{
{
name: "run echo command",
command: "echo",
args: []string{"hello"},
operation: "run",
},
{
name: "output echo command",
command: "echo",
args: []string{"world"},
operation: "output",
expectOut: "world\n",
},
{
name: "combined output echo command",
command: "echo",
args: []string{"combined"},
operation: "combined",
expectOut: "combined\n",
},
{
name: "failing command",
command: "false",
args: []string{},
operation: "run",
expectError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := New()
ctx := context.Background()
switch tt.operation {
case "run":
err := cmd.Run(ctx, tt.command, tt.args)
if tt.expectError {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
case "output":
stdout, stderr, err := cmd.Output(ctx, tt.command, tt.args)
require.NoError(t, err)
assert.Equal(t, tt.expectOut, string(stdout))
assert.NotNil(t, stderr)
case "combined":
combined, err := cmd.CombinedOutput(ctx, tt.command, tt.args)
require.NoError(t, err)
assert.Equal(t, tt.expectOut, string(combined))
}
})
}
}
func TestCommander_WithOptions(t *testing.T) {
tests := []struct {
name string
setup func() ([]Option, func(*testing.T, error, []byte))
command string
args []string
}{
{
name: "with stdin",
command: "cat",
args: []string{},
setup: func() ([]Option, func(*testing.T, error, []byte)) {
stdin := strings.NewReader("test input")
opts := []Option{WithStdin(stdin)}
return opts, func(t *testing.T, err error, output []byte) {
require.NoError(t, err)
assert.Equal(t, "test input", string(output))
}
},
},
{
name: "with environment",
command: "sh",
args: []string{"-c", "echo $TEST_VAR"},
setup: func() ([]Option, func(*testing.T, error, []byte)) {
opts := []Option{WithEnv([]string{"TEST_VAR=hello"})}
return opts, func(t *testing.T, err error, output []byte) {
require.NoError(t, err)
assert.Equal(t, "hello\n", string(output))
}
},
},
{
name: "with working directory",
command: "pwd",
args: []string{},
setup: func() ([]Option, func(*testing.T, error, []byte)) {
opts := []Option{WithDir("/tmp")}
return opts, func(t *testing.T, err error, output []byte) {
require.NoError(t, err)
assert.Equal(t, "/tmp\n", string(output))
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := New()
ctx := context.Background()
optFuncs, verify := tt.setup()
stdout, _, err := cmd.Output(ctx, tt.command, tt.args, optFuncs...)
verify(t, err, stdout)
})
}
}
func TestCommander_ProcessControl(t *testing.T) {
t.Run("start and wait", func(t *testing.T) {
cmd := New()
ctx := context.Background()
proc, err := cmd.Start(ctx, "echo", []string{"process test"})
require.NoError(t, err)
err = proc.Wait()
require.NoError(t, err)
})
t.Run("stdout stream", func(t *testing.T) {
cmd := New()
ctx := context.Background()
proc, err := cmd.Start(ctx, "echo", []string{"stdout test"})
require.NoError(t, err)
// Use Stream() instead of pipe
stdout := make(chan string, 10)
proc.Stream(stdout, nil)
// Collect all output
var lines []string
for line := range stdout {
lines = append(lines, line)
}
err = proc.Wait()
require.NoError(t, err)
// Verify we got the expected output
require.Len(t, lines, 1)
assert.Equal(t, "stdout test", lines[0])
})
t.Run("stderr stream", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Use a command that naturally writes to stderr
proc, err := cmd.Start(ctx, "sh", []string{"-c", "echo 'stderr test' >&2; sleep 0.1"})
require.NoError(t, err)
// Use Stream() instead of pipe
stderr := make(chan string, 10)
proc.Stream(nil, stderr)
// Collect all output
var lines []string
for line := range stderr {
lines = append(lines, line)
}
err = proc.Wait()
require.NoError(t, err)
// Verify we got the expected output
require.Len(t, lines, 1)
assert.Equal(t, "stderr test", lines[0])
})
}
func TestCommander_ContextCancellation(t *testing.T) {
tests := []struct {
name string
timeout time.Duration
command string
args []string
expectError bool
errorCheck func(t *testing.T, err error)
}{
{
name: "quick command with long timeout",
timeout: 5 * time.Second,
command: "echo",
args: []string{"quick"},
expectError: false,
},
{
name: "slow command with short timeout",
timeout: 100 * time.Millisecond,
command: "sleep",
args: []string{"1"},
expectError: true,
errorCheck: func(t *testing.T, err error) {
// With context timeout, we should get ErrTimeout
assert.ErrorIs(t, err, commonerrors.ErrTimeout, "Expected ErrTimeout, got: %s", err)
},
},
{
name: "medium command with medium timeout",
timeout: 200 * time.Millisecond,
command: "sleep",
args: []string{"0.1"},
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := New()
ctx := context.Background()
var err error
if tt.timeout > 0 {
// Use context timeout
timeoutCtx, cancel := context.WithTimeout(ctx, tt.timeout)
defer cancel()
err = cmd.Run(timeoutCtx, tt.command, tt.args)
} else {
err = cmd.Run(ctx, tt.command, tt.args)
}
if tt.expectError {
assert.Error(t, err)
if tt.errorCheck != nil {
tt.errorCheck(t, err)
}
} else {
assert.NoError(t, err)
}
})
}
}
func TestCommander_StreamingOutput(t *testing.T) {
t.Run("continuous output stream", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that outputs every second for 3 seconds
proc, err := cmd.Start(ctx, "bash", []string{"-c", "for i in {1..3}; do echo \"line $i\"; sleep 1; done"})
require.NoError(t, err)
// Use Stream() instead of StdoutPipe
stdout := make(chan string, 10)
proc.Stream(stdout, nil)
// Read output line by line as it comes
var lines []string
startTime := time.Now()
for line := range stdout {
lines = append(lines, line)
t.Logf("Received at %v: %s", time.Since(startTime), line)
}
err = proc.Wait()
require.NoError(t, err)
// Verify we got all expected lines
expectedLines := []string{"line 1", "line 2", "line 3"}
assert.Equal(t, expectedLines, lines)
// Verify it took approximately 3 seconds (with some tolerance)
duration := time.Since(startTime)
assert.True(t, duration >= 2*time.Second, "Should take at least 2 seconds")
assert.True(t, duration <= 5*time.Second, "Should complete within 5 seconds")
})
}
func TestCommander_EarlyTermination(t *testing.T) {
t.Run("cancel during continuous output", func(t *testing.T) {
cmd := New()
// Create a context we can cancel
ctx, cancel := context.WithCancel(context.Background())
// Command that outputs every 500ms for a long time
proc, err := cmd.Start(ctx, "bash", []string{"-c", "for i in {1..10}; do echo \"output $i\"; sleep 0.5; done"})
require.NoError(t, err)
// Use Stream() instead of StdoutPipe
stdout := make(chan string, 10)
proc.Stream(stdout, nil)
// Read some output, then cancel
var lines []string
startTime := time.Now()
// Read first 2 lines
for len(lines) < 2 {
select {
case line := <-stdout:
lines = append(lines, line)
t.Logf("Received at %v: %s", time.Since(startTime), line)
case <-time.After(2 * time.Second):
t.Fatal("Timeout waiting for initial output")
}
}
// Cancel the context after receiving some output
cancel()
// Try to read remaining output (should be limited)
timeout := time.After(2 * time.Second)
readLoop:
for {
select {
case line, ok := <-stdout:
if !ok {
// Channel closed
break readLoop
}
lines = append(lines, line)
t.Logf("Received after cancel at %v: %s", time.Since(startTime), line)
case <-timeout:
// Timeout reached, which is fine for this test
t.Log("Timeout reached waiting for process to finish")
break readLoop
}
}
// Process should return an error due to cancellation
err = proc.Wait()
assert.Error(t, err)
// Process should be killed or canceled
isKilled := errors.Is(err, commonerrors.ErrKilled) || strings.Contains(err.Error(), "signal: killed")
isCanceled := strings.Contains(err.Error(), "context canceled")
assert.True(t, isKilled || isCanceled,
"Expected cancellation or kill error, got: %s", err.Error())
// We should have received at least the first 2 lines
assert.GreaterOrEqual(t, len(lines), 2, "Should receive at least 2 lines before cancellation")
assert.LessOrEqual(t, len(lines), 5, "Should not receive all 10 lines due to early cancellation")
// Verify the lines we got are correct
for i, line := range lines {
expected := fmt.Sprintf("output %d", i+1)
assert.Equal(t, expected, line)
}
t.Logf("Total lines received: %d (expected 2-5 due to cancellation)", len(lines))
})
}
func TestCommander_DefaultOutputBehavior(t *testing.T) {
tests := []struct {
name string
command string
args []string
opts []Option
expectOut string
expectError bool
testFunc func(t *testing.T, cmd Commander, ctx context.Context)
}{
{
name: "default behavior - output discarded",
command: "echo",
args: []string{"this goes to /dev/null"},
opts: nil,
testFunc: func(t *testing.T, cmd Commander, ctx context.Context) {
// This should send output to /dev/null, not to our terminal
err := cmd.Run(ctx, "echo", []string{"this goes to /dev/null"})
assert.NoError(t, err)
t.Log("Command completed - output was discarded to /dev/null (Go stdlib default)")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := New()
ctx := context.Background()
if tt.testFunc != nil {
tt.testFunc(t, cmd, ctx)
}
})
}
t.Run("verify exec.Cmd defaults", func(t *testing.T) {
// Let's test this by creating our own exec.Cmd and seeing what the defaults are
cmd := exec.CommandContext(context.Background(), "echo", "test")
t.Logf("Default cmd.Stdout: %v", cmd.Stdout)
t.Logf("Default cmd.Stderr: %v", cmd.Stderr)
t.Logf("Default cmd.Stdin: %v", cmd.Stdin)
// According to Go docs:
// If Stdout is nil, Run connects the process stdout to os.DevNull
// If Stderr is nil, Run connects the process stderr to os.DevNull
// If Stdin is nil, the process reads from os.DevNull
})
}
func TestCommander_Stream(t *testing.T) {
tests := []struct {
name string
command string
args []string
testFunc func(t *testing.T, proc Process)
expectError bool
}{
{
name: "basic streaming",
command: "bash",
args: []string{"-c", "echo line1; echo line2; echo line3"},
testFunc: func(t *testing.T, proc Process) {
// Start streaming stdout only
stdout := make(chan string, 10)
proc.Stream(stdout, nil)
// Collect output
var lines []string
for line := range stdout {
lines = append(lines, line)
if len(lines) >= 3 {
break
}
}
// Verify we got the expected lines
assert.Len(t, lines, 3)
assert.Contains(t, lines[0], "line1")
assert.Contains(t, lines[1], "line2")
assert.Contains(t, lines[2], "line3")
// Lines should be raw without prefixes now
for _, line := range lines {
assert.NotContains(t, line, "[STDOUT]")
}
},
},
{
name: "stdout and stderr mixed",
command: "bash",
args: []string{"-c", "echo stdout1; echo stderr1 >&2; echo stdout2; echo stderr2 >&2"},
testFunc: func(t *testing.T, proc Process) {
stdout := make(chan string, 10)
stderr := make(chan string, 10)
proc.Stream(stdout, stderr)
var stdoutLines []string
var stderrLines []string
timeout := time.After(2 * time.Second)
readLoop:
for len(stdoutLines)+len(stderrLines) < 4 {
select {
case line := <-stdout:
stdoutLines = append(stdoutLines, line)
case line := <-stderr:
stderrLines = append(stderrLines, line)
case <-timeout:
break readLoop
}
}
// Should have received lines on both channels
assert.True(t, len(stdoutLines) > 0, "Should receive stdout lines")
assert.True(t, len(stderrLines) > 0, "Should receive stderr lines")
// Verify content
for _, line := range stdoutLines {
assert.Contains(t, line, "stdout")
}
for _, line := range stderrLines {
assert.Contains(t, line, "stderr")
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := New()
ctx := context.Background()
proc, err := cmd.Start(ctx, tt.command, tt.args)
if tt.expectError {
assert.Error(t, err)
return
}
require.NoError(t, err)
tt.testFunc(t, proc)
err = proc.Wait()
assert.NoError(t, err)
})
}
}
func TestCommander_StreamAdvanced(t *testing.T) {
t.Run("live streaming behavior - no history replay", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Start a command that outputs lines with delays
proc, err := cmd.Start(ctx, "bash", []string{
"-c",
"echo first; sleep 0.2; echo second; sleep 0.2; echo third; sleep 0.2; echo fourth",
})
require.NoError(t, err)
// Start first stream and read some lines
ch1 := make(chan string, 10)
proc.Stream(ch1, nil)
// Read first 2 lines
line1 := <-ch1
line2 := <-ch1
assert.Contains(t, line1, "first")
assert.Contains(t, line2, "second")
// Wait a bit for more output to be generated
time.Sleep(500 * time.Millisecond)
// Start second stream - should only get NEW lines, not replay
ch2 := make(chan string, 10)
proc.Stream(ch2, nil)
// This should get only the latest/new output, not the historical first/second lines
var newLines []string
timeout := time.After(1 * time.Second)
for {
select {
case line := <-ch2:
newLines = append(newLines, line)
if len(newLines) >= 2 || (len(newLines) >= 1 && strings.Contains(line, "fourth")) {
goto done
}
case <-timeout:
goto done
}
}
done:
// Verify we didn't get the first two lines again
for _, line := range newLines {
assert.NotContains(t, line, "first", "Should not replay first line")
assert.NotContains(t, line, "second", "Should not replay second line")
}
err = proc.Wait()
assert.NoError(t, err)
})
t.Run("join live stream in progress", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Start a command that outputs lines with delays - longer running
proc, err := cmd.Start(ctx, "bash", []string{
"-c",
"for i in {1..8}; do echo \"line $i\"; sleep 0.2; done",
})
require.NoError(t, err)
// Start first stream
stream1 := make(chan string, 10)
proc.Stream(stream1, nil)
// Let stream1 get a few lines first
var stream1Lines []string
for len(stream1Lines) < 3 {
select {
case line := <-stream1:
stream1Lines = append(stream1Lines, line)
t.Logf("Stream1 received: %s", line)
case <-time.After(1 * time.Second):
t.Fatal("Timeout waiting for stream1 to receive lines")
}
}
// Now start second stream WHILE first stream is still active and receiving
stream2 := make(chan string, 10)
proc.Stream(stream2, nil)
t.Logf("Stream2 joined after stream1 received %d lines", len(stream1Lines))
// Both streams should now receive the SAME remaining lines
var stream2Lines []string
timeout := time.After(3 * time.Second)
// Collect remaining lines from both streams
for len(stream1Lines) < 8 || len(stream2Lines) < 5 { // stream2 should get ~5 remaining lines
select {
case line := <-stream1:
stream1Lines = append(stream1Lines, line)
t.Logf("Stream1 got: %s (total: %d)", line, len(stream1Lines))
case line := <-stream2:
stream2Lines = append(stream2Lines, line)
t.Logf("Stream2 got: %s (total: %d)", line, len(stream2Lines))
case <-timeout:
goto verify
}
}
verify:
err = proc.Wait()
assert.NoError(t, err)
// Stream1 should have received all 8 lines (was there from start)
assert.True(t, len(stream1Lines) >= 7, "Stream1 should get most/all lines")
// Stream2 should have received the later lines (joined mid-stream)
assert.True(t, len(stream2Lines) >= 4, "Stream2 should get remaining lines after joining")
// The lines that both streams received should be identical
// Find the overlap period - lines that both streams got
stream1Set := make(map[string]bool)
for _, line := range stream1Lines {
stream1Set[line] = true
}
overlapCount := 0
for _, line := range stream2Lines {
if stream1Set[line] {
overlapCount++
}
}
assert.True(t, overlapCount >= 3, "Both streams should receive some identical lines")
t.Logf("Stream1 total: %d, Stream2 total: %d, Overlap: %d",
len(stream1Lines), len(stream2Lines), overlapCount)
})
t.Run("multiple concurrent streams", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Start a command that outputs several lines
proc, err := cmd.Start(ctx, "bash", []string{
"-c",
"for i in {1..5}; do echo \"line $i\"; sleep 0.1; done",
})
require.NoError(t, err)
// Start multiple streams simultaneously
ch1 := make(chan string, 10)
ch2 := make(chan string, 10)
ch3 := make(chan string, 10)
proc.Stream(ch1, nil)
proc.Stream(ch2, nil)
proc.Stream(ch3, nil)
// Collect output from all streams
var lines1, lines2, lines3 []string
timeout := time.After(2 * time.Second)
done := make(chan bool, 3)
// Reader for ch1
go func() {
for line := range ch1 {
lines1 = append(lines1, line)
if len(lines1) >= 5 {
break
}
}
done <- true
}()
// Reader for ch2
go func() {
for line := range ch2 {
lines2 = append(lines2, line)
if len(lines2) >= 5 {
break
}
}
done <- true
}()
// Reader for ch3
go func() {
for line := range ch3 {
lines3 = append(lines3, line)
if len(lines3) >= 5 {
break
}
}
done <- true
}()
// Wait for all readers to complete or timeout
completed := 0
for completed < 3 {
select {
case <-done:
completed++
case <-timeout:
t.Log("Timeout waiting for streams to complete")
goto checkResults
}
}
checkResults:
// All streams should receive the same lines (broadcast)
assert.True(t, len(lines1) > 0, "Stream 1 should receive lines")
assert.True(t, len(lines2) > 0, "Stream 2 should receive lines")
assert.True(t, len(lines3) > 0, "Stream 3 should receive lines")
// All streams should get the same content (broadcast behavior)
minLen := min(len(lines3), min(len(lines2), len(lines1)))
for i := range minLen {
assert.Equal(t, lines1[i], lines2[i], "Streams should receive same content")
assert.Equal(t, lines1[i], lines3[i], "Streams should receive same content")
}
err = proc.Wait()
assert.NoError(t, err)
})
}
func TestCommander_OutputAndCombinedOutput(t *testing.T) {
t.Run("output with error", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that fails
_, _, err := cmd.Output(ctx, "false", []string{})
assert.Error(t, err)
})
t.Run("combined output success", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that outputs to both stdout and stderr successfully
stdout, stderr, err := cmd.Output(ctx, "sh", []string{"-c", "echo stdout && echo stderr >&2"})
assert.NoError(t, err)
assert.Contains(t, string(stdout), "stdout")
assert.Contains(t, string(stderr), "stderr")
// Test combined output separately
combined, err := cmd.CombinedOutput(ctx, "sh", []string{"-c", "echo stdout && echo stderr >&2"})
assert.NoError(t, err)
assert.Contains(t, string(combined), "stdout")
assert.Contains(t, string(combined), "stderr")
})
t.Run("combined output with error", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that outputs to both stdout and stderr, then fails
stdout, stderr, err := cmd.Output(ctx, "sh", []string{"-c", "echo stdout && echo stderr >&2 && exit 1"})
assert.Error(t, err)
assert.Contains(t, string(stdout), "stdout")
assert.Contains(t, string(stderr), "stderr")
// Test combined output with error
combined, err := cmd.CombinedOutput(ctx, "sh", []string{"-c", "echo stdout && echo stderr >&2 && exit 1"})
assert.Error(t, err)
assert.Contains(t, string(combined), "stdout")
assert.Contains(t, string(combined), "stderr")
})
t.Run("output with context timeout", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that takes too long with context timeout
timeoutCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_, _, err := cmd.Output(timeoutCtx, "sleep", []string{"1"})
assert.Error(t, err)
assert.ErrorIs(t, err, commonerrors.ErrTimeout, "Expected ErrTimeout, got: %s", err)
})
t.Run("combined output with context timeout", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Command that takes too long with context timeout
timeoutCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_, _, err := cmd.Output(timeoutCtx, "sleep", []string{"1"})
assert.Error(t, err)
assert.ErrorIs(t, err, commonerrors.ErrTimeout, "Expected ErrTimeout, got: %s", err)
})
}
func TestCommander_ConcurrentRealCommands(t *testing.T) {
cmd := New()
ctx := context.Background()
// Define 3 different real commands to run concurrently
type commandTest struct {
name string
command string
args []string
expected string
}
tests := []commandTest{
{
name: "echo test",
command: "echo",
args: []string{"concurrent test 1"},
expected: "concurrent test 1\n",
},
{
name: "date command",
command: "date",
args: []string{"+%Y"},
expected: "202", // Should contain current year prefix
},
{
name: "wc line count",
command: "sh",
args: []string{"-c", "echo -e 'line1\\nline2\\nline3' | wc -l"},
expected: "3",
},
}
// Channels to collect results
results := make(chan struct {
name string
output string
err error
}, len(tests))
// Launch all commands concurrently
for _, test := range tests {
go func(tc commandTest) {
stdout, _, err := cmd.Output(ctx, tc.command, tc.args)
results <- struct {
name string
output string
err error
}{
name: tc.name,
output: string(stdout),
err: err,
}
}(test)
}
// Collect and verify all results
collectedResults := make(map[string]string)
for range tests {
select {
case result := <-results:
assert.NoError(t, result.err, "Command %s should not error", result.name)
collectedResults[result.name] = result.output
t.Logf("Command '%s' output: %q", result.name, result.output)
case <-time.After(5 * time.Second):
t.Fatal("Timeout waiting for concurrent commands to complete")
}
}
// Verify outputs contain expected content
assert.Contains(t, collectedResults["echo test"], "concurrent test 1")
assert.Contains(t, collectedResults["date command"], "202") // Current year should start with 202x
assert.Contains(t, collectedResults["wc line count"], "3")
t.Logf("All %d concurrent commands completed successfully", len(tests))
}
func TestCommander_ConcurrentLoadTest(t *testing.T) {
cmd := New()
ctx := context.Background()
// Test different load levels
loadLevels := []int{3, 20, 50, 100, 1000}
for _, numCommands := range loadLevels {
t.Run(fmt.Sprintf("load_test_%d_commands", numCommands), func(t *testing.T) {
startTime := time.Now()
// Create channels for results
results := make(chan struct {
id int
output string
err error
}, numCommands)
// Launch all commands concurrently
for i := range numCommands {
go func(cmdID int) {
// Mix different commands for realistic load
var output []byte
var err error
switch cmdID % 3 {
case 0:
output, _, err = cmd.Output(ctx, "echo", []string{fmt.Sprintf("command_%d", cmdID)})
case 1:
output, _, err = cmd.Output(ctx, "date", []string{"+%s"}) // Unix timestamp
case 2:
output, _, err = cmd.Output(ctx, "sh", []string{"-c", fmt.Sprintf("echo %d | wc -c", cmdID)})
}
results <- struct {
id int
output string
err error
}{
id: cmdID,
output: string(output),
err: err,
}
}(i)
}
// Collect all results with timeout
successCount := 0
errorCount := 0
timeout := time.After(30 * time.Second) // Generous timeout for 1000 commands
for range numCommands {
select {
case result := <-results:
if result.err != nil {
errorCount++
t.Logf("Command %d failed: %v", result.id, result.err)
} else {
successCount++
// Verify output is not empty
assert.NotEmpty(t, strings.TrimSpace(result.output),
"Command %d should produce output", result.id)
}
case <-timeout:
t.Fatalf("Timeout waiting for %d commands (got %d successes, %d errors)",
numCommands, successCount, errorCount)
}
}
duration := time.Since(startTime)
commandsPerSecond := float64(numCommands) / duration.Seconds()
// Verify results
assert.Equal(t, numCommands, successCount+errorCount,
"Should receive response from all commands")
assert.Equal(t, 0, errorCount, "All commands should succeed")
assert.Equal(t, numCommands, successCount, "All commands should succeed")
t.Logf("Load test completed: %d commands in %v (%.2f commands/sec)",
numCommands, duration, commandsPerSecond)
// Quick verification: check some outputs to ensure they're real
if numCommands >= 20 {
t.Logf("Sample verification - this was real command execution, not cached bullshit")
}
// Performance expectations (adjust based on system)
if numCommands <= 100 {
assert.Less(t, duration, 5*time.Second,
"Small loads should complete quickly")
}
})
}
}
func TestCommander_StreamingWithStop(t *testing.T) {
t.Run("streaming stops when process is stopped", func(t *testing.T) {
cmd := New()
ctx := context.Background()
// Start a long-running command that outputs continuously