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(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 testIntArrayOptOk(t *testing.T, n int, args []string) { var box []int var cli CliParser t.Logf("Arg set n. %d", n) addBoxOption(&cli, &box) cli.Init(args, "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)) } } func testIntArrayOptKo(t *testing.T, n int, args []string, msg string) { var box []int var cli CliParser t.Logf("Arg set n. %d", n) addBoxOption(&cli, &box) cli.Init(args, "1.0.0", "TestIntArrayOpt description") if err := cli.Parse(); err == nil { t.Errorf("Expected error, got nil") } else if err.Error() != msg { t.Errorf(`Invalid error: %q; expected: %q`, err.Error(), msg) } } func TestIntArrayOpt(t *testing.T) { var args []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) } } }() n := 0 n++ args = []string{ "TestIntArrayOpt", "--box=100,200,150,450", } testIntArrayOptOk(t, n, args) n++ args = []string{ "TestIntArrayOpt", "--box=100,200,150", } testIntArrayOptKo(t, n, args, "--box option requires exactly 4 items, 3 provided") n++ args = []string{ "TestIntArrayOpt", "--box", "100,200,150,450", } testIntArrayOptOk(t, n, args) n++ args = []string{ "TestIntArrayOpt", "--box", } testIntArrayOptKo(t, n, args, `option "box" requires a value`) n++ args = []string{ "TestIntArrayOpt", "--box", "100,200,150", "--box", "450", } testIntArrayOptOk(t, n, args) n++ args = []string{ "TestIntArrayOpt", "--box", "100,200,150", "--box", "450,12", } testIntArrayOptKo(t, n, args, "--box option requires exactly 4 items, 5 provided") }