1
16
17 package flag
18
19 import (
20 "fmt"
21 "reflect"
22 "strings"
23 "testing"
24
25 "github.com/spf13/pflag"
26 )
27
28 func TestNamedCertKeyArrayFlag(t *testing.T) {
29 tests := []struct {
30 args []string
31 def []NamedCertKey
32 expected []NamedCertKey
33 parseError string
34 }{
35 {
36 args: []string{},
37 expected: nil,
38 },
39 {
40 args: []string{"foo.crt,foo.key"},
41 expected: []NamedCertKey{{
42 KeyFile: "foo.key",
43 CertFile: "foo.crt",
44 }},
45 },
46 {
47 args: []string{" foo.crt , foo.key "},
48 expected: []NamedCertKey{{
49 KeyFile: "foo.key",
50 CertFile: "foo.crt",
51 }},
52 },
53 {
54 args: []string{"foo.crt,foo.key:abc"},
55 expected: []NamedCertKey{{
56 KeyFile: "foo.key",
57 CertFile: "foo.crt",
58 Names: []string{"abc"},
59 }},
60 },
61 {
62 args: []string{"foo.crt,foo.key: abc "},
63 expected: []NamedCertKey{{
64 KeyFile: "foo.key",
65 CertFile: "foo.crt",
66 Names: []string{"abc"},
67 }},
68 },
69 {
70 args: []string{"foo.crt,foo.key:"},
71 parseError: "empty names list is not allowed",
72 },
73 {
74 args: []string{""},
75 parseError: "expected comma separated certificate and key file paths",
76 },
77 {
78 args: []string{" "},
79 parseError: "expected comma separated certificate and key file paths",
80 },
81 {
82 args: []string{"a,b,c"},
83 parseError: "expected comma separated certificate and key file paths",
84 },
85 {
86 args: []string{"foo.crt,foo.key:abc,def,ghi"},
87 expected: []NamedCertKey{{
88 KeyFile: "foo.key",
89 CertFile: "foo.crt",
90 Names: []string{"abc", "def", "ghi"},
91 }},
92 },
93 {
94 args: []string{"foo.crt,foo.key:*.*.*"},
95 expected: []NamedCertKey{{
96 KeyFile: "foo.key",
97 CertFile: "foo.crt",
98 Names: []string{"*.*.*"},
99 }},
100 },
101 {
102 args: []string{"foo.crt,foo.key", "bar.crt,bar.key"},
103 expected: []NamedCertKey{{
104 KeyFile: "foo.key",
105 CertFile: "foo.crt",
106 }, {
107 KeyFile: "bar.key",
108 CertFile: "bar.crt",
109 }},
110 },
111 }
112 for i, test := range tests {
113 fs := pflag.NewFlagSet("testNamedCertKeyArray", pflag.ContinueOnError)
114 var nkcs []NamedCertKey
115 nkcs = append(nkcs, test.def...)
116
117 fs.Var(NewNamedCertKeyArray(&nkcs), "tls-sni-cert-key", "usage")
118
119 args := []string{}
120 for _, a := range test.args {
121 args = append(args, fmt.Sprintf("--tls-sni-cert-key=%s", a))
122 }
123
124 err := fs.Parse(args)
125 if test.parseError != "" {
126 if err == nil {
127 t.Errorf("%d: expected error %q, got nil", i, test.parseError)
128 } else if !strings.Contains(err.Error(), test.parseError) {
129 t.Errorf("%d: expected error %q, got %q", i, test.parseError, err)
130 }
131 } else if err != nil {
132 t.Errorf("%d: expected nil error, got %v", i, err)
133 }
134 if !reflect.DeepEqual(nkcs, test.expected) {
135 t.Errorf("%d: expected %+v, got %+v", i, test.expected, nkcs)
136 }
137 }
138 }
139
View as plain text