test: root cmd

pull/14/head
sundowndev 2023-01-03 14:57:22 +04:00
parent ad93c6b047
commit 934f9d1aa6
2 changed files with 80 additions and 0 deletions

57
cmd/root_test.go Normal file
View File

@ -0,0 +1,57 @@
package cmd
import (
"github.com/spf13/cobra"
"github.com/sundowndev/covermyass/v2/test"
"testing"
)
func TestRootCmd_ValidFlags(t *testing.T) {
rootCmd := NewRootCmd()
rootCmd.RunE = func(_ *cobra.Command, args []string) error { return nil }
cases := []struct {
args []string
}{
{args: []string{}},
{args: []string{"-n", "5"}},
{args: []string{"--write"}},
{args: []string{"-z"}},
{args: []string{"-l", "--no-read-only"}},
{args: []string{"-f", "/var/log/1/*.log", "--filter", "/var/log/2/*.log"}},
}
for _, tt := range cases {
output, err := test.Execute(rootCmd, tt.args...)
if output != "" {
t.Errorf("Unexpected output: %v", output)
}
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
}
func TestRootCmd_InvalidFlags(t *testing.T) {
rootCmd := NewRootCmd()
rootCmd.RunE = func(_ *cobra.Command, args []string) error { return nil }
cases := []struct {
args []string
expected string
}{
{args: []string{"-t"}, expected: "unknown shorthand flag: 't' in -t"},
{args: []string{"-n"}, expected: "flag needs an argument: 'n' in -n"},
{args: []string{"-f"}, expected: "flag needs an argument: 'f' in -f"},
}
for _, tt := range cases {
_, err := test.Execute(rootCmd, tt.args...)
if err == nil {
t.Errorf("Invalid arg should generate error")
}
if err.Error() != tt.expected {
t.Errorf("Expected '%v', got '%v'", tt.expected, err)
}
}
}

23
test/command.go Normal file
View File

@ -0,0 +1,23 @@
package test
import (
"bytes"
"github.com/spf13/cobra"
)
func Execute(cmd *cobra.Command, args ...string) (output string, err error) {
_, output, err = ExecuteC(cmd, args...)
return output, err
}
func ExecuteC(cmd *cobra.Command, args ...string) (c *cobra.Command, output string, err error) {
buf := new(bytes.Buffer)
cmd.SetOut(buf)
cmd.SetErr(buf)
cmd.SetArgs(args)
c, err = cmd.ExecuteC()
return c, buf.String(), err
}