Debian Codegraph @

docstore/driver/codec_test.go

raw
1 // Copyright 2019 The Go Cloud Development Kit 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 // https://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 driver
16
17 import (
18 "errors"
19 "fmt"
20 "reflect"
21 "testing"
22 "time"
23
24 "github.com/google/go-cmp/cmp"
25 "gocloud.dev/gcerrors"
26 "gocloud.dev/internal/gcerr"
27 "google.golang.org/protobuf/proto"
28 tspb "google.golang.org/protobuf/types/known/timestamppb"
29 )
30
31 type myString string
32
33 type te struct{ X byte }
34
35 func (e te) MarshalText() ([]byte, error) {
36 return []byte{e.X}, nil
37 }
38
39 func (e *te) UnmarshalText(b []byte) error {
40 if len(b) != 1 {
41 return errors.New("te.UnmarshalText: need exactly 1 byte")
42 }
43 e.X = b[0]
44 return nil
45 }
46
47 type special int
48
49 func (special) MarshalBinary() ([]byte, error) { panic("should never be called") }
50 func (*special) UnmarshalBinary([]byte) error { panic("should never be called") }
51
52 type badSpecial int
53
54 type Embed1 struct {
55 E1 string
56 }
57 type Embed2 struct {
58 E2 string
59 }
60
61 type embed3 struct {
62 E3 string
63 }
64
65 type embed4 struct {
66 E4 string
67 }
68
69 type MyStruct struct {
70 A int
71 B *bool
72 C []*te
73 D []time.Time
74 T *tspb.Timestamp
75 Embed1
76 *Embed2
77 embed3
78 *embed4
79 Omit int `docstore:"-"`
80 OmitEmpty int `docstore:",omitempty"`
81 Rename int `docstore:"rename"`
82 }
83
84 func TestEncode(t *testing.T) {
85 var seven int32 = 7
86 var nullptr *int
87 tm := time.Now()
88 tmb, err := tm.MarshalBinary()
89 if err != nil {
90 t.Fatal(err)
91 }
92 tru := true
93 ts := &tspb.Timestamp{Seconds: 25, Nanos: 300}
94 tsb, err := proto.Marshal(ts)
95 if err != nil {
96 t.Fatal(err)
97 }
98 for _, test := range []struct {
99 in, want any
100 }{
101 {nil, nil},
102 {0, int64(0)},
103 {uint64(999), uint64(999)},
104 {float32(3.5), float64(3.5)},
105 {"", ""},
106 {"x", "x"},
107 {true, true},
108 {nullptr, nil},
109 {seven, int64(seven)},
110 {&seven, int64(seven)},
111 {[]byte{1, 2}, []byte{1, 2}},
112 {[2]byte{3, 4}, []any{uint64(3), uint64(4)}},
113 {[]int(nil), nil},
114 {[]int{}, []any{}},
115 {[]int{1, 2}, []any{int64(1), int64(2)}},
116 {
117 [][]string{{"a", "b"}, {"c", "d"}},
118 []any{
119 []any{"a", "b"},
120 []any{"c", "d"},
121 },
122 },
123 {[...]int{1, 2}, []any{int64(1), int64(2)}},
124 {[]any{nil, false}, []any{nil, false}},
125 {map[string]int(nil), nil},
126 {map[string]int{}, map[string]any{}},
127 {
128 map[string]int{"a": 1, "b": 2},
129 map[string]any{"a": int64(1), "b": int64(2)},
130 },
131 {tm, tmb},
132 {ts, tsb},
133 {te{'A'}, "A"},
134 {special(17), 17},
135 {myString("x"), "x"},
136 {[]myString{"x"}, []any{"x"}},
137 {map[myString]myString{"a": "x"}, map[string]any{"a": "x"}},
138 {
139 map[int]bool{17: true},
140 map[string]any{"17": true},
141 },
142 {
143 map[uint]bool{18: true},
144 map[string]any{"18": true},
145 },
146 {
147 map[te]bool{{'B'}: true},
148 map[string]any{"B": true},
149 },
150 {
151 MyStruct{
152 A: 1,
153 B: &tru,
154 C: []*te{{'T'}},
155 D: []time.Time{tm},
156 T: ts,
157 Embed1: Embed1{E1: "E1"},
158 Embed2: &Embed2{E2: "E2"},
159 embed3: embed3{E3: "E3"},
160 embed4: &embed4{E4: "E4"},
161 Omit: 3,
162 OmitEmpty: 4,
163 Rename: 5,
164 },
165 map[string]any{
166 "A": int64(1),
167 "B": true,
168 "C": []any{"T"},
169 "D": []any{tmb},
170 "T": tsb,
171 "E1": "E1",
172 "E2": "E2",
173 "E3": "E3",
174 "E4": "E4",
175 "OmitEmpty": int64(4),
176 "rename": int64(5),
177 },
178 },
179 {
180 MyStruct{},
181 map[string]any{
182 "A": int64(0),
183 "B": nil,
184 "C": nil,
185 "D": nil,
186 "T": nil,
187 "E1": "",
188 "E3": "",
189 "rename": int64(0),
190 },
191 },
192 } {
193 enc := &testEncoder{}
194 if err := Encode(reflect.ValueOf(test.in), enc); err != nil {
195 t.Fatal(err)
196 }
197 got := enc.val
198 if diff := cmp.Diff(got, test.want); diff != "" {
199 t.Errorf("%#v (got=-, want=+):\n%s", test.in, diff)
200 }
201 }
202 }
203
204 type badBinaryMarshaler struct{}
205
206 func (badBinaryMarshaler) MarshalBinary() ([]byte, error) { return nil, errors.New("bad") }
207 func (*badBinaryMarshaler) UnmarshalBinary([]byte) error { return errors.New("bad") }
208
209 type badTextMarshaler struct{}
210
211 func (badTextMarshaler) MarshalText() ([]byte, error) { return nil, errors.New("bad") }
212 func (*badTextMarshaler) UnmarshalText([]byte) error { return errors.New("bad") }
213
214 func TestEncodeErrors(t *testing.T) {
215 for _, test := range []struct {
216 desc string
217 val any
218 }{
219 {"MarshalBinary fails", badBinaryMarshaler{}},
220 {"MarshalText fails", badTextMarshaler{}},
221 {"bad type", make(chan int)},
222 {"bad type in list", []any{func() {}}},
223 {"bad type in map", map[string]any{"a": func() {}}},
224 {"bad type in struct", &struct{ C chan int }{}},
225 {"bad map key type", map[float32]int{1: 1}},
226 {"MarshalText for map key fails", map[badTextMarshaler]int{{}: 1}},
227 } {
228 enc := &testEncoder{}
229 if err := Encode(reflect.ValueOf(test.val), enc); err == nil {
230 t.Errorf("%s: got nil, want error", test.desc)
231 } else if c := gcerrors.Code(err); c != gcerrors.InvalidArgument {
232 t.Errorf("%s: got code %s, want InvalidArgument", test.desc, c)
233 }
234 }
235 }
236
237 type testEncoder struct {
238 val any
239 }
240
241 func (e *testEncoder) EncodeNil() { e.val = nil }
242 func (e *testEncoder) EncodeBool(x bool) { e.val = x }
243 func (e *testEncoder) EncodeString(x string) { e.val = x }
244 func (e *testEncoder) EncodeInt(x int64) { e.val = x }
245 func (e *testEncoder) EncodeUint(x uint64) { e.val = x }
246 func (e *testEncoder) EncodeFloat(x float64) { e.val = x }
247 func (e *testEncoder) EncodeBytes(x []byte) { e.val = x }
248
249 var (
250 typeOfSpecial = reflect.TypeFor[special]()
251 typeOfBadSpecial = reflect.TypeFor[badSpecial]()
252 )
253
254 func (e *testEncoder) EncodeSpecial(v reflect.Value) (bool, error) {
255 // special would normally encode as a []byte, because it implements BinaryMarshaler.
256 // Encode it as an int instead.
257 if v.Type() == typeOfSpecial {
258 e.val = int(v.Interface().(special))
259 return true, nil
260 }
261 return false, nil
262 }
263
264 func (e *testEncoder) ListIndex(int) { panic("impossible") }
265 func (e *testEncoder) MapKey(string) { panic("impossible") }
266
267 func (e *testEncoder) EncodeList(n int) Encoder {
268 s := make([]any, n)
269 e.val = s
270 return &listEncoder{s: s}
271 }
272
273 func (e *testEncoder) EncodeMap(n int) Encoder {
274 m := make(map[string]any, n)
275 e.val = m
276 return &mapEncoder{m: m}
277 }
278
279 type listEncoder struct {
280 s []any
281 testEncoder
282 }
283
284 func (e *listEncoder) ListIndex(i int) { e.s[i] = e.val }
285
286 type mapEncoder struct {
287 m map[string]any
288 testEncoder
289 }
290
291 func (e *mapEncoder) MapKey(k string) { e.m[k] = e.val }
292
293 func TestDecode(t *testing.T) {
294 two := 2
295 tru := true
296 fa := false
297 ptru := &tru
298 pfa := &fa
299 tm := time.Now()
300 tmb, err := tm.MarshalBinary()
301 if err != nil {
302 t.Fatal(err)
303 }
304 ts := &tspb.Timestamp{Seconds: 25, Nanos: 300}
305 tsb, err := proto.Marshal(ts)
306 if err != nil {
307 t.Fatal(err)
308 }
309
310 for _, test := range []struct {
311 in any // pointer that will be set
312 val any // value to set it to
313 want any
314 exactMatch bool
315 }{
316 {new(any), nil, nil, true},
317 {new(int), int64(7), int(7), true},
318 {new(uint8), uint64(250), uint8(250), true},
319 {new(bool), true, true, true},
320 {new(string), "x", "x", true},
321 {new(float32), 4.25, float32(4.25), true},
322 {new(*int), int64(2), &two, true},
323 {new(*int), nil, (*int)(nil), true},
324 {new([]byte), []byte("foo"), []byte("foo"), true},
325 {new([]string), []any{"a", "b"}, []string{"a", "b"}, true},
326 {new([]**bool), []any{true, false}, []**bool{&ptru, &pfa}, true},
327 {&[1]int{1}, []any{2}, [1]int{2}, true},
328 {&[2]int{1, 2}, []any{3}, [2]int{3, 0}, true}, // zero extra elements
329 {&[]int{1, 2}, []any{3}, []int{3}, true}, // truncate slice
330 {
331 // extend slice
332 func() *[]int { s := make([]int, 1, 2); return &s }(),
333 []any{5, 6},
334 []int{5, 6},
335 true,
336 },
337 {
338 new(map[string]string),
339 map[string]any{"a": "b"},
340 map[string]string{"a": "b"},
341 true,
342 },
343 {
344 new(map[int]bool),
345 map[string]any{"17": true},
346 map[int]bool{17: true},
347 true,
348 },
349 {
350 new(map[te]bool),
351 map[string]any{"B": true},
352 map[te]bool{{'B'}: true},
353 true,
354 },
355 {
356 new(map[any]bool),
357 map[string]any{"B": true},
358 map[any]bool{"B": true},
359 true,
360 },
361 {
362 new(map[string][]bool),
363 map[string]any{
364 "a": []any{true, false},
365 "b": []any{false, true},
366 },
367 map[string][]bool{
368 "a": {true, false},
369 "b": {false, true},
370 },
371 true,
372 },
373 {new(special), 17, special(17), true},
374 {new(myString), "x", myString("x"), true},
375 {new([]myString), []any{"x"}, []myString{"x"}, true},
376 {new(time.Time), tmb, tm, true},
377 {new(*time.Time), tmb, &tm, true},
378 {new(*tspb.Timestamp), tsb, ts, true},
379 {new([]time.Time), []any{tmb}, []time.Time{tm}, true},
380 {new([]*time.Time), []any{tmb}, []*time.Time{&tm}, true},
381 {
382 new(map[myString]myString),
383 map[string]any{"a": "x"},
384 map[myString]myString{"a": "x"},
385 true,
386 },
387 {
388 new(map[string]time.Time),
389 map[string]any{"t": tmb},
390 map[string]time.Time{"t": tm},
391 true,
392 },
393 {
394 new(map[string]*time.Time),
395 map[string]any{"t": tmb},
396 map[string]*time.Time{"t": &tm},
397 true,
398 },
399 {new(te), "A", te{'A'}, true},
400 {new(**te), "B", func() **te { x := &te{'B'}; return &x }(), true},
401
402 {
403 &MyStruct{embed4: &embed4{}},
404 map[string]any{
405 "A": int64(1),
406 "B": true,
407 "C": []any{"T"},
408 "D": []any{tmb},
409 "T": tsb,
410 "E1": "E1",
411 "E2": "E2",
412 "E3": "E3",
413 "E4": "E4",
414 },
415 MyStruct{
416 A: 1, B: &tru, C: []*te{{'T'}}, D: []time.Time{tm}, T: ts,
417 Embed1: Embed1{E1: "E1"},
418 Embed2: &Embed2{E2: "E2"},
419 embed3: embed3{E3: "E3"},
420 embed4: &embed4{E4: "E4"},
421 },
422 true,
423 },
424 {
425 &MyStruct{embed4: &embed4{}},
426 map[string]any{
427 "a": int64(1),
428 "b": true,
429 "c": []any{"T"},
430 "d": []any{tmb},
431 "t": tsb,
432 "e1": "E1",
433 "e2": "E2",
434 "e3": "E3",
435 "e4": "E4",
436 },
437 MyStruct{
438 A: 1, B: &tru, C: []*te{{'T'}}, D: []time.Time{tm}, T: ts,
439 Embed1: Embed1{E1: "E1"},
440 Embed2: &Embed2{E2: "E2"},
441 embed3: embed3{E3: "E3"},
442 embed4: &embed4{E4: "E4"},
443 },
444 false,
445 },
446 } {
447 dec := &testDecoder{test.val, test.exactMatch}
448 if err := Decode(reflect.ValueOf(test.in).Elem(), dec); err != nil {
449 t.Fatalf("%T: %v", test.in, err)
450 }
451 got := reflect.ValueOf(test.in).Elem().Interface()
452 diff := cmp.Diff(got, test.want, cmp.Comparer(proto.Equal), cmp.AllowUnexported(MyStruct{}))
453 if diff != "" {
454 t.Errorf("%T (got=-, want=+): %s", test.in, diff)
455 }
456 }
457 }
458
459 func TestDecodeErrors(t *testing.T) {
460 for _, test := range []struct {
461 desc string
462 in, val any
463 }{
464 {
465 "bad type",
466 new(int),
467 "foo",
468 },
469 {
470 "bad type in list",
471 new([]int),
472 []any{1, "foo"},
473 },
474 {
475 "array too short",
476 new([1]bool),
477 []any{true, false},
478 },
479 {
480 "bad map key type",
481 new(map[float64]any),
482 map[string]any{"a": 1},
483 },
484 {
485 "unknown struct field",
486 new(MyStruct),
487 map[string]any{"bad": 1},
488 },
489 {
490 "nil embedded, unexported pointer to struct",
491 new(MyStruct),
492 map[string]any{"E4": "E4"},
493 },
494 {
495 "int overflow",
496 new(int8),
497 257,
498 },
499 {
500 "uint overflow",
501 new(uint8),
502 uint(257),
503 },
504 {
505 "non-integral float (int)",
506 new(int),
507 1.5,
508 },
509 {
510 "non-integral float (uint)",
511 new(uint),
512 1.5,
513 },
514 {
515 "bad special",
516 new(badSpecial),
517 badSpecial(0),
518 },
519 {
520 "bad binary unmarshal",
521 new(badBinaryMarshaler),
522 []byte{1},
523 },
524 {
525 "binary unmarshal with non-byte slice",
526 new(time.Time),
527 1,
528 },
529 {
530 "bad text unmarshal",
531 new(badTextMarshaler),
532 "foo",
533 },
534 {
535 "text unmarshal with non-string",
536 new(badTextMarshaler),
537 1,
538 },
539 {
540 "bad text unmarshal in map key",
541 new(map[badTextMarshaler]int),
542 map[string]any{"a": 1},
543 },
544 {
545 "bad int map key",
546 new(map[int]int),
547 map[string]any{"a": 1},
548 },
549 {
550 "overflow in int map key",
551 new(map[int8]int),
552 map[string]any{"256": 1},
553 },
554 {
555 "bad uint map key",
556 new(map[uint]int),
557 map[string]any{"a": 1},
558 },
559 {
560 "overflow in uint map key",
561 new(map[uint8]int),
562 map[string]any{"256": 1},
563 },
564 {
565 "case mismatch when decoding with exact match",
566 &MyStruct{embed4: &embed4{}},
567 map[string]any{
568 "a": int64(1),
569 "b": true,
570 "e1": "E1",
571 "e2": "E2",
572 },
573 },
574 } {
575 dec := &testDecoder{test.val, true}
576 err := Decode(reflect.ValueOf(test.in).Elem(), dec)
577 if e, ok := err.(*gcerr.Error); !ok || err == nil || e.Code != gcerr.InvalidArgument {
578 t.Errorf("%s: got %v, want InvalidArgument Error", test.desc, err)
579 }
580 }
581 }
582
583 func TestDecodeFail(t *testing.T) {
584 // Verify that failure to decode a value results in an error.
585 for _, in := range []any{
586 new(any), new(bool), new(string), new(int), new(uint), new(float32),
587 new([]byte), new([]int), new(map[string]any),
588 } {
589 dec := &failDecoder{}
590 err := Decode(reflect.ValueOf(in).Elem(), dec)
591 if e, ok := err.(*gcerr.Error); !ok || err == nil || e.Code != gcerr.InvalidArgument {
592 t.Errorf("%T: got %v, want InvalidArgument Error", in, err)
593 }
594 }
595 }
596
597 type testDecoder struct {
598 val any // assume encoded by testEncoder.
599 exactMatch bool
600 }
601
602 func (d testDecoder) String() string {
603 return fmt.Sprintf("%+v of type %T", d.val, d.val)
604 }
605
606 func (d testDecoder) AsNull() bool {
607 return d.val == nil
608 }
609
610 func (d testDecoder) AsBool() (bool, bool) { x, ok := d.val.(bool); return x, ok }
611 func (d testDecoder) AsString() (string, bool) { x, ok := d.val.(string); return x, ok }
612
613 func (d testDecoder) AsInt() (int64, bool) {
614 switch v := d.val.(type) {
615 case int64:
616 return v, true
617 case int:
618 return int64(v), true
619 default:
620 return 0, false
621 }
622 }
623
624 func (d testDecoder) AsUint() (uint64, bool) {
625 switch v := d.val.(type) {
626 case uint64:
627 return v, true
628 case uint:
629 return uint64(v), true
630 default:
631 return 0, false
632 }
633 }
634
635 func (d testDecoder) AsFloat() (float64, bool) { x, ok := d.val.(float64); return x, ok }
636 func (d testDecoder) AsBytes() ([]byte, bool) { x, ok := d.val.([]byte); return x, ok }
637
638 func (d testDecoder) ListLen() (int, bool) {
639 l, ok := d.val.([]any)
640 if !ok {
641 return 0, false
642 }
643 return len(l), true
644 }
645
646 func (d testDecoder) DecodeList(f func(i int, vd Decoder) bool) {
647 for i, v := range d.val.([]any) {
648 if !f(i, testDecoder{v, d.exactMatch}) {
649 break
650 }
651 }
652 }
653
654 func (d testDecoder) MapLen() (int, bool) {
655 if m, ok := d.val.(map[string]any); ok {
656 return len(m), true
657 }
658 return 0, false
659 }
660
661 func (d testDecoder) DecodeMap(f func(key string, vd Decoder, exactMatch bool) bool) {
662 for k, v := range d.val.(map[string]any) {
663 if !f(k, testDecoder{v, d.exactMatch}, d.exactMatch) {
664 break
665 }
666 }
667 }
668
669 func (d testDecoder) AsInterface() (any, error) {
670 return d.val, nil
671 }
672
673 func (d testDecoder) AsSpecial(v reflect.Value) (bool, any, error) {
674 switch v.Type() {
675 case typeOfSpecial:
676 return true, special(d.val.(int)), nil
677 case typeOfBadSpecial:
678 return true, nil, errors.New("bad special")
679 default:
680 return false, nil, nil
681 }
682 }
683
684 // All of failDecoder's methods return failure.
685 type failDecoder struct{}
686
687 func (failDecoder) String() string { return "failDecoder" }
688 func (failDecoder) AsNull() bool { return false }
689 func (failDecoder) AsBool() (bool, bool) { return false, false }
690 func (failDecoder) AsString() (string, bool) { return "", false }
691 func (failDecoder) AsInt() (int64, bool) { return 0, false }
692 func (failDecoder) AsUint() (uint64, bool) { return 0, false }
693 func (failDecoder) AsFloat() (float64, bool) { return 0, false }
694 func (failDecoder) AsBytes() ([]byte, bool) { return nil, false }
695 func (failDecoder) ListLen() (int, bool) { return 0, false }
696 func (failDecoder) DecodeList(func(i int, vd Decoder) bool) { panic("impossible") }
697 func (failDecoder) MapLen() (int, bool) { return 0, false }
698 func (failDecoder) DecodeMap(func(string, Decoder, bool) bool) { panic("impossible") }
699 func (failDecoder) AsSpecial(v reflect.Value) (bool, any, error) { return false, nil, nil }
700 func (failDecoder) AsInterface() (any, error) { return nil, errors.New("fail") }