-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmdexec_test.go
More file actions
70 lines (55 loc) · 1.52 KB
/
cmdexec_test.go
File metadata and controls
70 lines (55 loc) · 1.52 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
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// tests were inspired by this blog article: https://npf.io/2015/06/testing-exec-command/
type fakeexec struct {
t *testing.T
mockCount int
mocks []fakeexecparams
}
// nolint:musttag
type fakeexecparams struct {
WantCmd []string `json:"want_cmd"`
Output string `json:"output"`
ExitCode int `json:"exit_code"`
}
func fakeCmd(t *testing.T, params ...fakeexecparams) func(ctx context.Context, command string, args ...string) *exec.Cmd {
f := fakeexec{
t: t,
mocks: params,
}
return f.command
}
func (f *fakeexec) command(ctx context.Context, command string, args ...string) *exec.Cmd {
if f.mockCount >= len(f.mocks) {
require.Fail(f.t, "more commands called than mocks are available")
}
params := f.mocks[f.mockCount]
f.mockCount++
assert.Equal(f.t, params.WantCmd, append([]string{command}, args...))
j, err := json.Marshal(params)
require.NoError(f.t, err)
cs := []string{"-test.run=TestHelperProcess", "--", string(j)}
cmd := exec.CommandContext(ctx, os.Args[0], cs...) //nolint
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
var f fakeexecparams
err := json.Unmarshal([]byte(os.Args[3]), &f)
require.NoError(t, err)
_, err = fmt.Fprint(os.Stdout, f.Output)
require.NoError(t, err)
os.Exit(f.ExitCode)
}