1
2
3
4
5 package properties
6
7 import (
8 "flag"
9 "fmt"
10 "testing"
11 )
12
13
14 func TestFlag(t *testing.T) {
15 f := flag.NewFlagSet("src", flag.PanicOnError)
16 gotS := f.String("s", "?", "string flag")
17 gotI := f.Int("i", -1, "int flag")
18
19 p := NewProperties()
20 p.MustSet("s", "t")
21 p.MustSet("i", "9")
22 p.MustFlag(f)
23
24 if want := "t"; *gotS != want {
25 t.Errorf("Got string s=%q, want %q", *gotS, want)
26 }
27 if want := 9; *gotI != want {
28 t.Errorf("Got int i=%d, want %d", *gotI, want)
29 }
30 }
31
32
33 func TestFlagOverride(t *testing.T) {
34 f := flag.NewFlagSet("src", flag.PanicOnError)
35 gotA := f.Int("a", 1, "remain default")
36 gotB := f.Int("b", 2, "customized")
37 gotC := f.Int("c", 3, "overridden")
38
39 if err := f.Parse([]string{"-c", "4"}); err != nil {
40 t.Fatal(err)
41 }
42
43 p := NewProperties()
44 p.MustSet("b", "5")
45 p.MustSet("c", "6")
46 p.MustFlag(f)
47
48 if want := 1; *gotA != want {
49 t.Errorf("Got remain default a=%d, want %d", *gotA, want)
50 }
51 if want := 5; *gotB != want {
52 t.Errorf("Got customized b=%d, want %d", *gotB, want)
53 }
54 if want := 4; *gotC != want {
55 t.Errorf("Got overridden c=%d, want %d", *gotC, want)
56 }
57 }
58
59 func ExampleProperties_MustFlag() {
60 x := flag.Int("x", 0, "demo customize")
61 y := flag.Int("y", 0, "demo override")
62
63
64 flag.CommandLine.Parse([]string{"-y", "10"})
65 fmt.Printf("flagged as x=%d, y=%d\n", *x, *y)
66
67 p := NewProperties()
68 p.MustSet("x", "7")
69 p.MustSet("y", "42")
70 p.MustFlag(flag.CommandLine)
71 fmt.Printf("configured to x=%d, y=%d\n", *x, *y)
72
73
74
75
76 }
77
View as plain text