gocli_simple/main_test.go

67 lines
1.2 KiB
Go

package main
import (
"flag"
"os"
"testing"
)
// helper function to set os.Args for the test
func setArgs(args []string) {
os.Args = args
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) // reset flag state
}
func TestParseArgs(t *testing.T) {
tests := []struct {
name string
args []string
expect Args
}{
{
name: "Test Version Short Flag",
args: []string{"mycli", "-v"},
expect: Args{
Version: true,
Debug: false,
Help: false,
},
},
{
name: "Test Debug Long Flag",
args: []string{"mycli", "--debug"},
expect: Args{
Version: false,
Debug: true,
Help: false,
},
},
{
name: "Test Help Short Flag",
args: []string{"mycli", "-h"},
expect: Args{
Version: false,
Debug: false,
Help: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Set up os.Args for the test case
setArgs(tt.args)
// Call ParseArgs to parse the test case flags
got := ParseArgs()
// Compare the result with the expected result
if got.Version != tt.expect.Version ||
got.Debug != tt.expect.Debug ||
got.Help != tt.expect.Help {
t.Errorf("ParseArgs() = %v, want %v", got, tt.expect)
}
})
}
}