-
Notifications
You must be signed in to change notification settings - Fork 3
/
run_ext_test.go
85 lines (76 loc) · 2.01 KB
/
run_ext_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
package run_test
import (
"context"
"fmt"
"slices"
"testing"
"github.com/DavidGamba/dgtools/run"
)
func TestRunWithMocks(t *testing.T) {
t.Run("mock", func(t *testing.T) {
r := run.CMD("ls", "./run")
r.Mock(func(r *run.RunInfo) error {
r.Stdout.Write([]byte("hello world\n"))
r.Stderr.Write([]byte("hola mundo\n"))
return nil
})
out, err := r.CombinedOutput()
if err != nil {
t.Errorf("unexpected error")
}
if string(out) != "hello world\nhola mundo\n" {
t.Errorf("wrong output: %s\n", out)
}
})
t.Run("mock with context", func(t *testing.T) {
ctx := context.Background()
mockR := run.CMD().Mock(func(r *run.RunInfo) error {
r.Stdout.Write([]byte("hello world\n"))
r.Stderr.Write([]byte("hola mundo\n"))
return nil
})
ctx = run.ContextWithRunInfo(ctx, mockR)
r := run.CMDCtx(ctx, "ls", "./run")
out, err := r.CombinedOutput()
if err != nil {
t.Errorf("unexpected error")
}
if string(out) != "hello world\nhola mundo\n" {
t.Errorf("wrong output: %s\n", out)
}
})
t.Run("mock with context switch", func(t *testing.T) {
ctx := context.Background()
mockR := run.CMD().Mock(func(r *run.RunInfo) error {
cmd := r.Cmd
switch {
case slices.Compare(cmd, []string{"ls", "./run"}) == 0:
r.Stdout.Write([]byte("hello world\n"))
r.Stderr.Write([]byte("hola mundo\n"))
return nil
case slices.Compare(cmd, []string{"ls", "x"}) == 0:
r.Stderr.Write([]byte("not found x\n"))
return fmt.Errorf("not found x")
default:
return fmt.Errorf("unexpected command: %s", cmd)
}
})
ctx = run.ContextWithRunInfo(ctx, mockR)
r := run.CMDCtx(ctx, "ls", "./run")
out, err := r.CombinedOutput()
if err != nil {
t.Errorf("unexpected error: %s", err)
}
if string(out) != "hello world\nhola mundo\n" {
t.Errorf("wrong output: %s\n", out)
}
r = run.CMDCtx(ctx, "ls", "x")
out, err = r.CombinedOutput()
if err == nil {
t.Errorf("expected error")
}
if string(out) != "not found x\n" {
t.Errorf("wrong output: %s\n", out)
}
})
}