-
Notifications
You must be signed in to change notification settings - Fork 1
/
root_test.go
85 lines (79 loc) · 2.07 KB
/
root_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 main
import (
"bytes"
"errors"
"fmt"
"io"
"strings"
"testing"
)
type cobraTestOpts struct {
stdin io.Reader
}
func cobraTest(t *testing.T, opts *cobraTestOpts, args ...string) (string, error) {
t.Helper()
buf := new(bytes.Buffer)
rootCmd := NewRootCmd()
if opts != nil && opts.stdin != nil {
rootCmd.SetIn(opts.stdin)
}
rootCmd.SetOut(buf)
rootCmd.SetErr(buf)
rootCmd.SetArgs(args)
err := rootCmd.Execute()
return strings.TrimSpace(buf.String()), err
}
func TestRootCmd(t *testing.T) {
// TODO: copy testdata to a temp dir and test scan and update commands
tt := []struct {
name string
args []string
expectErr error
expectOut string
outContains bool
}{
{
name: "Version",
args: []string{"version"},
expectOut: "VCSRef:",
outContains: true,
},
{
name: "Check-Good",
args: []string{"check", "--conf", "./testdata/root-conf.yaml", "root-good.txt"},
},
{
name: "Check-Bad",
args: []string{"check", "--conf", "./testdata/root-conf.yaml", "root-bad.txt"},
expectErr: fmt.Errorf("changes detected"),
},
{
name: "Check-Old-Good",
args: []string{"check", "--conf", "./testdata/root-conf-old.yaml", "root-good.txt"},
},
{
name: "Check-Old-Bad",
args: []string{"check", "--conf", "./testdata/root-conf-old.yaml", "root-bad.txt"},
expectErr: fmt.Errorf("changes detected"),
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
out, err := cobraTest(t, nil, tc.args...)
if tc.expectErr != nil {
if err == nil {
t.Errorf("did not receive expected error: %v", tc.expectErr)
} else if !errors.Is(err, tc.expectErr) && err.Error() != tc.expectErr.Error() {
t.Errorf("unexpected error, received %v, expected %v", err, tc.expectErr)
}
return
}
if err != nil {
t.Fatalf("returned unexpected error: %v", err)
}
if (!tc.outContains && out != tc.expectOut) || (tc.outContains && !strings.Contains(out, tc.expectOut)) {
t.Errorf("unexpected output, expected %s, received %s", tc.expectOut, out)
}
})
}
}