Repository navigation
Expand file tree
/
Copy pathtypes_test.go
More file actions
365 lines (329 loc) · 12.8 KB
/
Copy pathtypes_test.go
File metadata and controls
365 lines (329 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package common
import (
"log/slog"
"testing"
"github.com/sagernet/sing/common/json"
"github.com/stretchr/testify/assert"
)
func TestConfigRequestSerialization(t *testing.T) {
original := ConfigRequest{
DeviceID: "device123",
SingboxVersion: "2.0.0",
Platform: "linux",
AppName: "testApp",
PreferredLocation: &ServerLocation{
Country: "USA",
City: "New York",
Latitude: 40.7128,
Longitude: -74.0060,
CountryCode: "US",
},
UserID: "user123",
WGPublicKey: "publicKey123",
}
// Serialize to JSON
data, err := json.Marshal(original)
if err != nil {
t.Fatalf("Failed to serialize ConfigRequest: %v", err)
}
slog.Info("Serialized ConfigRequest", slog.String("data", string(data)))
// Deserialize back to struct
var deserialized ConfigRequest
err = json.Unmarshal(data, &deserialized)
if err != nil {
t.Fatalf("Failed to deserialize ConfigRequest: %v", err)
}
// Check deep equality of structs.
assert.ObjectsAreEqual(original, deserialized)
}
func TestConfigRequestDefaultValues(t *testing.T) {
req := ConfigRequest{}
if req.DeviceID != "" {
t.Errorf("Expected default DeviceID to be empty, got: %s", req.DeviceID)
}
// PreferredLocation is a pointer, so its zero value is nil — dereferencing it
// to read .Country panics rather than testing anything.
if req.PreferredLocation != nil {
t.Errorf("Expected default PreferredLocation to be nil, got: %+v", req.PreferredLocation)
}
}
// A client holding no modules must serialize to exactly what it did before the
// field existed. The declaration is an optimization; it must not become a way to
// tell an older client from a newer one, nor a reason to treat them differently.
func TestConfigRequestModulesOmittedWhenEmpty(t *testing.T) {
// Decode and look for the key rather than substring-searching the JSON: a search for "modules"
// would also match the word appearing inside some other field's value, so it could pass for the
// wrong reason. The property under test is "no such key".
keys := func(t *testing.T, req ConfigRequest) map[string]json.RawMessage {
t.Helper()
data, err := json.Marshal(req)
if err != nil {
t.Fatalf("Failed to serialize ConfigRequest: %v", err)
}
var out map[string]json.RawMessage
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("Failed to deserialize ConfigRequest: %v", err)
}
return out
}
// Both empties, because they are different values that must behave the same. `omitempty` drops a
// map of length zero, so nil and an initialized-but-empty map are equivalent *today* — asserting
// only the nil case would let a later change to the tag or the field's type break the other
// silently, which is exactly the kind of gap this test exists to close.
for name, modules := range map[string]map[string]uint32{
"nil": nil,
"empty": {},
} {
t.Run(name, func(t *testing.T) {
assert.NotContains(t, keys(t, ConfigRequest{DeviceID: "d", Modules: modules}), "modules",
"a client holding no modules must send no `modules` key at all")
})
}
held := ConfigRequest{
DeviceID: "d",
Modules: map[string]uint32{"bip324": 3, "obfs-xor": 1},
}
assert.JSONEq(t, `{"bip324":3,"obfs-xor":1}`, string(keys(t, held)["modules"]))
data, err := json.Marshal(held)
if err != nil {
t.Fatalf("Failed to serialize ConfigRequest: %v", err)
}
var back ConfigRequest
if err := json.Unmarshal(data, &back); err != nil {
t.Fatalf("Failed to deserialize ConfigRequest: %v", err)
}
assert.Equal(t, map[string]uint32{"bip324": 3, "obfs-xor": 1}, back.Modules)
}
// The capability and the inventory answer different questions, and the server
// needs both: "can this client run a delivered module at all" is not the same as
// "which ones does it already have". A client that supports modules but holds
// none is the case that would otherwise be indistinguishable from one that
// cannot use them, since Modules is omitted when empty.
func TestTransportModulesCapabilityIsSeparateFromTheInventory(t *testing.T) {
supportsButHoldsNone := ConfigRequest{
DeviceID: "d",
Capabilities: []string{CapabilityTransportModules},
}
data, err := json.Marshal(supportsButHoldsNone)
if err != nil {
t.Fatalf("Failed to serialize ConfigRequest: %v", err)
}
var out map[string]json.RawMessage
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("Failed to deserialize ConfigRequest: %v", err)
}
assert.Contains(t, out, "capabilities", "the capability is what says the client can run a module")
assert.NotContains(t, out, "modules", "holding none must still omit the inventory")
// And a client that cannot use modules sends neither, so the server can tell
// the two apart — which is the whole point of the capability.
data, err = json.Marshal(ConfigRequest{DeviceID: "d"})
if err != nil {
t.Fatalf("Failed to serialize ConfigRequest: %v", err)
}
out = nil
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("Failed to deserialize ConfigRequest: %v", err)
}
assert.NotContains(t, out, "capabilities")
assert.NotContains(t, out, "modules")
}
func TestConfigResponseSerialization(t *testing.T) {
original := ConfigResponse{
Servers: []ServerLocation{
{
Country: "USA",
City: "New York",
Latitude: 40.7128,
Longitude: -74.0060,
CountryCode: "US",
},
{
Country: "Canada",
City: "Toronto",
Latitude: 43.65107,
Longitude: -79.347015,
CountryCode: "CA",
},
},
OutboundLocations: OutboundLocations{
"tag1": {
Country: "Germany",
City: "Berlin",
Latitude: 52.52,
Longitude: 13.405,
CountryCode: "DE",
},
},
}
// Serialize to JSON
data, err := json.Marshal(original)
if err != nil {
t.Fatalf("Failed to serialize ConfigResponse: %v", err)
}
slog.Info("Serialized ConfigResponse", slog.String("data", string(data)))
// Deserialize back to struct
var deserialized ConfigResponse
err = json.Unmarshal(data, &deserialized)
if err != nil {
t.Fatalf("Failed to deserialize ConfigResponse: %v", err)
}
// Compare original and deserialized structs
if len(original.Servers) != len(deserialized.Servers) ||
len(original.OutboundLocations) != len(deserialized.OutboundLocations) {
t.Errorf("Deserialized ConfigResponse does not match original.\nOriginal: %+v\nDeserialized: %+v", original, deserialized)
}
}
func TestPollIntervalSecondsRoundTrip(t *testing.T) {
original := ConfigResponse{
PollIntervalSeconds: 30,
}
data, err := json.Marshal(original)
assert.NoError(t, err)
// Non-zero value should appear in JSON
assert.Contains(t, string(data), `"poll_interval_seconds":30`)
var deserialized ConfigResponse
err = json.Unmarshal(data, &deserialized)
assert.NoError(t, err)
assert.Equal(t, 30, deserialized.PollIntervalSeconds)
// Zero value should be omitted from JSON
zeroResp := ConfigResponse{}
data, err = json.Marshal(zeroResp)
assert.NoError(t, err)
assert.NotContains(t, string(data), "poll_interval_seconds")
}
func TestNonSelectableOutboundsRoundTrip(t *testing.T) {
original := ConfigResponse{
NonSelectableOutbounds: []string{"proxyless"},
}
data, err := json.Marshal(original)
assert.NoError(t, err)
// Verify the JSON tag name is present (not an exact substring, which would be
// brittle to encoder formatting); the round-trip below verifies the value.
assert.Contains(t, string(data), `"non_selectable_outbounds"`)
var deserialized ConfigResponse
err = json.Unmarshal(data, &deserialized)
assert.NoError(t, err)
assert.Equal(t, []string{"proxyless"}, deserialized.NonSelectableOutbounds)
// Both nil and a non-nil empty slice should be omitted from JSON.
for _, empty := range []ConfigResponse{{}, {NonSelectableOutbounds: []string{}}} {
data, err = json.Marshal(empty)
assert.NoError(t, err)
assert.NotContains(t, string(data), "non_selectable_outbounds")
}
}
func TestCapabilitiesRoundTrip(t *testing.T) {
original := ConfigRequest{
Capabilities: []string{CapabilityNonSelectableOutbounds, CapabilityOutboundEvaluation},
}
data, err := json.Marshal(original)
assert.NoError(t, err)
assert.Contains(t, string(data), `"capabilities"`)
var deserialized ConfigRequest
err = json.Unmarshal(data, &deserialized)
assert.NoError(t, err)
assert.Equal(t, []string{CapabilityNonSelectableOutbounds, "outbound_evaluation"}, deserialized.Capabilities)
// Both nil and a non-nil empty slice should be omitted from JSON.
for _, empty := range []ConfigRequest{{}, {Capabilities: []string{}}} {
data, err = json.Marshal(empty)
assert.NoError(t, err)
assert.NotContains(t, string(data), `"capabilities"`)
}
}
func TestConfigResponseDefaultValues(t *testing.T) {
resp := ConfigResponse{}
if len(resp.Servers) != 0 {
t.Errorf("Expected default Servers to be empty, got: %+v", resp.Servers)
}
if len(resp.OutboundLocations) != 0 {
t.Errorf("Expected default OutboundLocations to be empty, got: %+v", resp.OutboundLocations)
}
}
func TestDonorSTUNConfigRoundTrip(t *testing.T) {
original := UnboundedConfig{STUNServers: DefaultDonorSTUNServers()}
encoded, err := json.Marshal(original)
assert.NoError(t, err)
var wire map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(encoded, &wire))
assert.Contains(t, wire, "stun_servers")
var decoded UnboundedConfig
assert.NoError(t, json.Unmarshal(encoded, &decoded))
assert.Equal(t, original.STUNServers, decoded.STUNServers)
original.STUNServers[0] = "changed"
assert.NotContains(t, DefaultDonorSTUNServers(), "changed")
}
func TestDonorSTUNConfigOmission(t *testing.T) {
for _, servers := range [][]string{nil, {}} {
encoded, err := json.Marshal(UnboundedConfig{STUNServers: servers})
assert.NoError(t, err)
assert.JSONEq(t, "{}", string(encoded))
}
}
func TestUnboundedTuningRoundTrip(t *testing.T) {
original := UnboundedConfig{Tuning: map[string]string{"ice_max_binding_requests": "25"}}
encoded, err := json.Marshal(original)
assert.NoError(t, err)
assert.JSONEq(t, `{"tuning":{"ice_max_binding_requests":"25"}}`, string(encoded))
var decoded UnboundedConfig
assert.NoError(t, json.Unmarshal(encoded, &decoded))
assert.True(t, original.Equal(&decoded))
for _, tuning := range []map[string]string{nil, {}} {
encoded, err := json.Marshal(UnboundedConfig{Tuning: tuning})
assert.NoError(t, err)
assert.JSONEq(t, "{}", string(encoded))
}
}
func TestUnboundedConfigEqual(t *testing.T) {
var absent *UnboundedConfig
assert.True(t, absent.Equal(nil))
assert.False(t, absent.Equal(&UnboundedConfig{}))
assert.False(t, (&UnboundedConfig{}).Equal(nil))
base := UnboundedConfig{
DiscoverySrv: "discovery", DiscoveryEndpoint: "/discover",
EgressAddr: "egress", EgressEndpoint: "/egress",
CTableSize: 1, PTableSize: 2,
STUNServers: []string{"stun:192.0.2.1:3478", "stun:192.0.2.2:3478"},
Tuning: map[string]string{"ice_max_binding_requests": "25"},
}
assert.True(t, base.Equal(&base))
copy := base
assert.True(t, base.Equal(©))
copy.STUNServers = []string{" stun:192.0.2.2:3478 ", "", "stun:192.0.2.1:3478", "stun:192.0.2.1:3478"}
assert.True(t, base.Equal(©))
for name, mutate := range map[string]func(*UnboundedConfig){
"discovery server": func(c *UnboundedConfig) { c.DiscoverySrv += "changed" },
"discovery endpoint": func(c *UnboundedConfig) { c.DiscoveryEndpoint += "changed" },
"egress address": func(c *UnboundedConfig) { c.EgressAddr += "changed" },
"egress endpoint": func(c *UnboundedConfig) { c.EgressEndpoint += "changed" },
"consumer table": func(c *UnboundedConfig) { c.CTableSize++ },
"producer table": func(c *UnboundedConfig) { c.PTableSize++ },
"STUN pool": func(c *UnboundedConfig) { c.STUNServers = []string{"stun:192.0.2.3:3478"} },
"tuning value": func(c *UnboundedConfig) { c.Tuning = map[string]string{"ice_max_binding_requests": "50"} },
"tuning removed": func(c *UnboundedConfig) { c.Tuning = nil },
} {
t.Run(name, func(t *testing.T) {
changed := base
mutate(&changed)
assert.False(t, base.Equal(&changed))
assert.False(t, changed.Equal(&base))
})
}
for _, servers := range [][]string{nil, {}, {"", " \t"}, DefaultDonorSTUNServers()} {
assert.True(t, (&UnboundedConfig{}).Equal(&UnboundedConfig{STUNServers: servers}))
}
assert.True(t, (&UnboundedConfig{}).Equal(&UnboundedConfig{Tuning: map[string]string{}}))
}
func TestNormalizeDonorSTUNServers(t *testing.T) {
input := []string{" stun:192.0.2.2:3478 ", "stun:192.0.2.1:3478", "", "stun:192.0.2.2:3478"}
original := append([]string(nil), input...)
pool := NormalizeDonorSTUNServers(input)
assert.Equal(t, []string{"stun:192.0.2.1:3478", "stun:192.0.2.2:3478"}, pool)
assert.Equal(t, original, input)
pool[0] = "changed"
assert.Equal(t, original, input)
for _, empty := range [][]string{nil, {}, {"", " \t"}} {
pool = NormalizeDonorSTUNServers(empty)
assert.ElementsMatch(t, DefaultDonorSTUNServers(), pool)
pool[0] = "changed"
assert.NotContains(t, NormalizeDonorSTUNServers(empty), "changed")
}
}