Files
ahp 1c9a69d362 cli: test option parsing
Table tests cover:
- bundles, including one that ends in a value option;
- attached and empty values, values that look like options;
- permutation, "--" and a lone "-";
- every usage error message.
2026-11-05 14:28:08 +03:30

77 lines
2.8 KiB
Go

package cli
import (
"errors"
"reflect"
"testing"
)
var testOptions = []Option{
{Name: "dest", Short: 'd', Long: "dest", Value: true},
{Name: "force", Short: 'f', Long: "force"},
{Name: "quiet", Short: 'q', Long: "quiet"},
{Name: "version", Long: "version"},
}
func TestParse(t *testing.T) {
tests := []struct {
name string
args []string
parsed []Arg
operands []string
}{
{"empty", nil, nil, nil},
{"operands only", []string{"a", "b"}, nil, []string{"a", "b"}},
{"separate value", []string{"-d", "out", "a"}, []Arg{{"dest", "out"}}, []string{"a"}},
{"attached value", []string{"-dout", "a"}, []Arg{{"dest", "out"}}, []string{"a"}},
{"long separate", []string{"--dest", "out"}, []Arg{{"dest", "out"}}, nil},
{"long attached", []string{"--dest=a=b"}, []Arg{{"dest", "a=b"}}, nil},
{"long empty value", []string{"--dest="}, []Arg{{"dest", ""}}, nil},
{"bundle", []string{"-qf"}, []Arg{{"quiet", ""}, {"force", ""}}, nil},
{"bundle ending in value", []string{"-qdout"}, []Arg{{"quiet", ""}, {"dest", "out"}}, nil},
{"bundle value next", []string{"-qd", "out"}, []Arg{{"quiet", ""}, {"dest", "out"}}, nil},
{"value that looks like option", []string{"-d", "-q"}, []Arg{{"dest", "-q"}}, nil},
{"permutation", []string{"a", "-q", "b"}, []Arg{{"quiet", ""}}, []string{"a", "b"}},
{"double dash", []string{"-q", "--", "-f", "--x"}, []Arg{{"quiet", ""}}, []string{"-f", "--x"}},
{"lone dash", []string{"-"}, nil, []string{"-"}},
{"order kept", []string{"-q", "--force", "-q"}, []Arg{{"quiet", ""}, {"force", ""}, {"quiet", ""}}, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
parsed, operands, err := Parse(testOptions, tt.args)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(parsed, tt.parsed) {
t.Errorf("parsed = %v, want %v", parsed, tt.parsed)
}
if !reflect.DeepEqual(operands, tt.operands) {
t.Errorf("operands = %q, want %q", operands, tt.operands)
}
})
}
}
func TestParseErrors(t *testing.T) {
tests := []struct {
args []string
msg string
}{
{[]string{"-z"}, "invalid option '-z'"},
{[]string{"-qz"}, "invalid option '-z'"},
{[]string{"--bogus"}, "unrecognized option '--bogus'"},
{[]string{"--bogus=1"}, "unrecognized option '--bogus'"},
{[]string{"-d"}, "option '-d' requires an argument"},
{[]string{"a", "--dest"}, "option '--dest' requires an argument"},
{[]string{"--force=yes"}, "option '--force' doesn't allow an argument"},
{[]string{"--for"}, "unrecognized option '--for'"}, // no abbreviations
}
for _, tt := range tests {
_, _, err := Parse(testOptions, tt.args)
var e *Error
if !errors.As(err, &e) || e.Code != ExitUsage || e.Msg != tt.msg {
t.Errorf("Parse(%q) error = %v, want usage error %q", tt.args, err, tt.msg)
}
}
}