1// Copyright 2018 Frank Schroeder. 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
5package properties
6
7import (
8	"flag"
9	"fmt"
10	"testing"
11)
12
13// TestFlag verifies Properties.MustFlag without flag.FlagSet.Parse
14func 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// TestFlagOverride verifies Properties.MustFlag with flag.FlagSet.Parse.
33func 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
59func ExampleProperties_MustFlag() {
60	x := flag.Int("x", 0, "demo customize")
61	y := flag.Int("y", 0, "demo override")
62
63	// Demo alternative for flag.Parse():
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") // note discard
70	p.MustFlag(flag.CommandLine)
71	fmt.Printf("configured to x=%d, y=%d\n", *x, *y)
72
73	// Output:
74	// flagged as x=0, y=10
75	// configured to x=7, y=10
76}
77