Skip to content

Commit a791139

Browse files
committed
chore(flags): add unit test for string to string flag parsing
1 parent 352189b commit a791139

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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+
// TODO: this isn't allowed
27+
/*{
28+
name: "flag set with empty value",
29+
flagValue: utils.Ptr(""),
30+
want: &map[string]string{},
31+
},*/
32+
{
33+
name: "flag set with single value",
34+
flagValue: utils.Ptr("foo=bar"),
35+
want: &map[string]string{
36+
"foo": "bar",
37+
},
38+
},
39+
{
40+
name: "flag set with multiple values",
41+
flagValue: utils.Ptr("foo=bar,label1=value1,label2=value2"),
42+
want: &map[string]string{
43+
"foo": "bar",
44+
"label1": "value1",
45+
"label2": "value2",
46+
},
47+
},
48+
}
49+
for _, tt := range tests {
50+
t.Run(tt.name, func(t *testing.T) {
51+
p := print.NewPrinter()
52+
// create a new, simple test command with a string-to-string flag
53+
cmd := func() *cobra.Command {
54+
cmd := &cobra.Command{
55+
Use: "greet",
56+
Short: "A simple greeting command",
57+
Long: "A simple greeting command",
58+
Run: func(cmd *cobra.Command, args []string) {
59+
fmt.Println("Hello world")
60+
},
61+
}
62+
cmd.Flags().StringToString(flagName, nil, "Labels are key-value string pairs.")
63+
return cmd
64+
}()
65+
66+
// set the flag value if a value use given, else consider the flag unset
67+
if tt.flagValue != nil {
68+
err := cmd.Flags().Set(flagName, *tt.flagValue)
69+
if err != nil {
70+
t.Error(err)
71+
}
72+
}
73+
74+
if got := FlagToStringToStringPointer(p, cmd, flagName); !reflect.DeepEqual(got, tt.want) {
75+
t.Errorf("FlagToStringToStringPointer() = %v, want %v", got, tt.want)
76+
}
77+
})
78+
}
79+
}

0 commit comments

Comments
 (0)