OSDN Git Service

libgo: Update to weekly.2012-01-15.
[pf3gnuchains/gcc-fork.git] / libgo / go / flag / flag_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package flag_test
6
7 import (
8         . "flag"
9         "fmt"
10         "os"
11         "sort"
12         "testing"
13         "time"
14 )
15
16 var (
17         test_bool     = Bool("test_bool", false, "bool value")
18         test_int      = Int("test_int", 0, "int value")
19         test_int64    = Int64("test_int64", 0, "int64 value")
20         test_uint     = Uint("test_uint", 0, "uint value")
21         test_uint64   = Uint64("test_uint64", 0, "uint64 value")
22         test_string   = String("test_string", "0", "string value")
23         test_float64  = Float64("test_float64", 0, "float64 value")
24         test_duration = Duration("test_duration", 0, "time.Duration value")
25 )
26
27 func boolString(s string) string {
28         if s == "0" {
29                 return "false"
30         }
31         return "true"
32 }
33
34 func TestEverything(t *testing.T) {
35         m := make(map[string]*Flag)
36         desired := "0"
37         visitor := func(f *Flag) {
38                 if len(f.Name) > 5 && f.Name[0:5] == "test_" {
39                         m[f.Name] = f
40                         ok := false
41                         switch {
42                         case f.Value.String() == desired:
43                                 ok = true
44                         case f.Name == "test_bool" && f.Value.String() == boolString(desired):
45                                 ok = true
46                         case f.Name == "test_duration" && f.Value.String() == desired+"s":
47                                 ok = true
48                         }
49                         if !ok {
50                                 t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
51                         }
52                 }
53         }
54         VisitAll(visitor)
55         if len(m) != 8 {
56                 t.Error("VisitAll misses some flags")
57                 for k, v := range m {
58                         t.Log(k, *v)
59                 }
60         }
61         m = make(map[string]*Flag)
62         Visit(visitor)
63         if len(m) != 0 {
64                 t.Errorf("Visit sees unset flags")
65                 for k, v := range m {
66                         t.Log(k, *v)
67                 }
68         }
69         // Now set all flags
70         Set("test_bool", "true")
71         Set("test_int", "1")
72         Set("test_int64", "1")
73         Set("test_uint", "1")
74         Set("test_uint64", "1")
75         Set("test_string", "1")
76         Set("test_float64", "1")
77         Set("test_duration", "1s")
78         desired = "1"
79         Visit(visitor)
80         if len(m) != 8 {
81                 t.Error("Visit fails after set")
82                 for k, v := range m {
83                         t.Log(k, *v)
84                 }
85         }
86         // Now test they're visited in sort order.
87         var flagNames []string
88         Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
89         if !sort.StringsAreSorted(flagNames) {
90                 t.Errorf("flag names not sorted: %v", flagNames)
91         }
92 }
93
94 func TestUsage(t *testing.T) {
95         called := false
96         ResetForTesting(func() { called = true })
97         if CommandLine().Parse([]string{"-x"}) == nil {
98                 t.Error("parse did not fail for unknown flag")
99         }
100         if !called {
101                 t.Error("did not call Usage for unknown flag")
102         }
103 }
104
105 func testParse(f *FlagSet, t *testing.T) {
106         if f.Parsed() {
107                 t.Error("f.Parse() = true before Parse")
108         }
109         boolFlag := f.Bool("bool", false, "bool value")
110         bool2Flag := f.Bool("bool2", false, "bool2 value")
111         intFlag := f.Int("int", 0, "int value")
112         int64Flag := f.Int64("int64", 0, "int64 value")
113         uintFlag := f.Uint("uint", 0, "uint value")
114         uint64Flag := f.Uint64("uint64", 0, "uint64 value")
115         stringFlag := f.String("string", "0", "string value")
116         float64Flag := f.Float64("float64", 0, "float64 value")
117         durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
118         extra := "one-extra-argument"
119         args := []string{
120                 "-bool",
121                 "-bool2=true",
122                 "--int", "22",
123                 "--int64", "0x23",
124                 "-uint", "24",
125                 "--uint64", "25",
126                 "-string", "hello",
127                 "-float64", "2718e28",
128                 "-duration", "2m",
129                 extra,
130         }
131         if err := f.Parse(args); err != nil {
132                 t.Fatal(err)
133         }
134         if !f.Parsed() {
135                 t.Error("f.Parse() = false after Parse")
136         }
137         if *boolFlag != true {
138                 t.Error("bool flag should be true, is ", *boolFlag)
139         }
140         if *bool2Flag != true {
141                 t.Error("bool2 flag should be true, is ", *bool2Flag)
142         }
143         if *intFlag != 22 {
144                 t.Error("int flag should be 22, is ", *intFlag)
145         }
146         if *int64Flag != 0x23 {
147                 t.Error("int64 flag should be 0x23, is ", *int64Flag)
148         }
149         if *uintFlag != 24 {
150                 t.Error("uint flag should be 24, is ", *uintFlag)
151         }
152         if *uint64Flag != 25 {
153                 t.Error("uint64 flag should be 25, is ", *uint64Flag)
154         }
155         if *stringFlag != "hello" {
156                 t.Error("string flag should be `hello`, is ", *stringFlag)
157         }
158         if *float64Flag != 2718e28 {
159                 t.Error("float64 flag should be 2718e28, is ", *float64Flag)
160         }
161         if *durationFlag != 2*time.Minute {
162                 t.Error("duration flag should be 2m, is ", *durationFlag)
163         }
164         if len(f.Args()) != 1 {
165                 t.Error("expected one argument, got", len(f.Args()))
166         } else if f.Args()[0] != extra {
167                 t.Errorf("expected argument %q got %q", extra, f.Args()[0])
168         }
169 }
170
171 func TestParse(t *testing.T) {
172         ResetForTesting(func() { t.Error("bad parse") })
173         testParse(CommandLine(), t)
174 }
175
176 func TestFlagSetParse(t *testing.T) {
177         testParse(NewFlagSet("test", ContinueOnError), t)
178 }
179
180 // Declare a user-defined flag type.
181 type flagVar []string
182
183 func (f *flagVar) String() string {
184         return fmt.Sprint([]string(*f))
185 }
186
187 func (f *flagVar) Set(value string) error {
188         *f = append(*f, value)
189         return nil
190 }
191
192 func TestUserDefined(t *testing.T) {
193         var flags FlagSet
194         flags.Init("test", ContinueOnError)
195         var v flagVar
196         flags.Var(&v, "v", "usage")
197         if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
198                 t.Error(err)
199         }
200         if len(v) != 3 {
201                 t.Fatal("expected 3 args; got ", len(v))
202         }
203         expect := "[1 2 3]"
204         if v.String() != expect {
205                 t.Errorf("expected value %q got %q", expect, v.String())
206         }
207 }
208
209 // This tests that one can reset the flags. This still works but not well, and is
210 // superseded by FlagSet.
211 func TestChangingArgs(t *testing.T) {
212         ResetForTesting(func() { t.Fatal("bad parse") })
213         oldArgs := os.Args
214         defer func() { os.Args = oldArgs }()
215         os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
216         before := Bool("before", false, "")
217         if err := CommandLine().Parse(os.Args[1:]); err != nil {
218                 t.Fatal(err)
219         }
220         cmd := Arg(0)
221         os.Args = Args()
222         after := Bool("after", false, "")
223         Parse()
224         args := Args()
225
226         if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
227                 t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
228         }
229 }
230
231 // Test that -help invokes the usage message and returns ErrHelp.
232 func TestHelp(t *testing.T) {
233         var helpCalled = false
234         fs := NewFlagSet("help test", ContinueOnError)
235         fs.Usage = func() { helpCalled = true }
236         var flag bool
237         fs.BoolVar(&flag, "flag", false, "regular flag")
238         // Regular flag invocation should work
239         err := fs.Parse([]string{"-flag=true"})
240         if err != nil {
241                 t.Fatal("expected no error; got ", err)
242         }
243         if !flag {
244                 t.Error("flag was not set by -flag")
245         }
246         if helpCalled {
247                 t.Error("help called for regular flag")
248                 helpCalled = false // reset for next test
249         }
250         // Help flag should work as expected.
251         err = fs.Parse([]string{"-help"})
252         if err == nil {
253                 t.Fatal("error expected")
254         }
255         if err != ErrHelp {
256                 t.Fatal("expected ErrHelp; got ", err)
257         }
258         if !helpCalled {
259                 t.Fatal("help was not called")
260         }
261         // If we define a help flag, that should override.
262         var help bool
263         fs.BoolVar(&help, "help", false, "help flag")
264         helpCalled = false
265         err = fs.Parse([]string{"-help"})
266         if err != nil {
267                 t.Fatal("expected no error for defined -help; got ", err)
268         }
269         if helpCalled {
270                 t.Fatal("help was called; should not have been for defined help flag")
271         }
272 }