Repository navigation
Expand file tree
/
Copy pathcodec_test.go
More file actions
592 lines (486 loc) · 14.1 KB
/
Copy pathcodec_test.go
File metadata and controls
592 lines (486 loc) · 14.1 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
package gush
import (
"encoding/json"
"reflect"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestEncode(t *testing.T) {
t.Run("nil returns nil", func(t *testing.T) {
result, err := Encode(nil)
require.NoError(t, err)
require.Nil(t, result)
})
t.Run("[]byte returns as-is", func(t *testing.T) {
input := []byte(`hello world`)
result, err := Encode(input)
require.NoError(t, err)
require.Equal(t, input, result)
})
t.Run("string returns raw bytes without JSON quotes", func(t *testing.T) {
result, err := Encode("hello")
require.NoError(t, err)
require.Equal(t, []byte("hello"), result)
})
t.Run("*string dereferences and returns raw bytes", func(t *testing.T) {
s := "hello"
result, err := Encode(&s)
require.NoError(t, err)
require.Equal(t, []byte("hello"), result)
})
t.Run("*[]byte dereferences and returns as-is", func(t *testing.T) {
b := []byte(`raw bytes`)
result, err := Encode(&b)
require.NoError(t, err)
require.Equal(t, b, result)
})
t.Run("struct marshals to JSON", func(t *testing.T) {
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
person := Person{Name: "John", Age: 30}
result, err := Encode(person)
require.NoError(t, err)
require.Equal(t, `{"name":"John","age":30}`, string(result))
})
t.Run("map marshals to JSON", func(t *testing.T) {
result, err := Encode(map[string]int{"a": 1})
require.NoError(t, err)
require.Equal(t, `{"a":1}`, string(result))
})
t.Run("HTML tags are not escaped", func(t *testing.T) {
result, err := Encode(map[string]string{"url": "https://example.com?a=1&b=2"})
require.NoError(t, err)
require.Contains(t, string(result), "&")
require.NotContains(t, string(result), `\u0026`)
})
t.Run("JSON output has no trailing newline", func(t *testing.T) {
result, err := Encode(42)
require.NoError(t, err)
require.Equal(t, "42", string(result))
})
}
type (
codecStatus string
codecBytes []byte
)
// codecTextStatus chooses its own JSON form through its text methods.
type codecTextStatus string
func (status codecTextStatus) MarshalText() ([]byte, error) {
return []byte("text:" + string(status)), nil
}
func (status *codecTextStatus) UnmarshalText(data []byte) error {
*status = codecTextStatus(strings.TrimPrefix(string(data), "text:"))
return nil
}
type (
codecMarshalsJSON string
codecUnmarshalsJSON string
codecMarshalsText string
codecUnmarshalsText string
)
func (codecMarshalsJSON) MarshalJSON() ([]byte, error) { return nil, nil }
func (*codecUnmarshalsJSON) UnmarshalJSON([]byte) error { return nil }
func (codecMarshalsText) MarshalText() ([]byte, error) { return nil, nil }
func (*codecUnmarshalsText) UnmarshalText([]byte) error { return nil }
func TestEncodeAndDecodeTypesBuiltOnStringsAndBytes(t *testing.T) {
t.Run("a string type has no quotes", func(t *testing.T) {
status := codecStatus("done")
for _, value := range []any{status, &status} {
raw, err := Encode(value)
require.NoError(t, err)
require.Equal(t, "done", string(raw))
}
})
t.Run("a string type reads back as itself or as a string", func(t *testing.T) {
raw, err := Encode(codecStatus("done"))
require.NoError(t, err)
var status codecStatus
require.NoError(t, Decode(raw, &status))
require.Equal(t, codecStatus("done"), status)
var plain string
require.NoError(t, Decode(raw, &plain))
require.Equal(t, "done", plain)
})
t.Run("a string reads back as a string type", func(t *testing.T) {
var status codecStatus
require.NoError(t, Decode([]byte("done"), &status))
require.Equal(t, codecStatus("done"), status)
})
t.Run("a bytes type is not base64", func(t *testing.T) {
original := codecBytes("raw bytes")
raw, err := Encode(original)
require.NoError(t, err)
require.Equal(t, "raw bytes", string(raw))
var decoded codecBytes
require.NoError(t, Decode(raw, &decoded))
require.Equal(t, original, decoded)
raw[0] = 'x'
require.Equal(t, byte('r'), decoded[0], "Decode must copy the data")
})
t.Run("a type with text methods stays JSON", func(t *testing.T) {
raw, err := Encode(codecTextStatus("done"))
require.NoError(t, err)
require.Equal(t, `"text:done"`, string(raw))
var status codecTextStatus
require.NoError(t, Decode(raw, &status))
require.Equal(t, codecTextStatus("done"), status)
})
t.Run("any one conversion method keeps a type JSON", func(t *testing.T) {
types := []reflect.Type{
reflect.TypeFor[codecMarshalsJSON](),
reflect.TypeFor[codecUnmarshalsJSON](),
reflect.TypeFor[codecMarshalsText](),
reflect.TypeFor[codecUnmarshalsText](),
}
for _, valueType := range types {
require.False(t, usedAsIs(valueType), "%v", valueType)
}
require.True(t, usedAsIs(reflect.TypeFor[codecStatus]()))
})
t.Run("json.RawMessage stays JSON", func(t *testing.T) {
raw, err := Encode(json.RawMessage(`{"a": 1}`))
require.NoError(t, err)
require.Equal(t, `{"a":1}`, string(raw))
var message json.RawMessage
require.NoError(t, Decode(raw, &message))
require.Equal(t, `{"a":1}`, string(message))
})
t.Run("a nil pointer target is an error", func(t *testing.T) {
var status *codecStatus
require.Error(t, Decode([]byte("done"), status))
var anything *any
require.Error(t, Decode([]byte("not json"), anything))
})
}
func TestDecode(t *testing.T) {
t.Run("[]byte assigned directly", func(t *testing.T) {
m := make([]byte, 0)
err := Decode([]byte(`{"age":30,"name":"John"}`), &m)
require.NoError(t, err)
require.Equal(t, []byte(`{"age":30,"name":"John"}`), m)
})
t.Run("*[]byte assigned directly", func(t *testing.T) {
m := new([]byte)
err := Decode([]byte(`{"age":30,"name":"John"}`), m)
require.NoError(t, err)
raw, err := Encode(m)
require.NoError(t, err)
require.Equal(t, []byte(`{"age":30,"name":"John"}`), raw)
})
t.Run("*string assigned directly without JSON parsing", func(t *testing.T) {
var s string
err := Decode([]byte("hello world"), &s)
require.NoError(t, err)
require.Equal(t, "hello world", s)
})
t.Run("struct unmarshals from JSON", func(t *testing.T) {
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
var p Person
err := Decode([]byte(`{"name":"John","age":30}`), &p)
require.NoError(t, err)
expected := Person{Name: "John", Age: 30}
require.Equal(t, expected, p)
})
t.Run("nil data resets float to zero", func(t *testing.T) {
m := float32(99)
err := Decode(nil, &m)
require.NoError(t, err)
require.Equal(t, float32(0), m)
})
t.Run("empty data resets string to zero", func(t *testing.T) {
s := "non-empty"
err := Decode([]byte{}, &s)
require.NoError(t, err)
require.Equal(t, "", s)
})
t.Run("nil data resets int to zero", func(t *testing.T) {
n := 99
err := Decode(nil, &n)
require.NoError(t, err)
require.Equal(t, 0, n)
})
t.Run("nil data resets slice to nil", func(t *testing.T) {
sl := []string{"a", "b"}
err := Decode(nil, &sl)
require.NoError(t, err)
require.Nil(t, sl)
})
}
func TestSetToZeroValue(t *testing.T) {
t.Run("basic types", func(t *testing.T) {
// Test string
str := "hello"
setToZeroValue(&str)
require.Equal(t, "", str)
// Test int
num := 42
setToZeroValue(&num)
require.Equal(t, 0, num)
// Test bool
flag := true
setToZeroValue(&flag)
require.Equal(t, false, flag)
// Test float
f := 3.14
setToZeroValue(&f)
require.Equal(t, 0.0, f)
})
t.Run("pointer types", func(t *testing.T) {
// Test string pointer
str := "hello"
strPtr := &str
setToZeroValue(&strPtr)
require.Nil(t, strPtr)
// Test int pointer
num := 42
numPtr := &num
setToZeroValue(&numPtr)
require.Nil(t, numPtr)
})
t.Run("slice types", func(t *testing.T) {
// Test string slice
slice := []string{"a", "b", "c"}
setToZeroValue(&slice)
require.Nil(t, slice)
// Test int slice
intSlice := []int{1, 2, 3}
setToZeroValue(&intSlice)
require.Nil(t, intSlice)
})
t.Run("map types", func(t *testing.T) {
// Test string map
m := map[string]int{"a": 1, "b": 2}
setToZeroValue(&m)
require.Nil(t, m)
})
t.Run("struct types", func(t *testing.T) {
type Person struct {
Name string
Age int
Active bool
Score float64
}
person := Person{
Name: "John",
Age: 30,
Active: true,
Score: 95.5,
}
setToZeroValue(&person)
var zero Person
require.Equal(t, zero, person)
})
t.Run("nested struct types", func(t *testing.T) {
type Address struct {
Street string
City string
}
type Person struct {
Name string
Age int
Address Address
Address2 *Address
}
person := Person{
Name: "John",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
},
Address2: &Address{
Street: "456 Main St",
City: "Los Angeles",
},
}
setToZeroValue(&person)
var zero Person
require.Equal(t, zero, person)
})
t.Run("struct with pointers", func(t *testing.T) {
type Person struct {
Name string
Age int
Address *string
Tags []string
}
address := "123 Main St"
person := Person{
Name: "John",
Age: 30,
Address: &address,
Tags: []string{"tag1", "tag2"},
}
setToZeroValue(&person)
expected := Person{}
require.Equal(t, expected, person)
})
t.Run("nil target", func(t *testing.T) {
// Should not panic
setToZeroValue(nil)
})
t.Run("non-pointer target", func(t *testing.T) {
// Should not panic
str := "hello"
setToZeroValue(str)
require.Equal(t, "hello", str) // Should remain unchanged
})
}
func TestEncodeNilPointerIsNil(t *testing.T) {
var value *struct{ A int }
result, err := Encode(value)
require.NoError(t, err)
require.Nil(t, result)
}
type pointerMarshaler struct{}
func (*pointerMarshaler) MarshalJSON() ([]byte, error) {
return []byte(`"custom"`), nil
}
func TestEncodeHonorsPointerReceiverMarshaler(t *testing.T) {
marshaler := &pointerMarshaler{}
result, err := Encode(marshaler)
require.NoError(t, err)
require.Equal(t, `"custom"`, string(result))
}
func TestPayloadRoundTrip(t *testing.T) {
input := map[string]int{"a": 1}
payload, err := EncodePayload(input)
require.NoError(t, err)
require.NotEqual(t, `{"a":1}`, string(payload))
var output map[string]int
require.NoError(t, DecodePayload(payload, &output))
require.Equal(t, input, output)
}
func TestDecodePayloadLeavesTargetAloneWhenEmpty(t *testing.T) {
output := "unchanged"
require.NoError(t, DecodePayload(nil, &output))
require.Equal(t, "unchanged", output)
require.NoError(t, DecodePayload(nil, nil))
}
func TestDecodePayloadRejectsCorruptData(t *testing.T) {
var output string
require.Error(t, DecodePayload([]byte("not zstd"), &output))
}
func TestResumeTokenRoundTrip(t *testing.T) {
token := []byte{0, 1, 2, 250}
decoded, err := decodeResumeToken(encodeResumeToken(token))
require.NoError(t, err)
require.Equal(t, token, decoded)
}
func TestEncodeFollowsAPointerToAny(t *testing.T) {
var holder any = "abc"
result, err := Encode(&holder)
require.NoError(t, err)
require.Equal(t, "abc", string(result))
holder = []byte("raw")
result, err = Encode(&holder)
require.NoError(t, err)
require.Equal(t, "raw", string(result))
holder = map[string]int{"a": 1}
result, err = Encode(&holder)
require.NoError(t, err)
require.Equal(t, `{"a":1}`, string(result))
}
func TestDecodeIntoAny(t *testing.T) {
var output any
require.NoError(t, Decode([]byte("hello"), &output))
require.Equal(t, "hello", output)
require.NoError(t, Decode([]byte(`{"a":1}`), &output))
expected := map[string]any{"a": 1.0}
require.Equal(t, expected, output)
}
type namedByte byte
type namedBytes []namedByte
// jsonByte has its own JSON form, which makes a slice of it a list, as in encoding/json.
type jsonByte byte
func (b jsonByte) MarshalJSON() ([]byte, error) {
return json.Marshal(int(b) + 1)
}
func (b *jsonByte) UnmarshalJSON(data []byte) error {
var value int
err := json.Unmarshal(data, &value)
if err != nil {
return err
}
*b = jsonByte(value - 1)
return nil
}
func TestSliceOfNamedBytesTravelsRaw(t *testing.T) {
encoded, err := Encode([]namedByte("raw"))
require.NoError(t, err)
require.Equal(t, "raw", string(encoded))
encoded, err = Encode(namedBytes("raw"))
require.NoError(t, err)
require.Equal(t, "raw", string(encoded))
var plain []namedByte
require.NoError(t, Decode([]byte("raw"), &plain))
require.Equal(t, []namedByte("raw"), plain)
var named namedBytes
require.NoError(t, Decode([]byte("raw"), &named))
require.Equal(t, namedBytes("raw"), named)
}
func TestSliceOfBytesWithTheirOwnJSONIsAList(t *testing.T) {
encoded, err := Encode([]jsonByte{1, 2})
require.NoError(t, err)
require.Equal(t, "[2,3]", string(encoded))
var decoded []jsonByte
require.NoError(t, Decode(encoded, &decoded))
require.Equal(t, []jsonByte{1, 2}, decoded)
}
func TestPointersOfAnyDepthReachRawValues(t *testing.T) {
text := "done"
pointer := &text
encoded, err := Encode(&pointer)
require.NoError(t, err)
require.Equal(t, "done", string(encoded))
var output *string
require.NoError(t, Decode([]byte("done"), &output))
require.NotNil(t, output)
require.Equal(t, "done", *output)
var deeper **string
require.NoError(t, Decode([]byte("done"), &deeper))
require.NotNil(t, deeper)
require.Equal(t, "done", **deeper)
var bytesOutput *[]byte
require.NoError(t, Decode([]byte("raw"), &bytesOutput))
require.NotNil(t, bytesOutput)
require.Equal(t, []byte("raw"), *bytesOutput)
}
func TestPointerToNilPointerEncodesToNil(t *testing.T) {
var pointer *string
encoded, err := Encode(&pointer)
require.NoError(t, err)
require.Nil(t, encoded)
var empty any
encoded, err = Encode(&empty)
require.NoError(t, err)
require.Nil(t, encoded)
}
func TestEmptyDataZeroesAPointerOutput(t *testing.T) {
text := "old"
output := &text
require.NoError(t, Decode(nil, &output))
require.Nil(t, output)
}
func TestPointerToAnyHoldingAPointerEncodesWhatItHolds(t *testing.T) {
text := "done"
var value any = &text
encoded, err := Encode(&value)
require.NoError(t, err)
require.Equal(t, "done", string(encoded))
}
func TestPointerOutputOfAStructStillDecodesJSON(t *testing.T) {
type receipt struct {
ID string `json:"id"`
}
var output *receipt
require.NoError(t, Decode([]byte(`{"id":"a"}`), &output))
require.NotNil(t, output)
require.Equal(t, "a", output.ID)
}