-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
utils.go
66 lines (56 loc) · 1.79 KB
/
utils.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
package ctltest
import (
"bytes"
"log"
"os"
"github.com/spf13/cobra"
"sigs.k8s.io/yaml"
api "github.com/weaveworks/eksctl/pkg/apis/eksctl.io/v1alpha5"
"github.com/weaveworks/eksctl/pkg/ctl/cmdutils"
)
type CommandFunction func(*cmdutils.Cmd, func(*cmdutils.Cmd) error)
// NewMockCmd returns a mock Cmd for a parent command (such as enable, get, utils) to be used for testing
// cli related features like flag and config file loading
func NewMockCmd(cmdFunc CommandFunction, parentCommand string, args ...string) *MockCmd {
mockCmd := &MockCmd{}
grouping := cmdutils.NewGrouping()
parentCmd := cmdutils.NewVerbCmd(parentCommand, "", "")
cmdutils.AddResourceCmd(grouping, parentCmd, func(cmd *cmdutils.Cmd) {
noOpRunFunc := func(cmd *cmdutils.Cmd) error {
mockCmd.Cmd = cmd
return nil // no-op, to only test input aggregation & validation.
}
cmdFunc(cmd, noOpRunFunc)
})
parentCmd.SetArgs(args)
mockCmd.parentCmd = parentCmd
return mockCmd
}
type MockCmd struct {
parentCmd *cobra.Command
Cmd *cmdutils.Cmd
}
func (c MockCmd) Execute() (string, error) {
buf := new(bytes.Buffer)
c.parentCmd.SetOut(buf)
err := c.parentCmd.Execute()
return buf.String(), err
}
// CreateConfigFile creates a temporary configuration file for testing by marshalling the given object in yaml. It
// returns the path to the file
func CreateConfigFile(cfg *api.ClusterConfig) string {
contents, err := yaml.Marshal(cfg)
if err != nil {
log.Fatalf("unable to marshal object: %s", err.Error())
}
file, err := os.CreateTemp("", "enable-test-config-file")
if err != nil {
log.Fatalf("unable to create temp config file: %s", err.Error())
}
defer file.Close()
_, err = file.Write(contents)
if err != nil {
log.Fatalf("unable to write to temp config file: %s", err.Error())
}
return file.Name()
}