1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
// Copyright 2017 Frank Schroeder. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package properties
import (
"flag"
"fmt"
"testing"
)
// TestFlag verifies Properties.MustFlag without flag.FlagSet.Parse
func TestFlag(t *testing.T) {
f := flag.NewFlagSet("src", flag.PanicOnError)
gotS := f.String("s", "?", "string flag")
gotI := f.Int("i", -1, "int flag")
p := NewProperties()
p.MustSet("s", "t")
p.MustSet("i", "9")
p.MustFlag(f)
if want := "t"; *gotS != want {
t.Errorf("Got string s=%q, want %q", *gotS, want)
}
if want := 9; *gotI != want {
t.Errorf("Got int i=%d, want %d", *gotI, want)
}
}
// TestFlagOverride verifies Properties.MustFlag with flag.FlagSet.Parse.
func TestFlagOverride(t *testing.T) {
f := flag.NewFlagSet("src", flag.PanicOnError)
gotA := f.Int("a", 1, "remain default")
gotB := f.Int("b", 2, "customized")
gotC := f.Int("c", 3, "overridden")
if err := f.Parse([]string{"-c", "4"}); err != nil {
t.Fatal(err)
}
p := NewProperties()
p.MustSet("b", "5")
p.MustSet("c", "6")
p.MustFlag(f)
if want := 1; *gotA != want {
t.Errorf("Got remain default a=%d, want %d", *gotA, want)
}
if want := 5; *gotB != want {
t.Errorf("Got customized b=%d, want %d", *gotB, want)
}
if want := 4; *gotC != want {
t.Errorf("Got overriden c=%d, want %d", *gotC, want)
}
}
func ExampleProperties_MustFlag() {
x := flag.Int("x", 0, "demo customize")
y := flag.Int("y", 0, "demo override")
// Demo alternative for flag.Parse():
flag.CommandLine.Parse([]string{"-y", "10"})
fmt.Printf("flagged as x=%d, y=%d\n", *x, *y)
p := NewProperties()
p.MustSet("x", "7")
p.MustSet("y", "42") // note discard
p.MustFlag(flag.CommandLine)
fmt.Printf("configured to x=%d, y=%d\n", *x, *y)
// Output:
// flagged as x=0, y=10
// configured to x=7, y=10
}
|