-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_decode_test.go
More file actions
787 lines (725 loc) · 16.7 KB
/
string_decode_test.go
File metadata and controls
787 lines (725 loc) · 16.7 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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
package cast_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"reflect"
"testing"
"time"
"go.osspkg.com/cast"
)
type testInitializer struct {
init bool
}
func (t *testInitializer) Initialize() error {
t.init = true
return nil
}
type testUnStringer struct {
Value string
}
func (u *testUnStringer) UnString(s string) {
u.Value = s
}
type testBinaryUnmarshaler struct {
Data []byte
}
func (b *testBinaryUnmarshaler) UnmarshalBinary(data []byte) error {
b.Data = append([]byte{}, data...)
return nil
}
type testTextUnmarshaler struct {
Text string
}
func (t *testTextUnmarshaler) UnmarshalText(text []byte) error {
t.Text = string(text)
return nil
}
type testJSONUnmarshaler struct {
Value string
}
func (j *testJSONUnmarshaler) UnmarshalJSON(data []byte) error {
return json.Unmarshal(data, &j.Value)
}
type testXMLUnmarshaler struct {
Object struct {
Value string `xml:"value"`
}
}
func (x *testXMLUnmarshaler) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
return d.DecodeElement(&x.Object, &start)
}
type testWriter struct {
Buffer *bytes.Buffer
}
func (w *testWriter) Write(p []byte) (n int, err error) {
return w.Buffer.Write(p)
}
type testStringWriter struct {
Buffer *bytes.Buffer
}
func (w *testStringWriter) WriteString(s string) (n int, err error) {
return w.Buffer.WriteString(s)
}
type testComplexStruct struct {
Pointer *string
Slice []int
Map map[string]string
}
func TestStringDecode(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
rfc3339Time := now.Format(time.RFC3339)
tests := []struct {
name string
obj any
input string
expected any
expectError bool
}{
// Тесты для базовых типов
{
name: "string",
obj: new(string),
input: "test string",
expected: "test string",
},
{
name: "int",
obj: new(int),
input: "42",
expected: 42,
},
{
name: "int8",
obj: new(int8),
input: "127",
expected: int8(127),
},
{
name: "int16",
obj: new(int16),
input: "32767",
expected: int16(32767),
},
{
name: "int32",
obj: new(int32),
input: "2147483647",
expected: int32(2147483647),
},
{
name: "int64",
obj: new(int64),
input: "9223372036854775807",
expected: int64(9223372036854775807),
},
{
name: "uint",
obj: new(uint),
input: "4294967295",
expected: uint(4294967295),
},
{
name: "uint8",
obj: new(uint8),
input: "255",
expected: uint8(255),
},
{
name: "uint16",
obj: new(uint16),
input: "65535",
expected: uint16(65535),
},
{
name: "uint32",
obj: new(uint32),
input: "4294967295",
expected: uint32(4294967295),
},
{
name: "uint64",
obj: new(uint64),
input: "18446744073709551615",
expected: uint64(18446744073709551615),
},
{
name: "float32",
obj: new(float32),
input: "3.14",
expected: float32(3.14),
},
{
name: "float64",
obj: new(float64),
input: "3.1415926535",
expected: 3.1415926535,
},
{
name: "bool true",
obj: new(bool),
input: "true",
expected: true,
},
{
name: "bool false",
obj: new(bool),
input: "false",
expected: false,
},
{
name: "duration",
obj: new(time.Duration),
input: "2s",
expected: 2 * time.Second,
},
{
name: "time",
obj: new(time.Time),
input: rfc3339Time,
expected: now,
},
{
name: "[]byte",
obj: new([]byte),
input: "bytes content",
expected: []byte("bytes content"),
},
// Тесты для интерфейсов
{
name: "io.Writer",
obj: &testWriter{Buffer: &bytes.Buffer{}},
input: "writer content",
expected: func() testWriter {
w := &testWriter{Buffer: &bytes.Buffer{}}
_, _ = w.Write([]byte("writer content"))
return *w
}(),
},
{
name: "io.StringWriter",
obj: &testStringWriter{Buffer: &bytes.Buffer{}},
input: "string writer content",
expected: func() testStringWriter {
w := &testStringWriter{Buffer: &bytes.Buffer{}}
_, _ = w.WriteString("string writer content")
return *w
}(),
},
{
name: "UnStringer",
obj: &testUnStringer{},
input: "unstringer content",
expected: testUnStringer{
Value: "unstringer content",
},
},
{
name: "BinaryUnmarshaler",
obj: &testBinaryUnmarshaler{},
input: "binary unmarshal content",
expected: testBinaryUnmarshaler{
Data: []byte("binary unmarshal content"),
},
},
{
name: "TextUnmarshaler",
obj: &testTextUnmarshaler{},
input: "text unmarshal content",
expected: testTextUnmarshaler{
Text: "text unmarshal content",
},
},
{
name: "JSONUnmarshaler",
obj: &testJSONUnmarshaler{},
input: `"json unmarshal content"`,
expected: testJSONUnmarshaler{
Value: "json unmarshal content",
},
},
{
name: "XMLUnmarshaler",
obj: &testXMLUnmarshaler{},
input: `<testXMLUnmarshaler><value>xml unmarshal content</value></testXMLUnmarshaler>`,
expected: testXMLUnmarshaler{
Object: testXMLStruct{
Value: "xml unmarshal content",
},
},
},
// Тесты для сложных типов через JSON
{
name: "struct",
obj: &testStruct{},
input: `{"name":"John","age":30}`,
expected: testStruct{
Name: "John",
Age: 30,
},
},
{
name: "map",
obj: &testMap{},
input: `{"a":1,"b":2}`,
expected: testMap{
"a": 1,
"b": 2,
},
},
{
name: "slice",
obj: &[]int{},
input: `[1,2,3]`,
expected: []int{
1, 2, 3,
},
},
{
name: "complex struct",
obj: &testComplexStruct{},
input: `{"Pointer":"test","Slice":[1,2,3],"Map":{"a":"b"}}`,
expected: testComplexStruct{
Pointer: func() *string { s := "test"; return &s }(),
Slice: []int{1, 2, 3},
Map: map[string]string{"a": "b"},
},
},
// Тесты для инициализации
{
name: "initializer",
obj: &testInitializer{},
input: "{}",
expected: testInitializer{
init: true,
},
},
// Негативные тесты
{
name: "not a pointer",
obj: "not a pointer",
input: "test",
expectError: true,
},
{
name: "nil pointer",
obj: (*string)(nil),
input: "test",
expectError: true,
},
{
name: "invalid int",
obj: new(int),
input: "invalid",
expectError: true,
},
{
name: "invalid bool",
obj: new(bool),
input: "invalid",
expectError: true,
},
{
name: "invalid duration",
obj: new(time.Duration),
input: "invalid",
expectError: true,
},
{
name: "invalid time",
obj: new(time.Time),
input: "invalid",
expectError: true,
},
{
name: "unsupported type",
obj: new(func()),
input: "test",
expectError: true,
},
{
name: "unsupported JSON",
obj: new(testStruct),
input: `{"name":"John","age":"invalid"}`,
expectError: true,
},
{
name: "empty string",
obj: new(string),
input: "",
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := cast.StringDecode(tt.obj, tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Сравнение результатов
result := reflect.ValueOf(tt.obj).Elem().Interface()
if !reflect.DeepEqual(result, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, result)
}
})
}
// Тест для проверки обработки ошибок в интерфейсах
t.Run("error in interface", func(t *testing.T) {
errUnmarshaler := &errorTextUnmarshaler{err: errors.New("unmarshal error")}
err := cast.StringDecode(errUnmarshaler, "test")
if err == nil {
t.Fatal("expected error but got nil")
}
if err.Error() != "unmarshal error" {
t.Errorf("unexpected error: %v", err)
}
})
// Тест для проверки обработки ошибок в JSON unmarshal
t.Run("error in json unmarshal", func(t *testing.T) {
var s testStruct
err := cast.StringDecode(&s, `{"name":"John","age":"invalid"}`)
if err == nil {
t.Fatal("expected error but got nil")
}
})
}
// Вспомогательные структуры для тестирования ошибок
type errorBinaryUnmarshaler struct {
err error
}
func (b *errorBinaryUnmarshaler) UnmarshalBinary(data []byte) error {
return b.err
}
type errorTextUnmarshaler struct {
err error
}
func (t *errorTextUnmarshaler) UnmarshalText(text []byte) error {
return t.err
}
type errorJSONUnmarshaler struct {
err error
}
func (j *errorJSONUnmarshaler) UnmarshalJSON(data []byte) error {
return j.err
}
type errorXMLUnmarshaler struct {
err error
}
func (x *errorXMLUnmarshaler) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
return x.err
}
func TestStrTo(t *testing.T) {
tests := []struct {
name string
input string
expected any
expectError bool
}{
// Базовые типы
{
name: "string",
input: "test",
expected: "test",
},
{
name: "int",
input: "42",
expected: 42,
},
{
name: "int8",
input: "127",
expected: int8(127),
},
{
name: "bool",
input: "true",
expected: true,
},
{
name: "duration",
input: "2s",
expected: 2 * time.Second,
},
{
name: "time",
input: time.Now().UTC().Truncate(time.Second).Format(time.RFC3339),
expected: time.Now().UTC().Truncate(time.Second),
},
// Пустая строка
{
name: "empty string",
input: "",
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Используем рефлексию для создания обобщенного вызова
result := reflect.New(reflect.TypeOf(tt.expected)).Elem().Interface()
switch result.(type) {
case string:
val, err := cast.StrTo[string](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if val != tt.expected {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
case int:
val, err := cast.StrTo[int](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if val != tt.expected {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
case int8:
val, err := cast.StrTo[int8](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if val != tt.expected {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
case bool:
val, err := cast.StrTo[bool](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if val != tt.expected {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
case time.Duration:
val, err := cast.StrTo[time.Duration](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if val != tt.expected {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
case time.Time:
val, err := cast.StrTo[time.Time](tt.input)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Сравниваем без наносекунд, так как time.Parse может их потерять
if !val.Truncate(time.Second).Equal(tt.expected.(time.Time).Truncate(time.Second)) {
t.Errorf("result mismatch\nexpected: %v\nactual: %v", tt.expected, val)
}
default:
t.Fatalf("unsupported test type: %T", tt.expected)
}
})
}
}
func TestStrToSlice(t *testing.T) {
tests := []struct {
name string
input string
sep string
expected any
expectError bool
}{
// Тесты для строк
{
name: "string slice",
input: "a,b,c",
sep: ",",
expected: []string{"a", "b", "c"},
},
{
name: "empty string slice",
input: "",
sep: ",",
expected: []string(nil),
},
// Тесты для чисел
{
name: "int slice",
input: "1,2,3",
sep: ",",
expected: []int{1, 2, 3},
},
{
name: "float slice",
input: "1.1,2.2,3.3",
sep: ",",
expected: []float64{1.1, 2.2, 3.3},
},
// Тесты для bool
{
name: "bool slice",
input: "true,false,true",
sep: ",",
expected: []bool{true, false, true},
},
// Тесты для времени
{
name: "duration slice",
input: fmt.Sprintf("%s,%s,%s", "1s", "2s", "3s"),
sep: ",",
expected: []time.Duration{
1 * time.Second,
2 * time.Second,
3 * time.Second,
},
},
// Негативные тесты
{
name: "invalid int slice",
input: "1,invalid,3",
sep: ",",
expectError: true,
expected: []int{},
},
{
name: "custom separator",
input: "a|b|c",
sep: "|",
expected: []string{"a", "b", "c"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Используем рефлексию для определения типа слайса
sliceType := reflect.TypeOf(tt.expected)
elemType := sliceType.Elem()
// Выполняем преобразование
switch elemType.Kind() {
case reflect.String:
val, err := cast.StrToSlice[string](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
case reflect.Int:
val, err := cast.StrToSlice[int](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
case reflect.Int64:
val, err := cast.StrToSlice[time.Duration](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
case reflect.Float64:
val, err := cast.StrToSlice[float64](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
case reflect.Bool:
val, err := cast.StrToSlice[bool](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
case reflect.Struct:
if elemType == reflect.TypeOf(time.Duration(0)) {
val, err := cast.StrToSlice[time.Duration](tt.input, tt.sep)
if tt.expectError {
if err == nil {
t.Fatal("expected error but got nil")
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(val, tt.expected) {
t.Errorf("result mismatch\nexpected: %#v\nactual: %#v", tt.expected, val)
}
}
default:
t.Fatalf("unsupported test type: %T", tt.expected)
}
})
}
}