forked from domodwyer/mgo
-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathbson_test.go
2039 lines (1759 loc) · 58.5 KB
/
bson_test.go
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// BSON library for Go
//
// Copyright (c) 2010-2012 - Gustavo Niemeyer <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// gobson - BSON library for Go.
package bson_test
import (
"encoding/binary"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"math/rand"
"net/url"
"reflect"
"strings"
"testing"
"time"
"github.com/globalsign/mgo/bson"
. "gopkg.in/check.v1"
)
func TestAll(t *testing.T) {
TestingT(t)
}
type S struct{}
var _ = Suite(&S{})
// Wrap up the document elements contained in data, prepending the int32
// length of the data, and appending the '\x00' value closing the document.
func wrapInDoc(data string) string {
result := make([]byte, len(data)+5)
binary.LittleEndian.PutUint32(result, uint32(len(result)))
copy(result[4:], []byte(data))
return string(result)
}
func makeZeroDoc(value interface{}) (zero interface{}) {
v := reflect.ValueOf(value)
t := v.Type()
switch t.Kind() {
case reflect.Map:
mv := reflect.MakeMap(t)
zero = mv.Interface()
case reflect.Ptr:
pv := reflect.New(v.Type().Elem())
zero = pv.Interface()
case reflect.Slice, reflect.Int, reflect.Int64, reflect.Struct:
zero = reflect.New(t).Interface()
default:
panic("unsupported doc type: " + t.Name())
}
return zero
}
func testUnmarshal(c *C, data string, obj interface{}) {
zero := makeZeroDoc(obj)
err := bson.Unmarshal([]byte(data), zero)
c.Assert(err, IsNil)
c.Assert(zero, DeepEquals, obj)
testUnmarshalRawElements(c, []byte(data))
}
func testUnmarshalRawElements(c *C, data []byte) {
elems := []bson.RawDocElem{}
err := bson.Unmarshal(data, &elems)
c.Assert(err, IsNil)
for _, elem := range elems {
if elem.Value.Kind == bson.ElementDocument || elem.Value.Kind == bson.ElementArray {
testUnmarshalRawElements(c, elem.Value.Data)
}
}
}
type testItemType struct {
obj interface{}
data string
}
// --------------------------------------------------------------------------
// Samples from bsonspec.org:
var sampleItems = []testItemType{
{bson.M{"hello": "world"},
"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"},
{bson.M{"BSON": []interface{}{"awesome", float64(5.05), 1986}},
"1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" +
"awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"},
{bson.M{"slice": []uint8{1, 2}},
"\x13\x00\x00\x00\x05slice\x00\x02\x00\x00\x00\x00\x01\x02\x00"},
{bson.M{"slice": []byte{1, 2}},
"\x13\x00\x00\x00\x05slice\x00\x02\x00\x00\x00\x00\x01\x02\x00"},
}
func (s *S) TestMarshalSampleItems(c *C) {
for i, item := range sampleItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, item.data, Commentf("Failed on item %d", i))
}
}
func (s *S) TestUnmarshalSampleItems(c *C) {
for i, item := range sampleItems {
value := bson.M{}
err := bson.Unmarshal([]byte(item.data), value)
c.Assert(err, IsNil)
c.Assert(value, DeepEquals, item.obj, Commentf("Failed on item %d", i))
}
}
// --------------------------------------------------------------------------
// Every type, ordered by the type flag. These are not wrapped with the
// length and last \x00 from the document. wrapInDoc() computes them.
// Note that all of them should be supported as two-way conversions.
var allItems = []testItemType{
{bson.M{},
""},
{bson.M{"_": float64(5.05)},
"\x01_\x00333333\x14@"},
{bson.M{"_": "yo"},
"\x02_\x00\x03\x00\x00\x00yo\x00"},
{bson.M{"_": bson.M{"a": true}},
"\x03_\x00\x09\x00\x00\x00\x08a\x00\x01\x00"},
{bson.M{"_": []interface{}{true, false}},
"\x04_\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"},
{bson.M{"_": []byte("yo")},
"\x05_\x00\x02\x00\x00\x00\x00yo"},
{bson.M{"_": bson.Binary{Kind: 0x80, Data: []byte("udef")}},
"\x05_\x00\x04\x00\x00\x00\x80udef"},
{bson.M{"_": bson.Undefined}, // Obsolete, but still seen in the wild.
"\x06_\x00"},
{bson.M{"_": bson.ObjectId("0123456789ab")},
"\x07_\x000123456789ab"},
{bson.M{"_": bson.DBPointer{Namespace: "testnamespace", Id: bson.ObjectId("0123456789ab")}},
"\x0C_\x00\x0e\x00\x00\x00testnamespace\x000123456789ab"},
{bson.M{"_": false},
"\x08_\x00\x00"},
{bson.M{"_": true},
"\x08_\x00\x01"},
{bson.M{"_": time.Unix(0, 258e6).UTC()}, // Note the NS <=> MS conversion.
"\x09_\x00\x02\x01\x00\x00\x00\x00\x00\x00"},
{bson.M{"_": nil},
"\x0A_\x00"},
{bson.M{"_": bson.RegEx{Pattern: "ab", Options: "cd"}},
"\x0B_\x00ab\x00cd\x00"},
{bson.M{"_": bson.JavaScript{Code: "code", Scope: nil}},
"\x0D_\x00\x05\x00\x00\x00code\x00"},
{bson.M{"_": bson.Symbol("sym")},
"\x0E_\x00\x04\x00\x00\x00sym\x00"},
{bson.M{"_": bson.JavaScript{Code: "code", Scope: bson.M{"": nil}}},
"\x0F_\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" +
"\x07\x00\x00\x00\x0A\x00\x00"},
{bson.M{"_": 258},
"\x10_\x00\x02\x01\x00\x00"},
{bson.M{"_": bson.MongoTimestamp(258)},
"\x11_\x00\x02\x01\x00\x00\x00\x00\x00\x00"},
{bson.M{"_": int64(258)},
"\x12_\x00\x02\x01\x00\x00\x00\x00\x00\x00"},
{bson.M{"_": int64(258 << 32)},
"\x12_\x00\x00\x00\x00\x00\x02\x01\x00\x00"},
{bson.M{"_": bson.MaxKey},
"\x7F_\x00"},
{bson.M{"_": bson.MinKey},
"\xFF_\x00"},
}
func (s *S) TestMarshalAllItems(c *C) {
for i, item := range allItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc(item.data), Commentf("Failed on item %d: %#v", i, item))
}
}
func (s *S) TestUnmarshalAllItems(c *C) {
for i, item := range allItems {
value := bson.M{}
err := bson.Unmarshal([]byte(wrapInDoc(item.data)), value)
c.Assert(err, IsNil)
c.Assert(value, DeepEquals, item.obj, Commentf("Failed on item %d: %#v", i, item))
}
}
func (s *S) TestUnmarshalRawAllItems(c *C) {
for i, item := range allItems {
if len(item.data) == 0 {
continue
}
value := item.obj.(bson.M)["_"]
if value == nil {
continue
}
pv := reflect.New(reflect.ValueOf(value).Type())
raw := bson.Raw{Kind: item.data[0], Data: []byte(item.data[3:])}
c.Logf("Unmarshal raw: %#v, %#v", raw, pv.Interface())
err := raw.Unmarshal(pv.Interface())
c.Assert(err, IsNil)
c.Assert(pv.Elem().Interface(), DeepEquals, value, Commentf("Failed on item %d: %#v", i, item))
}
}
func (s *S) TestUnmarshalRawIncompatible(c *C) {
raw := bson.Raw{Kind: 0x08, Data: []byte{0x01}} // true
err := raw.Unmarshal(&struct{}{})
c.Assert(err, ErrorMatches, "BSON kind 0x08 isn't compatible with type struct \\{\\}")
}
func (s *S) TestUnmarshalZeroesStruct(c *C) {
data, err := bson.Marshal(bson.M{"b": 2})
c.Assert(err, IsNil)
type T struct{ A, B int }
v := T{A: 1}
err = bson.Unmarshal(data, &v)
c.Assert(err, IsNil)
c.Assert(v.A, Equals, 0)
c.Assert(v.B, Equals, 2)
}
func (s *S) TestUnmarshalZeroesMap(c *C) {
data, err := bson.Marshal(bson.M{"b": 2})
c.Assert(err, IsNil)
m := bson.M{"a": 1}
err = bson.Unmarshal(data, &m)
c.Assert(err, IsNil)
c.Assert(m, DeepEquals, bson.M{"b": 2})
}
func (s *S) TestUnmarshalNonNilInterface(c *C) {
data, err := bson.Marshal(bson.M{"b": 2})
c.Assert(err, IsNil)
m := bson.M{"a": 1}
var i interface{}
i = m
err = bson.Unmarshal(data, &i)
c.Assert(err, IsNil)
c.Assert(i, DeepEquals, bson.M{"b": 2})
c.Assert(m, DeepEquals, bson.M{"a": 1})
}
func (s *S) TestMarshalBuffer(c *C) {
buf := make([]byte, 0, 256)
data, err := bson.MarshalBuffer(bson.M{"a": 1}, buf)
c.Assert(err, IsNil)
c.Assert(data, DeepEquals, buf[:len(data)])
}
func (s *S) TestPtrInline(c *C) {
cases := []struct {
In interface{}
Out bson.M
}{
{
In: inlinePtrStruct{A: 1, MStruct: &MStruct{M: 3}},
Out: bson.M{"a": 1, "m": 3},
},
{ // go deeper
In: inlinePtrPtrStruct{B: 10, inlinePtrStruct: &inlinePtrStruct{A: 20, MStruct: &MStruct{M: 30}}},
Out: bson.M{"b": 10, "a": 20, "m": 30},
},
{
// nil embed struct
In: &inlinePtrStruct{A: 3},
Out: bson.M{"a": 3},
},
{
// nil embed struct
In: &inlinePtrPtrStruct{B: 5},
Out: bson.M{"b": 5},
},
}
for _, cs := range cases {
data, err := bson.Marshal(cs.In)
c.Assert(err, IsNil)
var dataBSON bson.M
err = bson.Unmarshal(data, &dataBSON)
c.Assert(err, IsNil)
c.Assert(dataBSON, DeepEquals, cs.Out)
}
}
// --------------------------------------------------------------------------
// Some one way marshaling operations which would unmarshal differently.
var oneWayMarshalItems = []testItemType{
// These are being passed as pointers, and will unmarshal as values.
{bson.M{"": &bson.Binary{Kind: 0x02, Data: []byte("old")}},
"\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"},
{bson.M{"": &bson.Binary{Kind: 0x80, Data: []byte("udef")}},
"\x05\x00\x04\x00\x00\x00\x80udef"},
{bson.M{"": &bson.RegEx{Pattern: "ab", Options: "cd"}},
"\x0B\x00ab\x00cd\x00"},
{bson.M{"": &bson.JavaScript{Code: "code", Scope: nil}},
"\x0D\x00\x05\x00\x00\x00code\x00"},
{bson.M{"": &bson.JavaScript{Code: "code", Scope: bson.M{"": nil}}},
"\x0F\x00\x14\x00\x00\x00\x05\x00\x00\x00code\x00" +
"\x07\x00\x00\x00\x0A\x00\x00"},
// There's no float32 type in BSON. Will encode as a float64.
{bson.M{"": float32(5.05)},
"\x01\x00\x00\x00\x00@33\x14@"},
// The array will be unmarshaled as a slice instead.
{bson.M{"": [2]bool{true, false}},
"\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"},
// The typed slice will be unmarshaled as []interface{}.
{bson.M{"": []bool{true, false}},
"\x04\x00\r\x00\x00\x00\x080\x00\x01\x081\x00\x00\x00"},
// Will unmarshal as a []byte.
{bson.M{"": bson.Binary{Kind: 0x00, Data: []byte("yo")}},
"\x05\x00\x02\x00\x00\x00\x00yo"},
{bson.M{"": bson.Binary{Kind: 0x02, Data: []byte("old")}},
"\x05\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"},
// No way to preserve the type information here. We might encode as a zero
// value, but this would mean that pointer values in structs wouldn't be
// able to correctly distinguish between unset and set to the zero value.
{bson.M{"": (*byte)(nil)},
"\x0A\x00"},
// No int types smaller than int32 in BSON. Could encode this as a char,
// but it would still be ambiguous, take more, and be awkward in Go when
// loaded without typing information.
{bson.M{"": byte(8)},
"\x10\x00\x08\x00\x00\x00"},
// There are no unsigned types in BSON. Will unmarshal as int32 or int64.
{bson.M{"": uint32(258)},
"\x10\x00\x02\x01\x00\x00"},
{bson.M{"": uint64(258)},
"\x12\x00\x02\x01\x00\x00\x00\x00\x00\x00"},
{bson.M{"": uint64(258 << 32)},
"\x12\x00\x00\x00\x00\x00\x02\x01\x00\x00"},
// This will unmarshal as int.
{bson.M{"": int32(258)},
"\x10\x00\x02\x01\x00\x00"},
// That's a special case. The unsigned value is too large for an int32,
// so an int64 is used instead.
{bson.M{"": uint32(1<<32 - 1)},
"\x12\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"},
{bson.M{"": uint(1<<32 - 1)},
"\x12\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"},
}
func (s *S) TestOneWayMarshalItems(c *C) {
for i, item := range oneWayMarshalItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc(item.data),
Commentf("Failed on item %d", i))
}
}
// --------------------------------------------------------------------------
// Some ops marshaling operations which would encode []uint8 or []byte in array.
var arrayOpsMarshalItems = []testItemType{
{bson.M{"_": bson.M{"$in": []uint8{1, 2}}},
"\x03_\x00\x1d\x00\x00\x00\x04$in\x00\x13\x00\x00\x00\x100\x00\x01\x00\x00\x00\x101\x00\x02\x00\x00\x00\x00\x00"},
{bson.M{"_": bson.M{"$nin": []uint8{1, 2}}},
"\x03_\x00\x1e\x00\x00\x00\x04$nin\x00\x13\x00\x00\x00\x100\x00\x01\x00\x00\x00\x101\x00\x02\x00\x00\x00\x00\x00"},
{bson.M{"_": bson.M{"$all": []uint8{1, 2}}},
"\x03_\x00\x1e\x00\x00\x00\x04$all\x00\x13\x00\x00\x00\x100\x00\x01\x00\x00\x00\x101\x00\x02\x00\x00\x00\x00\x00"},
}
func (s *S) TestArrayOpsMarshalItems(c *C) {
for i, item := range arrayOpsMarshalItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc(item.data),
Commentf("Failed on item %d", i))
}
}
// --------------------------------------------------------------------------
// Two-way tests for user-defined structures using the samples
// from bsonspec.org.
type specSample1 struct {
Hello string
}
type specSample2 struct {
BSON []interface{} `bson:"BSON"`
}
var structSampleItems = []testItemType{
{&specSample1{"world"},
"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"},
{&specSample2{[]interface{}{"awesome", float64(5.05), 1986}},
"1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00\x00" +
"awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00\x00\x00\x00"},
}
func (s *S) TestMarshalStructSampleItems(c *C) {
for i, item := range structSampleItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, item.data,
Commentf("Failed on item %d", i))
}
}
func (s *S) TestUnmarshalStructSampleItems(c *C) {
for _, item := range structSampleItems {
testUnmarshal(c, item.data, item.obj)
}
}
func (s *S) Test64bitInt(c *C) {
var i int64 = (1 << 31)
if int(i) > 0 {
data, err := bson.Marshal(bson.M{"i": int(i)})
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc("\x12i\x00\x00\x00\x00\x80\x00\x00\x00\x00"))
var result struct{ I int }
err = bson.Unmarshal(data, &result)
c.Assert(err, IsNil)
c.Assert(int64(result.I), Equals, i)
}
}
// --------------------------------------------------------------------------
// Generic two-way struct marshaling tests.
type prefixPtr string
type prefixVal string
func (t *prefixPtr) GetBSON() (interface{}, error) {
if t == nil {
return nil, nil
}
return "foo-" + string(*t), nil
}
func (t *prefixPtr) SetBSON(raw bson.Raw) error {
var s string
if raw.Kind == 0x0A {
return bson.ErrSetZero
}
if err := raw.Unmarshal(&s); err != nil {
return err
}
if !strings.HasPrefix(s, "foo-") {
return errors.New("Prefix not found: " + s)
}
*t = prefixPtr(s[4:])
return nil
}
func (t prefixVal) GetBSON() (interface{}, error) {
return "foo-" + string(t), nil
}
func (t *prefixVal) SetBSON(raw bson.Raw) error {
var s string
if raw.Kind == 0x0A {
return bson.ErrSetZero
}
if err := raw.Unmarshal(&s); err != nil {
return err
}
if !strings.HasPrefix(s, "foo-") {
return errors.New("Prefix not found: " + s)
}
*t = prefixVal(s[4:])
return nil
}
var bytevar = byte(8)
var byteptr = &bytevar
var prefixptr = prefixPtr("bar")
var prefixval = prefixVal("bar")
var structItems = []testItemType{
{&struct{ Ptr *byte }{nil},
"\x0Aptr\x00"},
{&struct{ Ptr *byte }{&bytevar},
"\x10ptr\x00\x08\x00\x00\x00"},
{&struct{ Ptr **byte }{&byteptr},
"\x10ptr\x00\x08\x00\x00\x00"},
{&struct{ Byte byte }{8},
"\x10byte\x00\x08\x00\x00\x00"},
{&struct{ Byte byte }{0},
"\x10byte\x00\x00\x00\x00\x00"},
{&struct {
V byte `bson:"Tag"`
}{8},
"\x10Tag\x00\x08\x00\x00\x00"},
{&struct {
V *struct {
Byte byte
}
}{&struct{ Byte byte }{8}},
"\x03v\x00" + "\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00"},
{&struct{ priv byte }{}, ""},
// The order of the dumped fields should be the same in the struct.
{&struct{ A, C, B, D, F, E *byte }{},
"\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x0Ae\x00"},
{&struct{ V bson.Raw }{bson.Raw{Kind: 0x03, Data: []byte("\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00")}},
"\x03v\x00" + "\x0f\x00\x00\x00\x10byte\x00\b\x00\x00\x00\x00"},
{&struct{ V bson.Raw }{bson.Raw{Kind: 0x10, Data: []byte("\x00\x00\x00\x00")}},
"\x10v\x00" + "\x00\x00\x00\x00"},
// Byte arrays.
{&struct{ V [2]byte }{[2]byte{'y', 'o'}},
"\x05v\x00\x02\x00\x00\x00\x00yo"},
{&struct{ V prefixPtr }{prefixPtr("buzz")},
"\x02v\x00\x09\x00\x00\x00foo-buzz\x00"},
{&struct{ V *prefixPtr }{&prefixptr},
"\x02v\x00\x08\x00\x00\x00foo-bar\x00"},
{&struct{ V *prefixPtr }{nil},
"\x0Av\x00"},
{&struct{ V prefixVal }{prefixVal("buzz")},
"\x02v\x00\x09\x00\x00\x00foo-buzz\x00"},
{&struct{ V *prefixVal }{&prefixval},
"\x02v\x00\x08\x00\x00\x00foo-bar\x00"},
{&struct{ V *prefixVal }{nil},
"\x0Av\x00"},
}
func (s *S) TestMarshalStructItems(c *C) {
for i, item := range structItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc(item.data),
Commentf("Failed on item %d", i))
}
}
func (s *S) TestUnmarshalStructItems(c *C) {
for _, item := range structItems {
testUnmarshal(c, wrapInDoc(item.data), item.obj)
}
}
func (s *S) TestUnmarshalRawStructItems(c *C) {
for i, item := range structItems {
raw := bson.Raw{Kind: 0x03, Data: []byte(wrapInDoc(item.data))}
zero := makeZeroDoc(item.obj)
err := raw.Unmarshal(zero)
c.Assert(err, IsNil)
c.Assert(zero, DeepEquals, item.obj, Commentf("Failed on item %d: %#v", i, item))
}
}
func (s *S) TestUnmarshalRawNil(c *C) {
// Regression test: shouldn't try to nil out the pointer itself,
// as it's not settable.
raw := bson.Raw{Kind: 0x0A, Data: []byte{}}
err := raw.Unmarshal(&struct{}{})
c.Assert(err, IsNil)
}
// --------------------------------------------------------------------------
// One-way marshaling tests.
type dOnIface struct {
D interface{}
}
type ignoreField struct {
Before string
Ignore string `bson:"-"`
After string
}
var marshalItems = []testItemType{
// Ordered document dump. Will unmarshal as a dictionary by default.
{bson.D{{Name: "a", Value: nil}, {Name: "c", Value: nil}, {Name: "b", Value: nil}, {Name: "d", Value: nil}, {Name: "f", Value: nil}, {Name: "e", Value: true}},
"\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x08e\x00\x01"},
{MyD{{Name: "a", Value: nil}, {Name: "c", Value: nil}, {Name: "b", Value: nil}, {Name: "d", Value: nil}, {Name: "f", Value: nil}, {Name: "e", Value: true}},
"\x0Aa\x00\x0Ac\x00\x0Ab\x00\x0Ad\x00\x0Af\x00\x08e\x00\x01"},
{&dOnIface{bson.D{{Name: "a", Value: nil}, {Name: "c", Value: nil}, {Name: "b", Value: nil}, {Name: "d", Value: true}}},
"\x03d\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x0Ab\x00\x08d\x00\x01")},
{bson.RawD{{Name: "a", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "c", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "b", Value: bson.Raw{Kind: 0x08, Data: []byte{0x01}}}},
"\x0Aa\x00" + "\x0Ac\x00" + "\x08b\x00\x01"},
{MyRawD{{Name: "a", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "c", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "b", Value: bson.Raw{Kind: 0x08, Data: []byte{0x01}}}},
"\x0Aa\x00" + "\x0Ac\x00" + "\x08b\x00\x01"},
{&dOnIface{bson.RawD{{Name: "a", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "c", Value: bson.Raw{Kind: 0x0A, Data: nil}}, {Name: "b", Value: bson.Raw{Kind: 0x08, Data: []byte{0x01}}}}},
"\x03d\x00" + wrapInDoc("\x0Aa\x00"+"\x0Ac\x00"+"\x08b\x00\x01")},
{&ignoreField{"before", "ignore", "after"},
"\x02before\x00\a\x00\x00\x00before\x00\x02after\x00\x06\x00\x00\x00after\x00"},
// Marshalling a Raw document does nothing.
{bson.Raw{Kind: 0x03, Data: []byte(wrapInDoc("anything"))},
"anything"},
{bson.Raw{Data: []byte(wrapInDoc("anything"))},
"anything"},
}
func (s *S) TestMarshalOneWayItems(c *C) {
for _, item := range marshalItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, IsNil)
c.Assert(string(data), Equals, wrapInDoc(item.data))
}
}
// --------------------------------------------------------------------------
// One-way unmarshaling tests.
type intAlias int
var unmarshalItems = []testItemType{
// Field is private. Should not attempt to unmarshal it.
{&struct{ priv byte }{},
"\x10priv\x00\x08\x00\x00\x00"},
// Wrong casing. Field names are lowercased.
{&struct{ Byte byte }{},
"\x10Byte\x00\x08\x00\x00\x00"},
// Ignore non-existing field.
{&struct{ Byte byte }{9},
"\x10boot\x00\x08\x00\x00\x00" + "\x10byte\x00\x09\x00\x00\x00"},
// Do not unmarshal on ignored field.
{&ignoreField{"before", "", "after"},
"\x02before\x00\a\x00\x00\x00before\x00" +
"\x02-\x00\a\x00\x00\x00ignore\x00" +
"\x02after\x00\x06\x00\x00\x00after\x00"},
// Ignore unsuitable types silently.
{map[string]string{"str": "s"},
"\x02str\x00\x02\x00\x00\x00s\x00" + "\x10int\x00\x01\x00\x00\x00"},
{map[string][]int{"array": {5, 9}},
"\x04array\x00" + wrapInDoc("\x100\x00\x05\x00\x00\x00"+"\x021\x00\x02\x00\x00\x00s\x00"+"\x102\x00\x09\x00\x00\x00")},
// Wrong type. Shouldn't init pointer.
{&struct{ Str *byte }{},
"\x02str\x00\x02\x00\x00\x00s\x00"},
{&struct{ Str *struct{ Str string } }{},
"\x02str\x00\x02\x00\x00\x00s\x00"},
// Ordered document.
{&struct{ bson.D }{bson.D{{Name: "a", Value: nil}, {Name: "c", Value: nil}, {Name: "b", Value: nil}, {Name: "d", Value: true}}},
"\x03d\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x0Ab\x00\x08d\x00\x01")},
// Raw document.
{&bson.Raw{Kind: 0x03, Data: []byte(wrapInDoc("\x10byte\x00\x08\x00\x00\x00"))},
"\x10byte\x00\x08\x00\x00\x00"},
// RawD document.
{&struct{ bson.RawD }{bson.RawD{{Name: "a", Value: bson.Raw{Kind: 0x0A, Data: []byte{}}}, {Name: "c", Value: bson.Raw{Kind: 0x0A, Data: []byte{}}}, {Name: "b", Value: bson.Raw{Kind: 0x08, Data: []byte{0x01}}}}},
"\x03rawd\x00" + wrapInDoc("\x0Aa\x00\x0Ac\x00\x08b\x00\x01")},
// Decode old binary.
{bson.M{"_": []byte("old")},
"\x05_\x00\x07\x00\x00\x00\x02\x03\x00\x00\x00old"},
// Decode old binary without length. According to the spec, this shouldn't happen.
{bson.M{"_": []byte("old")},
"\x05_\x00\x03\x00\x00\x00\x02old"},
// Decode a doc within a doc in to a slice within a doc; shouldn't error
{&struct{ Foo []string }{},
"\x03\x66\x6f\x6f\x00\x05\x00\x00\x00\x00"},
// int key maps
{map[int]string{10: "s"},
"\x0210\x00\x02\x00\x00\x00s\x00"},
//// event if type is alias to int
{map[intAlias]string{10: "s"},
"\x0210\x00\x02\x00\x00\x00s\x00"},
}
func (s *S) TestUnmarshalOneWayItems(c *C) {
for _, item := range unmarshalItems {
testUnmarshal(c, wrapInDoc(item.data), item.obj)
}
}
func (s *S) TestUnmarshalNilInStruct(c *C) {
// Nil is the default value, so we need to ensure it's indeed being set.
b := byte(1)
v := &struct{ Ptr *byte }{&b}
err := bson.Unmarshal([]byte(wrapInDoc("\x0Aptr\x00")), v)
c.Assert(err, IsNil)
c.Assert(v, DeepEquals, &struct{ Ptr *byte }{nil})
}
// --------------------------------------------------------------------------
// Marshalling error cases.
type structWithDupKeys struct {
Name byte
Other byte `bson:"name"` // Tag should precede.
}
var marshalErrorItems = []testItemType{
{bson.M{"": uint64(1 << 63)},
"BSON has no uint64 type, and value is too large to fit correctly in an int64"},
{bson.M{"": bson.ObjectId("tooshort")},
"ObjectIDs must be exactly 12 bytes long \\(got 8\\)"},
{int64(123),
"Can't marshal int64 as a BSON document"},
{bson.M{"": 1i},
"Can't marshal complex128 in a BSON document"},
{&structWithDupKeys{},
"Duplicated key 'name' in struct bson_test.structWithDupKeys"},
{bson.Raw{Kind: 0xA, Data: []byte{}},
"Attempted to marshal Raw kind 10 as a document"},
{bson.Raw{Kind: 0x3, Data: []byte{}},
"Attempted to marshal empty Raw document"},
{bson.M{"w": bson.Raw{Kind: 0x3, Data: []byte{}}},
"Attempted to marshal empty Raw document"},
{&inlineDupName{1, struct{ A, B int }{2, 3}},
"Duplicated key 'a' in struct bson_test.inlineDupName"},
{&inlineDupMap{},
"Multiple ,inline maps in struct bson_test.inlineDupMap"},
{&inlineBadKeyMap{},
"Option ,inline needs a map with string keys in struct bson_test.inlineBadKeyMap"},
{&inlineMap{A: 1, M: map[string]interface{}{"a": 1}},
`Can't have key "a" in inlined map; conflicts with struct field`},
}
func (s *S) TestMarshalErrorItems(c *C) {
for _, item := range marshalErrorItems {
data, err := bson.Marshal(item.obj)
c.Assert(err, ErrorMatches, item.data)
c.Assert(data, IsNil)
}
}
// --------------------------------------------------------------------------
// Unmarshalling error cases.
type unmarshalErrorType struct {
obj interface{}
data string
error string
}
var unmarshalErrorItems = []unmarshalErrorType{
// Tag name conflicts with existing parameter.
{&structWithDupKeys{},
"\x10name\x00\x08\x00\x00\x00",
"Duplicated key 'name' in struct bson_test.structWithDupKeys"},
{nil,
"\xEEname\x00",
"Unknown element kind \\(0xEE\\)"},
{struct{ Name bool }{},
"\x10name\x00\x08\x00\x00\x00",
"unmarshal can't deal with struct values. Use a pointer"},
{123,
"\x10name\x00\x08\x00\x00\x00",
"unmarshal needs a map or a pointer to a struct"},
{nil,
"\x08\x62\x00\x02",
"encoded boolean must be 1 or 0, found 2"},
// Non-string and not numeric map key.
{map[bool]interface{}{true: 1},
"\x10true\x00\x01\x00\x00\x00",
"BSON map must have string or decimal keys. Got: map\\[bool\\]interface \\{\\}"},
}
func (s *S) TestUnmarshalErrorItems(c *C) {
for _, item := range unmarshalErrorItems {
data := []byte(wrapInDoc(item.data))
var value interface{}
switch reflect.ValueOf(item.obj).Kind() {
case reflect.Map, reflect.Ptr:
value = makeZeroDoc(item.obj)
case reflect.Invalid:
value = bson.M{}
default:
value = item.obj
}
err := bson.Unmarshal(data, value)
c.Assert(err, ErrorMatches, item.error)
}
}
type unmarshalRawErrorType struct {
obj interface{}
raw bson.Raw
error string
}
var unmarshalRawErrorItems = []unmarshalRawErrorType{
// Tag name conflicts with existing parameter.
{&structWithDupKeys{},
bson.Raw{Kind: 0x03, Data: []byte("\x10byte\x00\x08\x00\x00\x00")},
"Duplicated key 'name' in struct bson_test.structWithDupKeys"},
{&struct{}{},
bson.Raw{Kind: 0xEE, Data: []byte{}},
"Unknown element kind \\(0xEE\\)"},
{struct{ Name bool }{},
bson.Raw{Kind: 0x10, Data: []byte("\x08\x00\x00\x00")},
"raw Unmarshal can't deal with struct values. Use a pointer"},
{123,
bson.Raw{Kind: 0x10, Data: []byte("\x08\x00\x00\x00")},
"raw Unmarshal needs a map or a valid pointer"},
}
func (s *S) TestUnmarshalRawErrorItems(c *C) {
for i, item := range unmarshalRawErrorItems {
err := item.raw.Unmarshal(item.obj)
c.Assert(err, ErrorMatches, item.error, Commentf("Failed on item %d: %#v\n", i, item))
}
}
var corruptedData = []string{
"\x04\x00\x00\x00\x00", // Document shorter than minimum
"\x06\x00\x00\x00\x00", // Not enough data
"\x05\x00\x00", // Broken length
"\x05\x00\x00\x00\xff", // Corrupted termination
"\x0A\x00\x00\x00\x0Aooop\x00", // Unfinished C string
// Array end past end of string (s[2]=0x07 is correct)
wrapInDoc("\x04\x00\x09\x00\x00\x00\x0A\x00\x00"),
// Array end within string, but past acceptable.
wrapInDoc("\x04\x00\x08\x00\x00\x00\x0A\x00\x00"),
// Document end within string, but past acceptable.
wrapInDoc("\x03\x00\x08\x00\x00\x00\x0A\x00\x00"),
// String with corrupted end.
wrapInDoc("\x02\x00\x03\x00\x00\x00yo\xFF"),
// String with negative length (issue #116).
"\x0c\x00\x00\x00\x02x\x00\xff\xff\xff\xff\x00",
// String with zero length (must include trailing '\x00')
"\x0c\x00\x00\x00\x02x\x00\x00\x00\x00\x00\x00",
// Binary with negative length.
"\r\x00\x00\x00\x05x\x00\xff\xff\xff\xff\x00\x00",
}
func (s *S) TestUnmarshalMapDocumentTooShort(c *C) {
for _, data := range corruptedData {
err := bson.Unmarshal([]byte(data), bson.M{})
c.Assert(err, ErrorMatches, "Document is corrupted")
err = bson.Unmarshal([]byte(data), &struct{}{})
c.Assert(err, ErrorMatches, "Document is corrupted")
}
}
// --------------------------------------------------------------------------
// Setter test cases.
var setterResult = map[string]error{}
type setterType struct {
received interface{}
}
func (o *setterType) SetBSON(raw bson.Raw) error {
err := raw.Unmarshal(&o.received)
if err != nil {
panic("The panic:" + err.Error())
}
if s, ok := o.received.(string); ok {
if result, ok := setterResult[s]; ok {
return result
}
}
return nil
}
type ptrSetterDoc struct {
Field *setterType `bson:"_"`
}
type valSetterDoc struct {
Field setterType `bson:"_"`
}
func (s *S) TestUnmarshalAllItemsWithPtrSetter(c *C) {
for _, item := range allItems {
for i := 0; i != 2; i++ {
var field *setterType
if i == 0 {
obj := &ptrSetterDoc{}
err := bson.Unmarshal([]byte(wrapInDoc(item.data)), obj)
c.Assert(err, IsNil)
field = obj.Field
} else {
obj := &valSetterDoc{}
err := bson.Unmarshal([]byte(wrapInDoc(item.data)), obj)
c.Assert(err, IsNil)
field = &obj.Field
}
if item.data == "" {
// Nothing to unmarshal. Should be untouched.
if i == 0 {
c.Assert(field, IsNil)
} else {
c.Assert(field.received, IsNil)
}
} else {
expected := item.obj.(bson.M)["_"]
c.Assert(field, NotNil, Commentf("Pointer not initialized (%#v)", expected))
c.Assert(field.received, DeepEquals, expected)
}
}
}
}
func (s *S) TestUnmarshalWholeDocumentWithSetter(c *C) {
obj := &setterType{}
err := bson.Unmarshal([]byte(sampleItems[0].data), obj)
c.Assert(err, IsNil)
c.Assert(obj.received, DeepEquals, bson.M{"hello": "world"})
}
func (s *S) TestUnmarshalSetterOmits(c *C) {
setterResult["2"] = &bson.TypeError{}
setterResult["4"] = &bson.TypeError{}
defer func() {
delete(setterResult, "2")
delete(setterResult, "4")
}()
m := map[string]*setterType{}
data := wrapInDoc("\x02abc\x00\x02\x00\x00\x001\x00" +
"\x02def\x00\x02\x00\x00\x002\x00" +
"\x02ghi\x00\x02\x00\x00\x003\x00" +
"\x02jkl\x00\x02\x00\x00\x004\x00")
err := bson.Unmarshal([]byte(data), m)
c.Assert(err, IsNil)
c.Assert(m["abc"], NotNil)
c.Assert(m["def"], IsNil)
c.Assert(m["ghi"], NotNil)
c.Assert(m["jkl"], IsNil)
c.Assert(m["abc"].received, Equals, "1")
c.Assert(m["ghi"].received, Equals, "3")
}
func (s *S) TestUnmarshalSetterErrors(c *C) {
boom := errors.New("BOOM")
setterResult["2"] = boom
defer delete(setterResult, "2")
m := map[string]*setterType{}
data := wrapInDoc("\x02abc\x00\x02\x00\x00\x001\x00" +
"\x02def\x00\x02\x00\x00\x002\x00" +
"\x02ghi\x00\x02\x00\x00\x003\x00")
err := bson.Unmarshal([]byte(data), m)
c.Assert(err, Equals, boom)
c.Assert(m["abc"], NotNil)