istio

Форк
0
/
proxy_test.go 
296 строк · 8.2 Кб
1
// Copyright Istio Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package model_test
16

17
import (
18
	"encoding/json"
19
	"reflect"
20
	"testing"
21
	"time"
22

23
	"google.golang.org/protobuf/types/known/durationpb"
24

25
	meshconfig "istio.io/api/mesh/v1alpha1"
26
	"istio.io/api/networking/v1alpha3"
27
	"istio.io/istio/pkg/model"
28
	"istio.io/istio/pkg/test/util/assert"
29
)
30

31
func TestNodeMetadata(t *testing.T) {
32
	tests := []struct {
33
		name  string
34
		in    model.BootstrapNodeMetadata
35
		out   string
36
		inOut model.BootstrapNodeMetadata
37
	}{
38
		{
39
			"empty",
40
			model.BootstrapNodeMetadata{},
41
			"{}",
42
			model.BootstrapNodeMetadata{NodeMetadata: model.NodeMetadata{Raw: map[string]any{}}},
43
		},
44
		{
45
			"csvlists",
46
			model.BootstrapNodeMetadata{NodeMetadata: model.NodeMetadata{InstanceIPs: []string{"abc", "1.2.3.4"}}},
47
			`{"INSTANCE_IPS":"abc,1.2.3.4"}`,
48
			model.BootstrapNodeMetadata{
49
				NodeMetadata: model.NodeMetadata{
50
					InstanceIPs: []string{"abc", "1.2.3.4"},
51
					Raw: map[string]any{
52
						"INSTANCE_IPS": "abc,1.2.3.4",
53
					},
54
				},
55
			},
56
		},
57
		{
58
			"labels",
59
			model.BootstrapNodeMetadata{NodeMetadata: model.NodeMetadata{Labels: map[string]string{"foo": "bar"}}},
60
			`{"LABELS":{"foo":"bar"}}`,
61
			model.BootstrapNodeMetadata{
62
				NodeMetadata: model.NodeMetadata{
63
					Labels: map[string]string{"foo": "bar"},
64
					Raw: map[string]any{
65
						"LABELS": map[string]any{
66
							"foo": "bar",
67
						},
68
					},
69
				},
70
			},
71
		},
72
		{
73
			"proxy config",
74
			model.BootstrapNodeMetadata{
75
				NodeMetadata: model.NodeMetadata{
76
					ProxyConfig: (*model.NodeMetaProxyConfig)(&meshconfig.ProxyConfig{
77
						ConfigPath:             "foo",
78
						DrainDuration:          durationpb.New(time.Second * 5),
79
						ControlPlaneAuthPolicy: meshconfig.AuthenticationPolicy_MUTUAL_TLS,
80
						EnvoyAccessLogService: &meshconfig.RemoteService{
81
							Address: "address",
82
							TlsSettings: &v1alpha3.ClientTLSSettings{
83
								SubjectAltNames: []string{"san"},
84
							},
85
						},
86
					}),
87
				},
88
			},
89
			// nolint: lll
90
			`{"PROXY_CONFIG":{"configPath":"foo","drainDuration":"5s","controlPlaneAuthPolicy":"MUTUAL_TLS","envoyAccessLogService":{"address":"address","tlsSettings":{"subjectAltNames":["san"]}}}}`,
91
			model.BootstrapNodeMetadata{
92
				NodeMetadata: model.NodeMetadata{
93
					ProxyConfig: (*model.NodeMetaProxyConfig)(&meshconfig.ProxyConfig{
94
						ConfigPath:             "foo",
95
						DrainDuration:          durationpb.New(time.Second * 5),
96
						ControlPlaneAuthPolicy: meshconfig.AuthenticationPolicy_MUTUAL_TLS,
97
						EnvoyAccessLogService: &meshconfig.RemoteService{
98
							Address: "address",
99
							TlsSettings: &v1alpha3.ClientTLSSettings{
100
								SubjectAltNames: []string{"san"},
101
							},
102
						},
103
					}),
104
					Raw: map[string]any{
105
						"PROXY_CONFIG": map[string]any{
106
							"drainDuration":          "5s",
107
							"configPath":             "foo",
108
							"controlPlaneAuthPolicy": "MUTUAL_TLS",
109
							"envoyAccessLogService": map[string]any{
110
								"address": "address",
111
								"tlsSettings": map[string]any{
112
									"subjectAltNames": []any{"san"},
113
								},
114
							},
115
						},
116
					},
117
				},
118
			},
119
		},
120
	}
121
	for _, tt := range tests {
122
		t.Run(tt.name, func(t *testing.T) {
123
			j, err := json.Marshal(tt.in)
124
			if err != nil {
125
				t.Fatalf("failed to marshal: %v", err)
126
			}
127
			if string(j) != tt.out {
128
				t.Errorf("Got json '%s', expected '%s'", string(j), tt.out)
129
			}
130
			var meta model.BootstrapNodeMetadata
131
			if err := json.Unmarshal(j, &meta); err != nil {
132
				t.Fatalf("failed to unmarshal: %v", err)
133
			}
134

135
			assert.Equal(t, (*meshconfig.ProxyConfig)(meta.NodeMetadata.ProxyConfig), (*meshconfig.ProxyConfig)(tt.inOut.NodeMetadata.ProxyConfig))
136
			// cmp cannot handle the type-alias in the metadata, so check them separately.
137
			meta.NodeMetadata.ProxyConfig = nil
138
			tt.inOut.NodeMetadata.ProxyConfig = nil
139
			assert.Equal(t, meta, tt.inOut)
140
		})
141
	}
142
}
143

144
func TestStringList(t *testing.T) {
145
	cases := []struct {
146
		in          string
147
		expect      model.StringList
148
		noRoundTrip bool
149
	}{
150
		{in: `"a,b,c"`, expect: []string{"a", "b", "c"}},
151
		{in: `"\"a,b,c"`, expect: []string{`"a`, "b", "c"}},
152
		{in: `"a"`, expect: []string{"a"}},
153
		{in: `""`, expect: []string{}},
154
		{in: `"123,@#$#,abcdef"`, expect: []string{"123", "@#$#", "abcdef"}},
155
	}
156
	for _, tt := range cases {
157
		t.Run(tt.in, func(t *testing.T) {
158
			var out model.StringList
159
			if err := json.Unmarshal([]byte(tt.in), &out); err != nil {
160
				t.Fatal(err)
161
			}
162
			if !reflect.DeepEqual(out, tt.expect) {
163
				t.Fatalf("Expected %v, got %v", tt.expect, out)
164
			}
165
			b, err := json.Marshal(out)
166
			if err != nil {
167
				t.Fatal(err)
168
			}
169
			if tt.noRoundTrip {
170
				return
171
			}
172
			if !reflect.DeepEqual(string(b), tt.in) {
173
				t.Fatalf("Expected %v, got %v", tt.in, string(b))
174
			}
175
		})
176
	}
177
	// Invalid case
178
	var out model.StringList
179
	assert.Error(t, json.Unmarshal([]byte("1"), &out))
180
}
181

182
func TestPodPortList(t *testing.T) {
183
	cases := []struct {
184
		name            string
185
		in              string
186
		expect          model.PodPortList
187
		expUnmarshalErr string
188
	}{
189
		{"no port", `"[]"`, model.PodPortList{}, ""},
190
		{"one port", `"[{\"name\":\"foo\",\"containerPort\":9080,\"protocol\":\"TCP\"}]"`, model.PodPortList{{"foo", 9080, "TCP"}}, ""},
191
		{
192
			"two ports",
193
			`"[{\"name\":\"foo\",\"containerPort\":9080,\"protocol\":\"TCP\"},{\"containerPort\":8888,\"protocol\":\"TCP\"}]"`,
194
			model.PodPortList{{"foo", 9080, "TCP"}, {ContainerPort: 8888, Protocol: "TCP"}},
195
			"",
196
		},
197
		{"invalid syntax", `[]`, nil, "invalid syntax"},
198
	}
199
	for _, tt := range cases {
200
		t.Run(tt.name, func(t *testing.T) {
201
			var out model.PodPortList
202
			if err := json.Unmarshal([]byte(tt.in), &out); err != nil {
203
				if tt.expUnmarshalErr == "" {
204
					t.Fatal(err)
205
				}
206
				if out != nil {
207
					t.Fatalf("%s: Expected null unmarshal output but obtained a non-null one.", tt.name)
208
				}
209
				if err.Error() != tt.expUnmarshalErr {
210
					t.Fatalf("%s: Expected error: %s but got error: %s.", tt.name, tt.expUnmarshalErr, err.Error())
211
				}
212
				return
213
			}
214
			if !reflect.DeepEqual(out, tt.expect) {
215
				t.Fatalf("%s: Expected %v, got %v", tt.name, tt.expect, out)
216
			}
217
			b, err := json.Marshal(out)
218
			if err != nil {
219
				t.Fatal(err)
220
			}
221
			if !reflect.DeepEqual(string(b), tt.in) {
222
				t.Fatalf("%s: Expected %v, got %v", tt.name, tt.in, string(b))
223
			}
224
		})
225
	}
226
}
227

228
func TestStringBool(t *testing.T) {
229
	cases := []struct {
230
		name   string
231
		in     string
232
		expect string
233
	}{
234
		{"1", `"1"`, `"true"`},
235
		{"0", `"0"`, `"false"`},
236
		{"false", `"false"`, `"false"`},
237
		{"true", `"true"`, `"true"`},
238
		{"invalid input", `"foo"`, ``},
239
		{"no quotes", `true`, ``},
240
	}
241
	for _, tt := range cases {
242
		t.Run(tt.name, func(t *testing.T) {
243
			var out model.StringBool
244
			if err := json.Unmarshal([]byte(tt.in), &out); err != nil {
245
				if tt.expect == "" {
246
					return
247
				}
248
				t.Fatal(err)
249
			}
250
			b, err := json.Marshal(out)
251
			if err != nil {
252
				t.Fatal(err)
253
			}
254
			if !reflect.DeepEqual(string(b), tt.expect) {
255
				t.Fatalf("Expected %v, got %v", tt.expect, string(b))
256
			}
257
		})
258
	}
259
}
260

261
const (
262
	k8sSeparator = "."
263
)
264

265
func TestGetLocalityLabel(t *testing.T) {
266
	cases := []struct {
267
		name     string
268
		label    string
269
		expected string
270
	}{
271
		{
272
			name:     "with label",
273
			label:    "region/zone/subzone-1",
274
			expected: "region/zone/subzone-1",
275
		},
276
		{
277
			name:     "label with k8s label separator",
278
			label:    "region" + k8sSeparator + "zone" + k8sSeparator + "subzone-2",
279
			expected: "region/zone/subzone-2",
280
		},
281
		{
282
			name:     "label with both k8s label separators and slashes",
283
			label:    "region/zone/subzone.2",
284
			expected: "region/zone/subzone.2",
285
		},
286
	}
287

288
	for _, testCase := range cases {
289
		t.Run(testCase.name, func(t *testing.T) {
290
			got := model.GetLocalityLabel(testCase.label)
291
			if got != testCase.expected {
292
				t.Errorf("expected locality %s, but got %s", testCase.expected, got)
293
			}
294
		})
295
	}
296
}
297

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.