1package flags
2
3import (
4	"testing"
5	"time"
6)
7
8func expectConvert(t *testing.T, o *Option, expected string) {
9	s, err := convertToString(o.value, o.tag)
10
11	if err != nil {
12		t.Errorf("Unexpected error: %v", err)
13		return
14	}
15
16	assertString(t, s, expected)
17}
18
19func TestConvertToString(t *testing.T) {
20	d, _ := time.ParseDuration("1h2m4s")
21
22	var opts = struct {
23		String string `long:"string"`
24
25		Int   int   `long:"int"`
26		Int8  int8  `long:"int8"`
27		Int16 int16 `long:"int16"`
28		Int32 int32 `long:"int32"`
29		Int64 int64 `long:"int64"`
30
31		Uint   uint   `long:"uint"`
32		Uint8  uint8  `long:"uint8"`
33		Uint16 uint16 `long:"uint16"`
34		Uint32 uint32 `long:"uint32"`
35		Uint64 uint64 `long:"uint64"`
36
37		Float32 float32 `long:"float32"`
38		Float64 float64 `long:"float64"`
39
40		Duration time.Duration `long:"duration"`
41
42		Bool bool `long:"bool"`
43
44		IntSlice    []int           `long:"int-slice"`
45		IntFloatMap map[int]float64 `long:"int-float-map"`
46
47		PtrBool   *bool       `long:"ptr-bool"`
48		Interface interface{} `long:"interface"`
49
50		Int32Base  int32  `long:"int32-base" base:"16"`
51		Uint32Base uint32 `long:"uint32-base" base:"16"`
52	}{
53		"string",
54
55		-2,
56		-1,
57		0,
58		1,
59		2,
60
61		1,
62		2,
63		3,
64		4,
65		5,
66
67		1.2,
68		-3.4,
69
70		d,
71		true,
72
73		[]int{-3, 4, -2},
74		map[int]float64{-2: 4.5},
75
76		new(bool),
77		float32(5.2),
78
79		-5823,
80		4232,
81	}
82
83	p := NewNamedParser("test", Default)
84	grp, _ := p.AddGroup("test group", "", &opts)
85
86	expects := []string{
87		"string",
88		"-2",
89		"-1",
90		"0",
91		"1",
92		"2",
93
94		"1",
95		"2",
96		"3",
97		"4",
98		"5",
99
100		"1.2",
101		"-3.4",
102
103		"1h2m4s",
104		"true",
105
106		"[-3, 4, -2]",
107		"{-2:4.5}",
108
109		"false",
110		"5.2",
111
112		"-16bf",
113		"1088",
114	}
115
116	for i, v := range grp.Options() {
117		expectConvert(t, v, expects[i])
118	}
119}
120
121func TestConvertToStringInvalidIntBase(t *testing.T) {
122	var opts = struct {
123		Int int `long:"int" base:"no"`
124	}{
125		2,
126	}
127
128	p := NewNamedParser("test", Default)
129	grp, _ := p.AddGroup("test group", "", &opts)
130	o := grp.Options()[0]
131
132	_, err := convertToString(o.value, o.tag)
133
134	if err != nil {
135		err = newErrorf(ErrMarshal, "%v", err)
136	}
137
138	assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax")
139}
140
141func TestConvertToStringInvalidUintBase(t *testing.T) {
142	var opts = struct {
143		Uint uint `long:"uint" base:"no"`
144	}{
145		2,
146	}
147
148	p := NewNamedParser("test", Default)
149	grp, _ := p.AddGroup("test group", "", &opts)
150	o := grp.Options()[0]
151
152	_, err := convertToString(o.value, o.tag)
153
154	if err != nil {
155		err = newErrorf(ErrMarshal, "%v", err)
156	}
157
158	assertError(t, err, ErrMarshal, "strconv.ParseInt: parsing \"no\": invalid syntax")
159}
160