From 934f9d1aa686bf495dd7eb7797c85777eb3ec9c8 Mon Sep 17 00:00:00 2001 From: sundowndev Date: Tue, 3 Jan 2023 14:57:22 +0400 Subject: [PATCH] test: root cmd --- cmd/root_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++++ test/command.go | 23 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 cmd/root_test.go create mode 100644 test/command.go diff --git a/cmd/root_test.go b/cmd/root_test.go new file mode 100644 index 0000000..94510d8 --- /dev/null +++ b/cmd/root_test.go @@ -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) + } + } +} diff --git a/test/command.go b/test/command.go new file mode 100644 index 0000000..e5b7a4e --- /dev/null +++ b/test/command.go @@ -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 +}