Skip to content

Commit

Permalink
Testing for Shorthand Lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
eparis authored and n10v committed May 5, 2017
1 parent 75859d1 commit 80fe0fb
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 7 deletions.
18 changes: 12 additions & 6 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,26 @@ func Example() {
}

func ExampleShorthandLookup() {
pflag.BoolP("verbose", "v", false, "verbose output")

name := "verbose"
flag := pflag.ShorthandLookup(name[:1])
short := name[:1]

pflag.BoolP(name, short, false, "verbose output")

// len(short) must be == 1
flag := pflag.ShorthandLookup(short)

fmt.Println(flag.Name)
}

func ExampleFlagSet_ShorthandLookup() {
name := "verbose"
short := name[:1]

fs := pflag.NewFlagSet("Example", pflag.ContinueOnError)
fs.BoolP("verbose", "v", false, "verbose output")
fs.BoolP(name, short, false, "verbose output")

name := "verbose"
flag := fs.ShorthandLookup(name[:1])
// len(short) must be == 1
flag := fs.ShorthandLookup(short)

fmt.Println(flag.Name)
}
4 changes: 3 additions & 1 deletion flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,9 @@ func (f *FlagSet) ShorthandLookup(name string) *Flag {
return nil
}
if len(name) > 1 {
panic("can't look up for a shorthand with name more than one character")
msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
fmt.Fprintf(f.out(), msg)
panic(msg)
}
c := name[0]
return f.shorthands[c]
Expand Down
36 changes: 36 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,42 @@ func TestShorthand(t *testing.T) {
}
}

func TestShorthandLookup(t *testing.T) {
f := NewFlagSet("shorthand", ContinueOnError)
if f.Parsed() {
t.Error("f.Parse() = true before Parse")
}
f.BoolP("boola", "a", false, "bool value")
f.BoolP("boolb", "b", false, "bool2 value")
args := []string{
"-ab",
}
f.SetOutput(ioutil.Discard)
if err := f.Parse(args); err != nil {
t.Error("expected no error, got ", err)
}
if !f.Parsed() {
t.Error("f.Parse() = false after Parse")
}
flag := f.ShorthandLookup("a")
if flag == nil {
t.Errorf("f.ShorthandLookup(\"a\") returned nil")
}
if flag.Name != "boola" {
t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name)
}
flag = f.ShorthandLookup("")
if flag != nil {
t.Errorf("f.ShorthandLookup(\"\") did not return nil")
}
defer func() {
recover()
}()
flag = f.ShorthandLookup("ab")
// should NEVER get here. lookup should panic. defer'd func should recover it.
t.Errorf("f.ShorthandLookup(\"ab\") did not panic")
}

func TestParse(t *testing.T) {
ResetForTesting(func() { t.Error("bad parse") })
testParse(GetCommandLine(), t)
Expand Down

0 comments on commit 80fe0fb

Please sign in to comment.