package opt_test import ( "fmt" "testing" "git.sr.ht/~rjarry/go-opt/v2" "github.com/stretchr/testify/assert" ) type OptionStruct struct { Jobs int `opt:"-j,--jobs" required:"true"` Delay float64 `opt:"--delay" default:"0.5"` Zero bool `opt:"-z" aliases:"baz"` Backoff bool `opt:"-B,--backoff"` Name string `opt:"name" aliases:"bar" action:"ParseName"` } func (o *OptionStruct) ParseName(arg string) error { if arg == "invalid" { return fmt.Errorf("%q invalid value", arg) } o.Name = arg return nil } func TestArgsToStructErrors(t *testing.T) { vectors := []struct { cmdline string err string }{ {"foo", "-j is required"}, {"foo -j", "-j takes a value"}, {"foo --delay -B", "--delay takes a value"}, {"bar -j4", " is required"}, {"foo -j f", `strconv.ParseInt: parsing "f": invalid syntax.`}, {"foo --delay=m", `strconv.ParseFloat: parsing "m": invalid syntax.`}, {"foo --jobs 8 baz", `"baz" unexpected argument`}, {"foo -u8 hop", `"-u8" unexpected argument`}, {"foo -z", `"-z" unexpected argument`}, {"bar -j4 foo baz", `"baz" unexpected argument`}, {"bar -j4 invalid", `invalid value`}, } for _, v := range vectors { t.Run(v.cmdline, func(t *testing.T) { err := opt.CmdlineToStruct(v.cmdline, new(OptionStruct)) assert.ErrorContains(t, err, v.err) }) } spec := opt.NewCmdSpec("bar", new(OptionStruct)) assert.Equal(t, spec.Usage(), "bar -j [--delay ] [-B] ") } func TestArgsToStruct(t *testing.T) { vectors := []struct { cmdline string expected OptionStruct }{ { cmdline: `bar -j4 'f o o \(°