JMS #4: Flag testing

This commit is contained in:
Jeremy Saenz 2013-07-18 17:39:42 -07:00
parent 3f76896c4f
commit 3119b075d6
5 changed files with 100 additions and 69 deletions

View File

@ -5,18 +5,35 @@ import (
"testing"
)
func Test_SimpleCLIFlags(t *testing.T) {
func Test_SettingFlags(t *testing.T) {
Flags = []Flag{
StringFlag{"foo", "default", "a foo flag"},
StringFlag{"foo", "default", "a string flag"},
IntFlag{"bar", 42, "an int flag"},
BoolFlag{"bat", "a bool flag"},
}
Action = func(c *Context) {
expect(t, c.String("foo"), "hello world")
expect(t, c.Int("bar"), 245)
expect(t, c.Bool("bat"), true)
}
Run([]string{ "command", "--foo", "hello world" })
Run([]string{"command", "--foo", "hello world", "--bar", "245", "--bat"})
}
/* Helpers */
func Test_FlagDefaults(t *testing.T) {
Flags = []Flag{
StringFlag{"foo", "default", "a string flag"},
IntFlag{"bar", 42, "an int flag"},
BoolFlag{"bat", "a bool flag"},
}
Action = func(c *Context) {
expect(t, c.String("foo"), "default")
expect(t, c.Int("bar"), 42)
expect(t, c.Bool("bat"), false)
}
Run([]string{"command"})
}
/* Test Helpers */
func expect(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))

54
flag.go
View File

@ -8,25 +8,19 @@ type Flag interface {
Apply(*flag.FlagSet)
}
func flagSet(flags []Flag) *flag.FlagSet {
set := flag.NewFlagSet(Name, flag.ExitOnError)
for _, f := range flags {
f.Apply(set)
}
return set
}
type BoolFlag struct {
Name string
Usage string
}
type StringFlag struct {
Name string
Value string
Usage string
}
func (f StringFlag) String() string {
return fmt.Sprintf("--%v 'string'\t%v", f.Name, f.Usage)
}
func (f StringFlag) Apply(set *flag.FlagSet) {
set.String(f.Name, f.Value, f.Usage)
}
func (f BoolFlag) String() string {
return fmt.Sprintf("--%v\t%v", f.Name, f.Usage)
}
@ -35,10 +29,30 @@ func (f BoolFlag) Apply(set *flag.FlagSet) {
set.Bool(f.Name, false, f.Usage)
}
func flagSet(flags []Flag) *flag.FlagSet {
set := flag.NewFlagSet(Name, flag.ExitOnError)
for _, f := range flags {
f.Apply(set)
}
return set
type StringFlag struct {
Name string
Value string
Usage string
}
func (f StringFlag) String() string {
return fmt.Sprintf("--%v '%v'\t%v", f.Name, f.Value, f.Usage)
}
func (f StringFlag) Apply(set *flag.FlagSet) {
set.String(f.Name, f.Value, f.Usage)
}
type IntFlag struct {
Name string
Value int
Usage string
}
func (f IntFlag) String() string {
return fmt.Sprintf("--%v '%v'\t%v", f.Name, f.Value, f.Usage)
}
func (f IntFlag) Apply(set *flag.FlagSet) {
set.Int(f.Name, f.Value, f.Usage)
}