flag: refactor tests

This commit is contained in:
KimMachineGun 2020-11-22 15:41:11 +09:00
parent c045f1211a
commit fdc76e071e
1 changed files with 63 additions and 48 deletions

View File

@ -656,65 +656,80 @@ func TestExitCode(t *testing.T) {
} }
} }
func TestInvalidFlagDefinitions(t *testing.T) { func mustPanic(t *testing.T, expected string, f func()) {
mustPanic := func(t *testing.T, expected string) { defer func() {
switch msg := recover().(type) { switch msg := recover().(type) {
case nil: case nil:
t.Fatal("did not panic") t.Error("did not panic")
case string: case string:
if msg != expected { if msg != expected {
t.Fatalf("expected %q, bug got %q", expected, msg) t.Errorf("expected %q, bug got %q", expected, msg)
} }
default: default:
t.Fatalf("unexpected panic value: %T(%v)", msg, msg) t.Errorf("unexpected panic value: %T(%v)", msg, msg)
} }
}()
f()
}
func TestInvalidFlags(t *testing.T) {
tests := []struct {
flag string
errorMsg string
}{
{
flag: "-foo",
errorMsg: "flag \"-foo\" begins with -",
},
{
flag: "foo=bar",
errorMsg: "flag \"foo=bar\" contains =",
},
} }
t.Run("flag name begins with \"-\"", func(t *testing.T) { for _, test := range tests {
fs := NewFlagSet("", ContinueOnError) fs := NewFlagSet("", ContinueOnError)
var buf bytes.Buffer var buf bytes.Buffer
fs.SetOutput(&buf) fs.SetOutput(&buf)
defer mustPanic(t, "flag name begins with \"-\": -foo") mustPanic(t, test.errorMsg, func() {
var v flagVar
var v flagVar fs.Var(&v, test.flag, "")
fs.Var(&v, "-foo", "") })
}) if msg := test.errorMsg + "\n"; msg != buf.String() {
t.Errorf("expected %q, bug got %q", msg, buf.String())
t.Run("flag name contains \"=\"", func(t *testing.T) { }
fs := NewFlagSet("", ContinueOnError) }
var buf bytes.Buffer }
fs.SetOutput(&buf)
func TestRedefinedFlags(t *testing.T) {
defer mustPanic(t, "flag name contains \"=\": foo=bar") tests := []struct {
flagSetName string
var v flagVar errorMsg string
fs.Var(&v, "foo=bar", "") }{
}) {
flagSetName: "",
t.Run("flag redefined", func(t *testing.T) { errorMsg: "flag redefined: foo",
fs := NewFlagSet("", ContinueOnError) },
var buf bytes.Buffer {
fs.SetOutput(&buf) flagSetName: "fs",
errorMsg: "fs flag redefined: foo",
var v flagVar },
fs.Var(&v, "foo", "") }
defer mustPanic(t, "flag redefined: foo") for _, test := range tests {
fs := NewFlagSet(test.flagSetName, ContinueOnError)
fs.Var(&v, "foo", "") var buf bytes.Buffer
}) fs.SetOutput(&buf)
t.Run("flag redefined with named flag set", func(t *testing.T) { var v flagVar
fs := NewFlagSet("fs", ContinueOnError) fs.Var(&v, "foo", "")
var buf bytes.Buffer
fs.SetOutput(&buf) mustPanic(t, test.errorMsg, func() {
fs.Var(&v, "foo", "")
var v flagVar })
fs.Var(&v, "foo", "") if msg := test.errorMsg + "\n"; msg != buf.String() {
t.Errorf("expected %q, bug got %q", msg, buf.String())
defer mustPanic(t, "fs flag redefined: foo") }
}
fs.Var(&v, "foo", "")
})
} }