Skip to content

Commit 9896dba

Browse files
authored
chore(flags): add unit test for string to string flag parsing (#983)
1 parent fa8dea5 commit 9896dba

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package flags
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
8+
"github.com/spf13/cobra"
9+
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
10+
"github.com/stackitcloud/stackit-cli/internal/pkg/utils"
11+
)
12+
13+
func TestFlagToStringToStringPointer(t *testing.T) {
14+
const flagName = "labels"
15+
16+
tests := []struct {
17+
name string
18+
flagValue *string
19+
want *map[string]string
20+
}{
21+
{
22+
name: "flag unset",
23+
flagValue: nil,
24+
want: nil,
25+
},
26+
{
27+
name: "flag set with single value",
28+
flagValue: utils.Ptr("foo=bar"),
29+
want: &map[string]string{
30+
"foo": "bar",
31+
},
32+
},
33+
{
34+
name: "flag set with multiple values",
35+
flagValue: utils.Ptr("foo=bar,label1=value1,label2=value2"),
36+
want: &map[string]string{
37+
"foo": "bar",
38+
"label1": "value1",
39+
"label2": "value2",
40+
},
41+
},
42+
}
43+
for _, tt := range tests {
44+
t.Run(tt.name, func(t *testing.T) {
45+
p := print.NewPrinter()
46+
// create a new, simple test command with a string-to-string flag
47+
cmd := func() *cobra.Command {
48+
cmd := &cobra.Command{
49+
Use: "greet",
50+
Short: "A simple greeting command",
51+
Long: "A simple greeting command",
52+
Run: func(_ *cobra.Command, _ []string) {
53+
fmt.Println("Hello world")
54+
},
55+
}
56+
cmd.Flags().StringToString(flagName, nil, "Labels are key-value string pairs.")
57+
return cmd
58+
}()
59+
60+
// set the flag value if a value use given, else consider the flag unset
61+
if tt.flagValue != nil {
62+
err := cmd.Flags().Set(flagName, *tt.flagValue)
63+
if err != nil {
64+
t.Error(err)
65+
}
66+
}
67+
68+
if got := FlagToStringToStringPointer(p, cmd, flagName); !reflect.DeepEqual(got, tt.want) {
69+
t.Errorf("FlagToStringToStringPointer() = %v, want %v", got, tt.want)
70+
}
71+
})
72+
}
73+
}

0 commit comments

Comments
 (0)