package cli import ( "fmt" "testing" ) func TestOneOptWithEqual(t *testing.T) { var cli CliParser var color string // Always recover from panic to return error before adding options defer func() { if r := recover(); r != nil { if err := r.(error); err != nil { t.Error(err) } } }() // Define options cli.AddStringOpt("color", "c", &color, "white", "Set color") args := []string{ "TestOneOptWithEqual", "--color=blue", } cli.Init(args, "1.0.0", "TestOneOptWithEqual description") if err := cli.Parse(); err != nil { t.Error(err) } else if color != "blue" { t.Errorf("Expected color blue, got %q", color) } } func addBoxOption(cli *CliParser, boxPtr *[]int) { // Define options optRef := cli.AddIntArrayOpt("box", "b", boxPtr, []int{1, 2, 3, 4}, "Box spec: Left,Width,Top,Height; provide 4 int values") optRef.OnFinalCheck(func(cliValue string, currentValue any) (err error) { if array, ok := currentValue.([]int); ok { if len(array) != 4 { err = fmt.Errorf("--box option requires exactly 4 items, %d provided", len(array)) } } else { err = fmt.Errorf("wrong datatype for --box option value") } return }) } func TestIntArrayOpt(t *testing.T) { var box []int // Always recover from panic to return error before adding options defer func() { if r := recover(); r != nil { if err := r.(error); err != nil { t.Error(err) } } }() args_1 := []string{ "TestIntArrayOpt", "--box=100,200,150,450", } if true { var cli CliParser t.Logf("Arg set n. 1") addBoxOption(&cli, &box) cli.Init(args_1, "1.0.0", "TestIntArrayOpt description") if err := cli.Parse(); err != nil { t.Error(err) } else if len(box) != 4 { t.Errorf(`Expected 4 items, got %d`, len(box)) } } args_2 := []string{ "TestIntArrayOpt", "--box=100,200,150", } if true { var cli CliParser t.Logf("Arg set n. 2") addBoxOption(&cli, &box) cli.Init(args_2, "1.0.0", "TestIntArrayOpt description") if err := cli.Parse(); err == nil { t.Errorf("Expected error, got nil") } else if err.Error() != "--box option requires exactly 4 items, 3 provided" { t.Errorf(`Invalid error: %q; expected: "--box option requires exactly 4 items, 3 provided"`, err.Error()) } } args_3 := []string{ "TestIntArrayOpt", "--box", "100,200,150,450", } if true { var cli CliParser t.Logf("Arg set n. 3") addBoxOption(&cli, &box) cli.Init(args_3, "1.0.0", "TestIntArrayOpt description") if err := cli.Parse(); err != nil { t.Error(err) } else if len(box) != 4 { t.Errorf(`Expected 4 items, got %d`, len(box)) } } args_4 := []string{ "TestIntArrayOpt", "--box", } if true { var cli CliParser t.Logf("Arg set n. 4") addBoxOption(&cli, &box) cli.Init(args_4, "1.0.0", "TestIntArrayOpt description") if err := cli.Parse(); err == nil { t.Errorf("Expected error, got nil") } else if err.Error() != `option "box" requires a value` { t.Errorf(`Invalid error - Expected: 'option "box" requires a value'; got '%s'`, err.Error()) } } }