blob: 4a58ebe571456b203c4473ae1b0214ceb7d230a1 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2010 Google Inc. All rights reserved.
4// http://code.google.com/p/goprotobuf/
5//
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"
Rob Pikeaaa3a622010-03-20 22:32:34 -070037 "fmt"
David Symondsb79d99b2011-08-29 16:38:49 +100038 "math"
David Symonds22ac1502012-01-18 12:37:12 +110039 "math/rand"
David Symonds5b7775e2010-12-01 10:09:04 +110040 "reflect"
David Symonds22ac1502012-01-18 12:37:12 +110041 "runtime/debug"
David Symonds5b7775e2010-12-01 10:09:04 +110042 "strings"
Rob Pikeaaa3a622010-03-20 22:32:34 -070043 "testing"
David Symonds22ac1502012-01-18 12:37:12 +110044 "time"
Rob Pikeaaa3a622010-03-20 22:32:34 -070045
David Symonds704096f2012-03-15 15:10:26 +110046 . "./testdata"
Rob Pike3f6f2d82011-12-18 13:55:35 -080047 . "code.google.com/p/goprotobuf/proto"
Rob Pikeaaa3a622010-03-20 22:32:34 -070048)
49
50var globalO *Buffer
51
52func old() *Buffer {
53 if globalO == nil {
54 globalO = NewBuffer(nil)
55 }
56 globalO.Reset()
57 return globalO
58}
59
60func equalbytes(b1, b2 []byte, t *testing.T) {
61 if len(b1) != len(b2) {
62 t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
63 return
64 }
65 for i := 0; i < len(b1); i++ {
66 if b1[i] != b2[i] {
67 t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
68 }
69 }
70}
71
72func initGoTestField() *GoTestField {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070073 f := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -070074 f.Label = String("label")
75 f.Type = String("type")
76 return f
77}
78
79// These are all structurally equivalent but the tag numbers differ.
80// (It's remarkable that required, optional, and repeated all have
81// 8 letters.)
82func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070083 return &GoTest_RequiredGroup{
84 RequiredField: String("required"),
85 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070086}
87
88func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070089 return &GoTest_OptionalGroup{
90 RequiredField: String("optional"),
91 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070092}
93
94func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070095 return &GoTest_RepeatedGroup{
96 RequiredField: String("repeated"),
97 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070098}
99
100func initGoTest(setdefaults bool) *GoTest {
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700101 pb := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700102 if setdefaults {
103 pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
104 pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
105 pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
106 pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
107 pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
108 pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
109 pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
110 pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
111 pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
112 pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
113 pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
114 pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
115 pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
116 }
117
David Symondsefeca9a2012-05-08 10:36:04 +1000118 pb.Kind = GoTest_TIME.Enum()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700119 pb.RequiredField = initGoTestField()
120 pb.F_BoolRequired = Bool(true)
121 pb.F_Int32Required = Int32(3)
122 pb.F_Int64Required = Int64(6)
123 pb.F_Fixed32Required = Uint32(32)
124 pb.F_Fixed64Required = Uint64(64)
125 pb.F_Uint32Required = Uint32(3232)
126 pb.F_Uint64Required = Uint64(6464)
127 pb.F_FloatRequired = Float32(3232)
128 pb.F_DoubleRequired = Float64(6464)
129 pb.F_StringRequired = String("string")
130 pb.F_BytesRequired = []byte("bytes")
131 pb.F_Sint32Required = Int32(-32)
132 pb.F_Sint64Required = Int64(-64)
133 pb.Requiredgroup = initGoTest_RequiredGroup()
134
135 return pb
136}
137
138func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
139 data := b.Bytes()
140 ld := len(data)
141 ls := len(s) / 2
142
143 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
144
145 // find the interesting spot - n
146 n := ls
147 if ld < ls {
148 n = ld
149 }
150 j := 0
151 for i := 0; i < n; i++ {
152 bs := hex(s[j])*16 + hex(s[j+1])
153 j += 2
154 if data[i] == bs {
155 continue
156 }
157 n = i
158 break
159 }
160 l := n - 10
161 if l < 0 {
162 l = 0
163 }
164 h := n + 10
165
166 // find the interesting spot - n
167 fmt.Printf("is[%d]:", l)
168 for i := l; i < h; i++ {
169 if i >= ld {
170 fmt.Printf(" --")
171 continue
172 }
173 fmt.Printf(" %.2x", data[i])
174 }
175 fmt.Printf("\n")
176
177 fmt.Printf("sb[%d]:", l)
178 for i := l; i < h; i++ {
179 if i >= ls {
180 fmt.Printf(" --")
181 continue
182 }
183 bs := hex(s[j])*16 + hex(s[j+1])
184 j += 2
185 fmt.Printf(" %.2x", bs)
186 }
187 fmt.Printf("\n")
188
189 t.Fail()
190
Rob Pikeaaa3a622010-03-20 22:32:34 -0700191 // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes())
192 // Print the output in a partially-decoded format; can
193 // be helpful when updating the test. It produces the output
194 // that is pasted, with minor edits, into the argument to verify().
195 // data := b.Bytes()
196 // nesting := 0
197 // for b.Len() > 0 {
198 // start := len(data) - b.Len()
199 // var u uint64
200 // u, err := DecodeVarint(b)
201 // if err != nil {
202 // fmt.Printf("decode error on varint:", err)
203 // return
204 // }
205 // wire := u & 0x7
206 // tag := u >> 3
207 // switch wire {
208 // case WireVarint:
209 // v, err := DecodeVarint(b)
210 // if err != nil {
211 // fmt.Printf("decode error on varint:", err)
212 // return
213 // }
214 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
215 // data[start:len(data)-b.Len()], tag, wire, v)
216 // case WireFixed32:
217 // v, err := DecodeFixed32(b)
218 // if err != nil {
219 // fmt.Printf("decode error on fixed32:", err)
220 // return
221 // }
222 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
223 // data[start:len(data)-b.Len()], tag, wire, v)
224 // case WireFixed64:
225 // v, err := DecodeFixed64(b)
226 // if err != nil {
227 // fmt.Printf("decode error on fixed64:", err)
228 // return
229 // }
230 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
231 // data[start:len(data)-b.Len()], tag, wire, v)
232 // case WireBytes:
233 // nb, err := DecodeVarint(b)
234 // if err != nil {
235 // fmt.Printf("decode error on bytes:", err)
236 // return
237 // }
238 // after_tag := len(data) - b.Len()
239 // str := make([]byte, nb)
240 // _, err = b.Read(str)
241 // if err != nil {
242 // fmt.Printf("decode error on bytes:", err)
243 // return
244 // }
245 // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n",
246 // data[start:after_tag], str, tag, wire)
247 // case WireStartGroup:
248 // nesting++
249 // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n",
250 // data[start:len(data)-b.Len()], tag, nesting)
251 // case WireEndGroup:
252 // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n",
253 // data[start:len(data)-b.Len()], tag, nesting)
254 // nesting--
255 // default:
256 // fmt.Printf("unrecognized wire type %d\n", wire)
257 // return
258 // }
259 // }
260}
261
262func hex(c uint8) uint8 {
263 if '0' <= c && c <= '9' {
264 return c - '0'
265 }
266 if 'a' <= c && c <= 'f' {
267 return 10 + c - 'a'
268 }
269 if 'A' <= c && c <= 'F' {
270 return 10 + c - 'A'
271 }
272 return 0
273}
274
275func equal(b []byte, s string, t *testing.T) bool {
276 if 2*len(b) != len(s) {
277 // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
278 fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
279 return false
280 }
281 for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
282 x := hex(s[j])*16 + hex(s[j+1])
283 if b[i] != x {
284 // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
285 fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
286 return false
287 }
288 }
289 return true
290}
291
292func overify(t *testing.T, pb *GoTest, expected string) {
293 o := old()
294 err := o.Marshal(pb)
295 if err != nil {
296 fmt.Printf("overify marshal-1 err = %v", err)
297 o.DebugPrint("", o.Bytes())
298 t.Fatalf("expected = %s", expected)
299 }
300 if !equal(o.Bytes(), expected, t) {
301 o.DebugPrint("overify neq 1", o.Bytes())
302 t.Fatalf("expected = %s", expected)
303 }
304
305 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700306 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700307 err = o.Unmarshal(pbd)
308 if err != nil {
309 t.Fatalf("overify unmarshal err = %v", err)
310 o.DebugPrint("", o.Bytes())
311 t.Fatalf("string = %s", expected)
312 }
313 o.Reset()
314 err = o.Marshal(pbd)
315 if err != nil {
316 t.Errorf("overify marshal-2 err = %v", err)
317 o.DebugPrint("", o.Bytes())
318 t.Fatalf("string = %s", expected)
319 }
320 if !equal(o.Bytes(), expected, t) {
321 o.DebugPrint("overify neq 2", o.Bytes())
322 t.Fatalf("string = %s", expected)
323 }
324}
325
326// Simple tests for numeric encode/decode primitives (varint, etc.)
327func TestNumericPrimitives(t *testing.T) {
328 for i := uint64(0); i < 1e6; i += 111 {
329 o := old()
330 if o.EncodeVarint(i) != nil {
331 t.Error("EncodeVarint")
332 break
333 }
334 x, e := o.DecodeVarint()
335 if e != nil {
336 t.Fatal("DecodeVarint")
337 }
338 if x != i {
339 t.Fatal("varint decode fail:", i, x)
340 }
341
342 o = old()
343 if o.EncodeFixed32(i) != nil {
344 t.Fatal("encFixed32")
345 }
346 x, e = o.DecodeFixed32()
347 if e != nil {
348 t.Fatal("decFixed32")
349 }
350 if x != i {
351 t.Fatal("fixed32 decode fail:", i, x)
352 }
353
354 o = old()
355 if o.EncodeFixed64(i*1234567) != nil {
356 t.Error("encFixed64")
357 break
358 }
359 x, e = o.DecodeFixed64()
360 if e != nil {
361 t.Error("decFixed64")
362 break
363 }
364 if x != i*1234567 {
365 t.Error("fixed64 decode fail:", i*1234567, x)
366 break
367 }
368
369 o = old()
370 i32 := int32(i - 12345)
371 if o.EncodeZigzag32(uint64(i32)) != nil {
372 t.Fatal("EncodeZigzag32")
373 }
374 x, e = o.DecodeZigzag32()
375 if e != nil {
376 t.Fatal("DecodeZigzag32")
377 }
378 if x != uint64(uint32(i32)) {
379 t.Fatal("zigzag32 decode fail:", i32, x)
380 }
381
382 o = old()
383 i64 := int64(i - 12345)
384 if o.EncodeZigzag64(uint64(i64)) != nil {
385 t.Fatal("EncodeZigzag64")
386 }
387 x, e = o.DecodeZigzag64()
388 if e != nil {
389 t.Fatal("DecodeZigzag64")
390 }
391 if x != uint64(i64) {
392 t.Fatal("zigzag64 decode fail:", i64, x)
393 }
394 }
395}
396
397// Simple tests for bytes
398func TestBytesPrimitives(t *testing.T) {
399 o := old()
400 bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
401 if o.EncodeRawBytes(bytes) != nil {
402 t.Error("EncodeRawBytes")
403 }
404 decb, e := o.DecodeRawBytes(false)
405 if e != nil {
406 t.Error("DecodeRawBytes")
407 }
408 equalbytes(bytes, decb, t)
409}
410
411// Simple tests for strings
412func TestStringPrimitives(t *testing.T) {
413 o := old()
414 s := "now is the time"
415 if o.EncodeStringBytes(s) != nil {
416 t.Error("enc_string")
417 }
418 decs, e := o.DecodeStringBytes()
419 if e != nil {
420 t.Error("dec_string")
421 }
422 if s != decs {
423 t.Error("string encode/decode fail:", s, decs)
424 }
425}
426
427// Do we catch the "required bit not set" case?
428func TestRequiredBit(t *testing.T) {
429 o := old()
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700430 pb := new(GoTest)
David Symonds5b7775e2010-12-01 10:09:04 +1100431 err := o.Marshal(pb)
432 if err == nil {
433 t.Error("did not catch missing required fields")
Rob Pikea17fdd92011-11-02 12:43:05 -0700434 } else if strings.Index(err.Error(), "GoTest") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +1100435 t.Error("wrong error type:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700436 }
437}
438
439// Check that all fields are nil.
440// Clearly silly, and a residue from a more interesting test with an earlier,
441// different initialization property, but it once caught a compiler bug so
442// it lives.
443func checkInitialized(pb *GoTest, t *testing.T) {
444 if pb.F_BoolDefaulted != nil {
445 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
446 }
447 if pb.F_Int32Defaulted != nil {
448 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
449 }
450 if pb.F_Int64Defaulted != nil {
451 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
452 }
453 if pb.F_Fixed32Defaulted != nil {
454 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
455 }
456 if pb.F_Fixed64Defaulted != nil {
457 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
458 }
459 if pb.F_Uint32Defaulted != nil {
460 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
461 }
462 if pb.F_Uint64Defaulted != nil {
463 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
464 }
465 if pb.F_FloatDefaulted != nil {
466 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
467 }
468 if pb.F_DoubleDefaulted != nil {
469 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
470 }
471 if pb.F_StringDefaulted != nil {
472 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
473 }
474 if pb.F_BytesDefaulted != nil {
475 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
476 }
477 if pb.F_Sint32Defaulted != nil {
478 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
479 }
480 if pb.F_Sint64Defaulted != nil {
481 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
482 }
483}
484
485// Does Reset() reset?
486func TestReset(t *testing.T) {
487 pb := initGoTest(true)
488 // muck with some values
489 pb.F_BoolDefaulted = Bool(false)
490 pb.F_Int32Defaulted = Int32(237)
491 pb.F_Int64Defaulted = Int64(12346)
492 pb.F_Fixed32Defaulted = Uint32(32000)
493 pb.F_Fixed64Defaulted = Uint64(666)
494 pb.F_Uint32Defaulted = Uint32(323232)
495 pb.F_Uint64Defaulted = nil
496 pb.F_FloatDefaulted = nil
497 pb.F_DoubleDefaulted = Float64(0)
498 pb.F_StringDefaulted = String("gotcha")
499 pb.F_BytesDefaulted = []byte("asdfasdf")
500 pb.F_Sint32Defaulted = Int32(123)
501 pb.F_Sint64Defaulted = Int64(789)
502 pb.Reset()
503 checkInitialized(pb, t)
504}
505
506// All required fields set, no defaults provided.
507func TestEncodeDecode1(t *testing.T) {
508 pb := initGoTest(false)
509 overify(t, pb,
510 "0807"+ // field 1, encoding 0, value 7
511 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
512 "5001"+ // field 10, encoding 0, value 1
513 "5803"+ // field 11, encoding 0, value 3
514 "6006"+ // field 12, encoding 0, value 6
515 "6d20000000"+ // field 13, encoding 5, value 0x20
516 "714000000000000000"+ // field 14, encoding 1, value 0x40
517 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
518 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
519 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
520 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
521 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700522 "b304"+ // field 70, encoding 3, start group
523 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700524 "b404"+ // field 70, encoding 4, end group
525 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
526 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
527 "b8067f") // field 103, encoding 0, 0x7f zigzag64
Rob Pikeaaa3a622010-03-20 22:32:34 -0700528}
529
530// All required fields set, defaults provided.
531func TestEncodeDecode2(t *testing.T) {
532 pb := initGoTest(true)
533 overify(t, pb,
534 "0807"+ // field 1, encoding 0, value 7
535 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
536 "5001"+ // field 10, encoding 0, value 1
537 "5803"+ // field 11, encoding 0, value 3
538 "6006"+ // field 12, encoding 0, value 6
539 "6d20000000"+ // field 13, encoding 5, value 32
540 "714000000000000000"+ // field 14, encoding 1, value 64
541 "78a019"+ // field 15, encoding 0, value 3232
542 "8001c032"+ // field 16, encoding 0, value 6464
543 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
544 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
545 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700546 "c00201"+ // field 40, encoding 0, value 1
547 "c80220"+ // field 41, encoding 0, value 32
548 "d00240"+ // field 42, encoding 0, value 64
549 "dd0240010000"+ // field 43, encoding 5, value 320
550 "e1028002000000000000"+ // field 44, encoding 1, value 640
551 "e8028019"+ // field 45, encoding 0, value 3200
552 "f0028032"+ // field 46, encoding 0, value 6400
553 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
554 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
555 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700556 "b304"+ // start group field 70 level 1
557 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700558 "b404"+ // end group field 70 level 1
559 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
560 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
561 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
562 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
563 "90193f"+ // field 402, encoding 0, value 63
564 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700565
566}
567
568// All default fields set to their default value by hand
569func TestEncodeDecode3(t *testing.T) {
570 pb := initGoTest(false)
571 pb.F_BoolDefaulted = Bool(true)
572 pb.F_Int32Defaulted = Int32(32)
573 pb.F_Int64Defaulted = Int64(64)
574 pb.F_Fixed32Defaulted = Uint32(320)
575 pb.F_Fixed64Defaulted = Uint64(640)
576 pb.F_Uint32Defaulted = Uint32(3200)
577 pb.F_Uint64Defaulted = Uint64(6400)
578 pb.F_FloatDefaulted = Float32(314159)
579 pb.F_DoubleDefaulted = Float64(271828)
580 pb.F_StringDefaulted = String("hello, \"world!\"\n")
581 pb.F_BytesDefaulted = []byte("Bignose")
582 pb.F_Sint32Defaulted = Int32(-32)
583 pb.F_Sint64Defaulted = Int64(-64)
584
585 overify(t, pb,
586 "0807"+ // field 1, encoding 0, value 7
587 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
588 "5001"+ // field 10, encoding 0, value 1
589 "5803"+ // field 11, encoding 0, value 3
590 "6006"+ // field 12, encoding 0, value 6
591 "6d20000000"+ // field 13, encoding 5, value 32
592 "714000000000000000"+ // field 14, encoding 1, value 64
593 "78a019"+ // field 15, encoding 0, value 3232
594 "8001c032"+ // field 16, encoding 0, value 6464
595 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
596 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
597 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700598 "c00201"+ // field 40, encoding 0, value 1
599 "c80220"+ // field 41, encoding 0, value 32
600 "d00240"+ // field 42, encoding 0, value 64
601 "dd0240010000"+ // field 43, encoding 5, value 320
602 "e1028002000000000000"+ // field 44, encoding 1, value 640
603 "e8028019"+ // field 45, encoding 0, value 3200
604 "f0028032"+ // field 46, encoding 0, value 6400
605 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
606 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
607 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700608 "b304"+ // start group field 70 level 1
609 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
David Symondsd15e81b2011-10-03 14:31:12 -0700610 "b404"+ // end group field 70 level 1
611 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
612 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
613 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
614 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
615 "90193f"+ // field 402, encoding 0, value 63
616 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700617
618}
619
620// All required fields set, defaults provided, all non-defaulted optional fields have values.
621func TestEncodeDecode4(t *testing.T) {
622 pb := initGoTest(true)
623 pb.Table = String("hello")
624 pb.Param = Int32(7)
625 pb.OptionalField = initGoTestField()
626 pb.F_BoolOptional = Bool(true)
627 pb.F_Int32Optional = Int32(32)
628 pb.F_Int64Optional = Int64(64)
629 pb.F_Fixed32Optional = Uint32(3232)
630 pb.F_Fixed64Optional = Uint64(6464)
631 pb.F_Uint32Optional = Uint32(323232)
632 pb.F_Uint64Optional = Uint64(646464)
633 pb.F_FloatOptional = Float32(32.)
634 pb.F_DoubleOptional = Float64(64.)
635 pb.F_StringOptional = String("hello")
636 pb.F_BytesOptional = []byte("Bignose")
637 pb.F_Sint32Optional = Int32(-32)
638 pb.F_Sint64Optional = Int64(-64)
639 pb.Optionalgroup = initGoTest_OptionalGroup()
640
641 overify(t, pb,
642 "0807"+ // field 1, encoding 0, value 7
643 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
644 "1807"+ // field 3, encoding 0, value 7
645 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
646 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
647 "5001"+ // field 10, encoding 0, value 1
648 "5803"+ // field 11, encoding 0, value 3
649 "6006"+ // field 12, encoding 0, value 6
650 "6d20000000"+ // field 13, encoding 5, value 32
651 "714000000000000000"+ // field 14, encoding 1, value 64
652 "78a019"+ // field 15, encoding 0, value 3232
653 "8001c032"+ // field 16, encoding 0, value 6464
654 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
655 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
656 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700657 "f00101"+ // field 30, encoding 0, value 1
658 "f80120"+ // field 31, encoding 0, value 32
659 "800240"+ // field 32, encoding 0, value 64
660 "8d02a00c0000"+ // field 33, encoding 5, value 3232
661 "91024019000000000000"+ // field 34, encoding 1, value 6464
662 "9802a0dd13"+ // field 35, encoding 0, value 323232
663 "a002c0ba27"+ // field 36, encoding 0, value 646464
664 "ad0200000042"+ // field 37, encoding 5, value 32.0
665 "b1020000000000005040"+ // field 38, encoding 1, value 64.0
666 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700667 "c00201"+ // field 40, encoding 0, value 1
668 "c80220"+ // field 41, encoding 0, value 32
669 "d00240"+ // field 42, encoding 0, value 64
670 "dd0240010000"+ // field 43, encoding 5, value 320
671 "e1028002000000000000"+ // field 44, encoding 1, value 640
672 "e8028019"+ // field 45, encoding 0, value 3200
673 "f0028032"+ // field 46, encoding 0, value 6400
674 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
675 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
676 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700677 "b304"+ // start group field 70 level 1
678 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
679 "b404"+ // end group field 70 level 1
680 "d305"+ // start group field 90 level 1
681 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
David Symondsd15e81b2011-10-03 14:31:12 -0700682 "d405"+ // end group field 90 level 1
683 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
684 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
685 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
686 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
687 "f0123f"+ // field 302, encoding 0, value 63
688 "f8127f"+ // field 303, encoding 0, value 127
689 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
690 "90193f"+ // field 402, encoding 0, value 63
691 "98197f") // field 403, encoding 0, value 127
Rob Pikeaaa3a622010-03-20 22:32:34 -0700692
693}
694
695// All required fields set, defaults provided, all repeated fields given two values.
696func TestEncodeDecode5(t *testing.T) {
697 pb := initGoTest(true)
698 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
699 pb.F_BoolRepeated = []bool{false, true}
700 pb.F_Int32Repeated = []int32{32, 33}
701 pb.F_Int64Repeated = []int64{64, 65}
702 pb.F_Fixed32Repeated = []uint32{3232, 3333}
703 pb.F_Fixed64Repeated = []uint64{6464, 6565}
704 pb.F_Uint32Repeated = []uint32{323232, 333333}
705 pb.F_Uint64Repeated = []uint64{646464, 656565}
706 pb.F_FloatRepeated = []float32{32., 33.}
707 pb.F_DoubleRepeated = []float64{64., 65.}
708 pb.F_StringRepeated = []string{"hello", "sailor"}
709 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
710 pb.F_Sint32Repeated = []int32{32, -32}
711 pb.F_Sint64Repeated = []int64{64, -64}
712 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
713
714 overify(t, pb,
715 "0807"+ // field 1, encoding 0, value 7
716 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
717 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
718 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
719 "5001"+ // field 10, encoding 0, value 1
720 "5803"+ // field 11, encoding 0, value 3
721 "6006"+ // field 12, encoding 0, value 6
722 "6d20000000"+ // field 13, encoding 5, value 32
723 "714000000000000000"+ // field 14, encoding 1, value 64
724 "78a019"+ // field 15, encoding 0, value 3232
725 "8001c032"+ // field 16, encoding 0, value 6464
726 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
727 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
728 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700729 "a00100"+ // field 20, encoding 0, value 0
730 "a00101"+ // field 20, encoding 0, value 1
731 "a80120"+ // field 21, encoding 0, value 32
732 "a80121"+ // field 21, encoding 0, value 33
733 "b00140"+ // field 22, encoding 0, value 64
734 "b00141"+ // field 22, encoding 0, value 65
735 "bd01a00c0000"+ // field 23, encoding 5, value 3232
736 "bd01050d0000"+ // field 23, encoding 5, value 3333
737 "c1014019000000000000"+ // field 24, encoding 1, value 6464
738 "c101a519000000000000"+ // field 24, encoding 1, value 6565
739 "c801a0dd13"+ // field 25, encoding 0, value 323232
740 "c80195ac14"+ // field 25, encoding 0, value 333333
741 "d001c0ba27"+ // field 26, encoding 0, value 646464
742 "d001b58928"+ // field 26, encoding 0, value 656565
743 "dd0100000042"+ // field 27, encoding 5, value 32.0
744 "dd0100000442"+ // field 27, encoding 5, value 33.0
745 "e1010000000000005040"+ // field 28, encoding 1, value 64.0
746 "e1010000000000405040"+ // field 28, encoding 1, value 65.0
747 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
748 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700749 "c00201"+ // field 40, encoding 0, value 1
750 "c80220"+ // field 41, encoding 0, value 32
751 "d00240"+ // field 42, encoding 0, value 64
752 "dd0240010000"+ // field 43, encoding 5, value 320
753 "e1028002000000000000"+ // field 44, encoding 1, value 640
754 "e8028019"+ // field 45, encoding 0, value 3200
755 "f0028032"+ // field 46, encoding 0, value 6400
756 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
757 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
758 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700759 "b304"+ // start group field 70 level 1
760 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
761 "b404"+ // end group field 70 level 1
762 "8305"+ // start group field 80 level 1
763 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
764 "8405"+ // end group field 80 level 1
765 "8305"+ // start group field 80 level 1
766 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
David Symondsd15e81b2011-10-03 14:31:12 -0700767 "8405"+ // end group field 80 level 1
768 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
769 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
770 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
771 "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
772 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
773 "d00c40"+ // field 202, encoding 0, value 32
774 "d00c3f"+ // field 202, encoding 0, value -32
775 "d80c8001"+ // field 203, encoding 0, value 64
776 "d80c7f"+ // field 203, encoding 0, value -64
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
Rob Pikeaaa3a622010-03-20 22:32:34 -0700780
781}
782
David Symonds5b7775e2010-12-01 10:09:04 +1100783// All required fields set, all packed repeated fields given two values.
784func TestEncodeDecode6(t *testing.T) {
785 pb := initGoTest(false)
786 pb.F_BoolRepeatedPacked = []bool{false, true}
787 pb.F_Int32RepeatedPacked = []int32{32, 33}
788 pb.F_Int64RepeatedPacked = []int64{64, 65}
789 pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
790 pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
791 pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
792 pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
793 pb.F_FloatRepeatedPacked = []float32{32., 33.}
794 pb.F_DoubleRepeatedPacked = []float64{64., 65.}
795 pb.F_Sint32RepeatedPacked = []int32{32, -32}
796 pb.F_Sint64RepeatedPacked = []int64{64, -64}
797
798 overify(t, pb,
799 "0807"+ // field 1, encoding 0, value 7
800 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
801 "5001"+ // field 10, encoding 0, value 1
802 "5803"+ // field 11, encoding 0, value 3
803 "6006"+ // field 12, encoding 0, value 6
804 "6d20000000"+ // field 13, encoding 5, value 32
805 "714000000000000000"+ // field 14, encoding 1, value 64
806 "78a019"+ // field 15, encoding 0, value 3232
807 "8001c032"+ // field 16, encoding 0, value 6464
808 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
809 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
810 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
David Symonds5b7775e2010-12-01 10:09:04 +1100811 "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
812 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
813 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
814 "aa0308"+ // field 53, encoding 2, 8 bytes
815 "a00c0000050d0000"+ // value 3232, value 3333
816 "b20310"+ // field 54, encoding 2, 16 bytes
817 "4019000000000000a519000000000000"+ // value 6464, value 6565
818 "ba0306"+ // field 55, encoding 2, 6 bytes
819 "a0dd1395ac14"+ // value 323232, value 333333
820 "c20306"+ // field 56, encoding 2, 6 bytes
821 "c0ba27b58928"+ // value 646464, value 656565
822 "ca0308"+ // field 57, encoding 2, 8 bytes
823 "0000004200000442"+ // value 32.0, value 33.0
824 "d20310"+ // field 58, encoding 2, 16 bytes
825 "00000000000050400000000000405040"+ // value 64.0, value 65.0
David Symondsd15e81b2011-10-03 14:31:12 -0700826 "b304"+ // start group field 70 level 1
827 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
828 "b404"+ // end group field 70 level 1
829 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
830 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
831 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
David Symonds5b7775e2010-12-01 10:09:04 +1100832 "b21f02"+ // field 502, encoding 2, 2 bytes
833 "403f"+ // value 32, value -32
834 "ba1f03"+ // field 503, encoding 2, 3 bytes
David Symondsd15e81b2011-10-03 14:31:12 -0700835 "80017f") // value 64, value -64
David Symonds5b7775e2010-12-01 10:09:04 +1100836}
837
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800838// Test that we can encode empty bytes fields.
839func TestEncodeDecodeBytes1(t *testing.T) {
840 pb := initGoTest(false)
841
842 // Create our bytes
843 pb.F_BytesRequired = []byte{}
David Symondsd9da6ba2011-08-30 14:41:30 +1000844 pb.F_BytesRepeated = [][]byte{{}}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800845 pb.F_BytesOptional = []byte{}
846
847 d, err := Marshal(pb)
848 if err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700849 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800850 }
851
852 pbd := new(GoTest)
853 if err := Unmarshal(d, pbd); err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700854 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800855 }
856
857 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
Rob Pikea17fdd92011-11-02 12:43:05 -0700858 t.Error("required empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800859 }
860 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700861 t.Error("repeated empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800862 }
863 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
Rob Pikea17fdd92011-11-02 12:43:05 -0700864 t.Error("optional empty bytes field is incorrect")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800865 }
866}
867
868// Test that we encode nil-valued fields of a repeated bytes field correctly.
869// Since entries in a repeated field cannot be nil, nil must mean empty value.
870func TestEncodeDecodeBytes2(t *testing.T) {
871 pb := initGoTest(false)
872
873 // Create our bytes
David Symonds5b7775e2010-12-01 10:09:04 +1100874 pb.F_BytesRepeated = [][]byte{nil}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800875
876 d, err := Marshal(pb)
David Symonds5b7775e2010-12-01 10:09:04 +1100877 if err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700878 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800879 }
880
881 pbd := new(GoTest)
882 if err := Unmarshal(d, pbd); err != nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700883 t.Error(err)
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800884 }
885
886 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
Rob Pikea17fdd92011-11-02 12:43:05 -0700887 t.Error("Unexpected value for repeated bytes field")
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800888 }
889}
890
Rob Pikeaaa3a622010-03-20 22:32:34 -0700891// All required fields set, defaults provided, all repeated fields given two values.
892func TestSkippingUnrecognizedFields(t *testing.T) {
893 o := old()
894 pb := initGoTestField()
895
896 // Marshal it normally.
897 o.Marshal(pb)
898
899 // Now new a GoSkipTest record.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700900 skip := &GoSkipTest{
901 SkipInt32: Int32(32),
902 SkipFixed32: Uint32(3232),
903 SkipFixed64: Uint64(6464),
904 SkipString: String("skipper"),
905 Skipgroup: &GoSkipTest_SkipGroup{
906 GroupInt32: Int32(75),
907 GroupString: String("wxyz"),
908 },
909 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700910
911 // Marshal it into same buffer.
912 o.Marshal(skip)
913
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700914 pbd := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700915 o.Unmarshal(pbd)
916
917 // The __unrecognized field should be a marshaling of GoSkipTest
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700918 skipd := new(GoSkipTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700919
920 o.SetBuf(pbd.XXX_unrecognized)
921 o.Unmarshal(skipd)
922
923 if *skipd.SkipInt32 != *skip.SkipInt32 {
924 t.Error("skip int32", skipd.SkipInt32)
925 }
926 if *skipd.SkipFixed32 != *skip.SkipFixed32 {
927 t.Error("skip fixed32", skipd.SkipFixed32)
928 }
929 if *skipd.SkipFixed64 != *skip.SkipFixed64 {
930 t.Error("skip fixed64", skipd.SkipFixed64)
931 }
932 if *skipd.SkipString != *skip.SkipString {
933 t.Error("skip string", *skipd.SkipString)
934 }
935 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
936 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
937 }
938 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
939 t.Error("skip group string", *skipd.Skipgroup.GroupString)
940 }
941}
942
943// Check that we can grow an array (repeated field) to have many elements.
944// This test doesn't depend only on our encoding; for variety, it makes sure
945// we create, encode, and decode the correct contents explicitly. It's therefore
946// a bit messier.
947// This test also uses (and hence tests) the Marshal/Unmarshal functions
948// instead of the methods.
949func TestBigRepeated(t *testing.T) {
950 pb := initGoTest(true)
951
952 // Create the arrays
953 const N = 50 // Internally the library starts much smaller.
954 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
955 pb.F_Sint64Repeated = make([]int64, N)
956 pb.F_Sint32Repeated = make([]int32, N)
957 pb.F_BytesRepeated = make([][]byte, N)
958 pb.F_StringRepeated = make([]string, N)
959 pb.F_DoubleRepeated = make([]float64, N)
960 pb.F_FloatRepeated = make([]float32, N)
961 pb.F_Uint64Repeated = make([]uint64, N)
962 pb.F_Uint32Repeated = make([]uint32, N)
963 pb.F_Fixed64Repeated = make([]uint64, N)
964 pb.F_Fixed32Repeated = make([]uint32, N)
965 pb.F_Int64Repeated = make([]int64, N)
966 pb.F_Int32Repeated = make([]int32, N)
967 pb.F_BoolRepeated = make([]bool, N)
968 pb.RepeatedField = make([]*GoTestField, N)
969
970 // Fill in the arrays with checkable values.
971 igtf := initGoTestField()
972 igtrg := initGoTest_RepeatedGroup()
973 for i := 0; i < N; i++ {
974 pb.Repeatedgroup[i] = igtrg
975 pb.F_Sint64Repeated[i] = int64(i)
976 pb.F_Sint32Repeated[i] = int32(i)
977 s := fmt.Sprint(i)
978 pb.F_BytesRepeated[i] = []byte(s)
979 pb.F_StringRepeated[i] = s
980 pb.F_DoubleRepeated[i] = float64(i)
981 pb.F_FloatRepeated[i] = float32(i)
982 pb.F_Uint64Repeated[i] = uint64(i)
983 pb.F_Uint32Repeated[i] = uint32(i)
984 pb.F_Fixed64Repeated[i] = uint64(i)
985 pb.F_Fixed32Repeated[i] = uint32(i)
986 pb.F_Int64Repeated[i] = int64(i)
987 pb.F_Int32Repeated[i] = int32(i)
988 pb.F_BoolRepeated[i] = i%2 == 0
989 pb.RepeatedField[i] = igtf
990 }
991
992 // Marshal.
993 buf, _ := Marshal(pb)
994
995 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700996 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700997 Unmarshal(buf, pbd)
998
999 // Check the checkable values
1000 for i := uint64(0); i < N; i++ {
1001 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
1002 t.Error("pbd.Repeatedgroup bad")
1003 }
1004 var x uint64
1005 x = uint64(pbd.F_Sint64Repeated[i])
1006 if x != i {
1007 t.Error("pbd.F_Sint64Repeated bad", x, i)
1008 }
1009 x = uint64(pbd.F_Sint32Repeated[i])
1010 if x != i {
1011 t.Error("pbd.F_Sint32Repeated bad", x, i)
1012 }
1013 s := fmt.Sprint(i)
1014 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
1015 if pbd.F_StringRepeated[i] != s {
1016 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
1017 }
1018 x = uint64(pbd.F_DoubleRepeated[i])
1019 if x != i {
1020 t.Error("pbd.F_DoubleRepeated bad", x, i)
1021 }
1022 x = uint64(pbd.F_FloatRepeated[i])
1023 if x != i {
1024 t.Error("pbd.F_FloatRepeated bad", x, i)
1025 }
1026 x = pbd.F_Uint64Repeated[i]
1027 if x != i {
1028 t.Error("pbd.F_Uint64Repeated bad", x, i)
1029 }
1030 x = uint64(pbd.F_Uint32Repeated[i])
1031 if x != i {
1032 t.Error("pbd.F_Uint32Repeated bad", x, i)
1033 }
1034 x = pbd.F_Fixed64Repeated[i]
1035 if x != i {
1036 t.Error("pbd.F_Fixed64Repeated bad", x, i)
1037 }
1038 x = uint64(pbd.F_Fixed32Repeated[i])
1039 if x != i {
1040 t.Error("pbd.F_Fixed32Repeated bad", x, i)
1041 }
1042 x = uint64(pbd.F_Int64Repeated[i])
1043 if x != i {
1044 t.Error("pbd.F_Int64Repeated bad", x, i)
1045 }
1046 x = uint64(pbd.F_Int32Repeated[i])
1047 if x != i {
1048 t.Error("pbd.F_Int32Repeated bad", x, i)
1049 }
1050 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
1051 t.Error("pbd.F_BoolRepeated bad", x, i)
1052 }
1053 if pbd.RepeatedField[i] == nil { // TODO: more checking?
1054 t.Error("pbd.RepeatedField bad")
1055 }
1056 }
1057}
1058
1059// Verify we give a useful message when decoding to the wrong structure type.
1060func TestTypeMismatch(t *testing.T) {
1061 pb1 := initGoTest(true)
1062
1063 // Marshal
1064 o := old()
1065 o.Marshal(pb1)
1066
1067 // Now Unmarshal it to the wrong type.
1068 pb2 := initGoTestField()
1069 err := o.Unmarshal(pb2)
1070 switch err {
1071 case ErrWrongType:
1072 // fine
1073 case nil:
1074 t.Error("expected wrong type error, got no error")
1075 default:
1076 t.Error("expected wrong type error, got", err)
1077 }
1078}
1079
David Symonds5b7775e2010-12-01 10:09:04 +11001080func encodeDecode(t *testing.T, in, out interface{}, msg string) {
1081 buf, err := Marshal(in)
1082 if err != nil {
1083 t.Fatalf("failed marshaling %v: %v", msg, err)
1084 }
1085 if err := Unmarshal(buf, out); err != nil {
1086 t.Fatalf("failed unmarshaling %v: %v", msg, err)
1087 }
1088}
1089
1090func TestPackedNonPackedDecoderSwitching(t *testing.T) {
1091 np, p := new(NonPackedTest), new(PackedTest)
1092
1093 // non-packed -> packed
1094 np.A = []int32{0, 1, 1, 2, 3, 5}
1095 encodeDecode(t, np, p, "non-packed -> packed")
1096 if !reflect.DeepEqual(np.A, p.B) {
1097 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
1098 }
1099
1100 // packed -> non-packed
1101 np.Reset()
1102 p.B = []int32{3, 1, 4, 1, 5, 9}
1103 encodeDecode(t, p, np, "packed -> non-packed")
1104 if !reflect.DeepEqual(p.B, np.A) {
1105 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
1106 }
1107}
1108
Rob Pikeaaa3a622010-03-20 22:32:34 -07001109func TestProto1RepeatedGroup(t *testing.T) {
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001110 pb := &MessageList{
1111 Message: []*MessageList_Message{
1112 &MessageList_Message{
1113 Name: String("blah"),
1114 Count: Int32(7),
1115 },
1116 // NOTE: pb.Message[1] is a nil
1117 nil,
1118 },
1119 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001120
1121 o := old()
1122 if err := o.Marshal(pb); err != ErrRepeatedHasNil {
1123 t.Fatalf("unexpected or no error when marshaling: %v", err)
1124 }
1125}
1126
Rob Pikeaaa3a622010-03-20 22:32:34 -07001127// Test that enums work. Checks for a bug introduced by making enums
1128// named types instead of int32: newInt32FromUint64 would crash with
1129// a type mismatch in reflect.PointTo.
1130func TestEnum(t *testing.T) {
1131 pb := new(GoEnum)
David Symondsefeca9a2012-05-08 10:36:04 +10001132 pb.Foo = FOO_FOO1.Enum()
Rob Pikeaaa3a622010-03-20 22:32:34 -07001133 o := old()
1134 if err := o.Marshal(pb); err != nil {
Rob Pike853f9112010-12-17 13:56:46 -08001135 t.Fatal("error encoding enum:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001136 }
1137 pb1 := new(GoEnum)
1138 if err := o.Unmarshal(pb1); err != nil {
Rob Pike853f9112010-12-17 13:56:46 -08001139 t.Fatal("error decoding enum:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001140 }
1141 if *pb1.Foo != FOO_FOO1 {
Rob Pike853f9112010-12-17 13:56:46 -08001142 t.Error("expected 7 but got ", *pb1.Foo)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001143 }
1144}
1145
David Symondse37856c2011-06-22 12:52:53 +10001146// Enum types have String methods. Check that enum fields can be printed.
1147// We don't care what the value actually is, just as long as it doesn't crash.
1148func TestPrintingNilEnumFields(t *testing.T) {
1149 pb := new(GoEnum)
1150 fmt.Sprintf("%+v", pb)
1151}
1152
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001153// Verify that absent required fields cause Marshal/Unmarshal to return errors.
1154func TestRequiredFieldEnforcement(t *testing.T) {
1155 pb := new(GoTestField)
1156 _, err := Marshal(pb)
David Symonds5b7775e2010-12-01 10:09:04 +11001157 if err == nil {
1158 t.Error("marshal: expected error, got nil")
Rob Pikea17fdd92011-11-02 12:43:05 -07001159 } else if strings.Index(err.Error(), "GoTestField") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +11001160 t.Errorf("marshal: bad error type: %v", err)
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001161 }
1162
1163 // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
1164 // so simply counting the required fields is insufficient.
1165 // field 1, encoding 2, value "hi"
1166 buf := []byte("\x0A\x02hi\x0A\x02hi")
1167 err = Unmarshal(buf, pb)
David Symonds5b7775e2010-12-01 10:09:04 +11001168 if err == nil {
1169 t.Error("unmarshal: expected error, got nil")
Rob Pikea17fdd92011-11-02 12:43:05 -07001170 } else if strings.Index(err.Error(), "GoTestField") < 0 {
David Symonds5b7775e2010-12-01 10:09:04 +11001171 t.Errorf("unmarshal: bad error type: %v", err)
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001172 }
1173}
1174
David Symonds03c9d412010-08-26 14:23:18 +10001175// A type that implements the Marshaler interface, but is not nillable.
1176type nonNillableInt uint64
1177
Rob Pikea17fdd92011-11-02 12:43:05 -07001178func (nni nonNillableInt) Marshal() ([]byte, error) {
David Symonds03c9d412010-08-26 14:23:18 +10001179 return EncodeVarint(uint64(nni)), nil
1180}
1181
1182type NNIMessage struct {
1183 nni nonNillableInt
1184}
1185
1186// A type that implements the Marshaler interface and is nillable.
1187type nillableMessage struct {
1188 x uint64
1189}
1190
Rob Pikea17fdd92011-11-02 12:43:05 -07001191func (nm *nillableMessage) Marshal() ([]byte, error) {
David Symonds03c9d412010-08-26 14:23:18 +10001192 return EncodeVarint(nm.x), nil
1193}
1194
1195type NMMessage struct {
1196 nm *nillableMessage
1197}
1198
1199// Verify a type that uses the Marshaler interface, but has a nil pointer.
1200func TestNilMarshaler(t *testing.T) {
1201 // Try a struct with a Marshaler field that is nil.
1202 // It should be directly marshable.
1203 nmm := new(NMMessage)
1204 if _, err := Marshal(nmm); err != nil {
1205 t.Error("unexpected error marshaling nmm: ", err)
1206 }
1207
1208 // Try a struct with a Marshaler field that is not nillable.
1209 nnim := new(NNIMessage)
1210 nnim.nni = 7
1211 var _ Marshaler = nnim.nni // verify it is truly a Marshaler
1212 if _, err := Marshal(nnim); err != nil {
1213 t.Error("unexpected error marshaling nnim: ", err)
1214 }
1215}
1216
David Symonds147f5b32012-04-09 17:01:56 +10001217// Check that passing things other than pointer to struct to Marshal
1218// returns a good error, rather than panicking.
1219func TestStructTyping(t *testing.T) {
1220 om := &OtherMessage{}
1221 bad := [...]interface{}{*om, &om}
1222 for _, pb := range bad {
1223 _, err := Marshal(pb)
1224 if err != ErrNotPtr {
1225 t.Errorf("marshaling %T: got %v, expected %v", pb, err, ErrNotPtr)
1226 }
1227 if err := Unmarshal([]byte{}, pb); err != ErrNotPtr {
1228 t.Errorf("unmarshaling %T: got %v, expected %v", pb, err, ErrNotPtr)
1229 }
David Symonds7656e742011-07-22 14:54:17 +10001230 }
1231}
1232
David Symondsb79d99b2011-08-29 16:38:49 +10001233func TestAllSetDefaults(t *testing.T) {
1234 // Exercise SetDefaults with all scalar field types.
1235 m := &Defaults{
1236 // NaN != NaN, so override that here.
1237 F_Nan: Float32(1.7),
1238 }
1239 expected := &Defaults{
1240 F_Bool: Bool(true),
1241 F_Int32: Int32(32),
1242 F_Int64: Int64(64),
1243 F_Fixed32: Uint32(320),
1244 F_Fixed64: Uint64(640),
1245 F_Uint32: Uint32(3200),
1246 F_Uint64: Uint64(6400),
1247 F_Float: Float32(314159),
1248 F_Double: Float64(271828),
1249 F_String: String(`hello, "world!"` + "\n"),
1250 F_Bytes: []byte("Bignose"),
1251 F_Sint32: Int32(-32),
1252 F_Sint64: Int64(-64),
David Symondsefeca9a2012-05-08 10:36:04 +10001253 F_Enum: Defaults_GREEN.Enum(),
David Symondsb79d99b2011-08-29 16:38:49 +10001254 F_Pinf: Float32(float32(math.Inf(1))),
1255 F_Ninf: Float32(float32(math.Inf(-1))),
1256 F_Nan: Float32(1.7),
1257 }
1258 SetDefaults(m)
1259 if !Equal(m, expected) {
1260 t.Errorf(" got %v\nwant %v", m, expected)
1261 }
1262}
1263
1264func TestSetDefaultsWithSetField(t *testing.T) {
1265 // Check that a set value is not overridden.
1266 m := &Defaults{
1267 F_Int32: Int32(12),
1268 }
1269 SetDefaults(m)
1270 if v := GetInt32(m.F_Int32); v != 12 {
1271 t.Errorf("m.FInt32 = %v, want 12", v)
1272 }
1273}
1274
1275func TestSetDefaultsWithSubMessage(t *testing.T) {
1276 m := &OtherMessage{
1277 Key: Int64(123),
1278 Inner: &InnerMessage{
1279 Host: String("gopher"),
1280 },
1281 }
1282 expected := &OtherMessage{
1283 Key: Int64(123),
1284 Inner: &InnerMessage{
1285 Host: String("gopher"),
1286 Port: Int32(4000),
1287 },
1288 }
1289 SetDefaults(m)
1290 if !Equal(m, expected) {
David Symonds814b9362011-12-13 09:10:47 +11001291 t.Errorf("\n got %v\nwant %v", m, expected)
David Symondsb79d99b2011-08-29 16:38:49 +10001292 }
1293}
1294
David Symondsd73d7b12011-09-28 10:56:43 -07001295func TestMaximumTagNumber(t *testing.T) {
1296 m := &MaxTag{
1297 LastField: String("natural goat essence"),
1298 }
1299 buf, err := Marshal(m)
1300 if err != nil {
1301 t.Fatalf("proto.Marshal failed: %v", err)
1302 }
1303 m2 := new(MaxTag)
1304 if err := Unmarshal(buf, m2); err != nil {
1305 t.Fatalf("proto.Unmarshal failed: %v", err)
1306 }
1307 if got, want := GetString(m2.LastField), *m.LastField; got != want {
1308 t.Errorf("got %q, want %q", got, want)
1309 }
1310}
1311
David Symonds002ec402011-09-29 17:24:20 -07001312func TestJSON(t *testing.T) {
1313 m := &MyMessage{
1314 Count: Int32(4),
1315 Pet: []string{"bunny", "kitty"},
1316 Inner: &InnerMessage{
1317 Host: String("cauchy"),
1318 },
1319 }
1320 const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"}}`
1321
1322 b, err := json.Marshal(m)
1323 if err != nil {
1324 t.Fatalf("json.Marshal failed: %v", err)
1325 }
1326 s := string(b)
1327 if s != expected {
1328 t.Errorf("got %s\nwant %s", s, expected)
1329 }
1330}
1331
David Symonds22ac1502012-01-18 12:37:12 +11001332func TestBadWireType(t *testing.T) {
1333 b := []byte{7<<3 | 6} // field 7, wire type 6
1334 pb := new(OtherMessage)
1335 if err := Unmarshal(b, pb); err == nil {
1336 t.Errorf("Unmarshal did not fail")
1337 } else if !strings.Contains(err.Error(), "unknown wire type") {
1338 t.Errorf("wrong error: %v", err)
1339 }
1340}
1341
1342func TestBytesWithInvalidLength(t *testing.T) {
1343 // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
1344 b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
1345 Unmarshal(b, new(MyMessage))
1346}
1347
1348func TestUnmarshalFuzz(t *testing.T) {
1349 const N = 1000
1350 seed := time.Now().UnixNano()
1351 t.Logf("RNG seed is %d", seed)
1352 rng := rand.New(rand.NewSource(seed))
1353 buf := make([]byte, 20)
1354 for i := 0; i < N; i++ {
1355 for j := range buf {
1356 buf[j] = byte(rng.Intn(256))
1357 }
1358 fuzzUnmarshal(t, buf)
1359 }
1360}
1361
1362func fuzzUnmarshal(t *testing.T, data []byte) {
1363 defer func() {
1364 if e := recover(); e != nil {
1365 t.Errorf("These bytes caused a panic: %+v", data)
1366 t.Logf("Stack:\n%s", debug.Stack())
1367 t.FailNow()
1368 }
1369 }()
1370
1371 pb := new(MyMessage)
1372 Unmarshal(data, pb)
1373}
1374
Rob Pikeaaa3a622010-03-20 22:32:34 -07001375func BenchmarkMarshal(b *testing.B) {
1376 b.StopTimer()
1377
1378 pb := initGoTest(true)
1379
1380 // Create an array
1381 const N = 1000 // Internally the library starts much smaller.
1382 pb.F_Int32Repeated = make([]int32, N)
David Symondsd9da6ba2011-08-30 14:41:30 +10001383 pb.F_DoubleRepeated = make([]float64, N)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001384
1385 // Fill in the array with some values.
1386 for i := 0; i < N; i++ {
1387 pb.F_Int32Repeated[i] = int32(i)
David Symondsd9da6ba2011-08-30 14:41:30 +10001388 pb.F_DoubleRepeated[i] = float64(i)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001389 }
David Symondsd9da6ba2011-08-30 14:41:30 +10001390
Rob Pikeaaa3a622010-03-20 22:32:34 -07001391 p := NewBuffer(nil)
1392
1393 b.StartTimer()
1394 for i := 0; i < b.N; i++ {
1395 p.Reset()
1396 p.Marshal(pb)
1397 }
1398}
1399
1400func BenchmarkUnmarshal(b *testing.B) {
1401 b.StopTimer()
1402
1403 pb := initGoTest(true)
1404
1405 // Create an array
1406 const N = 1000 // Internally the library starts much smaller.
1407 pb.F_Int32Repeated = make([]int32, N)
1408
1409 // Fill in the array with some values.
1410 for i := 0; i < N; i++ {
1411 pb.F_Int32Repeated[i] = int32(i)
1412 }
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001413 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001414 p := NewBuffer(nil)
1415 p.Marshal(pb)
1416 p2 := NewBuffer(nil)
1417
1418 b.StartTimer()
1419 for i := 0; i < b.N; i++ {
1420 p2.SetBuf(p.Bytes())
1421 p2.Unmarshal(pbd)
1422 }
1423}