1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
10 // * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 // * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
16 // * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47 . "github.com/golang/protobuf/proto"
48 . "github.com/golang/protobuf/proto/testdata"
55 globalO = NewBuffer(nil)
61 func equalbytes(b1, b2 []byte, t *testing.T) {
62 if len(b1) != len(b2) {
63 t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
66 for i := 0; i < len(b1); i++ {
68 t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
73 func initGoTestField() *GoTestField {
75 f.Label = String("label")
76 f.Type = String("type")
80 // These are all structurally equivalent but the tag numbers differ.
81 // (It's remarkable that required, optional, and repeated all have
83 func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
84 return &GoTest_RequiredGroup{
85 RequiredField: String("required"),
89 func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
90 return &GoTest_OptionalGroup{
91 RequiredField: String("optional"),
95 func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
96 return &GoTest_RepeatedGroup{
97 RequiredField: String("repeated"),
101 func initGoTest(setdefaults bool) *GoTest {
104 pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
105 pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
106 pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
107 pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
108 pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
109 pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
110 pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
111 pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
112 pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
113 pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
114 pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
115 pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
116 pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
119 pb.Kind = GoTest_TIME.Enum()
120 pb.RequiredField = initGoTestField()
121 pb.F_BoolRequired = Bool(true)
122 pb.F_Int32Required = Int32(3)
123 pb.F_Int64Required = Int64(6)
124 pb.F_Fixed32Required = Uint32(32)
125 pb.F_Fixed64Required = Uint64(64)
126 pb.F_Uint32Required = Uint32(3232)
127 pb.F_Uint64Required = Uint64(6464)
128 pb.F_FloatRequired = Float32(3232)
129 pb.F_DoubleRequired = Float64(6464)
130 pb.F_StringRequired = String("string")
131 pb.F_BytesRequired = []byte("bytes")
132 pb.F_Sint32Required = Int32(-32)
133 pb.F_Sint64Required = Int64(-64)
134 pb.Requiredgroup = initGoTest_RequiredGroup()
139 func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
144 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
146 // find the interesting spot - n
152 for i := 0; i < n; i++ {
153 bs := hex(s[j])*16 + hex(s[j+1])
167 // find the interesting spot - n
168 fmt.Printf("is[%d]:", l)
169 for i := l; i < h; i++ {
174 fmt.Printf(" %.2x", data[i])
178 fmt.Printf("sb[%d]:", l)
179 for i := l; i < h; i++ {
184 bs := hex(s[j])*16 + hex(s[j+1])
186 fmt.Printf(" %.2x", bs)
192 // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes())
193 // Print the output in a partially-decoded format; can
194 // be helpful when updating the test. It produces the output
195 // that is pasted, with minor edits, into the argument to verify().
199 // start := len(data) - b.Len()
201 // u, err := DecodeVarint(b)
203 // fmt.Printf("decode error on varint:", err)
210 // v, err := DecodeVarint(b)
212 // fmt.Printf("decode error on varint:", err)
215 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
216 // data[start:len(data)-b.Len()], tag, wire, v)
218 // v, err := DecodeFixed32(b)
220 // fmt.Printf("decode error on fixed32:", err)
223 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
224 // data[start:len(data)-b.Len()], tag, wire, v)
226 // v, err := DecodeFixed64(b)
228 // fmt.Printf("decode error on fixed64:", err)
231 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
232 // data[start:len(data)-b.Len()], tag, wire, v)
234 // nb, err := DecodeVarint(b)
236 // fmt.Printf("decode error on bytes:", err)
239 // after_tag := len(data) - b.Len()
240 // str := make([]byte, nb)
241 // _, err = b.Read(str)
243 // fmt.Printf("decode error on bytes:", err)
246 // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n",
247 // data[start:after_tag], str, tag, wire)
248 // case WireStartGroup:
250 // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n",
251 // data[start:len(data)-b.Len()], tag, nesting)
252 // case WireEndGroup:
253 // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n",
254 // data[start:len(data)-b.Len()], tag, nesting)
257 // fmt.Printf("unrecognized wire type %d\n", wire)
263 func hex(c uint8) uint8 {
264 if '0' <= c && c <= '9' {
267 if 'a' <= c && c <= 'f' {
270 if 'A' <= c && c <= 'F' {
276 func equal(b []byte, s string, t *testing.T) bool {
277 if 2*len(b) != len(s) {
278 // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
279 fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
282 for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
283 x := hex(s[j])*16 + hex(s[j+1])
285 // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
286 fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
293 func overify(t *testing.T, pb *GoTest, expected string) {
297 fmt.Printf("overify marshal-1 err = %v", err)
298 o.DebugPrint("", o.Bytes())
299 t.Fatalf("expected = %s", expected)
301 if !equal(o.Bytes(), expected, t) {
302 o.DebugPrint("overify neq 1", o.Bytes())
303 t.Fatalf("expected = %s", expected)
306 // Now test Unmarshal by recreating the original buffer.
308 err = o.Unmarshal(pbd)
310 t.Fatalf("overify unmarshal err = %v", err)
311 o.DebugPrint("", o.Bytes())
312 t.Fatalf("string = %s", expected)
317 t.Errorf("overify marshal-2 err = %v", err)
318 o.DebugPrint("", o.Bytes())
319 t.Fatalf("string = %s", expected)
321 if !equal(o.Bytes(), expected, t) {
322 o.DebugPrint("overify neq 2", o.Bytes())
323 t.Fatalf("string = %s", expected)
327 // Simple tests for numeric encode/decode primitives (varint, etc.)
328 func TestNumericPrimitives(t *testing.T) {
329 for i := uint64(0); i < 1e6; i += 111 {
331 if o.EncodeVarint(i) != nil {
332 t.Error("EncodeVarint")
335 x, e := o.DecodeVarint()
337 t.Fatal("DecodeVarint")
340 t.Fatal("varint decode fail:", i, x)
344 if o.EncodeFixed32(i) != nil {
345 t.Fatal("encFixed32")
347 x, e = o.DecodeFixed32()
349 t.Fatal("decFixed32")
352 t.Fatal("fixed32 decode fail:", i, x)
356 if o.EncodeFixed64(i*1234567) != nil {
357 t.Error("encFixed64")
360 x, e = o.DecodeFixed64()
362 t.Error("decFixed64")
366 t.Error("fixed64 decode fail:", i*1234567, x)
371 i32 := int32(i - 12345)
372 if o.EncodeZigzag32(uint64(i32)) != nil {
373 t.Fatal("EncodeZigzag32")
375 x, e = o.DecodeZigzag32()
377 t.Fatal("DecodeZigzag32")
379 if x != uint64(uint32(i32)) {
380 t.Fatal("zigzag32 decode fail:", i32, x)
384 i64 := int64(i - 12345)
385 if o.EncodeZigzag64(uint64(i64)) != nil {
386 t.Fatal("EncodeZigzag64")
388 x, e = o.DecodeZigzag64()
390 t.Fatal("DecodeZigzag64")
392 if x != uint64(i64) {
393 t.Fatal("zigzag64 decode fail:", i64, x)
398 // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
399 type fakeMarshaler struct {
404 func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
405 func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
406 func (f *fakeMarshaler) ProtoMessage() {}
407 func (f *fakeMarshaler) Reset() {}
409 type msgWithFakeMarshaler struct {
410 M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
413 func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) }
414 func (m *msgWithFakeMarshaler) ProtoMessage() {}
415 func (m *msgWithFakeMarshaler) Reset() {}
417 // Simple tests for proto messages that implement the Marshaler interface.
418 func TestMarshalerEncoding(t *testing.T) {
426 name: "Marshaler that fails",
428 err: errors.New("some marshal err"),
431 // Since the Marshal method returned bytes, they should be written to the
432 // buffer. (For efficiency, we assume that Marshal implementations are
433 // always correct w.r.t. RequiredNotSetError and output.)
434 want: []byte{5, 6, 7},
435 errType: reflect.TypeOf(errors.New("some marshal err")),
438 name: "Marshaler that fails with RequiredNotSetError",
439 m: &msgWithFakeMarshaler{
441 err: &RequiredNotSetError{},
445 // Since there's an error that can be continued after,
446 // the buffer should be written.
448 10, 3, // for &msgWithFakeMarshaler
449 5, 6, 7, // for &fakeMarshaler
451 errType: reflect.TypeOf(&RequiredNotSetError{}),
454 name: "Marshaler that succeeds",
456 b: []byte{0, 1, 2, 3, 4, 127, 255},
458 want: []byte{0, 1, 2, 3, 4, 127, 255},
461 for _, test := range tests {
463 err := b.Marshal(test.m)
464 if reflect.TypeOf(err) != test.errType {
465 t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType)
467 if !reflect.DeepEqual(test.want, b.Bytes()) {
468 t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
470 if size := Size(test.m); size != len(b.Bytes()) {
471 t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes()))
474 m, mErr := Marshal(test.m)
475 if !bytes.Equal(b.Bytes(), m) {
476 t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes())
478 if !reflect.DeepEqual(err, mErr) {
479 t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q",
480 test.name, fmt.Sprint(mErr), fmt.Sprint(err))
485 // Simple tests for bytes
486 func TestBytesPrimitives(t *testing.T) {
488 bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
489 if o.EncodeRawBytes(bytes) != nil {
490 t.Error("EncodeRawBytes")
492 decb, e := o.DecodeRawBytes(false)
494 t.Error("DecodeRawBytes")
496 equalbytes(bytes, decb, t)
499 // Simple tests for strings
500 func TestStringPrimitives(t *testing.T) {
502 s := "now is the time"
503 if o.EncodeStringBytes(s) != nil {
504 t.Error("enc_string")
506 decs, e := o.DecodeStringBytes()
508 t.Error("dec_string")
511 t.Error("string encode/decode fail:", s, decs)
515 // Do we catch the "required bit not set" case?
516 func TestRequiredBit(t *testing.T) {
521 t.Error("did not catch missing required fields")
522 } else if strings.Index(err.Error(), "Kind") < 0 {
523 t.Error("wrong error type:", err)
527 // Check that all fields are nil.
528 // Clearly silly, and a residue from a more interesting test with an earlier,
529 // different initialization property, but it once caught a compiler bug so
531 func checkInitialized(pb *GoTest, t *testing.T) {
532 if pb.F_BoolDefaulted != nil {
533 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
535 if pb.F_Int32Defaulted != nil {
536 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
538 if pb.F_Int64Defaulted != nil {
539 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
541 if pb.F_Fixed32Defaulted != nil {
542 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
544 if pb.F_Fixed64Defaulted != nil {
545 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
547 if pb.F_Uint32Defaulted != nil {
548 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
550 if pb.F_Uint64Defaulted != nil {
551 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
553 if pb.F_FloatDefaulted != nil {
554 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
556 if pb.F_DoubleDefaulted != nil {
557 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
559 if pb.F_StringDefaulted != nil {
560 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
562 if pb.F_BytesDefaulted != nil {
563 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
565 if pb.F_Sint32Defaulted != nil {
566 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
568 if pb.F_Sint64Defaulted != nil {
569 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
573 // Does Reset() reset?
574 func TestReset(t *testing.T) {
575 pb := initGoTest(true)
576 // muck with some values
577 pb.F_BoolDefaulted = Bool(false)
578 pb.F_Int32Defaulted = Int32(237)
579 pb.F_Int64Defaulted = Int64(12346)
580 pb.F_Fixed32Defaulted = Uint32(32000)
581 pb.F_Fixed64Defaulted = Uint64(666)
582 pb.F_Uint32Defaulted = Uint32(323232)
583 pb.F_Uint64Defaulted = nil
584 pb.F_FloatDefaulted = nil
585 pb.F_DoubleDefaulted = Float64(0)
586 pb.F_StringDefaulted = String("gotcha")
587 pb.F_BytesDefaulted = []byte("asdfasdf")
588 pb.F_Sint32Defaulted = Int32(123)
589 pb.F_Sint64Defaulted = Int64(789)
591 checkInitialized(pb, t)
594 // All required fields set, no defaults provided.
595 func TestEncodeDecode1(t *testing.T) {
596 pb := initGoTest(false)
598 "0807"+ // field 1, encoding 0, value 7
599 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
600 "5001"+ // field 10, encoding 0, value 1
601 "5803"+ // field 11, encoding 0, value 3
602 "6006"+ // field 12, encoding 0, value 6
603 "6d20000000"+ // field 13, encoding 5, value 0x20
604 "714000000000000000"+ // field 14, encoding 1, value 0x40
605 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
606 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
607 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
608 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
609 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
610 "b304"+ // field 70, encoding 3, start group
611 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
612 "b404"+ // field 70, encoding 4, end group
613 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
614 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
615 "b8067f") // field 103, encoding 0, 0x7f zigzag64
618 // All required fields set, defaults provided.
619 func TestEncodeDecode2(t *testing.T) {
620 pb := initGoTest(true)
622 "0807"+ // field 1, encoding 0, value 7
623 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
624 "5001"+ // field 10, encoding 0, value 1
625 "5803"+ // field 11, encoding 0, value 3
626 "6006"+ // field 12, encoding 0, value 6
627 "6d20000000"+ // field 13, encoding 5, value 32
628 "714000000000000000"+ // field 14, encoding 1, value 64
629 "78a019"+ // field 15, encoding 0, value 3232
630 "8001c032"+ // field 16, encoding 0, value 6464
631 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
632 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
633 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
634 "c00201"+ // field 40, encoding 0, value 1
635 "c80220"+ // field 41, encoding 0, value 32
636 "d00240"+ // field 42, encoding 0, value 64
637 "dd0240010000"+ // field 43, encoding 5, value 320
638 "e1028002000000000000"+ // field 44, encoding 1, value 640
639 "e8028019"+ // field 45, encoding 0, value 3200
640 "f0028032"+ // field 46, encoding 0, value 6400
641 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
642 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
643 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
644 "b304"+ // start group field 70 level 1
645 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
646 "b404"+ // end group field 70 level 1
647 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
648 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
649 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
650 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
651 "90193f"+ // field 402, encoding 0, value 63
652 "98197f") // field 403, encoding 0, value 127
656 // All default fields set to their default value by hand
657 func TestEncodeDecode3(t *testing.T) {
658 pb := initGoTest(false)
659 pb.F_BoolDefaulted = Bool(true)
660 pb.F_Int32Defaulted = Int32(32)
661 pb.F_Int64Defaulted = Int64(64)
662 pb.F_Fixed32Defaulted = Uint32(320)
663 pb.F_Fixed64Defaulted = Uint64(640)
664 pb.F_Uint32Defaulted = Uint32(3200)
665 pb.F_Uint64Defaulted = Uint64(6400)
666 pb.F_FloatDefaulted = Float32(314159)
667 pb.F_DoubleDefaulted = Float64(271828)
668 pb.F_StringDefaulted = String("hello, \"world!\"\n")
669 pb.F_BytesDefaulted = []byte("Bignose")
670 pb.F_Sint32Defaulted = Int32(-32)
671 pb.F_Sint64Defaulted = Int64(-64)
674 "0807"+ // field 1, encoding 0, value 7
675 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
676 "5001"+ // field 10, encoding 0, value 1
677 "5803"+ // field 11, encoding 0, value 3
678 "6006"+ // field 12, encoding 0, value 6
679 "6d20000000"+ // field 13, encoding 5, value 32
680 "714000000000000000"+ // field 14, encoding 1, value 64
681 "78a019"+ // field 15, encoding 0, value 3232
682 "8001c032"+ // field 16, encoding 0, value 6464
683 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
684 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
685 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
686 "c00201"+ // field 40, encoding 0, value 1
687 "c80220"+ // field 41, encoding 0, value 32
688 "d00240"+ // field 42, encoding 0, value 64
689 "dd0240010000"+ // field 43, encoding 5, value 320
690 "e1028002000000000000"+ // field 44, encoding 1, value 640
691 "e8028019"+ // field 45, encoding 0, value 3200
692 "f0028032"+ // field 46, encoding 0, value 6400
693 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
694 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
695 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
696 "b304"+ // start group field 70 level 1
697 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
698 "b404"+ // end group field 70 level 1
699 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
700 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
701 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
702 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
703 "90193f"+ // field 402, encoding 0, value 63
704 "98197f") // field 403, encoding 0, value 127
708 // All required fields set, defaults provided, all non-defaulted optional fields have values.
709 func TestEncodeDecode4(t *testing.T) {
710 pb := initGoTest(true)
711 pb.Table = String("hello")
713 pb.OptionalField = initGoTestField()
714 pb.F_BoolOptional = Bool(true)
715 pb.F_Int32Optional = Int32(32)
716 pb.F_Int64Optional = Int64(64)
717 pb.F_Fixed32Optional = Uint32(3232)
718 pb.F_Fixed64Optional = Uint64(6464)
719 pb.F_Uint32Optional = Uint32(323232)
720 pb.F_Uint64Optional = Uint64(646464)
721 pb.F_FloatOptional = Float32(32.)
722 pb.F_DoubleOptional = Float64(64.)
723 pb.F_StringOptional = String("hello")
724 pb.F_BytesOptional = []byte("Bignose")
725 pb.F_Sint32Optional = Int32(-32)
726 pb.F_Sint64Optional = Int64(-64)
727 pb.Optionalgroup = initGoTest_OptionalGroup()
730 "0807"+ // field 1, encoding 0, value 7
731 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
732 "1807"+ // field 3, encoding 0, value 7
733 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
734 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
735 "5001"+ // field 10, encoding 0, value 1
736 "5803"+ // field 11, encoding 0, value 3
737 "6006"+ // field 12, encoding 0, value 6
738 "6d20000000"+ // field 13, encoding 5, value 32
739 "714000000000000000"+ // field 14, encoding 1, value 64
740 "78a019"+ // field 15, encoding 0, value 3232
741 "8001c032"+ // field 16, encoding 0, value 6464
742 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
743 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
744 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
745 "f00101"+ // field 30, encoding 0, value 1
746 "f80120"+ // field 31, encoding 0, value 32
747 "800240"+ // field 32, encoding 0, value 64
748 "8d02a00c0000"+ // field 33, encoding 5, value 3232
749 "91024019000000000000"+ // field 34, encoding 1, value 6464
750 "9802a0dd13"+ // field 35, encoding 0, value 323232
751 "a002c0ba27"+ // field 36, encoding 0, value 646464
752 "ad0200000042"+ // field 37, encoding 5, value 32.0
753 "b1020000000000005040"+ // field 38, encoding 1, value 64.0
754 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
755 "c00201"+ // field 40, encoding 0, value 1
756 "c80220"+ // field 41, encoding 0, value 32
757 "d00240"+ // field 42, encoding 0, value 64
758 "dd0240010000"+ // field 43, encoding 5, value 320
759 "e1028002000000000000"+ // field 44, encoding 1, value 640
760 "e8028019"+ // field 45, encoding 0, value 3200
761 "f0028032"+ // field 46, encoding 0, value 6400
762 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
763 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
764 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
765 "b304"+ // start group field 70 level 1
766 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
767 "b404"+ // end group field 70 level 1
768 "d305"+ // start group field 90 level 1
769 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
770 "d405"+ // end group field 90 level 1
771 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
772 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
773 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
774 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
775 "f0123f"+ // field 302, encoding 0, value 63
776 "f8127f"+ // field 303, encoding 0, value 127
777 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
778 "90193f"+ // field 402, encoding 0, value 63
779 "98197f") // field 403, encoding 0, value 127
783 // All required fields set, defaults provided, all repeated fields given two values.
784 func TestEncodeDecode5(t *testing.T) {
785 pb := initGoTest(true)
786 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
787 pb.F_BoolRepeated = []bool{false, true}
788 pb.F_Int32Repeated = []int32{32, 33}
789 pb.F_Int64Repeated = []int64{64, 65}
790 pb.F_Fixed32Repeated = []uint32{3232, 3333}
791 pb.F_Fixed64Repeated = []uint64{6464, 6565}
792 pb.F_Uint32Repeated = []uint32{323232, 333333}
793 pb.F_Uint64Repeated = []uint64{646464, 656565}
794 pb.F_FloatRepeated = []float32{32., 33.}
795 pb.F_DoubleRepeated = []float64{64., 65.}
796 pb.F_StringRepeated = []string{"hello", "sailor"}
797 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
798 pb.F_Sint32Repeated = []int32{32, -32}
799 pb.F_Sint64Repeated = []int64{64, -64}
800 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
803 "0807"+ // field 1, encoding 0, value 7
804 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
805 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
806 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
807 "5001"+ // field 10, encoding 0, value 1
808 "5803"+ // field 11, encoding 0, value 3
809 "6006"+ // field 12, encoding 0, value 6
810 "6d20000000"+ // field 13, encoding 5, value 32
811 "714000000000000000"+ // field 14, encoding 1, value 64
812 "78a019"+ // field 15, encoding 0, value 3232
813 "8001c032"+ // field 16, encoding 0, value 6464
814 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
815 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
816 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
817 "a00100"+ // field 20, encoding 0, value 0
818 "a00101"+ // field 20, encoding 0, value 1
819 "a80120"+ // field 21, encoding 0, value 32
820 "a80121"+ // field 21, encoding 0, value 33
821 "b00140"+ // field 22, encoding 0, value 64
822 "b00141"+ // field 22, encoding 0, value 65
823 "bd01a00c0000"+ // field 23, encoding 5, value 3232
824 "bd01050d0000"+ // field 23, encoding 5, value 3333
825 "c1014019000000000000"+ // field 24, encoding 1, value 6464
826 "c101a519000000000000"+ // field 24, encoding 1, value 6565
827 "c801a0dd13"+ // field 25, encoding 0, value 323232
828 "c80195ac14"+ // field 25, encoding 0, value 333333
829 "d001c0ba27"+ // field 26, encoding 0, value 646464
830 "d001b58928"+ // field 26, encoding 0, value 656565
831 "dd0100000042"+ // field 27, encoding 5, value 32.0
832 "dd0100000442"+ // field 27, encoding 5, value 33.0
833 "e1010000000000005040"+ // field 28, encoding 1, value 64.0
834 "e1010000000000405040"+ // field 28, encoding 1, value 65.0
835 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
836 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
837 "c00201"+ // field 40, encoding 0, value 1
838 "c80220"+ // field 41, encoding 0, value 32
839 "d00240"+ // field 42, encoding 0, value 64
840 "dd0240010000"+ // field 43, encoding 5, value 320
841 "e1028002000000000000"+ // field 44, encoding 1, value 640
842 "e8028019"+ // field 45, encoding 0, value 3200
843 "f0028032"+ // field 46, encoding 0, value 6400
844 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
845 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
846 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
847 "b304"+ // start group field 70 level 1
848 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
849 "b404"+ // end group field 70 level 1
850 "8305"+ // start group field 80 level 1
851 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
852 "8405"+ // end group field 80 level 1
853 "8305"+ // start group field 80 level 1
854 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
855 "8405"+ // end group field 80 level 1
856 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
857 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
858 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
859 "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
860 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
861 "d00c40"+ // field 202, encoding 0, value 32
862 "d00c3f"+ // field 202, encoding 0, value -32
863 "d80c8001"+ // field 203, encoding 0, value 64
864 "d80c7f"+ // field 203, encoding 0, value -64
865 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
866 "90193f"+ // field 402, encoding 0, value 63
867 "98197f") // field 403, encoding 0, value 127
871 // All required fields set, all packed repeated fields given two values.
872 func TestEncodeDecode6(t *testing.T) {
873 pb := initGoTest(false)
874 pb.F_BoolRepeatedPacked = []bool{false, true}
875 pb.F_Int32RepeatedPacked = []int32{32, 33}
876 pb.F_Int64RepeatedPacked = []int64{64, 65}
877 pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
878 pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
879 pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
880 pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
881 pb.F_FloatRepeatedPacked = []float32{32., 33.}
882 pb.F_DoubleRepeatedPacked = []float64{64., 65.}
883 pb.F_Sint32RepeatedPacked = []int32{32, -32}
884 pb.F_Sint64RepeatedPacked = []int64{64, -64}
887 "0807"+ // field 1, encoding 0, value 7
888 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
889 "5001"+ // field 10, encoding 0, value 1
890 "5803"+ // field 11, encoding 0, value 3
891 "6006"+ // field 12, encoding 0, value 6
892 "6d20000000"+ // field 13, encoding 5, value 32
893 "714000000000000000"+ // field 14, encoding 1, value 64
894 "78a019"+ // field 15, encoding 0, value 3232
895 "8001c032"+ // field 16, encoding 0, value 6464
896 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
897 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
898 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
899 "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
900 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
901 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
902 "aa0308"+ // field 53, encoding 2, 8 bytes
903 "a00c0000050d0000"+ // value 3232, value 3333
904 "b20310"+ // field 54, encoding 2, 16 bytes
905 "4019000000000000a519000000000000"+ // value 6464, value 6565
906 "ba0306"+ // field 55, encoding 2, 6 bytes
907 "a0dd1395ac14"+ // value 323232, value 333333
908 "c20306"+ // field 56, encoding 2, 6 bytes
909 "c0ba27b58928"+ // value 646464, value 656565
910 "ca0308"+ // field 57, encoding 2, 8 bytes
911 "0000004200000442"+ // value 32.0, value 33.0
912 "d20310"+ // field 58, encoding 2, 16 bytes
913 "00000000000050400000000000405040"+ // value 64.0, value 65.0
914 "b304"+ // start group field 70 level 1
915 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
916 "b404"+ // end group field 70 level 1
917 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
918 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
919 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
920 "b21f02"+ // field 502, encoding 2, 2 bytes
921 "403f"+ // value 32, value -32
922 "ba1f03"+ // field 503, encoding 2, 3 bytes
923 "80017f") // value 64, value -64
926 // Test that we can encode empty bytes fields.
927 func TestEncodeDecodeBytes1(t *testing.T) {
928 pb := initGoTest(false)
931 pb.F_BytesRequired = []byte{}
932 pb.F_BytesRepeated = [][]byte{{}}
933 pb.F_BytesOptional = []byte{}
935 d, err := Marshal(pb)
941 if err := Unmarshal(d, pbd); err != nil {
945 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
946 t.Error("required empty bytes field is incorrect")
948 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
949 t.Error("repeated empty bytes field is incorrect")
951 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
952 t.Error("optional empty bytes field is incorrect")
956 // Test that we encode nil-valued fields of a repeated bytes field correctly.
957 // Since entries in a repeated field cannot be nil, nil must mean empty value.
958 func TestEncodeDecodeBytes2(t *testing.T) {
959 pb := initGoTest(false)
962 pb.F_BytesRepeated = [][]byte{nil}
964 d, err := Marshal(pb)
970 if err := Unmarshal(d, pbd); err != nil {
974 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
975 t.Error("Unexpected value for repeated bytes field")
979 // All required fields set, defaults provided, all repeated fields given two values.
980 func TestSkippingUnrecognizedFields(t *testing.T) {
982 pb := initGoTestField()
984 // Marshal it normally.
987 // Now new a GoSkipTest record.
989 SkipInt32: Int32(32),
990 SkipFixed32: Uint32(3232),
991 SkipFixed64: Uint64(6464),
992 SkipString: String("skipper"),
993 Skipgroup: &GoSkipTest_SkipGroup{
994 GroupInt32: Int32(75),
995 GroupString: String("wxyz"),
999 // Marshal it into same buffer.
1002 pbd := new(GoTestField)
1005 // The __unrecognized field should be a marshaling of GoSkipTest
1006 skipd := new(GoSkipTest)
1008 o.SetBuf(pbd.XXX_unrecognized)
1011 if *skipd.SkipInt32 != *skip.SkipInt32 {
1012 t.Error("skip int32", skipd.SkipInt32)
1014 if *skipd.SkipFixed32 != *skip.SkipFixed32 {
1015 t.Error("skip fixed32", skipd.SkipFixed32)
1017 if *skipd.SkipFixed64 != *skip.SkipFixed64 {
1018 t.Error("skip fixed64", skipd.SkipFixed64)
1020 if *skipd.SkipString != *skip.SkipString {
1021 t.Error("skip string", *skipd.SkipString)
1023 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
1024 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
1026 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
1027 t.Error("skip group string", *skipd.Skipgroup.GroupString)
1031 // Check that unrecognized fields of a submessage are preserved.
1032 func TestSubmessageUnrecognizedFields(t *testing.T) {
1034 Nested: &NewMessage_Nested{
1035 Name: String("Nigel"),
1036 FoodGroup: String("carbs"),
1039 b, err := Marshal(nm)
1041 t.Fatalf("Marshal of NewMessage: %v", err)
1044 // Unmarshal into an OldMessage.
1045 om := new(OldMessage)
1046 if err := Unmarshal(b, om); err != nil {
1047 t.Fatalf("Unmarshal to OldMessage: %v", err)
1050 Nested: &OldMessage_Nested{
1051 Name: String("Nigel"),
1052 // normal protocol buffer users should not do this
1053 XXX_unrecognized: []byte("\x12\x05carbs"),
1056 if !Equal(om, exp) {
1057 t.Errorf("om = %v, want %v", om, exp)
1060 // Clone the OldMessage.
1061 om = Clone(om).(*OldMessage)
1062 if !Equal(om, exp) {
1063 t.Errorf("Clone(om) = %v, want %v", om, exp)
1066 // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
1067 if b, err = Marshal(om); err != nil {
1068 t.Fatalf("Marshal of OldMessage: %v", err)
1070 t.Logf("Marshal(%v) -> %q", om, b)
1071 nm2 := new(NewMessage)
1072 if err := Unmarshal(b, nm2); err != nil {
1073 t.Fatalf("Unmarshal to NewMessage: %v", err)
1075 if !Equal(nm, nm2) {
1076 t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
1080 // Check that an int32 field can be upgraded to an int64 field.
1081 func TestNegativeInt32(t *testing.T) {
1085 b, err := Marshal(om)
1087 t.Fatalf("Marshal of OldMessage: %v", err)
1090 // Check the size. It should be 11 bytes;
1091 // 1 for the field/wire type, and 10 for the negative number.
1093 t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
1096 // Unmarshal into a NewMessage.
1097 nm := new(NewMessage)
1098 if err := Unmarshal(b, nm); err != nil {
1099 t.Fatalf("Unmarshal to NewMessage: %v", err)
1101 want := &NewMessage{
1104 if !Equal(nm, want) {
1105 t.Errorf("nm = %v, want %v", nm, want)
1109 // Check that we can grow an array (repeated field) to have many elements.
1110 // This test doesn't depend only on our encoding; for variety, it makes sure
1111 // we create, encode, and decode the correct contents explicitly. It's therefore
1113 // This test also uses (and hence tests) the Marshal/Unmarshal functions
1114 // instead of the methods.
1115 func TestBigRepeated(t *testing.T) {
1116 pb := initGoTest(true)
1118 // Create the arrays
1119 const N = 50 // Internally the library starts much smaller.
1120 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
1121 pb.F_Sint64Repeated = make([]int64, N)
1122 pb.F_Sint32Repeated = make([]int32, N)
1123 pb.F_BytesRepeated = make([][]byte, N)
1124 pb.F_StringRepeated = make([]string, N)
1125 pb.F_DoubleRepeated = make([]float64, N)
1126 pb.F_FloatRepeated = make([]float32, N)
1127 pb.F_Uint64Repeated = make([]uint64, N)
1128 pb.F_Uint32Repeated = make([]uint32, N)
1129 pb.F_Fixed64Repeated = make([]uint64, N)
1130 pb.F_Fixed32Repeated = make([]uint32, N)
1131 pb.F_Int64Repeated = make([]int64, N)
1132 pb.F_Int32Repeated = make([]int32, N)
1133 pb.F_BoolRepeated = make([]bool, N)
1134 pb.RepeatedField = make([]*GoTestField, N)
1136 // Fill in the arrays with checkable values.
1137 igtf := initGoTestField()
1138 igtrg := initGoTest_RepeatedGroup()
1139 for i := 0; i < N; i++ {
1140 pb.Repeatedgroup[i] = igtrg
1141 pb.F_Sint64Repeated[i] = int64(i)
1142 pb.F_Sint32Repeated[i] = int32(i)
1144 pb.F_BytesRepeated[i] = []byte(s)
1145 pb.F_StringRepeated[i] = s
1146 pb.F_DoubleRepeated[i] = float64(i)
1147 pb.F_FloatRepeated[i] = float32(i)
1148 pb.F_Uint64Repeated[i] = uint64(i)
1149 pb.F_Uint32Repeated[i] = uint32(i)
1150 pb.F_Fixed64Repeated[i] = uint64(i)
1151 pb.F_Fixed32Repeated[i] = uint32(i)
1152 pb.F_Int64Repeated[i] = int64(i)
1153 pb.F_Int32Repeated[i] = int32(i)
1154 pb.F_BoolRepeated[i] = i%2 == 0
1155 pb.RepeatedField[i] = igtf
1159 buf, _ := Marshal(pb)
1161 // Now test Unmarshal by recreating the original buffer.
1165 // Check the checkable values
1166 for i := uint64(0); i < N; i++ {
1167 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
1168 t.Error("pbd.Repeatedgroup bad")
1171 x = uint64(pbd.F_Sint64Repeated[i])
1173 t.Error("pbd.F_Sint64Repeated bad", x, i)
1175 x = uint64(pbd.F_Sint32Repeated[i])
1177 t.Error("pbd.F_Sint32Repeated bad", x, i)
1180 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
1181 if pbd.F_StringRepeated[i] != s {
1182 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
1184 x = uint64(pbd.F_DoubleRepeated[i])
1186 t.Error("pbd.F_DoubleRepeated bad", x, i)
1188 x = uint64(pbd.F_FloatRepeated[i])
1190 t.Error("pbd.F_FloatRepeated bad", x, i)
1192 x = pbd.F_Uint64Repeated[i]
1194 t.Error("pbd.F_Uint64Repeated bad", x, i)
1196 x = uint64(pbd.F_Uint32Repeated[i])
1198 t.Error("pbd.F_Uint32Repeated bad", x, i)
1200 x = pbd.F_Fixed64Repeated[i]
1202 t.Error("pbd.F_Fixed64Repeated bad", x, i)
1204 x = uint64(pbd.F_Fixed32Repeated[i])
1206 t.Error("pbd.F_Fixed32Repeated bad", x, i)
1208 x = uint64(pbd.F_Int64Repeated[i])
1210 t.Error("pbd.F_Int64Repeated bad", x, i)
1212 x = uint64(pbd.F_Int32Repeated[i])
1214 t.Error("pbd.F_Int32Repeated bad", x, i)
1216 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
1217 t.Error("pbd.F_BoolRepeated bad", x, i)
1219 if pbd.RepeatedField[i] == nil { // TODO: more checking?
1220 t.Error("pbd.RepeatedField bad")
1225 // Verify we give a useful message when decoding to the wrong structure type.
1226 func TestTypeMismatch(t *testing.T) {
1227 pb1 := initGoTest(true)
1233 // Now Unmarshal it to the wrong type.
1234 pb2 := initGoTestField()
1235 err := o.Unmarshal(pb2)
1237 t.Error("expected error, got no error")
1238 } else if !strings.Contains(err.Error(), "bad wiretype") {
1239 t.Error("expected bad wiretype error, got", err)
1243 func encodeDecode(t *testing.T, in, out Message, msg string) {
1244 buf, err := Marshal(in)
1246 t.Fatalf("failed marshaling %v: %v", msg, err)
1248 if err := Unmarshal(buf, out); err != nil {
1249 t.Fatalf("failed unmarshaling %v: %v", msg, err)
1253 func TestPackedNonPackedDecoderSwitching(t *testing.T) {
1254 np, p := new(NonPackedTest), new(PackedTest)
1256 // non-packed -> packed
1257 np.A = []int32{0, 1, 1, 2, 3, 5}
1258 encodeDecode(t, np, p, "non-packed -> packed")
1259 if !reflect.DeepEqual(np.A, p.B) {
1260 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
1263 // packed -> non-packed
1265 p.B = []int32{3, 1, 4, 1, 5, 9}
1266 encodeDecode(t, p, np, "packed -> non-packed")
1267 if !reflect.DeepEqual(p.B, np.A) {
1268 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
1272 func TestProto1RepeatedGroup(t *testing.T) {
1274 Message: []*MessageList_Message{
1276 Name: String("blah"),
1279 // NOTE: pb.Message[1] is a nil
1285 err := o.Marshal(pb)
1286 if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
1287 t.Fatalf("unexpected or no error when marshaling: %v", err)
1291 // Test that enums work. Checks for a bug introduced by making enums
1292 // named types instead of int32: newInt32FromUint64 would crash with
1293 // a type mismatch in reflect.PointTo.
1294 func TestEnum(t *testing.T) {
1296 pb.Foo = FOO_FOO1.Enum()
1298 if err := o.Marshal(pb); err != nil {
1299 t.Fatal("error encoding enum:", err)
1302 if err := o.Unmarshal(pb1); err != nil {
1303 t.Fatal("error decoding enum:", err)
1305 if *pb1.Foo != FOO_FOO1 {
1306 t.Error("expected 7 but got ", *pb1.Foo)
1310 // Enum types have String methods. Check that enum fields can be printed.
1311 // We don't care what the value actually is, just as long as it doesn't crash.
1312 func TestPrintingNilEnumFields(t *testing.T) {
1314 _ = fmt.Sprintf("%+v", pb)
1317 // Verify that absent required fields cause Marshal/Unmarshal to return errors.
1318 func TestRequiredFieldEnforcement(t *testing.T) {
1319 pb := new(GoTestField)
1320 _, err := Marshal(pb)
1322 t.Error("marshal: expected error, got nil")
1323 } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") {
1324 t.Errorf("marshal: bad error type: %v", err)
1327 // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
1328 // so simply counting the required fields is insufficient.
1329 // field 1, encoding 2, value "hi"
1330 buf := []byte("\x0A\x02hi\x0A\x02hi")
1331 err = Unmarshal(buf, pb)
1333 t.Error("unmarshal: expected error, got nil")
1334 } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") {
1335 t.Errorf("unmarshal: bad error type: %v", err)
1339 // Verify that absent required fields in groups cause Marshal/Unmarshal to return errors.
1340 func TestRequiredFieldEnforcementGroups(t *testing.T) {
1341 pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}}
1342 if _, err := Marshal(pb); err == nil {
1343 t.Error("marshal: expected error, got nil")
1344 } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") {
1345 t.Errorf("marshal: bad error type: %v", err)
1348 buf := []byte{11, 12}
1349 if err := Unmarshal(buf, pb); err == nil {
1350 t.Error("unmarshal: expected error, got nil")
1351 } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") {
1352 t.Errorf("unmarshal: bad error type: %v", err)
1356 func TestTypedNilMarshal(t *testing.T) {
1357 // A typed nil should return ErrNil and not crash.
1360 if _, err := Marshal(m); err != ErrNil {
1361 t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
1366 m := &Communique{Union: &Communique_Msg{nil}}
1367 if _, err := Marshal(m); err == nil || err == ErrNil {
1368 t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err)
1373 // A type that implements the Marshaler interface, but is not nillable.
1374 type nonNillableInt uint64
1376 func (nni nonNillableInt) Marshal() ([]byte, error) {
1377 return EncodeVarint(uint64(nni)), nil
1380 type NNIMessage struct {
1384 func (*NNIMessage) Reset() {}
1385 func (*NNIMessage) String() string { return "" }
1386 func (*NNIMessage) ProtoMessage() {}
1388 // A type that implements the Marshaler interface and is nillable.
1389 type nillableMessage struct {
1393 func (nm *nillableMessage) Marshal() ([]byte, error) {
1394 return EncodeVarint(nm.x), nil
1397 type NMMessage struct {
1401 func (*NMMessage) Reset() {}
1402 func (*NMMessage) String() string { return "" }
1403 func (*NMMessage) ProtoMessage() {}
1405 // Verify a type that uses the Marshaler interface, but has a nil pointer.
1406 func TestNilMarshaler(t *testing.T) {
1407 // Try a struct with a Marshaler field that is nil.
1408 // It should be directly marshable.
1409 nmm := new(NMMessage)
1410 if _, err := Marshal(nmm); err != nil {
1411 t.Error("unexpected error marshaling nmm: ", err)
1414 // Try a struct with a Marshaler field that is not nillable.
1415 nnim := new(NNIMessage)
1417 var _ Marshaler = nnim.nni // verify it is truly a Marshaler
1418 if _, err := Marshal(nnim); err != nil {
1419 t.Error("unexpected error marshaling nnim: ", err)
1423 func TestAllSetDefaults(t *testing.T) {
1424 // Exercise SetDefaults with all scalar field types.
1426 // NaN != NaN, so override that here.
1427 F_Nan: Float32(1.7),
1429 expected := &Defaults{
1433 F_Fixed32: Uint32(320),
1434 F_Fixed64: Uint64(640),
1435 F_Uint32: Uint32(3200),
1436 F_Uint64: Uint64(6400),
1437 F_Float: Float32(314159),
1438 F_Double: Float64(271828),
1439 F_String: String(`hello, "world!"` + "\n"),
1440 F_Bytes: []byte("Bignose"),
1441 F_Sint32: Int32(-32),
1442 F_Sint64: Int64(-64),
1443 F_Enum: Defaults_GREEN.Enum(),
1444 F_Pinf: Float32(float32(math.Inf(1))),
1445 F_Ninf: Float32(float32(math.Inf(-1))),
1446 F_Nan: Float32(1.7),
1447 StrZero: String(""),
1450 if !Equal(m, expected) {
1451 t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected)
1455 func TestSetDefaultsWithSetField(t *testing.T) {
1456 // Check that a set value is not overridden.
1461 if v := m.GetF_Int32(); v != 12 {
1462 t.Errorf("m.FInt32 = %v, want 12", v)
1466 func TestSetDefaultsWithSubMessage(t *testing.T) {
1469 Inner: &InnerMessage{
1470 Host: String("gopher"),
1473 expected := &OtherMessage{
1475 Inner: &InnerMessage{
1476 Host: String("gopher"),
1481 if !Equal(m, expected) {
1482 t.Errorf("\n got %v\nwant %v", m, expected)
1486 func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
1488 RepInner: []*InnerMessage{{}},
1490 expected := &MyMessage{
1491 RepInner: []*InnerMessage{{
1496 if !Equal(m, expected) {
1497 t.Errorf("\n got %v\nwant %v", m, expected)
1501 func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
1503 Pet: []string{"turtle", "wombat"},
1505 expected := Clone(m)
1507 if !Equal(m, expected) {
1508 t.Errorf("\n got %v\nwant %v", m, expected)
1512 func TestMaximumTagNumber(t *testing.T) {
1514 LastField: String("natural goat essence"),
1516 buf, err := Marshal(m)
1518 t.Fatalf("proto.Marshal failed: %v", err)
1521 if err := Unmarshal(buf, m2); err != nil {
1522 t.Fatalf("proto.Unmarshal failed: %v", err)
1524 if got, want := m2.GetLastField(), *m.LastField; got != want {
1525 t.Errorf("got %q, want %q", got, want)
1529 func TestJSON(t *testing.T) {
1532 Pet: []string{"bunny", "kitty"},
1533 Inner: &InnerMessage{
1534 Host: String("cauchy"),
1536 Bikeshed: MyMessage_GREEN.Enum(),
1538 const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
1540 b, err := json.Marshal(m)
1542 t.Fatalf("json.Marshal failed: %v", err)
1546 t.Errorf("got %s\nwant %s", s, expected)
1549 received := new(MyMessage)
1550 if err := json.Unmarshal(b, received); err != nil {
1551 t.Fatalf("json.Unmarshal failed: %v", err)
1553 if !Equal(received, m) {
1554 t.Fatalf("got %s, want %s", received, m)
1557 // Test unmarshalling of JSON with symbolic enum name.
1558 const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
1560 if err := json.Unmarshal([]byte(old), received); err != nil {
1561 t.Fatalf("json.Unmarshal failed: %v", err)
1563 if !Equal(received, m) {
1564 t.Fatalf("got %s, want %s", received, m)
1568 func TestBadWireType(t *testing.T) {
1569 b := []byte{7<<3 | 6} // field 7, wire type 6
1570 pb := new(OtherMessage)
1571 if err := Unmarshal(b, pb); err == nil {
1572 t.Errorf("Unmarshal did not fail")
1573 } else if !strings.Contains(err.Error(), "unknown wire type") {
1574 t.Errorf("wrong error: %v", err)
1578 func TestBytesWithInvalidLength(t *testing.T) {
1579 // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
1580 b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
1581 Unmarshal(b, new(MyMessage))
1584 func TestLengthOverflow(t *testing.T) {
1585 // Overflowing a length should not panic.
1586 b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01}
1587 Unmarshal(b, new(MyMessage))
1590 func TestVarintOverflow(t *testing.T) {
1591 // Overflowing a 64-bit length should not be allowed.
1592 b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01}
1593 if err := Unmarshal(b, new(MyMessage)); err == nil {
1594 t.Fatalf("Overflowed uint64 length without error")
1598 func TestUnmarshalFuzz(t *testing.T) {
1600 seed := time.Now().UnixNano()
1601 t.Logf("RNG seed is %d", seed)
1602 rng := rand.New(rand.NewSource(seed))
1603 buf := make([]byte, 20)
1604 for i := 0; i < N; i++ {
1605 for j := range buf {
1606 buf[j] = byte(rng.Intn(256))
1608 fuzzUnmarshal(t, buf)
1612 func TestMergeMessages(t *testing.T) {
1613 pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}}
1614 data, err := Marshal(pb)
1616 t.Fatalf("Marshal: %v", err)
1619 pb1 := new(MessageList)
1620 if err := Unmarshal(data, pb1); err != nil {
1621 t.Fatalf("first Unmarshal: %v", err)
1623 if err := Unmarshal(data, pb1); err != nil {
1624 t.Fatalf("second Unmarshal: %v", err)
1626 if len(pb1.Message) != 1 {
1627 t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
1630 pb2 := new(MessageList)
1631 if err := UnmarshalMerge(data, pb2); err != nil {
1632 t.Fatalf("first UnmarshalMerge: %v", err)
1634 if err := UnmarshalMerge(data, pb2); err != nil {
1635 t.Fatalf("second UnmarshalMerge: %v", err)
1637 if len(pb2.Message) != 2 {
1638 t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
1642 func TestExtensionMarshalOrder(t *testing.T) {
1643 m := &MyMessage{Count: Int(123)}
1644 if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil {
1645 t.Fatalf("SetExtension: %v", err)
1647 if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil {
1648 t.Fatalf("SetExtension: %v", err)
1650 if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil {
1651 t.Fatalf("SetExtension: %v", err)
1654 // Serialize m several times, and check we get the same bytes each time.
1656 for i := 0; i < 100; i++ {
1657 b, err := Marshal(m)
1659 t.Fatalf("Marshal: %v", err)
1665 if !bytes.Equal(b, orig) {
1666 t.Errorf("Bytes differ on attempt #%d", i)
1671 // Many extensions, because small maps might not iterate differently on each iteration.
1672 var exts = []*ExtensionDesc{
1725 func TestMessageSetMarshalOrder(t *testing.T) {
1726 m := &MyMessageSet{}
1727 for _, x := range exts {
1728 if err := SetExtension(m, x, &Empty{}); err != nil {
1729 t.Fatalf("SetExtension: %v", err)
1733 buf, err := Marshal(m)
1735 t.Fatalf("Marshal: %v", err)
1738 // Serialize m several times, and check we get the same bytes each time.
1739 for i := 0; i < 10; i++ {
1740 b1, err := Marshal(m)
1742 t.Fatalf("Marshal: %v", err)
1744 if !bytes.Equal(b1, buf) {
1745 t.Errorf("Bytes differ on re-Marshal #%d", i)
1748 m2 := &MyMessageSet{}
1749 if err := Unmarshal(buf, m2); err != nil {
1750 t.Errorf("Unmarshal: %v", err)
1752 b2, err := Marshal(m2)
1754 t.Errorf("re-Marshal: %v", err)
1756 if !bytes.Equal(b2, buf) {
1757 t.Errorf("Bytes differ on round-trip #%d", i)
1762 func TestUnmarshalMergesMessages(t *testing.T) {
1763 // If a nested message occurs twice in the input,
1764 // the fields should be merged when decoding.
1767 Inner: &InnerMessage{
1768 Host: String("polhode"),
1772 aData, err := Marshal(a)
1774 t.Fatalf("Marshal(a): %v", err)
1777 Weight: Float32(1.2),
1778 Inner: &InnerMessage{
1779 Host: String("herpolhode"),
1780 Connected: Bool(true),
1783 bData, err := Marshal(b)
1785 t.Fatalf("Marshal(b): %v", err)
1787 want := &OtherMessage{
1789 Weight: Float32(1.2),
1790 Inner: &InnerMessage{
1791 Host: String("herpolhode"),
1793 Connected: Bool(true),
1796 got := new(OtherMessage)
1797 if err := Unmarshal(append(aData, bData...), got); err != nil {
1798 t.Fatalf("Unmarshal: %v", err)
1800 if !Equal(got, want) {
1801 t.Errorf("\n got %v\nwant %v", got, want)
1805 func TestEncodingSizes(t *testing.T) {
1810 {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6},
1811 {&Defaults{F_Int32: Int32(math.MinInt32)}, 11},
1812 {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6},
1813 {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6},
1815 for _, test := range tests {
1816 b, err := Marshal(test.m)
1818 t.Errorf("Marshal(%v): %v", test.m, err)
1821 if len(b) != test.n {
1822 t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
1827 func TestRequiredNotSetError(t *testing.T) {
1828 pb := initGoTest(false)
1829 pb.RequiredField.Label = nil
1830 pb.F_Int32Required = nil
1831 pb.F_Int64Required = nil
1833 expected := "0807" + // field 1, encoding 0, value 7
1834 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField)
1835 "5001" + // field 10, encoding 0, value 1
1836 "6d20000000" + // field 13, encoding 5, value 0x20
1837 "714000000000000000" + // field 14, encoding 1, value 0x40
1838 "78a019" + // field 15, encoding 0, value 0xca0 = 3232
1839 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464
1840 "8d0100004a45" + // field 17, encoding 5, value 3232.0
1841 "9101000000000040b940" + // field 18, encoding 1, value 6464.0
1842 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string"
1843 "b304" + // field 70, encoding 3, start group
1844 "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required"
1845 "b404" + // field 70, encoding 4, end group
1846 "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes"
1847 "b0063f" + // field 102, encoding 0, 0x3f zigzag32
1848 "b8067f" // field 103, encoding 0, 0x7f zigzag64
1851 bytes, err := Marshal(pb)
1852 if _, ok := err.(*RequiredNotSetError); !ok {
1853 fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err)
1854 o.DebugPrint("", bytes)
1855 t.Fatalf("expected = %s", expected)
1857 if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1858 t.Errorf("marshal-1 wrong err msg: %v", err)
1860 if !equal(bytes, expected, t) {
1861 o.DebugPrint("neq 1", bytes)
1862 t.Fatalf("expected = %s", expected)
1865 // Now test Unmarshal by recreating the original buffer.
1867 err = Unmarshal(bytes, pbd)
1868 if _, ok := err.(*RequiredNotSetError); !ok {
1869 t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err)
1870 o.DebugPrint("", bytes)
1871 t.Fatalf("string = %s", expected)
1873 if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 {
1874 t.Errorf("unmarshal wrong err msg: %v", err)
1876 bytes, err = Marshal(pbd)
1877 if _, ok := err.(*RequiredNotSetError); !ok {
1878 t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
1879 o.DebugPrint("", bytes)
1880 t.Fatalf("string = %s", expected)
1882 if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1883 t.Errorf("marshal-2 wrong err msg: %v", err)
1885 if !equal(bytes, expected, t) {
1886 o.DebugPrint("neq 2", bytes)
1887 t.Fatalf("string = %s", expected)
1891 func fuzzUnmarshal(t *testing.T, data []byte) {
1893 if e := recover(); e != nil {
1894 t.Errorf("These bytes caused a panic: %+v", data)
1895 t.Logf("Stack:\n%s", debug.Stack())
1900 pb := new(MyMessage)
1904 func TestMapFieldMarshal(t *testing.T) {
1905 m := &MessageWithMap{
1906 NameMapping: map[int32]string{
1912 b, err := Marshal(m)
1914 t.Fatalf("Marshal: %v", err)
1917 // b should be the concatenation of these three byte sequences in some order.
1919 "\n\a\b\x01\x12\x03Rob",
1920 "\n\a\b\x04\x12\x03Ian",
1921 "\n\b\b\x08\x12\x04Dave",
1924 for i := range parts {
1925 for j := range parts {
1929 for k := range parts {
1930 if k == i || k == j {
1933 try := parts[i] + parts[j] + parts[k]
1934 if bytes.Equal(b, []byte(try)) {
1942 t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
1944 t.Logf("FYI b: %q", b)
1946 (new(Buffer)).DebugPrint("Dump of b", b)
1949 func TestMapFieldRoundTrips(t *testing.T) {
1950 m := &MessageWithMap{
1951 NameMapping: map[int32]string{
1956 MsgMapping: map[int64]*FloatingPoint{
1957 0x7001: &FloatingPoint{F: Float64(2.0)},
1959 ByteMapping: map[bool][]byte{
1960 false: []byte("that's not right!"),
1961 true: []byte("aye, 'tis true!"),
1964 b, err := Marshal(m)
1966 t.Fatalf("Marshal: %v", err)
1968 t.Logf("FYI b: %q", b)
1969 m2 := new(MessageWithMap)
1970 if err := Unmarshal(b, m2); err != nil {
1971 t.Fatalf("Unmarshal: %v", err)
1973 for _, pair := range [][2]interface{}{
1974 {m.NameMapping, m2.NameMapping},
1975 {m.MsgMapping, m2.MsgMapping},
1976 {m.ByteMapping, m2.ByteMapping},
1978 if !reflect.DeepEqual(pair[0], pair[1]) {
1979 t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1])
1984 func TestMapFieldWithNil(t *testing.T) {
1985 m1 := &MessageWithMap{
1986 MsgMapping: map[int64]*FloatingPoint{
1990 b, err := Marshal(m1)
1992 t.Fatalf("Marshal: %v", err)
1994 m2 := new(MessageWithMap)
1995 if err := Unmarshal(b, m2); err != nil {
1996 t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
1998 if v, ok := m2.MsgMapping[1]; !ok {
1999 t.Error("msg_mapping[1] not present")
2000 } else if v != nil {
2001 t.Errorf("msg_mapping[1] not nil: %v", v)
2005 func TestMapFieldWithNilBytes(t *testing.T) {
2006 m1 := &MessageWithMap{
2007 ByteMapping: map[bool][]byte{
2013 b, err := Marshal(m1)
2015 t.Fatalf("Marshal: %v", err)
2018 t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b))
2020 m2 := new(MessageWithMap)
2021 if err := Unmarshal(b, m2); err != nil {
2022 t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
2024 if v, ok := m2.ByteMapping[false]; !ok {
2025 t.Error("byte_mapping[false] not present")
2026 } else if len(v) != 0 {
2027 t.Errorf("byte_mapping[false] not empty: %#v", v)
2029 if v, ok := m2.ByteMapping[true]; !ok {
2030 t.Error("byte_mapping[true] not present")
2031 } else if len(v) != 0 {
2032 t.Errorf("byte_mapping[true] not empty: %#v", v)
2036 func TestDecodeMapFieldMissingKey(t *testing.T) {
2038 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
2040 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
2042 got := &MessageWithMap{}
2043 err := Unmarshal(b, got)
2045 t.Fatalf("failed to marshal map with missing key: %v", err)
2047 want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}}
2048 if !Equal(got, want) {
2049 t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
2053 func TestDecodeMapFieldMissingValue(t *testing.T) {
2055 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes
2056 0x08, 0x01, // varint key, value 1
2059 got := &MessageWithMap{}
2060 err := Unmarshal(b, got)
2062 t.Fatalf("failed to marshal map with missing value: %v", err)
2064 want := &MessageWithMap{NameMapping: map[int32]string{1: ""}}
2065 if !Equal(got, want) {
2066 t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
2070 func TestOneof(t *testing.T) {
2072 b, err := Marshal(m)
2074 t.Fatalf("Marshal of empty message with oneof: %v", err)
2077 t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
2081 Union: &Communique_Name{"Barry"},
2087 t.Fatalf("Marshal of message with oneof: %v", err)
2089 if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
2090 t.Errorf("Incorrect marshal of message with oneof: %v", b)
2093 if err := Unmarshal(b, m); err != nil {
2094 t.Fatalf("Unmarshal of message with oneof: %v", err)
2096 if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" {
2097 t.Errorf("After round trip, Union = %+v", m.Union)
2099 if name := m.GetName(); name != "Barry" {
2100 t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
2103 // Let's try with a message in the oneof.
2104 m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}}
2107 t.Fatalf("Marshal of message with oneof set to message: %v", err)
2109 if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
2110 t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
2113 if err := Unmarshal(b, m); err != nil {
2114 t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
2116 ss, ok := m.Union.(*Communique_Msg)
2117 if !ok || ss.Msg.GetStringField() != "deep deep string" {
2118 t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
2122 func TestInefficientPackedBool(t *testing.T) {
2123 // https://github.com/golang/protobuf/issues/76
2125 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes
2126 // Usually a bool should take a single byte,
2127 // but it is permitted to be any varint.
2130 if err := Unmarshal(inp, new(MoreRepeated)); err != nil {
2137 func testMsg() *GoTest {
2138 pb := initGoTest(true)
2139 const N = 1000 // Internally the library starts much smaller.
2140 pb.F_Int32Repeated = make([]int32, N)
2141 pb.F_DoubleRepeated = make([]float64, N)
2142 for i := 0; i < N; i++ {
2143 pb.F_Int32Repeated[i] = int32(i)
2144 pb.F_DoubleRepeated[i] = float64(i)
2149 func bytesMsg() *GoTest {
2150 pb := initGoTest(true)
2151 buf := make([]byte, 4000)
2152 for i := range buf {
2155 pb.F_BytesDefaulted = buf
2159 func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) {
2161 b.SetBytes(int64(len(d)))
2163 for i := 0; i < b.N; i++ {
2168 func benchmarkBufferMarshal(b *testing.B, pb Message) {
2170 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2172 err := p.Marshal(pb0)
2173 return p.Bytes(), err
2177 func benchmarkSize(b *testing.B, pb Message) {
2178 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2184 func newOf(pb Message) Message {
2185 in := reflect.ValueOf(pb)
2189 return reflect.New(in.Type().Elem()).Interface().(Message)
2192 func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) {
2194 b.SetBytes(int64(len(d)))
2198 for i := 0; i < b.N; i++ {
2203 func benchmarkBufferUnmarshal(b *testing.B, pb Message) {
2205 benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error {
2207 return p.Unmarshal(pb0)
2211 // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes}
2213 func BenchmarkMarshal(b *testing.B) {
2214 benchmarkMarshal(b, testMsg(), Marshal)
2217 func BenchmarkBufferMarshal(b *testing.B) {
2218 benchmarkBufferMarshal(b, testMsg())
2221 func BenchmarkSize(b *testing.B) {
2222 benchmarkSize(b, testMsg())
2225 func BenchmarkUnmarshal(b *testing.B) {
2226 benchmarkUnmarshal(b, testMsg(), Unmarshal)
2229 func BenchmarkBufferUnmarshal(b *testing.B) {
2230 benchmarkBufferUnmarshal(b, testMsg())
2233 func BenchmarkMarshalBytes(b *testing.B) {
2234 benchmarkMarshal(b, bytesMsg(), Marshal)
2237 func BenchmarkBufferMarshalBytes(b *testing.B) {
2238 benchmarkBufferMarshal(b, bytesMsg())
2241 func BenchmarkSizeBytes(b *testing.B) {
2242 benchmarkSize(b, bytesMsg())
2245 func BenchmarkUnmarshalBytes(b *testing.B) {
2246 benchmarkUnmarshal(b, bytesMsg(), Unmarshal)
2249 func BenchmarkBufferUnmarshalBytes(b *testing.B) {
2250 benchmarkBufferUnmarshal(b, bytesMsg())
2253 func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) {
2255 pb := initGoTestField()
2256 skip := &GoSkipTest{
2257 SkipInt32: Int32(32),
2258 SkipFixed32: Uint32(3232),
2259 SkipFixed64: Uint64(6464),
2260 SkipString: String("skipper"),
2261 Skipgroup: &GoSkipTest_SkipGroup{
2262 GroupInt32: Int32(75),
2263 GroupString: String("wxyz"),
2267 pbd := new(GoTestField)
2271 p2 := NewBuffer(nil)
2274 for i := 0; i < b.N; i++ {
2275 p2.SetBuf(p.Bytes())