blob: 48883080a3c7f6a60be35d22e11a1ad6cc967c64 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
David Symondsee6e9c52012-11-29 08:51:07 +11003// Copyright 2010 The Go Authors. All rights reserved.
David Symonds558f13f2014-11-24 10:28:53 +11004// https://github.com/golang/protobuf
Rob Pikeaaa3a622010-03-20 22:32:34 -07005//
6// Redistribution and use in source and binary forms, with or without
7// modification, are permitted provided that the following conditions are
8// met:
9//
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
15// distribution.
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.
19//
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.
31
Rob Pikeaaa3a622010-03-20 22:32:34 -070032package proto_test
33
34import (
35 "bytes"
Rob Pike022b1012011-11-08 16:33:51 -080036 "encoding/json"
David Symonds29bcc892014-04-15 14:01:13 +100037 "errors"
Rob Pikeaaa3a622010-03-20 22:32:34 -070038 "fmt"
David Symondsb79d99b2011-08-29 16:38:49 +100039 "math"
David Symonds22ac1502012-01-18 12:37:12 +110040 "math/rand"
David Symonds5b7775e2010-12-01 10:09:04 +110041 "reflect"
David Symonds22ac1502012-01-18 12:37:12 +110042 "runtime/debug"
David Symonds5b7775e2010-12-01 10:09:04 +110043 "strings"
Rob Pikeaaa3a622010-03-20 22:32:34 -070044 "testing"
David Symonds22ac1502012-01-18 12:37:12 +110045 "time"
Rob Pikeaaa3a622010-03-20 22:32:34 -070046
David Symonds558f13f2014-11-24 10:28:53 +110047 . "github.com/golang/protobuf/proto"
David Symondsa8de2842015-03-20 16:24:29 +110048 . "github.com/golang/protobuf/proto/testdata"
Rob Pikeaaa3a622010-03-20 22:32:34 -070049)
50
51var globalO *Buffer
52
53func old() *Buffer {
54 if globalO == nil {
55 globalO = NewBuffer(nil)
56 }
57 globalO.Reset()
58 return globalO
59}
60
61func 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))
64 return
65 }
66 for i := 0; i < len(b1); i++ {
67 if b1[i] != b2[i] {
68 t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
69 }
70 }
71}
72
73func initGoTestField() *GoTestField {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070074 f := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -070075 f.Label = String("label")
76 f.Type = String("type")
77 return f
78}
79
80// These are all structurally equivalent but the tag numbers differ.
81// (It's remarkable that required, optional, and repeated all have
82// 8 letters.)
83func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070084 return &GoTest_RequiredGroup{
85 RequiredField: String("required"),
86 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070087}
88
89func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070090 return &GoTest_OptionalGroup{
91 RequiredField: String("optional"),
92 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070093}
94
95func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070096 return &GoTest_RepeatedGroup{
97 RequiredField: String("repeated"),
98 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070099}
100
101func initGoTest(setdefaults bool) *GoTest {
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700102 pb := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700103 if setdefaults {
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)
117 }
118
David Symondsefeca9a2012-05-08 10:36:04 +1000119 pb.Kind = GoTest_TIME.Enum()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700120 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()
135
136 return pb
137}
138
139func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
140 data := b.Bytes()
141 ld := len(data)
142 ls := len(s) / 2
143
144 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
145
146 // find the interesting spot - n
147 n := ls
148 if ld < ls {
149 n = ld
150 }
151 j := 0
152 for i := 0; i < n; i++ {
153 bs := hex(s[j])*16 + hex(s[j+1])
154 j += 2
155 if data[i] == bs {
156 continue
157 }
158 n = i
159 break
160 }
161 l := n - 10
162 if l < 0 {
163 l = 0
164 }
165 h := n + 10
166
167 // find the interesting spot - n
168 fmt.Printf("is[%d]:", l)
169 for i := l; i < h; i++ {
170 if i >= ld {
171 fmt.Printf(" --")
172 continue
173 }
174 fmt.Printf(" %.2x", data[i])
175 }
176 fmt.Printf("\n")
177
178 fmt.Printf("sb[%d]:", l)
179 for i := l; i < h; i++ {
180 if i >= ls {
181 fmt.Printf(" --")
182 continue
183 }
184 bs := hex(s[j])*16 + hex(s[j+1])
185 j += 2
186 fmt.Printf(" %.2x", bs)
187 }
188 fmt.Printf("\n")
189
190 t.Fail()
191
Rob Pikeaaa3a622010-03-20 22:32:34 -0700192 // 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().
196 // data := b.Bytes()
197 // nesting := 0
198 // for b.Len() > 0 {
199 // start := len(data) - b.Len()
200 // var u uint64
201 // u, err := DecodeVarint(b)
202 // if err != nil {
203 // fmt.Printf("decode error on varint:", err)
204 // return
205 // }
206 // wire := u & 0x7
207 // tag := u >> 3
208 // switch wire {
209 // case WireVarint:
210 // v, err := DecodeVarint(b)
211 // if err != nil {
212 // fmt.Printf("decode error on varint:", err)
213 // return
214 // }
215 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
216 // data[start:len(data)-b.Len()], tag, wire, v)
217 // case WireFixed32:
218 // v, err := DecodeFixed32(b)
219 // if err != nil {
220 // fmt.Printf("decode error on fixed32:", err)
221 // return
222 // }
223 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
224 // data[start:len(data)-b.Len()], tag, wire, v)
225 // case WireFixed64:
226 // v, err := DecodeFixed64(b)
227 // if err != nil {
228 // fmt.Printf("decode error on fixed64:", err)
229 // return
230 // }
231 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
232 // data[start:len(data)-b.Len()], tag, wire, v)
233 // case WireBytes:
234 // nb, err := DecodeVarint(b)
235 // if err != nil {
236 // fmt.Printf("decode error on bytes:", err)
237 // return
238 // }
239 // after_tag := len(data) - b.Len()
240 // str := make([]byte, nb)
241 // _, err = b.Read(str)
242 // if err != nil {
243 // fmt.Printf("decode error on bytes:", err)
244 // return
245 // }
246 // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n",
247 // data[start:after_tag], str, tag, wire)
248 // case WireStartGroup:
249 // nesting++
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)
255 // nesting--
256 // default:
257 // fmt.Printf("unrecognized wire type %d\n", wire)
258 // return
259 // }
260 // }
261}
262
263func hex(c uint8) uint8 {
264 if '0' <= c && c <= '9' {
265 return c - '0'
266 }
267 if 'a' <= c && c <= 'f' {
268 return 10 + c - 'a'
269 }
270 if 'A' <= c && c <= 'F' {
271 return 10 + c - 'A'
272 }
273 return 0
274}
275
276func 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))
280 return false
281 }
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])
284 if b[i] != x {
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)
287 return false
288 }
289 }
290 return true
291}
292
293func overify(t *testing.T, pb *GoTest, expected string) {
294 o := old()
295 err := o.Marshal(pb)
296 if err != nil {
297 fmt.Printf("overify marshal-1 err = %v", err)
298 o.DebugPrint("", o.Bytes())
299 t.Fatalf("expected = %s", expected)
300 }
301 if !equal(o.Bytes(), expected, t) {
302 o.DebugPrint("overify neq 1", o.Bytes())
303 t.Fatalf("expected = %s", expected)
304 }
305
306 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700307 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700308 err = o.Unmarshal(pbd)
309 if err != nil {
310 t.Fatalf("overify unmarshal err = %v", err)
311 o.DebugPrint("", o.Bytes())
312 t.Fatalf("string = %s", expected)
313 }
314 o.Reset()
315 err = o.Marshal(pbd)
316 if err != nil {
317 t.Errorf("overify marshal-2 err = %v", err)
318 o.DebugPrint("", o.Bytes())
319 t.Fatalf("string = %s", expected)
320 }
321 if !equal(o.Bytes(), expected, t) {
322 o.DebugPrint("overify neq 2", o.Bytes())
323 t.Fatalf("string = %s", expected)
324 }
325}
326
327// Simple tests for numeric encode/decode primitives (varint, etc.)
328func TestNumericPrimitives(t *testing.T) {
329 for i := uint64(0); i < 1e6; i += 111 {
330 o := old()
331 if o.EncodeVarint(i) != nil {
332 t.Error("EncodeVarint")
333 break
334 }
335 x, e := o.DecodeVarint()
336 if e != nil {
337 t.Fatal("DecodeVarint")
338 }
339 if x != i {
340 t.Fatal("varint decode fail:", i, x)
341 }
342
343 o = old()
344 if o.EncodeFixed32(i) != nil {
345 t.Fatal("encFixed32")
346 }
347 x, e = o.DecodeFixed32()
348 if e != nil {
349 t.Fatal("decFixed32")
350 }
351 if x != i {
352 t.Fatal("fixed32 decode fail:", i, x)
353 }
354
355 o = old()
356 if o.EncodeFixed64(i*1234567) != nil {
357 t.Error("encFixed64")
358 break
359 }
360 x, e = o.DecodeFixed64()
361 if e != nil {
362 t.Error("decFixed64")
363 break
364 }
365 if x != i*1234567 {
366 t.Error("fixed64 decode fail:", i*1234567, x)
367 break
368 }
369
370 o = old()
371 i32 := int32(i - 12345)
372 if o.EncodeZigzag32(uint64(i32)) != nil {
373 t.Fatal("EncodeZigzag32")
374 }
375 x, e = o.DecodeZigzag32()
376 if e != nil {
377 t.Fatal("DecodeZigzag32")
378 }
379 if x != uint64(uint32(i32)) {
380 t.Fatal("zigzag32 decode fail:", i32, x)
381 }
382
383 o = old()
384 i64 := int64(i - 12345)
385 if o.EncodeZigzag64(uint64(i64)) != nil {
386 t.Fatal("EncodeZigzag64")
387 }
388 x, e = o.DecodeZigzag64()
389 if e != nil {
390 t.Fatal("DecodeZigzag64")
391 }
392 if x != uint64(i64) {
393 t.Fatal("zigzag64 decode fail:", i64, x)
394 }
395 }
396}
397
David Symonds29bcc892014-04-15 14:01:13 +1000398// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
399type fakeMarshaler struct {
400 b []byte
401 err error
402}
403
David Symonds68c687d2015-07-27 19:06:00 +1000404func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
405func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
406func (f *fakeMarshaler) ProtoMessage() {}
407func (f *fakeMarshaler) Reset() {}
408
409type msgWithFakeMarshaler struct {
410 M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
David Symonds29bcc892014-04-15 14:01:13 +1000411}
412
David Symonds68c687d2015-07-27 19:06:00 +1000413func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) }
414func (m *msgWithFakeMarshaler) ProtoMessage() {}
415func (m *msgWithFakeMarshaler) Reset() {}
David Symonds29bcc892014-04-15 14:01:13 +1000416
417// Simple tests for proto messages that implement the Marshaler interface.
418func TestMarshalerEncoding(t *testing.T) {
419 tests := []struct {
420 name string
421 m Message
422 want []byte
423 wantErr error
424 }{
425 {
426 name: "Marshaler that fails",
David Symonds68c687d2015-07-27 19:06:00 +1000427 m: &fakeMarshaler{
David Symonds29bcc892014-04-15 14:01:13 +1000428 err: errors.New("some marshal err"),
429 b: []byte{5, 6, 7},
430 },
431 // Since there's an error, nothing should be written to buffer.
432 want: nil,
433 wantErr: errors.New("some marshal err"),
434 },
435 {
David Symonds68c687d2015-07-27 19:06:00 +1000436 name: "Marshaler that fails with RequiredNotSetError",
437 m: &msgWithFakeMarshaler{
438 M: &fakeMarshaler{
439 err: &RequiredNotSetError{},
440 b: []byte{5, 6, 7},
441 },
442 },
443 // Since there's an error that can be continued after,
444 // the buffer should be written.
445 want: []byte{
446 10, 3, // for &msgWithFakeMarshaler
447 5, 6, 7, // for &fakeMarshaler
448 },
449 wantErr: &RequiredNotSetError{},
450 },
451 {
David Symonds29bcc892014-04-15 14:01:13 +1000452 name: "Marshaler that succeeds",
David Symonds68c687d2015-07-27 19:06:00 +1000453 m: &fakeMarshaler{
David Symonds29bcc892014-04-15 14:01:13 +1000454 b: []byte{0, 1, 2, 3, 4, 127, 255},
455 },
456 want: []byte{0, 1, 2, 3, 4, 127, 255},
457 wantErr: nil,
458 },
459 }
460 for _, test := range tests {
461 b := NewBuffer(nil)
462 err := b.Marshal(test.m)
David Symonds68c687d2015-07-27 19:06:00 +1000463 if _, ok := err.(*RequiredNotSetError); ok {
464 // We're not in package proto, so we can only assert the type in this case.
465 err = &RequiredNotSetError{}
466 }
David Symonds29bcc892014-04-15 14:01:13 +1000467 if !reflect.DeepEqual(test.wantErr, err) {
468 t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr)
469 }
470 if !reflect.DeepEqual(test.want, b.Bytes()) {
471 t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
472 }
473 }
474}
475
Rob Pikeaaa3a622010-03-20 22:32:34 -0700476// Simple tests for bytes
477func TestBytesPrimitives(t *testing.T) {
478 o := old()
479 bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
480 if o.EncodeRawBytes(bytes) != nil {
481 t.Error("EncodeRawBytes")
482 }
483 decb, e := o.DecodeRawBytes(false)
484 if e != nil {
485 t.Error("DecodeRawBytes")
486 }
487 equalbytes(bytes, decb, t)
488}
489
490// Simple tests for strings
491func TestStringPrimitives(t *testing.T) {
492 o := old()
493 s := "now is the time"
494 if o.EncodeStringBytes(s) != nil {
495 t.Error("enc_string")
496 }
497 decs, e := o.DecodeStringBytes()
498 if e != nil {
499 t.Error("dec_string")
500 }
501 if s != decs {
502 t.Error("string encode/decode fail:", s, decs)
503 }
504}
505
506// Do we catch the "required bit not set" case?
507func TestRequiredBit(t *testing.T) {
508 o := old()
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700509 pb := new(GoTest)
David Symonds5b7775e2010-12-01 10:09:04 +1100510 err := o.Marshal(pb)
511 if err == nil {
512 t.Error("did not catch missing required fields")
David Symonds4646c372013-09-09 13:18:58 +1000513 } else if strings.Index(err.Error(), "Kind") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +1100514 t.Error("wrong error type:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700515 }
516}
517
518// Check that all fields are nil.
519// Clearly silly, and a residue from a more interesting test with an earlier,
520// different initialization property, but it once caught a compiler bug so
521// it lives.
522func checkInitialized(pb *GoTest, t *testing.T) {
523 if pb.F_BoolDefaulted != nil {
524 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
525 }
526 if pb.F_Int32Defaulted != nil {
527 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
528 }
529 if pb.F_Int64Defaulted != nil {
530 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
531 }
532 if pb.F_Fixed32Defaulted != nil {
533 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
534 }
535 if pb.F_Fixed64Defaulted != nil {
536 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
537 }
538 if pb.F_Uint32Defaulted != nil {
539 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
540 }
541 if pb.F_Uint64Defaulted != nil {
542 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
543 }
544 if pb.F_FloatDefaulted != nil {
545 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
546 }
547 if pb.F_DoubleDefaulted != nil {
548 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
549 }
550 if pb.F_StringDefaulted != nil {
551 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
552 }
553 if pb.F_BytesDefaulted != nil {
554 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
555 }
556 if pb.F_Sint32Defaulted != nil {
557 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
558 }
559 if pb.F_Sint64Defaulted != nil {
560 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
561 }
562}
563
564// Does Reset() reset?
565func TestReset(t *testing.T) {
566 pb := initGoTest(true)
567 // muck with some values
568 pb.F_BoolDefaulted = Bool(false)
569 pb.F_Int32Defaulted = Int32(237)
570 pb.F_Int64Defaulted = Int64(12346)
571 pb.F_Fixed32Defaulted = Uint32(32000)
572 pb.F_Fixed64Defaulted = Uint64(666)
573 pb.F_Uint32Defaulted = Uint32(323232)
574 pb.F_Uint64Defaulted = nil
575 pb.F_FloatDefaulted = nil
576 pb.F_DoubleDefaulted = Float64(0)
577 pb.F_StringDefaulted = String("gotcha")
578 pb.F_BytesDefaulted = []byte("asdfasdf")
579 pb.F_Sint32Defaulted = Int32(123)
580 pb.F_Sint64Defaulted = Int64(789)
581 pb.Reset()
582 checkInitialized(pb, t)
583}
584
585// All required fields set, no defaults provided.
586func TestEncodeDecode1(t *testing.T) {
587 pb := initGoTest(false)
588 overify(t, pb,
589 "0807"+ // field 1, encoding 0, value 7
590 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
591 "5001"+ // field 10, encoding 0, value 1
592 "5803"+ // field 11, encoding 0, value 3
593 "6006"+ // field 12, encoding 0, value 6
594 "6d20000000"+ // field 13, encoding 5, value 0x20
595 "714000000000000000"+ // field 14, encoding 1, value 0x40
596 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
597 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
598 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
599 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
600 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700601 "b304"+ // field 70, encoding 3, start group
602 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700603 "b404"+ // field 70, encoding 4, end group
604 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
605 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
606 "b8067f") // field 103, encoding 0, 0x7f zigzag64
Rob Pikeaaa3a622010-03-20 22:32:34 -0700607}
608
609// All required fields set, defaults provided.
610func TestEncodeDecode2(t *testing.T) {
611 pb := initGoTest(true)
612 overify(t, pb,
613 "0807"+ // field 1, encoding 0, value 7
614 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
615 "5001"+ // field 10, encoding 0, value 1
616 "5803"+ // field 11, encoding 0, value 3
617 "6006"+ // field 12, encoding 0, value 6
618 "6d20000000"+ // field 13, encoding 5, value 32
619 "714000000000000000"+ // field 14, encoding 1, value 64
620 "78a019"+ // field 15, encoding 0, value 3232
621 "8001c032"+ // field 16, encoding 0, value 6464
622 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
623 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
624 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700625 "c00201"+ // field 40, encoding 0, value 1
626 "c80220"+ // field 41, encoding 0, value 32
627 "d00240"+ // field 42, encoding 0, value 64
628 "dd0240010000"+ // field 43, encoding 5, value 320
629 "e1028002000000000000"+ // field 44, encoding 1, value 640
630 "e8028019"+ // field 45, encoding 0, value 3200
631 "f0028032"+ // field 46, encoding 0, value 6400
632 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
633 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
634 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700635 "b304"+ // start group field 70 level 1
636 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700637 "b404"+ // end group field 70 level 1
638 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
639 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
640 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
641 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
642 "90193f"+ // field 402, encoding 0, value 63
643 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700644
645}
646
647// All default fields set to their default value by hand
648func TestEncodeDecode3(t *testing.T) {
649 pb := initGoTest(false)
650 pb.F_BoolDefaulted = Bool(true)
651 pb.F_Int32Defaulted = Int32(32)
652 pb.F_Int64Defaulted = Int64(64)
653 pb.F_Fixed32Defaulted = Uint32(320)
654 pb.F_Fixed64Defaulted = Uint64(640)
655 pb.F_Uint32Defaulted = Uint32(3200)
656 pb.F_Uint64Defaulted = Uint64(6400)
657 pb.F_FloatDefaulted = Float32(314159)
658 pb.F_DoubleDefaulted = Float64(271828)
659 pb.F_StringDefaulted = String("hello, \"world!\"\n")
660 pb.F_BytesDefaulted = []byte("Bignose")
661 pb.F_Sint32Defaulted = Int32(-32)
662 pb.F_Sint64Defaulted = Int64(-64)
663
664 overify(t, pb,
665 "0807"+ // field 1, encoding 0, value 7
666 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
667 "5001"+ // field 10, encoding 0, value 1
668 "5803"+ // field 11, encoding 0, value 3
669 "6006"+ // field 12, encoding 0, value 6
670 "6d20000000"+ // field 13, encoding 5, value 32
671 "714000000000000000"+ // field 14, encoding 1, value 64
672 "78a019"+ // field 15, encoding 0, value 3232
673 "8001c032"+ // field 16, encoding 0, value 6464
674 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
675 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
676 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700677 "c00201"+ // field 40, encoding 0, value 1
678 "c80220"+ // field 41, encoding 0, value 32
679 "d00240"+ // field 42, encoding 0, value 64
680 "dd0240010000"+ // field 43, encoding 5, value 320
681 "e1028002000000000000"+ // field 44, encoding 1, value 640
682 "e8028019"+ // field 45, encoding 0, value 3200
683 "f0028032"+ // field 46, encoding 0, value 6400
684 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
685 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
686 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700687 "b304"+ // start group field 70 level 1
688 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700689 "b404"+ // end group field 70 level 1
690 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
691 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
692 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
693 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
694 "90193f"+ // field 402, encoding 0, value 63
695 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700696
697}
698
699// All required fields set, defaults provided, all non-defaulted optional fields have values.
700func TestEncodeDecode4(t *testing.T) {
701 pb := initGoTest(true)
702 pb.Table = String("hello")
703 pb.Param = Int32(7)
704 pb.OptionalField = initGoTestField()
705 pb.F_BoolOptional = Bool(true)
706 pb.F_Int32Optional = Int32(32)
707 pb.F_Int64Optional = Int64(64)
708 pb.F_Fixed32Optional = Uint32(3232)
709 pb.F_Fixed64Optional = Uint64(6464)
710 pb.F_Uint32Optional = Uint32(323232)
711 pb.F_Uint64Optional = Uint64(646464)
712 pb.F_FloatOptional = Float32(32.)
713 pb.F_DoubleOptional = Float64(64.)
714 pb.F_StringOptional = String("hello")
715 pb.F_BytesOptional = []byte("Bignose")
716 pb.F_Sint32Optional = Int32(-32)
717 pb.F_Sint64Optional = Int64(-64)
718 pb.Optionalgroup = initGoTest_OptionalGroup()
719
720 overify(t, pb,
721 "0807"+ // field 1, encoding 0, value 7
722 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
723 "1807"+ // field 3, encoding 0, value 7
724 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
725 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
726 "5001"+ // field 10, encoding 0, value 1
727 "5803"+ // field 11, encoding 0, value 3
728 "6006"+ // field 12, encoding 0, value 6
729 "6d20000000"+ // field 13, encoding 5, value 32
730 "714000000000000000"+ // field 14, encoding 1, value 64
731 "78a019"+ // field 15, encoding 0, value 3232
732 "8001c032"+ // field 16, encoding 0, value 6464
733 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
734 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
735 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700736 "f00101"+ // field 30, encoding 0, value 1
737 "f80120"+ // field 31, encoding 0, value 32
738 "800240"+ // field 32, encoding 0, value 64
739 "8d02a00c0000"+ // field 33, encoding 5, value 3232
740 "91024019000000000000"+ // field 34, encoding 1, value 6464
741 "9802a0dd13"+ // field 35, encoding 0, value 323232
742 "a002c0ba27"+ // field 36, encoding 0, value 646464
743 "ad0200000042"+ // field 37, encoding 5, value 32.0
744 "b1020000000000005040"+ // field 38, encoding 1, value 64.0
745 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700746 "c00201"+ // field 40, encoding 0, value 1
747 "c80220"+ // field 41, encoding 0, value 32
748 "d00240"+ // field 42, encoding 0, value 64
749 "dd0240010000"+ // field 43, encoding 5, value 320
750 "e1028002000000000000"+ // field 44, encoding 1, value 640
751 "e8028019"+ // field 45, encoding 0, value 3200
752 "f0028032"+ // field 46, encoding 0, value 6400
753 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
754 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
755 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700756 "b304"+ // start group field 70 level 1
757 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
758 "b404"+ // end group field 70 level 1
759 "d305"+ // start group field 90 level 1
760 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
David Symondsd15e81b2011-10-03 14:31:12 -0700761 "d405"+ // end group field 90 level 1
762 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
763 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
764 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
765 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
766 "f0123f"+ // field 302, encoding 0, value 63
767 "f8127f"+ // field 303, encoding 0, value 127
768 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
769 "90193f"+ // field 402, encoding 0, value 63
770 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700771
772}
773
774// All required fields set, defaults provided, all repeated fields given two values.
775func TestEncodeDecode5(t *testing.T) {
776 pb := initGoTest(true)
777 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
778 pb.F_BoolRepeated = []bool{false, true}
779 pb.F_Int32Repeated = []int32{32, 33}
780 pb.F_Int64Repeated = []int64{64, 65}
781 pb.F_Fixed32Repeated = []uint32{3232, 3333}
782 pb.F_Fixed64Repeated = []uint64{6464, 6565}
783 pb.F_Uint32Repeated = []uint32{323232, 333333}
784 pb.F_Uint64Repeated = []uint64{646464, 656565}
785 pb.F_FloatRepeated = []float32{32., 33.}
786 pb.F_DoubleRepeated = []float64{64., 65.}
787 pb.F_StringRepeated = []string{"hello", "sailor"}
788 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
789 pb.F_Sint32Repeated = []int32{32, -32}
790 pb.F_Sint64Repeated = []int64{64, -64}
791 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
792
793 overify(t, pb,
794 "0807"+ // field 1, encoding 0, value 7
795 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
796 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
797 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
798 "5001"+ // field 10, encoding 0, value 1
799 "5803"+ // field 11, encoding 0, value 3
800 "6006"+ // field 12, encoding 0, value 6
801 "6d20000000"+ // field 13, encoding 5, value 32
802 "714000000000000000"+ // field 14, encoding 1, value 64
803 "78a019"+ // field 15, encoding 0, value 3232
804 "8001c032"+ // field 16, encoding 0, value 6464
805 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
806 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
807 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700808 "a00100"+ // field 20, encoding 0, value 0
809 "a00101"+ // field 20, encoding 0, value 1
810 "a80120"+ // field 21, encoding 0, value 32
811 "a80121"+ // field 21, encoding 0, value 33
812 "b00140"+ // field 22, encoding 0, value 64
813 "b00141"+ // field 22, encoding 0, value 65
814 "bd01a00c0000"+ // field 23, encoding 5, value 3232
815 "bd01050d0000"+ // field 23, encoding 5, value 3333
816 "c1014019000000000000"+ // field 24, encoding 1, value 6464
817 "c101a519000000000000"+ // field 24, encoding 1, value 6565
818 "c801a0dd13"+ // field 25, encoding 0, value 323232
819 "c80195ac14"+ // field 25, encoding 0, value 333333
820 "d001c0ba27"+ // field 26, encoding 0, value 646464
821 "d001b58928"+ // field 26, encoding 0, value 656565
822 "dd0100000042"+ // field 27, encoding 5, value 32.0
823 "dd0100000442"+ // field 27, encoding 5, value 33.0
824 "e1010000000000005040"+ // field 28, encoding 1, value 64.0
825 "e1010000000000405040"+ // field 28, encoding 1, value 65.0
826 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
827 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700828 "c00201"+ // field 40, encoding 0, value 1
829 "c80220"+ // field 41, encoding 0, value 32
830 "d00240"+ // field 42, encoding 0, value 64
831 "dd0240010000"+ // field 43, encoding 5, value 320
832 "e1028002000000000000"+ // field 44, encoding 1, value 640
833 "e8028019"+ // field 45, encoding 0, value 3200
834 "f0028032"+ // field 46, encoding 0, value 6400
835 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
836 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
837 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700838 "b304"+ // start group field 70 level 1
839 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
840 "b404"+ // end group field 70 level 1
841 "8305"+ // start group field 80 level 1
842 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
843 "8405"+ // end group field 80 level 1
844 "8305"+ // start group field 80 level 1
845 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
David Symondsd15e81b2011-10-03 14:31:12 -0700846 "8405"+ // end group field 80 level 1
847 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
848 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
849 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
850 "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
851 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
852 "d00c40"+ // field 202, encoding 0, value 32
853 "d00c3f"+ // field 202, encoding 0, value -32
854 "d80c8001"+ // field 203, encoding 0, value 64
855 "d80c7f"+ // field 203, encoding 0, value -64
856 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
857 "90193f"+ // field 402, encoding 0, value 63
858 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700859
860}
861
David Symonds5b7775e2010-12-01 10:09:04 +1100862// All required fields set, all packed repeated fields given two values.
863func TestEncodeDecode6(t *testing.T) {
864 pb := initGoTest(false)
865 pb.F_BoolRepeatedPacked = []bool{false, true}
866 pb.F_Int32RepeatedPacked = []int32{32, 33}
867 pb.F_Int64RepeatedPacked = []int64{64, 65}
868 pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
869 pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
870 pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
871 pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
872 pb.F_FloatRepeatedPacked = []float32{32., 33.}
873 pb.F_DoubleRepeatedPacked = []float64{64., 65.}
874 pb.F_Sint32RepeatedPacked = []int32{32, -32}
875 pb.F_Sint64RepeatedPacked = []int64{64, -64}
876
877 overify(t, pb,
878 "0807"+ // field 1, encoding 0, value 7
879 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
880 "5001"+ // field 10, encoding 0, value 1
881 "5803"+ // field 11, encoding 0, value 3
882 "6006"+ // field 12, encoding 0, value 6
883 "6d20000000"+ // field 13, encoding 5, value 32
884 "714000000000000000"+ // field 14, encoding 1, value 64
885 "78a019"+ // field 15, encoding 0, value 3232
886 "8001c032"+ // field 16, encoding 0, value 6464
887 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
888 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
889 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
David Symonds5b7775e2010-12-01 10:09:04 +1100890 "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
891 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
892 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
893 "aa0308"+ // field 53, encoding 2, 8 bytes
894 "a00c0000050d0000"+ // value 3232, value 3333
895 "b20310"+ // field 54, encoding 2, 16 bytes
896 "4019000000000000a519000000000000"+ // value 6464, value 6565
897 "ba0306"+ // field 55, encoding 2, 6 bytes
898 "a0dd1395ac14"+ // value 323232, value 333333
899 "c20306"+ // field 56, encoding 2, 6 bytes
900 "c0ba27b58928"+ // value 646464, value 656565
901 "ca0308"+ // field 57, encoding 2, 8 bytes
902 "0000004200000442"+ // value 32.0, value 33.0
903 "d20310"+ // field 58, encoding 2, 16 bytes
904 "00000000000050400000000000405040"+ // value 64.0, value 65.0
David Symondsd15e81b2011-10-03 14:31:12 -0700905 "b304"+ // start group field 70 level 1
906 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
907 "b404"+ // end group field 70 level 1
908 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
909 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
910 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
David Symonds5b7775e2010-12-01 10:09:04 +1100911 "b21f02"+ // field 502, encoding 2, 2 bytes
912 "403f"+ // value 32, value -32
913 "ba1f03"+ // field 503, encoding 2, 3 bytes
David Symondsd15e81b2011-10-03 14:31:12 -0700914 "80017f") // value 64, value -64
David Symonds5b7775e2010-12-01 10:09:04 +1100915}
916
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800917// Test that we can encode empty bytes fields.
918func TestEncodeDecodeBytes1(t *testing.T) {
919 pb := initGoTest(false)
920
921 // Create our bytes
922 pb.F_BytesRequired = []byte{}
David Symondsd9da6ba2011-08-30 14:41:30 +1000923 pb.F_BytesRepeated = [][]byte{{}}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800924 pb.F_BytesOptional = []byte{}
925
926 d, err := Marshal(pb)
927 if err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700928 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800929 }
930
931 pbd := new(GoTest)
932 if err := Unmarshal(d, pbd); err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700933 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800934 }
935
936 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
Rob Pikea17fdd92011-11-02 12:43:05 -0700937 t.Error("required empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800938 }
939 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700940 t.Error("repeated empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800941 }
942 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
Rob Pikea17fdd92011-11-02 12:43:05 -0700943 t.Error("optional empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800944 }
945}
946
947// Test that we encode nil-valued fields of a repeated bytes field correctly.
948// Since entries in a repeated field cannot be nil, nil must mean empty value.
949func TestEncodeDecodeBytes2(t *testing.T) {
950 pb := initGoTest(false)
951
952 // Create our bytes
David Symonds5b7775e2010-12-01 10:09:04 +1100953 pb.F_BytesRepeated = [][]byte{nil}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800954
955 d, err := Marshal(pb)
David Symonds5b7775e2010-12-01 10:09:04 +1100956 if err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700957 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800958 }
959
960 pbd := new(GoTest)
961 if err := Unmarshal(d, pbd); err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700962 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800963 }
964
965 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700966 t.Error("Unexpected value for repeated bytes field")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800967 }
968}
969
Rob Pikeaaa3a622010-03-20 22:32:34 -0700970// All required fields set, defaults provided, all repeated fields given two values.
971func TestSkippingUnrecognizedFields(t *testing.T) {
972 o := old()
973 pb := initGoTestField()
974
975 // Marshal it normally.
976 o.Marshal(pb)
977
978 // Now new a GoSkipTest record.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700979 skip := &GoSkipTest{
980 SkipInt32: Int32(32),
981 SkipFixed32: Uint32(3232),
982 SkipFixed64: Uint64(6464),
983 SkipString: String("skipper"),
984 Skipgroup: &GoSkipTest_SkipGroup{
985 GroupInt32: Int32(75),
986 GroupString: String("wxyz"),
987 },
988 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700989
990 // Marshal it into same buffer.
991 o.Marshal(skip)
992
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700993 pbd := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700994 o.Unmarshal(pbd)
995
996 // The __unrecognized field should be a marshaling of GoSkipTest
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700997 skipd := new(GoSkipTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700998
999 o.SetBuf(pbd.XXX_unrecognized)
1000 o.Unmarshal(skipd)
1001
1002 if *skipd.SkipInt32 != *skip.SkipInt32 {
1003 t.Error("skip int32", skipd.SkipInt32)
1004 }
1005 if *skipd.SkipFixed32 != *skip.SkipFixed32 {
1006 t.Error("skip fixed32", skipd.SkipFixed32)
1007 }
1008 if *skipd.SkipFixed64 != *skip.SkipFixed64 {
1009 t.Error("skip fixed64", skipd.SkipFixed64)
1010 }
1011 if *skipd.SkipString != *skip.SkipString {
1012 t.Error("skip string", *skipd.SkipString)
1013 }
1014 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
1015 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
1016 }
1017 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
1018 t.Error("skip group string", *skipd.Skipgroup.GroupString)
1019 }
1020}
1021
David Symonds10c93ba2012-08-04 16:38:08 +10001022// Check that unrecognized fields of a submessage are preserved.
1023func TestSubmessageUnrecognizedFields(t *testing.T) {
1024 nm := &NewMessage{
1025 Nested: &NewMessage_Nested{
1026 Name: String("Nigel"),
1027 FoodGroup: String("carbs"),
1028 },
1029 }
1030 b, err := Marshal(nm)
1031 if err != nil {
1032 t.Fatalf("Marshal of NewMessage: %v", err)
1033 }
1034
1035 // Unmarshal into an OldMessage.
1036 om := new(OldMessage)
1037 if err := Unmarshal(b, om); err != nil {
1038 t.Fatalf("Unmarshal to OldMessage: %v", err)
1039 }
1040 exp := &OldMessage{
1041 Nested: &OldMessage_Nested{
1042 Name: String("Nigel"),
1043 // normal protocol buffer users should not do this
1044 XXX_unrecognized: []byte("\x12\x05carbs"),
1045 },
1046 }
1047 if !Equal(om, exp) {
1048 t.Errorf("om = %v, want %v", om, exp)
1049 }
1050
1051 // Clone the OldMessage.
1052 om = Clone(om).(*OldMessage)
1053 if !Equal(om, exp) {
1054 t.Errorf("Clone(om) = %v, want %v", om, exp)
1055 }
1056
1057 // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
1058 if b, err = Marshal(om); err != nil {
1059 t.Fatalf("Marshal of OldMessage: %v", err)
1060 }
1061 t.Logf("Marshal(%v) -> %q", om, b)
1062 nm2 := new(NewMessage)
1063 if err := Unmarshal(b, nm2); err != nil {
1064 t.Fatalf("Unmarshal to NewMessage: %v", err)
1065 }
1066 if !Equal(nm, nm2) {
1067 t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
1068 }
1069}
1070
David Symondsf054e842014-07-22 14:06:27 +10001071// Check that an int32 field can be upgraded to an int64 field.
1072func TestNegativeInt32(t *testing.T) {
1073 om := &OldMessage{
1074 Num: Int32(-1),
1075 }
1076 b, err := Marshal(om)
1077 if err != nil {
1078 t.Fatalf("Marshal of OldMessage: %v", err)
1079 }
1080
1081 // Check the size. It should be 11 bytes;
1082 // 1 for the field/wire type, and 10 for the negative number.
1083 if len(b) != 11 {
1084 t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
1085 }
1086
1087 // Unmarshal into a NewMessage.
1088 nm := new(NewMessage)
1089 if err := Unmarshal(b, nm); err != nil {
1090 t.Fatalf("Unmarshal to NewMessage: %v", err)
1091 }
1092 want := &NewMessage{
1093 Num: Int64(-1),
1094 }
1095 if !Equal(nm, want) {
1096 t.Errorf("nm = %v, want %v", nm, want)
1097 }
1098}
1099
Rob Pikeaaa3a622010-03-20 22:32:34 -07001100// Check that we can grow an array (repeated field) to have many elements.
1101// This test doesn't depend only on our encoding; for variety, it makes sure
1102// we create, encode, and decode the correct contents explicitly. It's therefore
1103// a bit messier.
1104// This test also uses (and hence tests) the Marshal/Unmarshal functions
1105// instead of the methods.
1106func TestBigRepeated(t *testing.T) {
1107 pb := initGoTest(true)
1108
1109 // Create the arrays
1110 const N = 50 // Internally the library starts much smaller.
1111 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
1112 pb.F_Sint64Repeated = make([]int64, N)
1113 pb.F_Sint32Repeated = make([]int32, N)
1114 pb.F_BytesRepeated = make([][]byte, N)
1115 pb.F_StringRepeated = make([]string, N)
1116 pb.F_DoubleRepeated = make([]float64, N)
1117 pb.F_FloatRepeated = make([]float32, N)
1118 pb.F_Uint64Repeated = make([]uint64, N)
1119 pb.F_Uint32Repeated = make([]uint32, N)
1120 pb.F_Fixed64Repeated = make([]uint64, N)
1121 pb.F_Fixed32Repeated = make([]uint32, N)
1122 pb.F_Int64Repeated = make([]int64, N)
1123 pb.F_Int32Repeated = make([]int32, N)
1124 pb.F_BoolRepeated = make([]bool, N)
1125 pb.RepeatedField = make([]*GoTestField, N)
1126
1127 // Fill in the arrays with checkable values.
1128 igtf := initGoTestField()
1129 igtrg := initGoTest_RepeatedGroup()
1130 for i := 0; i < N; i++ {
1131 pb.Repeatedgroup[i] = igtrg
1132 pb.F_Sint64Repeated[i] = int64(i)
1133 pb.F_Sint32Repeated[i] = int32(i)
1134 s := fmt.Sprint(i)
1135 pb.F_BytesRepeated[i] = []byte(s)
1136 pb.F_StringRepeated[i] = s
1137 pb.F_DoubleRepeated[i] = float64(i)
1138 pb.F_FloatRepeated[i] = float32(i)
1139 pb.F_Uint64Repeated[i] = uint64(i)
1140 pb.F_Uint32Repeated[i] = uint32(i)
1141 pb.F_Fixed64Repeated[i] = uint64(i)
1142 pb.F_Fixed32Repeated[i] = uint32(i)
1143 pb.F_Int64Repeated[i] = int64(i)
1144 pb.F_Int32Repeated[i] = int32(i)
1145 pb.F_BoolRepeated[i] = i%2 == 0
1146 pb.RepeatedField[i] = igtf
1147 }
1148
1149 // Marshal.
1150 buf, _ := Marshal(pb)
1151
1152 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001153 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001154 Unmarshal(buf, pbd)
1155
1156 // Check the checkable values
1157 for i := uint64(0); i < N; i++ {
1158 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
1159 t.Error("pbd.Repeatedgroup bad")
1160 }
1161 var x uint64
1162 x = uint64(pbd.F_Sint64Repeated[i])
1163 if x != i {
1164 t.Error("pbd.F_Sint64Repeated bad", x, i)
1165 }
1166 x = uint64(pbd.F_Sint32Repeated[i])
1167 if x != i {
1168 t.Error("pbd.F_Sint32Repeated bad", x, i)
1169 }
1170 s := fmt.Sprint(i)
1171 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
1172 if pbd.F_StringRepeated[i] != s {
1173 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
1174 }
1175 x = uint64(pbd.F_DoubleRepeated[i])
1176 if x != i {
1177 t.Error("pbd.F_DoubleRepeated bad", x, i)
1178 }
1179 x = uint64(pbd.F_FloatRepeated[i])
1180 if x != i {
1181 t.Error("pbd.F_FloatRepeated bad", x, i)
1182 }
1183 x = pbd.F_Uint64Repeated[i]
1184 if x != i {
1185 t.Error("pbd.F_Uint64Repeated bad", x, i)
1186 }
1187 x = uint64(pbd.F_Uint32Repeated[i])
1188 if x != i {
1189 t.Error("pbd.F_Uint32Repeated bad", x, i)
1190 }
1191 x = pbd.F_Fixed64Repeated[i]
1192 if x != i {
1193 t.Error("pbd.F_Fixed64Repeated bad", x, i)
1194 }
1195 x = uint64(pbd.F_Fixed32Repeated[i])
1196 if x != i {
1197 t.Error("pbd.F_Fixed32Repeated bad", x, i)
1198 }
1199 x = uint64(pbd.F_Int64Repeated[i])
1200 if x != i {
1201 t.Error("pbd.F_Int64Repeated bad", x, i)
1202 }
1203 x = uint64(pbd.F_Int32Repeated[i])
1204 if x != i {
1205 t.Error("pbd.F_Int32Repeated bad", x, i)
1206 }
1207 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
1208 t.Error("pbd.F_BoolRepeated bad", x, i)
1209 }
1210 if pbd.RepeatedField[i] == nil { // TODO: more checking?
1211 t.Error("pbd.RepeatedField bad")
1212 }
1213 }
1214}
1215
1216// Verify we give a useful message when decoding to the wrong structure type.
1217func TestTypeMismatch(t *testing.T) {
1218 pb1 := initGoTest(true)
1219
1220 // Marshal
1221 o := old()
1222 o.Marshal(pb1)
1223
1224 // Now Unmarshal it to the wrong type.
1225 pb2 := initGoTestField()
1226 err := o.Unmarshal(pb2)
David Symondsbaeae8b2014-06-23 09:41:27 +10001227 if err == nil {
1228 t.Error("expected error, got no error")
1229 } else if !strings.Contains(err.Error(), "bad wiretype") {
1230 t.Error("expected bad wiretype error, got", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001231 }
1232}
1233
David Symonds9f60f432012-06-14 09:45:25 +10001234func encodeDecode(t *testing.T, in, out Message, msg string) {
David Symonds5b7775e2010-12-01 10:09:04 +11001235 buf, err := Marshal(in)
1236 if err != nil {
1237 t.Fatalf("failed marshaling %v: %v", msg, err)
1238 }
1239 if err := Unmarshal(buf, out); err != nil {
1240 t.Fatalf("failed unmarshaling %v: %v", msg, err)
1241 }
1242}
1243
1244func TestPackedNonPackedDecoderSwitching(t *testing.T) {
1245 np, p := new(NonPackedTest), new(PackedTest)
1246
1247 // non-packed -> packed
1248 np.A = []int32{0, 1, 1, 2, 3, 5}
1249 encodeDecode(t, np, p, "non-packed -> packed")
1250 if !reflect.DeepEqual(np.A, p.B) {
1251 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
1252 }
1253
1254 // packed -> non-packed
1255 np.Reset()
1256 p.B = []int32{3, 1, 4, 1, 5, 9}
1257 encodeDecode(t, p, np, "packed -> non-packed")
1258 if !reflect.DeepEqual(p.B, np.A) {
1259 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
1260 }
1261}
1262
Rob Pikeaaa3a622010-03-20 22:32:34 -07001263func TestProto1RepeatedGroup(t *testing.T) {
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001264 pb := &MessageList{
1265 Message: []*MessageList_Message{
Albert Strasheim4676f6a2013-04-07 08:59:06 +10001266 {
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001267 Name: String("blah"),
1268 Count: Int32(7),
1269 },
1270 // NOTE: pb.Message[1] is a nil
1271 nil,
1272 },
1273 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001274
1275 o := old()
David Symondsf62db482015-02-23 12:37:00 +11001276 err := o.Marshal(pb)
1277 if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
Rob Pikeaaa3a622010-03-20 22:32:34 -07001278 t.Fatalf("unexpected or no error when marshaling: %v", err)
1279 }
1280}
1281
Rob Pikeaaa3a622010-03-20 22:32:34 -07001282// Test that enums work. Checks for a bug introduced by making enums
1283// named types instead of int32: newInt32FromUint64 would crash with
1284// a type mismatch in reflect.PointTo.
1285func TestEnum(t *testing.T) {
1286 pb := new(GoEnum)
David Symondsefeca9a2012-05-08 10:36:04 +10001287 pb.Foo = FOO_FOO1.Enum()
Rob Pikeaaa3a622010-03-20 22:32:34 -07001288 o := old()
1289 if err := o.Marshal(pb); err != nil {
Rob Pike853f9112010-12-17 13:56:46 -08001290 t.Fatal("error encoding enum:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001291 }
1292 pb1 := new(GoEnum)
1293 if err := o.Unmarshal(pb1); err != nil {
Rob Pike853f9112010-12-17 13:56:46 -08001294 t.Fatal("error decoding enum:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001295 }
1296 if *pb1.Foo != FOO_FOO1 {
Rob Pike853f9112010-12-17 13:56:46 -08001297 t.Error("expected 7 but got ", *pb1.Foo)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001298 }
1299}
1300
David Symondse37856c2011-06-22 12:52:53 +10001301// Enum types have String methods. Check that enum fields can be printed.
1302// We don't care what the value actually is, just as long as it doesn't crash.
1303func TestPrintingNilEnumFields(t *testing.T) {
1304 pb := new(GoEnum)
1305 fmt.Sprintf("%+v", pb)
1306}
1307
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001308// Verify that absent required fields cause Marshal/Unmarshal to return errors.
1309func TestRequiredFieldEnforcement(t *testing.T) {
1310 pb := new(GoTestField)
1311 _, err := Marshal(pb)
David Symonds5b7775e2010-12-01 10:09:04 +11001312 if err == nil {
1313 t.Error("marshal: expected error, got nil")
David Symonds4646c372013-09-09 13:18:58 +10001314 } else if strings.Index(err.Error(), "Label") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +11001315 t.Errorf("marshal: bad error type: %v", err)
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001316 }
1317
1318 // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
1319 // so simply counting the required fields is insufficient.
1320 // field 1, encoding 2, value "hi"
1321 buf := []byte("\x0A\x02hi\x0A\x02hi")
1322 err = Unmarshal(buf, pb)
David Symonds5b7775e2010-12-01 10:09:04 +11001323 if err == nil {
1324 t.Error("unmarshal: expected error, got nil")
David Symonds4646c372013-09-09 13:18:58 +10001325 } else if strings.Index(err.Error(), "{Unknown}") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +11001326 t.Errorf("unmarshal: bad error type: %v", err)
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001327 }
1328}
1329
David Symondsd4661c52012-08-30 15:17:53 +10001330func TestTypedNilMarshal(t *testing.T) {
1331 // A typed nil should return ErrNil and not crash.
1332 _, err := Marshal((*GoEnum)(nil))
1333 if err != ErrNil {
1334 t.Errorf("Marshal: got err %v, want ErrNil", err)
1335 }
1336}
1337
David Symonds03c9d412010-08-26 14:23:18 +10001338// A type that implements the Marshaler interface, but is not nillable.
1339type nonNillableInt uint64
1340
Rob Pikea17fdd92011-11-02 12:43:05 -07001341func (nni nonNillableInt) Marshal() ([]byte, error) {
David Symonds03c9d412010-08-26 14:23:18 +10001342 return EncodeVarint(uint64(nni)), nil
1343}
1344
1345type NNIMessage struct {
1346 nni nonNillableInt
1347}
1348
David Symonds9f60f432012-06-14 09:45:25 +10001349func (*NNIMessage) Reset() {}
1350func (*NNIMessage) String() string { return "" }
1351func (*NNIMessage) ProtoMessage() {}
1352
David Symonds03c9d412010-08-26 14:23:18 +10001353// A type that implements the Marshaler interface and is nillable.
1354type nillableMessage struct {
1355 x uint64
1356}
1357
Rob Pikea17fdd92011-11-02 12:43:05 -07001358func (nm *nillableMessage) Marshal() ([]byte, error) {
David Symonds03c9d412010-08-26 14:23:18 +10001359 return EncodeVarint(nm.x), nil
1360}
1361
1362type NMMessage struct {
1363 nm *nillableMessage
1364}
1365
David Symonds9f60f432012-06-14 09:45:25 +10001366func (*NMMessage) Reset() {}
1367func (*NMMessage) String() string { return "" }
1368func (*NMMessage) ProtoMessage() {}
1369
David Symonds03c9d412010-08-26 14:23:18 +10001370// Verify a type that uses the Marshaler interface, but has a nil pointer.
1371func TestNilMarshaler(t *testing.T) {
1372 // Try a struct with a Marshaler field that is nil.
1373 // It should be directly marshable.
1374 nmm := new(NMMessage)
1375 if _, err := Marshal(nmm); err != nil {
1376 t.Error("unexpected error marshaling nmm: ", err)
1377 }
1378
1379 // Try a struct with a Marshaler field that is not nillable.
1380 nnim := new(NNIMessage)
1381 nnim.nni = 7
1382 var _ Marshaler = nnim.nni // verify it is truly a Marshaler
1383 if _, err := Marshal(nnim); err != nil {
1384 t.Error("unexpected error marshaling nnim: ", err)
1385 }
1386}
1387
David Symondsb79d99b2011-08-29 16:38:49 +10001388func TestAllSetDefaults(t *testing.T) {
1389 // Exercise SetDefaults with all scalar field types.
1390 m := &Defaults{
1391 // NaN != NaN, so override that here.
1392 F_Nan: Float32(1.7),
1393 }
1394 expected := &Defaults{
1395 F_Bool: Bool(true),
1396 F_Int32: Int32(32),
1397 F_Int64: Int64(64),
1398 F_Fixed32: Uint32(320),
1399 F_Fixed64: Uint64(640),
1400 F_Uint32: Uint32(3200),
1401 F_Uint64: Uint64(6400),
1402 F_Float: Float32(314159),
1403 F_Double: Float64(271828),
1404 F_String: String(`hello, "world!"` + "\n"),
1405 F_Bytes: []byte("Bignose"),
1406 F_Sint32: Int32(-32),
1407 F_Sint64: Int64(-64),
David Symondsefeca9a2012-05-08 10:36:04 +10001408 F_Enum: Defaults_GREEN.Enum(),
David Symondsb79d99b2011-08-29 16:38:49 +10001409 F_Pinf: Float32(float32(math.Inf(1))),
1410 F_Ninf: Float32(float32(math.Inf(-1))),
1411 F_Nan: Float32(1.7),
David Symonds7e810982014-08-12 13:11:17 +10001412 StrZero: String(""),
David Symondsb79d99b2011-08-29 16:38:49 +10001413 }
1414 SetDefaults(m)
1415 if !Equal(m, expected) {
David Symonds7e810982014-08-12 13:11:17 +10001416 t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected)
David Symondsb79d99b2011-08-29 16:38:49 +10001417 }
1418}
1419
1420func TestSetDefaultsWithSetField(t *testing.T) {
1421 // Check that a set value is not overridden.
1422 m := &Defaults{
1423 F_Int32: Int32(12),
1424 }
1425 SetDefaults(m)
David Symonds0e084922012-07-02 16:04:40 -07001426 if v := m.GetF_Int32(); v != 12 {
David Symondsb79d99b2011-08-29 16:38:49 +10001427 t.Errorf("m.FInt32 = %v, want 12", v)
1428 }
1429}
1430
1431func TestSetDefaultsWithSubMessage(t *testing.T) {
1432 m := &OtherMessage{
1433 Key: Int64(123),
1434 Inner: &InnerMessage{
1435 Host: String("gopher"),
1436 },
1437 }
1438 expected := &OtherMessage{
1439 Key: Int64(123),
1440 Inner: &InnerMessage{
1441 Host: String("gopher"),
1442 Port: Int32(4000),
1443 },
1444 }
1445 SetDefaults(m)
1446 if !Equal(m, expected) {
David Symonds814b9362011-12-13 09:10:47 +11001447 t.Errorf("\n got %v\nwant %v", m, expected)
David Symondsb79d99b2011-08-29 16:38:49 +10001448 }
1449}
1450
David Symonds472e2592013-07-15 11:10:07 +10001451func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
1452 m := &MyMessage{
1453 RepInner: []*InnerMessage{{}},
1454 }
1455 expected := &MyMessage{
1456 RepInner: []*InnerMessage{{
1457 Port: Int32(4000),
1458 }},
1459 }
1460 SetDefaults(m)
1461 if !Equal(m, expected) {
1462 t.Errorf("\n got %v\nwant %v", m, expected)
1463 }
1464}
1465
David Symondsde8c5232015-03-20 16:29:30 +11001466func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
1467 m := &MyMessage{
1468 Pet: []string{"turtle", "wombat"},
1469 }
1470 expected := Clone(m)
1471 SetDefaults(m)
1472 if !Equal(m, expected) {
1473 t.Errorf("\n got %v\nwant %v", m, expected)
1474 }
1475}
1476
David Symondsd73d7b12011-09-28 10:56:43 -07001477func TestMaximumTagNumber(t *testing.T) {
1478 m := &MaxTag{
1479 LastField: String("natural goat essence"),
1480 }
1481 buf, err := Marshal(m)
1482 if err != nil {
1483 t.Fatalf("proto.Marshal failed: %v", err)
1484 }
1485 m2 := new(MaxTag)
1486 if err := Unmarshal(buf, m2); err != nil {
1487 t.Fatalf("proto.Unmarshal failed: %v", err)
1488 }
David Symonds0e084922012-07-02 16:04:40 -07001489 if got, want := m2.GetLastField(), *m.LastField; got != want {
David Symondsd73d7b12011-09-28 10:56:43 -07001490 t.Errorf("got %q, want %q", got, want)
1491 }
1492}
1493
David Symonds002ec402011-09-29 17:24:20 -07001494func TestJSON(t *testing.T) {
1495 m := &MyMessage{
1496 Count: Int32(4),
1497 Pet: []string{"bunny", "kitty"},
1498 Inner: &InnerMessage{
1499 Host: String("cauchy"),
1500 },
David Symonds62539862012-08-04 10:06:55 +10001501 Bikeshed: MyMessage_GREEN.Enum(),
David Symonds002ec402011-09-29 17:24:20 -07001502 }
David Symonds4af5f1f2013-10-11 10:08:35 +11001503 const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
David Symonds002ec402011-09-29 17:24:20 -07001504
1505 b, err := json.Marshal(m)
1506 if err != nil {
1507 t.Fatalf("json.Marshal failed: %v", err)
1508 }
1509 s := string(b)
1510 if s != expected {
1511 t.Errorf("got %s\nwant %s", s, expected)
1512 }
David Symonds62539862012-08-04 10:06:55 +10001513
1514 received := new(MyMessage)
1515 if err := json.Unmarshal(b, received); err != nil {
1516 t.Fatalf("json.Unmarshal failed: %v", err)
1517 }
1518 if !Equal(received, m) {
1519 t.Fatalf("got %s, want %s", received, m)
1520 }
1521
David Symonds4af5f1f2013-10-11 10:08:35 +11001522 // Test unmarshalling of JSON with symbolic enum name.
1523 const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
David Symonds62539862012-08-04 10:06:55 +10001524 received.Reset()
1525 if err := json.Unmarshal([]byte(old), received); err != nil {
1526 t.Fatalf("json.Unmarshal failed: %v", err)
1527 }
1528 if !Equal(received, m) {
1529 t.Fatalf("got %s, want %s", received, m)
1530 }
David Symonds002ec402011-09-29 17:24:20 -07001531}
1532
David Symonds22ac1502012-01-18 12:37:12 +11001533func TestBadWireType(t *testing.T) {
1534 b := []byte{7<<3 | 6} // field 7, wire type 6
1535 pb := new(OtherMessage)
1536 if err := Unmarshal(b, pb); err == nil {
1537 t.Errorf("Unmarshal did not fail")
1538 } else if !strings.Contains(err.Error(), "unknown wire type") {
1539 t.Errorf("wrong error: %v", err)
1540 }
1541}
1542
1543func TestBytesWithInvalidLength(t *testing.T) {
1544 // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
1545 b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
1546 Unmarshal(b, new(MyMessage))
1547}
1548
Adam Langley28c83cb2013-07-13 14:54:54 +10001549func TestLengthOverflow(t *testing.T) {
1550 // Overflowing a length should not panic.
1551 b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01}
1552 Unmarshal(b, new(MyMessage))
1553}
1554
1555func TestVarintOverflow(t *testing.T) {
1556 // Overflowing a 64-bit length should not be allowed.
1557 b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01}
1558 if err := Unmarshal(b, new(MyMessage)); err == nil {
1559 t.Fatalf("Overflowed uint64 length without error")
1560 }
1561}
1562
David Symonds22ac1502012-01-18 12:37:12 +11001563func TestUnmarshalFuzz(t *testing.T) {
1564 const N = 1000
1565 seed := time.Now().UnixNano()
1566 t.Logf("RNG seed is %d", seed)
1567 rng := rand.New(rand.NewSource(seed))
1568 buf := make([]byte, 20)
1569 for i := 0; i < N; i++ {
1570 for j := range buf {
1571 buf[j] = byte(rng.Intn(256))
1572 }
1573 fuzzUnmarshal(t, buf)
1574 }
1575}
1576
David Symondse182aaf2013-01-30 17:04:37 +11001577func TestMergeMessages(t *testing.T) {
David Symonds525838c2012-07-20 15:42:49 +10001578 pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}}
1579 data, err := Marshal(pb)
1580 if err != nil {
1581 t.Fatalf("Marshal: %v", err)
1582 }
1583
1584 pb1 := new(MessageList)
1585 if err := Unmarshal(data, pb1); err != nil {
1586 t.Fatalf("first Unmarshal: %v", err)
1587 }
1588 if err := Unmarshal(data, pb1); err != nil {
1589 t.Fatalf("second Unmarshal: %v", err)
1590 }
1591 if len(pb1.Message) != 1 {
1592 t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
1593 }
1594
1595 pb2 := new(MessageList)
David Symondsd4b52d02013-01-15 14:30:26 +11001596 if err := UnmarshalMerge(data, pb2); err != nil {
1597 t.Fatalf("first UnmarshalMerge: %v", err)
David Symonds525838c2012-07-20 15:42:49 +10001598 }
David Symondsd4b52d02013-01-15 14:30:26 +11001599 if err := UnmarshalMerge(data, pb2); err != nil {
1600 t.Fatalf("second UnmarshalMerge: %v", err)
David Symonds525838c2012-07-20 15:42:49 +10001601 }
1602 if len(pb2.Message) != 2 {
David Symondsd4b52d02013-01-15 14:30:26 +11001603 t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
David Symonds525838c2012-07-20 15:42:49 +10001604 }
1605}
1606
David Symondsdf583ae2012-12-06 14:06:53 +11001607func TestExtensionMarshalOrder(t *testing.T) {
David Symonds0c1184e2013-06-08 15:42:12 +10001608 m := &MyMessage{Count: Int(123)}
David Symondsdf583ae2012-12-06 14:06:53 +11001609 if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil {
1610 t.Fatalf("SetExtension: %v", err)
1611 }
1612 if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil {
1613 t.Fatalf("SetExtension: %v", err)
1614 }
1615 if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil {
1616 t.Fatalf("SetExtension: %v", err)
1617 }
1618
1619 // Serialize m several times, and check we get the same bytes each time.
1620 var orig []byte
David Symonds0c1184e2013-06-08 15:42:12 +10001621 for i := 0; i < 100; i++ {
David Symondsdf583ae2012-12-06 14:06:53 +11001622 b, err := Marshal(m)
1623 if err != nil {
1624 t.Fatalf("Marshal: %v", err)
1625 }
1626 if i == 0 {
1627 orig = b
1628 continue
1629 }
1630 if !bytes.Equal(b, orig) {
1631 t.Errorf("Bytes differ on attempt #%d", i)
1632 }
1633 }
1634}
1635
David Symonds0c1184e2013-06-08 15:42:12 +10001636// Many extensions, because small maps might not iterate differently on each iteration.
1637var exts = []*ExtensionDesc{
1638 E_X201,
1639 E_X202,
1640 E_X203,
1641 E_X204,
1642 E_X205,
1643 E_X206,
1644 E_X207,
1645 E_X208,
1646 E_X209,
1647 E_X210,
1648 E_X211,
1649 E_X212,
1650 E_X213,
1651 E_X214,
1652 E_X215,
1653 E_X216,
1654 E_X217,
1655 E_X218,
1656 E_X219,
1657 E_X220,
1658 E_X221,
1659 E_X222,
1660 E_X223,
1661 E_X224,
1662 E_X225,
1663 E_X226,
1664 E_X227,
1665 E_X228,
1666 E_X229,
1667 E_X230,
1668 E_X231,
1669 E_X232,
1670 E_X233,
1671 E_X234,
1672 E_X235,
1673 E_X236,
1674 E_X237,
1675 E_X238,
1676 E_X239,
1677 E_X240,
1678 E_X241,
1679 E_X242,
1680 E_X243,
1681 E_X244,
1682 E_X245,
1683 E_X246,
1684 E_X247,
1685 E_X248,
1686 E_X249,
1687 E_X250,
1688}
1689
1690func TestMessageSetMarshalOrder(t *testing.T) {
1691 m := &MyMessageSet{}
1692 for _, x := range exts {
1693 if err := SetExtension(m, x, &Empty{}); err != nil {
1694 t.Fatalf("SetExtension: %v", err)
1695 }
1696 }
1697
1698 buf, err := Marshal(m)
1699 if err != nil {
1700 t.Fatalf("Marshal: %v", err)
1701 }
1702
1703 // Serialize m several times, and check we get the same bytes each time.
1704 for i := 0; i < 10; i++ {
1705 b1, err := Marshal(m)
1706 if err != nil {
1707 t.Fatalf("Marshal: %v", err)
1708 }
1709 if !bytes.Equal(b1, buf) {
1710 t.Errorf("Bytes differ on re-Marshal #%d", i)
1711 }
1712
1713 m2 := &MyMessageSet{}
1714 if err := Unmarshal(buf, m2); err != nil {
1715 t.Errorf("Unmarshal: %v", err)
1716 }
1717 b2, err := Marshal(m2)
1718 if err != nil {
1719 t.Errorf("re-Marshal: %v", err)
1720 }
1721 if !bytes.Equal(b2, buf) {
1722 t.Errorf("Bytes differ on round-trip #%d", i)
1723 }
1724 }
1725}
1726
David Symonds2ce8ed42013-06-20 13:22:17 +10001727func TestUnmarshalMergesMessages(t *testing.T) {
1728 // If a nested message occurs twice in the input,
1729 // the fields should be merged when decoding.
1730 a := &OtherMessage{
1731 Key: Int64(123),
1732 Inner: &InnerMessage{
1733 Host: String("polhode"),
1734 Port: Int32(1234),
1735 },
1736 }
1737 aData, err := Marshal(a)
1738 if err != nil {
1739 t.Fatalf("Marshal(a): %v", err)
1740 }
1741 b := &OtherMessage{
1742 Weight: Float32(1.2),
1743 Inner: &InnerMessage{
1744 Host: String("herpolhode"),
1745 Connected: Bool(true),
1746 },
1747 }
1748 bData, err := Marshal(b)
1749 if err != nil {
1750 t.Fatalf("Marshal(b): %v", err)
1751 }
1752 want := &OtherMessage{
1753 Key: Int64(123),
1754 Weight: Float32(1.2),
1755 Inner: &InnerMessage{
1756 Host: String("herpolhode"),
1757 Port: Int32(1234),
1758 Connected: Bool(true),
1759 },
1760 }
1761 got := new(OtherMessage)
1762 if err := Unmarshal(append(aData, bData...), got); err != nil {
1763 t.Fatalf("Unmarshal: %v", err)
1764 }
1765 if !Equal(got, want) {
1766 t.Errorf("\n got %v\nwant %v", got, want)
1767 }
1768}
1769
David Symondsc31645c2013-06-22 17:57:36 +10001770func TestEncodingSizes(t *testing.T) {
1771 tests := []struct {
1772 m Message
1773 n int
1774 }{
1775 {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6},
David Symondsf054e842014-07-22 14:06:27 +10001776 {&Defaults{F_Int32: Int32(math.MinInt32)}, 11},
1777 {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6},
David Symondsc31645c2013-06-22 17:57:36 +10001778 {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6},
1779 }
1780 for _, test := range tests {
1781 b, err := Marshal(test.m)
1782 if err != nil {
1783 t.Errorf("Marshal(%v): %v", test.m, err)
1784 continue
1785 }
1786 if len(b) != test.n {
1787 t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
1788 }
1789 }
1790}
1791
David Symondse583a5f2013-09-27 10:02:37 +10001792func TestRequiredNotSetError(t *testing.T) {
David Symonds4646c372013-09-09 13:18:58 +10001793 pb := initGoTest(false)
1794 pb.RequiredField.Label = nil
1795 pb.F_Int32Required = nil
1796 pb.F_Int64Required = nil
1797
1798 expected := "0807" + // field 1, encoding 0, value 7
1799 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField)
1800 "5001" + // field 10, encoding 0, value 1
1801 "6d20000000" + // field 13, encoding 5, value 0x20
1802 "714000000000000000" + // field 14, encoding 1, value 0x40
1803 "78a019" + // field 15, encoding 0, value 0xca0 = 3232
1804 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464
1805 "8d0100004a45" + // field 17, encoding 5, value 3232.0
1806 "9101000000000040b940" + // field 18, encoding 1, value 6464.0
1807 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string"
1808 "b304" + // field 70, encoding 3, start group
1809 "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required"
1810 "b404" + // field 70, encoding 4, end group
1811 "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes"
1812 "b0063f" + // field 102, encoding 0, 0x3f zigzag32
1813 "b8067f" // field 103, encoding 0, 0x7f zigzag64
1814
1815 o := old()
1816 bytes, err := Marshal(pb)
David Symondse583a5f2013-09-27 10:02:37 +10001817 if _, ok := err.(*RequiredNotSetError); !ok {
1818 fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err)
David Symonds4646c372013-09-09 13:18:58 +10001819 o.DebugPrint("", bytes)
1820 t.Fatalf("expected = %s", expected)
1821 }
1822 if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1823 t.Errorf("marshal-1 wrong err msg: %v", err)
1824 }
1825 if !equal(bytes, expected, t) {
1826 o.DebugPrint("neq 1", bytes)
1827 t.Fatalf("expected = %s", expected)
1828 }
1829
1830 // Now test Unmarshal by recreating the original buffer.
1831 pbd := new(GoTest)
1832 err = Unmarshal(bytes, pbd)
David Symondse583a5f2013-09-27 10:02:37 +10001833 if _, ok := err.(*RequiredNotSetError); !ok {
1834 t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err)
David Symonds4646c372013-09-09 13:18:58 +10001835 o.DebugPrint("", bytes)
1836 t.Fatalf("string = %s", expected)
1837 }
1838 if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 {
1839 t.Errorf("unmarshal wrong err msg: %v", err)
1840 }
1841 bytes, err = Marshal(pbd)
David Symondse583a5f2013-09-27 10:02:37 +10001842 if _, ok := err.(*RequiredNotSetError); !ok {
1843 t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
David Symonds4646c372013-09-09 13:18:58 +10001844 o.DebugPrint("", bytes)
1845 t.Fatalf("string = %s", expected)
1846 }
1847 if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1848 t.Errorf("marshal-2 wrong err msg: %v", err)
1849 }
1850 if !equal(bytes, expected, t) {
1851 o.DebugPrint("neq 2", bytes)
1852 t.Fatalf("string = %s", expected)
1853 }
1854}
1855
David Symonds22ac1502012-01-18 12:37:12 +11001856func fuzzUnmarshal(t *testing.T, data []byte) {
1857 defer func() {
1858 if e := recover(); e != nil {
1859 t.Errorf("These bytes caused a panic: %+v", data)
1860 t.Logf("Stack:\n%s", debug.Stack())
1861 t.FailNow()
1862 }
1863 }()
1864
1865 pb := new(MyMessage)
1866 Unmarshal(data, pb)
1867}
1868
David Symonds3ea3e052014-12-22 16:15:28 +11001869func TestMapFieldMarshal(t *testing.T) {
1870 m := &MessageWithMap{
1871 NameMapping: map[int32]string{
1872 1: "Rob",
1873 4: "Ian",
1874 8: "Dave",
1875 },
1876 }
1877 b, err := Marshal(m)
1878 if err != nil {
1879 t.Fatalf("Marshal: %v", err)
1880 }
1881
1882 // b should be the concatenation of these three byte sequences in some order.
1883 parts := []string{
1884 "\n\a\b\x01\x12\x03Rob",
1885 "\n\a\b\x04\x12\x03Ian",
1886 "\n\b\b\x08\x12\x04Dave",
1887 }
1888 ok := false
1889 for i := range parts {
1890 for j := range parts {
1891 if j == i {
1892 continue
1893 }
1894 for k := range parts {
1895 if k == i || k == j {
1896 continue
1897 }
1898 try := parts[i] + parts[j] + parts[k]
1899 if bytes.Equal(b, []byte(try)) {
1900 ok = true
1901 break
1902 }
1903 }
1904 }
1905 }
1906 if !ok {
1907 t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
1908 }
1909 t.Logf("FYI b: %q", b)
1910
1911 (new(Buffer)).DebugPrint("Dump of b", b)
1912}
1913
1914func TestMapFieldRoundTrips(t *testing.T) {
1915 m := &MessageWithMap{
1916 NameMapping: map[int32]string{
1917 1: "Rob",
1918 4: "Ian",
1919 8: "Dave",
1920 },
1921 MsgMapping: map[int64]*FloatingPoint{
1922 0x7001: &FloatingPoint{F: Float64(2.0)},
1923 },
1924 ByteMapping: map[bool][]byte{
1925 false: []byte("that's not right!"),
1926 true: []byte("aye, 'tis true!"),
1927 },
1928 }
1929 b, err := Marshal(m)
1930 if err != nil {
1931 t.Fatalf("Marshal: %v", err)
1932 }
1933 t.Logf("FYI b: %q", b)
1934 m2 := new(MessageWithMap)
1935 if err := Unmarshal(b, m2); err != nil {
1936 t.Fatalf("Unmarshal: %v", err)
1937 }
1938 for _, pair := range [][2]interface{}{
1939 {m.NameMapping, m2.NameMapping},
1940 {m.MsgMapping, m2.MsgMapping},
1941 {m.ByteMapping, m2.ByteMapping},
1942 } {
1943 if !reflect.DeepEqual(pair[0], pair[1]) {
1944 t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1])
1945 }
1946 }
1947}
1948
David Symondscab84a32015-05-19 09:29:00 +10001949func TestMapFieldWithNil(t *testing.T) {
1950 m := &MessageWithMap{
1951 MsgMapping: map[int64]*FloatingPoint{
1952 1: nil,
1953 },
1954 }
1955 b, err := Marshal(m)
1956 if err == nil {
1957 t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b)
1958 }
1959}
1960
Michael Matloobcde632b2016-03-08 09:25:00 +11001961func TestDecodeMapFieldMissingKey(t *testing.T) {
1962 b := []byte{
1963 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
1964 // no key
1965 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
1966 }
1967 got := &MessageWithMap{}
1968 err := Unmarshal(b, got)
1969 if err != nil {
1970 t.Fatalf("failed to marshal map with missing key: %v", err)
1971 }
1972 want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}}
1973 if !Equal(got, want) {
1974 t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
1975 }
1976}
1977
1978func TestDecodeMapFieldMissingValue(t *testing.T) {
1979 b := []byte{
1980 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes
1981 0x08, 0x01, // varint key, value 1
1982 // no value
1983 }
1984 got := &MessageWithMap{}
1985 err := Unmarshal(b, got)
1986 if err != nil {
1987 t.Fatalf("failed to marshal map with missing value: %v", err)
1988 }
1989 want := &MessageWithMap{NameMapping: map[int32]string{1: ""}}
1990 if !Equal(got, want) {
1991 t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
1992 }
1993}
1994
David Symonds59b73b32015-08-24 13:22:02 +10001995func TestOneof(t *testing.T) {
1996 m := &Communique{}
1997 b, err := Marshal(m)
1998 if err != nil {
1999 t.Fatalf("Marshal of empty message with oneof: %v", err)
2000 }
2001 if len(b) != 0 {
2002 t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
2003 }
2004
2005 m = &Communique{
2006 Union: &Communique_Name{"Barry"},
2007 }
2008
2009 // Round-trip.
2010 b, err = Marshal(m)
2011 if err != nil {
2012 t.Fatalf("Marshal of message with oneof: %v", err)
2013 }
2014 if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
2015 t.Errorf("Incorrect marshal of message with oneof: %v", b)
2016 }
2017 m.Reset()
2018 if err := Unmarshal(b, m); err != nil {
2019 t.Fatalf("Unmarshal of message with oneof: %v", err)
2020 }
2021 if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" {
2022 t.Errorf("After round trip, Union = %+v", m.Union)
2023 }
2024 if name := m.GetName(); name != "Barry" {
2025 t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
2026 }
2027
2028 // Let's try with a message in the oneof.
2029 m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}}
2030 b, err = Marshal(m)
2031 if err != nil {
2032 t.Fatalf("Marshal of message with oneof set to message: %v", err)
2033 }
2034 if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
2035 t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
2036 }
2037 m.Reset()
2038 if err := Unmarshal(b, m); err != nil {
2039 t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
2040 }
2041 ss, ok := m.Union.(*Communique_Msg)
2042 if !ok || ss.Msg.GetStringField() != "deep deep string" {
2043 t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
2044 }
2045}
2046
David Symonds0c959e82015-09-28 15:17:00 +10002047func TestInefficientPackedBool(t *testing.T) {
2048 // https://github.com/golang/protobuf/issues/76
2049 inp := []byte{
2050 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes
2051 // Usually a bool should take a single byte,
2052 // but it is permitted to be any varint.
2053 0xb9, 0x30,
2054 }
2055 if err := Unmarshal(inp, new(MoreRepeated)); err != nil {
2056 t.Error(err)
2057 }
2058}
2059
David Symonds0bf1ad52013-10-11 09:07:50 +11002060// Benchmarks
2061
2062func testMsg() *GoTest {
Rob Pikeaaa3a622010-03-20 22:32:34 -07002063 pb := initGoTest(true)
David Symonds0bf1ad52013-10-11 09:07:50 +11002064 const N = 1000 // Internally the library starts much smaller.
2065 pb.F_Int32Repeated = make([]int32, N)
2066 pb.F_DoubleRepeated = make([]float64, N)
2067 for i := 0; i < N; i++ {
2068 pb.F_Int32Repeated[i] = int32(i)
2069 pb.F_DoubleRepeated[i] = float64(i)
Rob Pikeaaa3a622010-03-20 22:32:34 -07002070 }
Russ Coxd4ce3f12012-09-12 10:36:26 +10002071 return pb
2072}
David Symondsd9da6ba2011-08-30 14:41:30 +10002073
David Symonds0bf1ad52013-10-11 09:07:50 +11002074func bytesMsg() *GoTest {
2075 pb := initGoTest(true)
2076 buf := make([]byte, 4000)
2077 for i := range buf {
2078 buf[i] = byte(i)
2079 }
2080 pb.F_BytesDefaulted = buf
2081 return pb
2082}
2083
2084func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) {
2085 d, _ := marshal(pb)
2086 b.SetBytes(int64(len(d)))
2087 b.ResetTimer()
2088 for i := 0; i < b.N; i++ {
2089 marshal(pb)
2090 }
2091}
2092
2093func benchmarkBufferMarshal(b *testing.B, pb Message) {
Rob Pikeaaa3a622010-03-20 22:32:34 -07002094 p := NewBuffer(nil)
David Symonds0bf1ad52013-10-11 09:07:50 +11002095 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2096 p.Reset()
2097 err := p.Marshal(pb0)
2098 return p.Bytes(), err
2099 })
2100}
2101
2102func benchmarkSize(b *testing.B, pb Message) {
2103 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2104 Size(pb)
2105 return nil, nil
2106 })
2107}
2108
2109func newOf(pb Message) Message {
2110 in := reflect.ValueOf(pb)
2111 if in.IsNil() {
2112 return pb
2113 }
2114 return reflect.New(in.Type().Elem()).Interface().(Message)
2115}
2116
2117func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) {
2118 d, _ := Marshal(pb)
2119 b.SetBytes(int64(len(d)))
2120 pbd := newOf(pb)
Rob Pikeaaa3a622010-03-20 22:32:34 -07002121
Russ Coxd4ce3f12012-09-12 10:36:26 +10002122 b.ResetTimer()
Rob Pikeaaa3a622010-03-20 22:32:34 -07002123 for i := 0; i < b.N; i++ {
David Symonds0bf1ad52013-10-11 09:07:50 +11002124 unmarshal(d, pbd)
Rob Pikeaaa3a622010-03-20 22:32:34 -07002125 }
David Symonds0bf1ad52013-10-11 09:07:50 +11002126}
2127
2128func benchmarkBufferUnmarshal(b *testing.B, pb Message) {
2129 p := NewBuffer(nil)
2130 benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error {
2131 p.SetBuf(d)
2132 return p.Unmarshal(pb0)
2133 })
2134}
2135
2136// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes}
2137
2138func BenchmarkMarshal(b *testing.B) {
2139 benchmarkMarshal(b, testMsg(), Marshal)
2140}
2141
2142func BenchmarkBufferMarshal(b *testing.B) {
2143 benchmarkBufferMarshal(b, testMsg())
2144}
2145
2146func BenchmarkSize(b *testing.B) {
2147 benchmarkSize(b, testMsg())
Rob Pikeaaa3a622010-03-20 22:32:34 -07002148}
2149
2150func BenchmarkUnmarshal(b *testing.B) {
David Symonds0bf1ad52013-10-11 09:07:50 +11002151 benchmarkUnmarshal(b, testMsg(), Unmarshal)
2152}
Rob Pikeaaa3a622010-03-20 22:32:34 -07002153
David Symonds0bf1ad52013-10-11 09:07:50 +11002154func BenchmarkBufferUnmarshal(b *testing.B) {
2155 benchmarkBufferUnmarshal(b, testMsg())
Russ Coxd4ce3f12012-09-12 10:36:26 +10002156}
2157
2158func BenchmarkMarshalBytes(b *testing.B) {
David Symonds0bf1ad52013-10-11 09:07:50 +11002159 benchmarkMarshal(b, bytesMsg(), Marshal)
2160}
Russ Coxd4ce3f12012-09-12 10:36:26 +10002161
David Symonds0bf1ad52013-10-11 09:07:50 +11002162func BenchmarkBufferMarshalBytes(b *testing.B) {
2163 benchmarkBufferMarshal(b, bytesMsg())
2164}
2165
2166func BenchmarkSizeBytes(b *testing.B) {
2167 benchmarkSize(b, bytesMsg())
Russ Coxd4ce3f12012-09-12 10:36:26 +10002168}
2169
2170func BenchmarkUnmarshalBytes(b *testing.B) {
David Symonds0bf1ad52013-10-11 09:07:50 +11002171 benchmarkUnmarshal(b, bytesMsg(), Unmarshal)
2172}
Russ Coxd4ce3f12012-09-12 10:36:26 +10002173
David Symonds0bf1ad52013-10-11 09:07:50 +11002174func BenchmarkBufferUnmarshalBytes(b *testing.B) {
2175 benchmarkBufferUnmarshal(b, bytesMsg())
Rob Pikeaaa3a622010-03-20 22:32:34 -07002176}
David Symondsc0287172012-08-15 11:10:30 +10002177
2178func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) {
2179 b.StopTimer()
2180 pb := initGoTestField()
2181 skip := &GoSkipTest{
2182 SkipInt32: Int32(32),
2183 SkipFixed32: Uint32(3232),
2184 SkipFixed64: Uint64(6464),
2185 SkipString: String("skipper"),
2186 Skipgroup: &GoSkipTest_SkipGroup{
2187 GroupInt32: Int32(75),
2188 GroupString: String("wxyz"),
2189 },
2190 }
2191
2192 pbd := new(GoTestField)
2193 p := NewBuffer(nil)
2194 p.Marshal(pb)
2195 p.Marshal(skip)
2196 p2 := NewBuffer(nil)
2197
2198 b.StartTimer()
2199 for i := 0; i < b.N; i++ {
2200 p2.SetBuf(p.Bytes())
2201 p2.Unmarshal(pbd)
2202 }
2203}