1package testing 2 3import ( 4 "io/ioutil" 5 "log" 6 "os" 7 8 "github.com/sensu/sensu-go/cli" 9 "github.com/sensu/sensu-go/cli/client" 10 "github.com/sensu/sensu-go/cli/client/config/basic" 11 clientmock "github.com/sensu/sensu-go/cli/client/testing" 12 "github.com/spf13/cobra" 13) 14 15// NewCLI returns a SensuCLI instace with mocked values with json format 16func NewCLI() *cli.SensuCli { 17 cli := NewMockCLI() 18 config := cli.Config.(*clientmock.MockConfig) 19 config.On("Format").Return("json") 20 21 return cli 22} 23 24// NewMockCLI return SensuCLI instance w/ mocked values 25func NewMockCLI() *cli.SensuCli { 26 config := &clientmock.MockConfig{} 27 client := &clientmock.MockClient{} 28 29 // Set defaults ... 30 config.On("Namespace").Return("default") 31 32 return &cli.SensuCli{ 33 Client: client, 34 Config: config, 35 InFile: os.Stdin, 36 } 37} 38 39// SimpleSensuCLI return SensuCLI instance w/ given client & live config 40func SimpleSensuCLI(apiClient client.APIClient) *cli.SensuCli { 41 c := basic.Load(nil) 42 43 return &cli.SensuCli{ 44 Client: apiClient, 45 Config: c, 46 } 47} 48 49// RunCmd runs your SensuCLI command and returns any output and errors the 50// command might have returned. Works with commands that have implemented Run 51// or RunE hooks. 52func RunCmd(cmd *cobra.Command, args []string) (string, error) { 53 var err error 54 55 // So that we can capture output we reassign cmd.output 56 tmpFile, err := ioutil.TempFile(os.TempDir(), "sensu-cli-") 57 if err != nil { 58 log.Panic("Error creating tmpFile: ", tmpFile.Name()) 59 } 60 61 defer func() { 62 _ = os.Remove(tmpFile.Name()) 63 }() 64 65 cmd.SetOutput(tmpFile) 66 67 // Run given command 68 if cmd.Run != nil { 69 cmd.Run(cmd, args) 70 } else if cmd.RunE != nil { 71 err = cmd.RunE(cmd, args) 72 } 73 74 // Close the file so that we can read from it 75 _ = tmpFile.Close() 76 77 // Store the contents of the reader as a string 78 bytes, _ := ioutil.ReadFile(tmpFile.Name()) 79 80 return string(bytes), err 81} 82