-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathcmd_testcase.go
60 lines (51 loc) · 1.25 KB
/
cmd_testcase.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
package cocatest
import (
"bytes"
"github.com/mattn/go-shellwords"
"github.com/modernizing/coca/cocatest/testcase"
"github.com/spf13/cobra"
"io"
"os"
"path/filepath"
"strings"
"testing"
)
func RunTestCaseWithCmd(t *testing.T, tests []testcase.CmdTestCase, rootCmd func(out io.Writer) *cobra.Command) {
t.Helper()
for _, tt := range tests {
t.Run(tt.Name, func(t *testing.T) {
defer ResetEnv()()
t.Log("running Cmd: ", tt.Cmd)
_, output, err := executeActionCommandC(tt.Cmd, rootCmd)
if (err != nil) != tt.WantError {
t.Errorf("expected error, got '%v'", err)
}
if tt.Golden != "" {
abs, _ := filepath.Abs(tt.Golden)
slash := filepath.FromSlash(abs)
AssertGoldenString(t, output, slash)
}
})
}
}
func executeActionCommandC(cmd string, rootCmd func(out io.Writer) *cobra.Command) (*cobra.Command, string, error) {
args, err := shellwords.Parse(cmd)
if err != nil {
return nil, "", err
}
buf := new(bytes.Buffer)
command := rootCmd(buf)
command.SetArgs(args)
c, err := command.ExecuteC()
return c, buf.String(), err
}
func ResetEnv() func() {
origEnv := os.Environ()
return func() {
os.Clearenv()
for _, pair := range origEnv {
kv := strings.SplitN(pair, "=", 2)
os.Setenv(kv[0], kv[1])
}
}
}