blob: ae419aa577af85fbb7350a5ad30eb2a4665d3076 [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 -070032
33package proto_test
34
35import (
36 "bytes"
37 "fmt"
David Symonds002ec402011-09-29 17:24:20 -070038 "json"
David Symondsb79d99b2011-08-29 16:38:49 +100039 "math"
David Symonds03c9d412010-08-26 14:23:18 +100040 "os"
David Symonds5b7775e2010-12-01 10:09:04 +110041 "reflect"
42 "strings"
Rob Pikeaaa3a622010-03-20 22:32:34 -070043 "testing"
44
45 . "goprotobuf.googlecode.com/hg/proto"
46 . "./testdata/_obj/test_proto"
47)
48
49var globalO *Buffer
50
51func old() *Buffer {
52 if globalO == nil {
53 globalO = NewBuffer(nil)
54 }
55 globalO.Reset()
56 return globalO
57}
58
59func equalbytes(b1, b2 []byte, t *testing.T) {
60 if len(b1) != len(b2) {
61 t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
62 return
63 }
64 for i := 0; i < len(b1); i++ {
65 if b1[i] != b2[i] {
66 t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
67 }
68 }
69}
70
71func initGoTestField() *GoTestField {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070072 f := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -070073 f.Label = String("label")
74 f.Type = String("type")
75 return f
76}
77
78// These are all structurally equivalent but the tag numbers differ.
79// (It's remarkable that required, optional, and repeated all have
80// 8 letters.)
81func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070082 return &GoTest_RequiredGroup{
83 RequiredField: String("required"),
84 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070085}
86
87func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070088 return &GoTest_OptionalGroup{
89 RequiredField: String("optional"),
90 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070091}
92
93func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
Rob Pikec6d8e4a2010-07-28 15:34:32 -070094 return &GoTest_RepeatedGroup{
95 RequiredField: String("repeated"),
96 }
Rob Pikeaaa3a622010-03-20 22:32:34 -070097}
98
99func initGoTest(setdefaults bool) *GoTest {
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700100 pb := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700101 if setdefaults {
102 pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
103 pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
104 pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
105 pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
106 pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
107 pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
108 pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
109 pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
110 pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
111 pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
112 pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
113 pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
114 pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
115 }
116
David Symondsdd9ca042011-08-29 16:07:16 +1000117 pb.Kind = NewGoTest_KIND(GoTest_TIME)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700118 pb.RequiredField = initGoTestField()
119 pb.F_BoolRequired = Bool(true)
120 pb.F_Int32Required = Int32(3)
121 pb.F_Int64Required = Int64(6)
122 pb.F_Fixed32Required = Uint32(32)
123 pb.F_Fixed64Required = Uint64(64)
124 pb.F_Uint32Required = Uint32(3232)
125 pb.F_Uint64Required = Uint64(6464)
126 pb.F_FloatRequired = Float32(3232)
127 pb.F_DoubleRequired = Float64(6464)
128 pb.F_StringRequired = String("string")
129 pb.F_BytesRequired = []byte("bytes")
130 pb.F_Sint32Required = Int32(-32)
131 pb.F_Sint64Required = Int64(-64)
132 pb.Requiredgroup = initGoTest_RequiredGroup()
133
134 return pb
135}
136
137func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
138 data := b.Bytes()
139 ld := len(data)
140 ls := len(s) / 2
141
142 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
143
144 // find the interesting spot - n
145 n := ls
146 if ld < ls {
147 n = ld
148 }
149 j := 0
150 for i := 0; i < n; i++ {
151 bs := hex(s[j])*16 + hex(s[j+1])
152 j += 2
153 if data[i] == bs {
154 continue
155 }
156 n = i
157 break
158 }
159 l := n - 10
160 if l < 0 {
161 l = 0
162 }
163 h := n + 10
164
165 // find the interesting spot - n
166 fmt.Printf("is[%d]:", l)
167 for i := l; i < h; i++ {
168 if i >= ld {
169 fmt.Printf(" --")
170 continue
171 }
172 fmt.Printf(" %.2x", data[i])
173 }
174 fmt.Printf("\n")
175
176 fmt.Printf("sb[%d]:", l)
177 for i := l; i < h; i++ {
178 if i >= ls {
179 fmt.Printf(" --")
180 continue
181 }
182 bs := hex(s[j])*16 + hex(s[j+1])
183 j += 2
184 fmt.Printf(" %.2x", bs)
185 }
186 fmt.Printf("\n")
187
188 t.Fail()
189
Rob Pikeaaa3a622010-03-20 22:32:34 -0700190 // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes())
191 // Print the output in a partially-decoded format; can
192 // be helpful when updating the test. It produces the output
193 // that is pasted, with minor edits, into the argument to verify().
194 // data := b.Bytes()
195 // nesting := 0
196 // for b.Len() > 0 {
197 // start := len(data) - b.Len()
198 // var u uint64
199 // u, err := DecodeVarint(b)
200 // if err != nil {
201 // fmt.Printf("decode error on varint:", err)
202 // return
203 // }
204 // wire := u & 0x7
205 // tag := u >> 3
206 // switch wire {
207 // case WireVarint:
208 // v, err := DecodeVarint(b)
209 // if err != nil {
210 // fmt.Printf("decode error on varint:", err)
211 // return
212 // }
213 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
214 // data[start:len(data)-b.Len()], tag, wire, v)
215 // case WireFixed32:
216 // v, err := DecodeFixed32(b)
217 // if err != nil {
218 // fmt.Printf("decode error on fixed32:", err)
219 // return
220 // }
221 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
222 // data[start:len(data)-b.Len()], tag, wire, v)
223 // case WireFixed64:
224 // v, err := DecodeFixed64(b)
225 // if err != nil {
226 // fmt.Printf("decode error on fixed64:", err)
227 // return
228 // }
229 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
230 // data[start:len(data)-b.Len()], tag, wire, v)
231 // case WireBytes:
232 // nb, err := DecodeVarint(b)
233 // if err != nil {
234 // fmt.Printf("decode error on bytes:", err)
235 // return
236 // }
237 // after_tag := len(data) - b.Len()
238 // str := make([]byte, nb)
239 // _, err = b.Read(str)
240 // if err != nil {
241 // fmt.Printf("decode error on bytes:", err)
242 // return
243 // }
244 // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n",
245 // data[start:after_tag], str, tag, wire)
246 // case WireStartGroup:
247 // nesting++
248 // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n",
249 // data[start:len(data)-b.Len()], tag, nesting)
250 // case WireEndGroup:
251 // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n",
252 // data[start:len(data)-b.Len()], tag, nesting)
253 // nesting--
254 // default:
255 // fmt.Printf("unrecognized wire type %d\n", wire)
256 // return
257 // }
258 // }
259}
260
261func hex(c uint8) uint8 {
262 if '0' <= c && c <= '9' {
263 return c - '0'
264 }
265 if 'a' <= c && c <= 'f' {
266 return 10 + c - 'a'
267 }
268 if 'A' <= c && c <= 'F' {
269 return 10 + c - 'A'
270 }
271 return 0
272}
273
274func equal(b []byte, s string, t *testing.T) bool {
275 if 2*len(b) != len(s) {
276 // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
277 fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
278 return false
279 }
280 for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
281 x := hex(s[j])*16 + hex(s[j+1])
282 if b[i] != x {
283 // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
284 fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
285 return false
286 }
287 }
288 return true
289}
290
291func overify(t *testing.T, pb *GoTest, expected string) {
292 o := old()
293 err := o.Marshal(pb)
294 if err != nil {
295 fmt.Printf("overify marshal-1 err = %v", err)
296 o.DebugPrint("", o.Bytes())
297 t.Fatalf("expected = %s", expected)
298 }
299 if !equal(o.Bytes(), expected, t) {
300 o.DebugPrint("overify neq 1", o.Bytes())
301 t.Fatalf("expected = %s", expected)
302 }
303
304 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700305 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700306 err = o.Unmarshal(pbd)
307 if err != nil {
308 t.Fatalf("overify unmarshal err = %v", err)
309 o.DebugPrint("", o.Bytes())
310 t.Fatalf("string = %s", expected)
311 }
312 o.Reset()
313 err = o.Marshal(pbd)
314 if err != nil {
315 t.Errorf("overify marshal-2 err = %v", err)
316 o.DebugPrint("", o.Bytes())
317 t.Fatalf("string = %s", expected)
318 }
319 if !equal(o.Bytes(), expected, t) {
320 o.DebugPrint("overify neq 2", o.Bytes())
321 t.Fatalf("string = %s", expected)
322 }
323}
324
325// Simple tests for numeric encode/decode primitives (varint, etc.)
326func TestNumericPrimitives(t *testing.T) {
327 for i := uint64(0); i < 1e6; i += 111 {
328 o := old()
329 if o.EncodeVarint(i) != nil {
330 t.Error("EncodeVarint")
331 break
332 }
333 x, e := o.DecodeVarint()
334 if e != nil {
335 t.Fatal("DecodeVarint")
336 }
337 if x != i {
338 t.Fatal("varint decode fail:", i, x)
339 }
340
341 o = old()
342 if o.EncodeFixed32(i) != nil {
343 t.Fatal("encFixed32")
344 }
345 x, e = o.DecodeFixed32()
346 if e != nil {
347 t.Fatal("decFixed32")
348 }
349 if x != i {
350 t.Fatal("fixed32 decode fail:", i, x)
351 }
352
353 o = old()
354 if o.EncodeFixed64(i*1234567) != nil {
355 t.Error("encFixed64")
356 break
357 }
358 x, e = o.DecodeFixed64()
359 if e != nil {
360 t.Error("decFixed64")
361 break
362 }
363 if x != i*1234567 {
364 t.Error("fixed64 decode fail:", i*1234567, x)
365 break
366 }
367
368 o = old()
369 i32 := int32(i - 12345)
370 if o.EncodeZigzag32(uint64(i32)) != nil {
371 t.Fatal("EncodeZigzag32")
372 }
373 x, e = o.DecodeZigzag32()
374 if e != nil {
375 t.Fatal("DecodeZigzag32")
376 }
377 if x != uint64(uint32(i32)) {
378 t.Fatal("zigzag32 decode fail:", i32, x)
379 }
380
381 o = old()
382 i64 := int64(i - 12345)
383 if o.EncodeZigzag64(uint64(i64)) != nil {
384 t.Fatal("EncodeZigzag64")
385 }
386 x, e = o.DecodeZigzag64()
387 if e != nil {
388 t.Fatal("DecodeZigzag64")
389 }
390 if x != uint64(i64) {
391 t.Fatal("zigzag64 decode fail:", i64, x)
392 }
393 }
394}
395
396// Simple tests for bytes
397func TestBytesPrimitives(t *testing.T) {
398 o := old()
399 bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
400 if o.EncodeRawBytes(bytes) != nil {
401 t.Error("EncodeRawBytes")
402 }
403 decb, e := o.DecodeRawBytes(false)
404 if e != nil {
405 t.Error("DecodeRawBytes")
406 }
407 equalbytes(bytes, decb, t)
408}
409
410// Simple tests for strings
411func TestStringPrimitives(t *testing.T) {
412 o := old()
413 s := "now is the time"
414 if o.EncodeStringBytes(s) != nil {
415 t.Error("enc_string")
416 }
417 decs, e := o.DecodeStringBytes()
418 if e != nil {
419 t.Error("dec_string")
420 }
421 if s != decs {
422 t.Error("string encode/decode fail:", s, decs)
423 }
424}
425
426// Do we catch the "required bit not set" case?
427func TestRequiredBit(t *testing.T) {
428 o := old()
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700429 pb := new(GoTest)
David Symonds5b7775e2010-12-01 10:09:04 +1100430 err := o.Marshal(pb)
431 if err == nil {
432 t.Error("did not catch missing required fields")
433 } else if strings.Index(err.String(), "GoTest") < 0 {
434 t.Error("wrong error type:", err)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700435 }
436}
437
438// Check that all fields are nil.
439// Clearly silly, and a residue from a more interesting test with an earlier,
440// different initialization property, but it once caught a compiler bug so
441// it lives.
442func checkInitialized(pb *GoTest, t *testing.T) {
443 if pb.F_BoolDefaulted != nil {
444 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
445 }
446 if pb.F_Int32Defaulted != nil {
447 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
448 }
449 if pb.F_Int64Defaulted != nil {
450 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
451 }
452 if pb.F_Fixed32Defaulted != nil {
453 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
454 }
455 if pb.F_Fixed64Defaulted != nil {
456 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
457 }
458 if pb.F_Uint32Defaulted != nil {
459 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
460 }
461 if pb.F_Uint64Defaulted != nil {
462 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
463 }
464 if pb.F_FloatDefaulted != nil {
465 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
466 }
467 if pb.F_DoubleDefaulted != nil {
468 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
469 }
470 if pb.F_StringDefaulted != nil {
471 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
472 }
473 if pb.F_BytesDefaulted != nil {
474 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
475 }
476 if pb.F_Sint32Defaulted != nil {
477 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
478 }
479 if pb.F_Sint64Defaulted != nil {
480 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
481 }
482}
483
484// Does Reset() reset?
485func TestReset(t *testing.T) {
486 pb := initGoTest(true)
487 // muck with some values
488 pb.F_BoolDefaulted = Bool(false)
489 pb.F_Int32Defaulted = Int32(237)
490 pb.F_Int64Defaulted = Int64(12346)
491 pb.F_Fixed32Defaulted = Uint32(32000)
492 pb.F_Fixed64Defaulted = Uint64(666)
493 pb.F_Uint32Defaulted = Uint32(323232)
494 pb.F_Uint64Defaulted = nil
495 pb.F_FloatDefaulted = nil
496 pb.F_DoubleDefaulted = Float64(0)
497 pb.F_StringDefaulted = String("gotcha")
498 pb.F_BytesDefaulted = []byte("asdfasdf")
499 pb.F_Sint32Defaulted = Int32(123)
500 pb.F_Sint64Defaulted = Int64(789)
501 pb.Reset()
502 checkInitialized(pb, t)
503}
504
505// All required fields set, no defaults provided.
506func TestEncodeDecode1(t *testing.T) {
507 pb := initGoTest(false)
508 overify(t, pb,
509 "0807"+ // field 1, encoding 0, value 7
510 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
511 "5001"+ // field 10, encoding 0, value 1
512 "5803"+ // field 11, encoding 0, value 3
513 "6006"+ // field 12, encoding 0, value 6
514 "6d20000000"+ // field 13, encoding 5, value 0x20
515 "714000000000000000"+ // field 14, encoding 1, value 0x40
516 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
517 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
518 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
519 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
520 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
521 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
522 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
523 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
524 "b304"+ // field 70, encoding 3, start group
525 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
526 "b404") // field 70, encoding 4, end group
527}
528
529// All required fields set, defaults provided.
530func TestEncodeDecode2(t *testing.T) {
531 pb := initGoTest(true)
532 overify(t, pb,
533 "0807"+ // field 1, encoding 0, value 7
534 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
535 "5001"+ // field 10, encoding 0, value 1
536 "5803"+ // field 11, encoding 0, value 3
537 "6006"+ // field 12, encoding 0, value 6
538 "6d20000000"+ // field 13, encoding 5, value 32
539 "714000000000000000"+ // field 14, encoding 1, value 64
540 "78a019"+ // field 15, encoding 0, value 3232
541 "8001c032"+ // field 16, encoding 0, value 6464
542 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
543 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
544 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
545 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
546 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
547 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
548 "c00201"+ // field 40, encoding 0, value 1
549 "c80220"+ // field 41, encoding 0, value 32
550 "d00240"+ // field 42, encoding 0, value 64
551 "dd0240010000"+ // field 43, encoding 5, value 320
552 "e1028002000000000000"+ // field 44, encoding 1, value 640
553 "e8028019"+ // field 45, encoding 0, value 3200
554 "f0028032"+ // field 46, encoding 0, value 6400
555 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
556 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
557 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100558 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700559 "90193f"+ // field 402, encoding 0, value 63
560 "98197f"+ // field 403, encoding 0, value 127
561 "b304"+ // start group field 70 level 1
562 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
563 "b404") // end group field 70 level 1
564
565}
566
567// All default fields set to their default value by hand
568func TestEncodeDecode3(t *testing.T) {
569 pb := initGoTest(false)
570 pb.F_BoolDefaulted = Bool(true)
571 pb.F_Int32Defaulted = Int32(32)
572 pb.F_Int64Defaulted = Int64(64)
573 pb.F_Fixed32Defaulted = Uint32(320)
574 pb.F_Fixed64Defaulted = Uint64(640)
575 pb.F_Uint32Defaulted = Uint32(3200)
576 pb.F_Uint64Defaulted = Uint64(6400)
577 pb.F_FloatDefaulted = Float32(314159)
578 pb.F_DoubleDefaulted = Float64(271828)
579 pb.F_StringDefaulted = String("hello, \"world!\"\n")
580 pb.F_BytesDefaulted = []byte("Bignose")
581 pb.F_Sint32Defaulted = Int32(-32)
582 pb.F_Sint64Defaulted = Int64(-64)
583
584 overify(t, pb,
585 "0807"+ // field 1, encoding 0, value 7
586 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
587 "5001"+ // field 10, encoding 0, value 1
588 "5803"+ // field 11, encoding 0, value 3
589 "6006"+ // field 12, encoding 0, value 6
590 "6d20000000"+ // field 13, encoding 5, value 32
591 "714000000000000000"+ // field 14, encoding 1, value 64
592 "78a019"+ // field 15, encoding 0, value 3232
593 "8001c032"+ // field 16, encoding 0, value 6464
594 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
595 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
596 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
597 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
598 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
599 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
600 "c00201"+ // field 40, encoding 0, value 1
601 "c80220"+ // field 41, encoding 0, value 32
602 "d00240"+ // field 42, encoding 0, value 64
603 "dd0240010000"+ // field 43, encoding 5, value 320
604 "e1028002000000000000"+ // field 44, encoding 1, value 640
605 "e8028019"+ // field 45, encoding 0, value 3200
606 "f0028032"+ // field 46, encoding 0, value 6400
607 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
608 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
609 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100610 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700611 "90193f"+ // field 402, encoding 0, value 63
612 "98197f"+ // field 403, encoding 0, value 127
613 "b304"+ // start group field 70 level 1
614 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
615 "b404") // end group field 70 level 1
616
617}
618
619// All required fields set, defaults provided, all non-defaulted optional fields have values.
620func TestEncodeDecode4(t *testing.T) {
621 pb := initGoTest(true)
622 pb.Table = String("hello")
623 pb.Param = Int32(7)
624 pb.OptionalField = initGoTestField()
625 pb.F_BoolOptional = Bool(true)
626 pb.F_Int32Optional = Int32(32)
627 pb.F_Int64Optional = Int64(64)
628 pb.F_Fixed32Optional = Uint32(3232)
629 pb.F_Fixed64Optional = Uint64(6464)
630 pb.F_Uint32Optional = Uint32(323232)
631 pb.F_Uint64Optional = Uint64(646464)
632 pb.F_FloatOptional = Float32(32.)
633 pb.F_DoubleOptional = Float64(64.)
634 pb.F_StringOptional = String("hello")
635 pb.F_BytesOptional = []byte("Bignose")
636 pb.F_Sint32Optional = Int32(-32)
637 pb.F_Sint64Optional = Int64(-64)
638 pb.Optionalgroup = initGoTest_OptionalGroup()
639
640 overify(t, pb,
641 "0807"+ // field 1, encoding 0, value 7
642 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
643 "1807"+ // field 3, encoding 0, value 7
644 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
645 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
646 "5001"+ // field 10, encoding 0, value 1
647 "5803"+ // field 11, encoding 0, value 3
648 "6006"+ // field 12, encoding 0, value 6
649 "6d20000000"+ // field 13, encoding 5, value 32
650 "714000000000000000"+ // field 14, encoding 1, value 64
651 "78a019"+ // field 15, encoding 0, value 3232
652 "8001c032"+ // field 16, encoding 0, value 6464
653 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
654 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
655 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
656 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
657 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
658 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
659 "f00101"+ // field 30, encoding 0, value 1
660 "f80120"+ // field 31, encoding 0, value 32
661 "800240"+ // field 32, encoding 0, value 64
662 "8d02a00c0000"+ // field 33, encoding 5, value 3232
663 "91024019000000000000"+ // field 34, encoding 1, value 6464
664 "9802a0dd13"+ // field 35, encoding 0, value 323232
665 "a002c0ba27"+ // field 36, encoding 0, value 646464
666 "ad0200000042"+ // field 37, encoding 5, value 32.0
667 "b1020000000000005040"+ // field 38, encoding 1, value 64.0
668 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
669 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
670 "f0123f"+ // field 302, encoding 0, value 63
671 "f8127f"+ // field 303, encoding 0, value 127
672 "c00201"+ // field 40, encoding 0, value 1
673 "c80220"+ // field 41, encoding 0, value 32
674 "d00240"+ // field 42, encoding 0, value 64
675 "dd0240010000"+ // field 43, encoding 5, value 320
676 "e1028002000000000000"+ // field 44, encoding 1, value 640
677 "e8028019"+ // field 45, encoding 0, value 3200
678 "f0028032"+ // field 46, encoding 0, value 6400
679 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
680 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
681 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100682 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700683 "90193f"+ // field 402, encoding 0, value 63
684 "98197f"+ // field 403, encoding 0, value 127
685 "b304"+ // start group field 70 level 1
686 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
687 "b404"+ // end group field 70 level 1
688 "d305"+ // start group field 90 level 1
689 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
690 "d405") // end group field 90 level 1
691
692}
693
694// All required fields set, defaults provided, all repeated fields given two values.
695func TestEncodeDecode5(t *testing.T) {
696 pb := initGoTest(true)
697 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
698 pb.F_BoolRepeated = []bool{false, true}
699 pb.F_Int32Repeated = []int32{32, 33}
700 pb.F_Int64Repeated = []int64{64, 65}
701 pb.F_Fixed32Repeated = []uint32{3232, 3333}
702 pb.F_Fixed64Repeated = []uint64{6464, 6565}
703 pb.F_Uint32Repeated = []uint32{323232, 333333}
704 pb.F_Uint64Repeated = []uint64{646464, 656565}
705 pb.F_FloatRepeated = []float32{32., 33.}
706 pb.F_DoubleRepeated = []float64{64., 65.}
707 pb.F_StringRepeated = []string{"hello", "sailor"}
708 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
709 pb.F_Sint32Repeated = []int32{32, -32}
710 pb.F_Sint64Repeated = []int64{64, -64}
711 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
712
713 overify(t, pb,
714 "0807"+ // field 1, encoding 0, value 7
715 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
716 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
717 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
718 "5001"+ // field 10, encoding 0, value 1
719 "5803"+ // field 11, encoding 0, value 3
720 "6006"+ // field 12, encoding 0, value 6
721 "6d20000000"+ // field 13, encoding 5, value 32
722 "714000000000000000"+ // field 14, encoding 1, value 64
723 "78a019"+ // field 15, encoding 0, value 3232
724 "8001c032"+ // field 16, encoding 0, value 6464
725 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
726 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
727 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
728 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
729 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
730 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
731 "a00100"+ // field 20, encoding 0, value 0
732 "a00101"+ // field 20, encoding 0, value 1
733 "a80120"+ // field 21, encoding 0, value 32
734 "a80121"+ // field 21, encoding 0, value 33
735 "b00140"+ // field 22, encoding 0, value 64
736 "b00141"+ // field 22, encoding 0, value 65
737 "bd01a00c0000"+ // field 23, encoding 5, value 3232
738 "bd01050d0000"+ // field 23, encoding 5, value 3333
739 "c1014019000000000000"+ // field 24, encoding 1, value 6464
740 "c101a519000000000000"+ // field 24, encoding 1, value 6565
741 "c801a0dd13"+ // field 25, encoding 0, value 323232
742 "c80195ac14"+ // field 25, encoding 0, value 333333
743 "d001c0ba27"+ // field 26, encoding 0, value 646464
744 "d001b58928"+ // field 26, encoding 0, value 656565
745 "dd0100000042"+ // field 27, encoding 5, value 32.0
746 "dd0100000442"+ // field 27, encoding 5, value 33.0
747 "e1010000000000005040"+ // field 28, encoding 1, value 64.0
748 "e1010000000000405040"+ // field 28, encoding 1, value 65.0
749 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
750 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
751 "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
752 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
David Symonds5b7775e2010-12-01 10:09:04 +1100753 "d00c40"+ // field 202, encoding 0, value 32
754 "d00c3f"+ // field 202, encoding 0, value -32
755 "d80c8001"+ // field 203, encoding 0, value 64
756 "d80c7f"+ // field 203, encoding 0, value -64
Rob Pikeaaa3a622010-03-20 22:32:34 -0700757 "c00201"+ // field 40, encoding 0, value 1
758 "c80220"+ // field 41, encoding 0, value 32
759 "d00240"+ // field 42, encoding 0, value 64
760 "dd0240010000"+ // field 43, encoding 5, value 320
761 "e1028002000000000000"+ // field 44, encoding 1, value 640
762 "e8028019"+ // field 45, encoding 0, value 3200
763 "f0028032"+ // field 46, encoding 0, value 6400
764 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
765 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
766 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100767 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700768 "90193f"+ // field 402, encoding 0, value 63
769 "98197f"+ // field 403, encoding 0, value 127
770 "b304"+ // start group field 70 level 1
771 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
772 "b404"+ // end group field 70 level 1
773 "8305"+ // start group field 80 level 1
774 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
775 "8405"+ // end group field 80 level 1
776 "8305"+ // start group field 80 level 1
777 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
778 "8405") // end group field 80 level 1
779
780}
781
David Symonds5b7775e2010-12-01 10:09:04 +1100782// All required fields set, all packed repeated fields given two values.
783func TestEncodeDecode6(t *testing.T) {
784 pb := initGoTest(false)
785 pb.F_BoolRepeatedPacked = []bool{false, true}
786 pb.F_Int32RepeatedPacked = []int32{32, 33}
787 pb.F_Int64RepeatedPacked = []int64{64, 65}
788 pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
789 pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
790 pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
791 pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
792 pb.F_FloatRepeatedPacked = []float32{32., 33.}
793 pb.F_DoubleRepeatedPacked = []float64{64., 65.}
794 pb.F_Sint32RepeatedPacked = []int32{32, -32}
795 pb.F_Sint64RepeatedPacked = []int64{64, -64}
796
797 overify(t, pb,
798 "0807"+ // field 1, encoding 0, value 7
799 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
800 "5001"+ // field 10, encoding 0, value 1
801 "5803"+ // field 11, encoding 0, value 3
802 "6006"+ // field 12, encoding 0, value 6
803 "6d20000000"+ // field 13, encoding 5, value 32
804 "714000000000000000"+ // field 14, encoding 1, value 64
805 "78a019"+ // field 15, encoding 0, value 3232
806 "8001c032"+ // field 16, encoding 0, value 6464
807 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
808 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
809 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
810 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
811 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
812 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
813 "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
814 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
815 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
816 "aa0308"+ // field 53, encoding 2, 8 bytes
817 "a00c0000050d0000"+ // value 3232, value 3333
818 "b20310"+ // field 54, encoding 2, 16 bytes
819 "4019000000000000a519000000000000"+ // value 6464, value 6565
820 "ba0306"+ // field 55, encoding 2, 6 bytes
821 "a0dd1395ac14"+ // value 323232, value 333333
822 "c20306"+ // field 56, encoding 2, 6 bytes
823 "c0ba27b58928"+ // value 646464, value 656565
824 "ca0308"+ // field 57, encoding 2, 8 bytes
825 "0000004200000442"+ // value 32.0, value 33.0
826 "d20310"+ // field 58, encoding 2, 16 bytes
827 "00000000000050400000000000405040"+ // value 64.0, value 65.0
828 "b21f02"+ // field 502, encoding 2, 2 bytes
829 "403f"+ // value 32, value -32
830 "ba1f03"+ // field 503, encoding 2, 3 bytes
831 "80017f"+ // value 64, value -64
832 "b304"+ // start group field 70 level 1
833 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
834 "b404") // end group field 70 level 1
835}
836
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800837// Test that we can encode empty bytes fields.
838func TestEncodeDecodeBytes1(t *testing.T) {
839 pb := initGoTest(false)
840
841 // Create our bytes
842 pb.F_BytesRequired = []byte{}
David Symondsd9da6ba2011-08-30 14:41:30 +1000843 pb.F_BytesRepeated = [][]byte{{}}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800844 pb.F_BytesOptional = []byte{}
845
846 d, err := Marshal(pb)
847 if err != nil {
848 t.Errorf(err.String())
849 }
850
851 pbd := new(GoTest)
852 if err := Unmarshal(d, pbd); err != nil {
853 t.Errorf(err.String())
854 }
855
856 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
857 t.Errorf("required empty bytes field is incorrect")
858 }
859 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
860 t.Errorf("repeated empty bytes field is incorrect")
861 }
862 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
863 t.Errorf("optional empty bytes field is incorrect")
864 }
865}
866
867// Test that we encode nil-valued fields of a repeated bytes field correctly.
868// Since entries in a repeated field cannot be nil, nil must mean empty value.
869func TestEncodeDecodeBytes2(t *testing.T) {
870 pb := initGoTest(false)
871
872 // Create our bytes
David Symonds5b7775e2010-12-01 10:09:04 +1100873 pb.F_BytesRepeated = [][]byte{nil}
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800874
875 d, err := Marshal(pb)
David Symonds5b7775e2010-12-01 10:09:04 +1100876 if err != nil {
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800877 t.Errorf(err.String())
878 }
879
880 pbd := new(GoTest)
881 if err := Unmarshal(d, pbd); err != nil {
882 t.Errorf(err.String())
883 }
884
885 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
886 t.Errorf("Unexpected value for repeated bytes field")
887 }
888}
889
Rob Pikeaaa3a622010-03-20 22:32:34 -0700890// All required fields set, defaults provided, all repeated fields given two values.
891func TestSkippingUnrecognizedFields(t *testing.T) {
892 o := old()
893 pb := initGoTestField()
894
895 // Marshal it normally.
896 o.Marshal(pb)
897
898 // Now new a GoSkipTest record.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700899 skip := &GoSkipTest{
900 SkipInt32: Int32(32),
901 SkipFixed32: Uint32(3232),
902 SkipFixed64: Uint64(6464),
903 SkipString: String("skipper"),
904 Skipgroup: &GoSkipTest_SkipGroup{
905 GroupInt32: Int32(75),
906 GroupString: String("wxyz"),
907 },
908 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700909
910 // Marshal it into same buffer.
911 o.Marshal(skip)
912
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700913 pbd := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700914 o.Unmarshal(pbd)
915
916 // The __unrecognized field should be a marshaling of GoSkipTest
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700917 skipd := new(GoSkipTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700918
919 o.SetBuf(pbd.XXX_unrecognized)
920 o.Unmarshal(skipd)
921
922 if *skipd.SkipInt32 != *skip.SkipInt32 {
923 t.Error("skip int32", skipd.SkipInt32)
924 }
925 if *skipd.SkipFixed32 != *skip.SkipFixed32 {
926 t.Error("skip fixed32", skipd.SkipFixed32)
927 }
928 if *skipd.SkipFixed64 != *skip.SkipFixed64 {
929 t.Error("skip fixed64", skipd.SkipFixed64)
930 }
931 if *skipd.SkipString != *skip.SkipString {
932 t.Error("skip string", *skipd.SkipString)
933 }
934 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
935 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
936 }
937 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
938 t.Error("skip group string", *skipd.Skipgroup.GroupString)
939 }
940}
941
942// Check that we can grow an array (repeated field) to have many elements.
943// This test doesn't depend only on our encoding; for variety, it makes sure
944// we create, encode, and decode the correct contents explicitly. It's therefore
945// a bit messier.
946// This test also uses (and hence tests) the Marshal/Unmarshal functions
947// instead of the methods.
948func TestBigRepeated(t *testing.T) {
949 pb := initGoTest(true)
950
951 // Create the arrays
952 const N = 50 // Internally the library starts much smaller.
953 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
954 pb.F_Sint64Repeated = make([]int64, N)
955 pb.F_Sint32Repeated = make([]int32, N)
956 pb.F_BytesRepeated = make([][]byte, N)
957 pb.F_StringRepeated = make([]string, N)
958 pb.F_DoubleRepeated = make([]float64, N)
959 pb.F_FloatRepeated = make([]float32, N)
960 pb.F_Uint64Repeated = make([]uint64, N)
961 pb.F_Uint32Repeated = make([]uint32, N)
962 pb.F_Fixed64Repeated = make([]uint64, N)
963 pb.F_Fixed32Repeated = make([]uint32, N)
964 pb.F_Int64Repeated = make([]int64, N)
965 pb.F_Int32Repeated = make([]int32, N)
966 pb.F_BoolRepeated = make([]bool, N)
967 pb.RepeatedField = make([]*GoTestField, N)
968
969 // Fill in the arrays with checkable values.
970 igtf := initGoTestField()
971 igtrg := initGoTest_RepeatedGroup()
972 for i := 0; i < N; i++ {
973 pb.Repeatedgroup[i] = igtrg
974 pb.F_Sint64Repeated[i] = int64(i)
975 pb.F_Sint32Repeated[i] = int32(i)
976 s := fmt.Sprint(i)
977 pb.F_BytesRepeated[i] = []byte(s)
978 pb.F_StringRepeated[i] = s
979 pb.F_DoubleRepeated[i] = float64(i)
980 pb.F_FloatRepeated[i] = float32(i)
981 pb.F_Uint64Repeated[i] = uint64(i)
982 pb.F_Uint32Repeated[i] = uint32(i)
983 pb.F_Fixed64Repeated[i] = uint64(i)
984 pb.F_Fixed32Repeated[i] = uint32(i)
985 pb.F_Int64Repeated[i] = int64(i)
986 pb.F_Int32Repeated[i] = int32(i)
987 pb.F_BoolRepeated[i] = i%2 == 0
988 pb.RepeatedField[i] = igtf
989 }
990
991 // Marshal.
992 buf, _ := Marshal(pb)
993
994 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700995 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700996 Unmarshal(buf, pbd)
997
998 // Check the checkable values
999 for i := uint64(0); i < N; i++ {
1000 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
1001 t.Error("pbd.Repeatedgroup bad")
1002 }
1003 var x uint64
1004 x = uint64(pbd.F_Sint64Repeated[i])
1005 if x != i {
1006 t.Error("pbd.F_Sint64Repeated bad", x, i)
1007 }
1008 x = uint64(pbd.F_Sint32Repeated[i])
1009 if x != i {
1010 t.Error("pbd.F_Sint32Repeated bad", x, i)
1011 }
1012 s := fmt.Sprint(i)
1013 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
1014 if pbd.F_StringRepeated[i] != s {
1015 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
1016 }
1017 x = uint64(pbd.F_DoubleRepeated[i])
1018 if x != i {
1019 t.Error("pbd.F_DoubleRepeated bad", x, i)
1020 }
1021 x = uint64(pbd.F_FloatRepeated[i])
1022 if x != i {
1023 t.Error("pbd.F_FloatRepeated bad", x, i)
1024 }
1025 x = pbd.F_Uint64Repeated[i]
1026 if x != i {
1027 t.Error("pbd.F_Uint64Repeated bad", x, i)
1028 }
1029 x = uint64(pbd.F_Uint32Repeated[i])
1030 if x != i {
1031 t.Error("pbd.F_Uint32Repeated bad", x, i)
1032 }
1033 x = pbd.F_Fixed64Repeated[i]
1034 if x != i {
1035 t.Error("pbd.F_Fixed64Repeated bad", x, i)
1036 }
1037 x = uint64(pbd.F_Fixed32Repeated[i])
1038 if x != i {
1039 t.Error("pbd.F_Fixed32Repeated bad", x, i)
1040 }
1041 x = uint64(pbd.F_Int64Repeated[i])
1042 if x != i {
1043 t.Error("pbd.F_Int64Repeated bad", x, i)
1044 }
1045 x = uint64(pbd.F_Int32Repeated[i])
1046 if x != i {
1047 t.Error("pbd.F_Int32Repeated bad", x, i)
1048 }
1049 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
1050 t.Error("pbd.F_BoolRepeated bad", x, i)
1051 }
1052 if pbd.RepeatedField[i] == nil { // TODO: more checking?
1053 t.Error("pbd.RepeatedField bad")
1054 }
1055 }
1056}
1057
1058// Verify we give a useful message when decoding to the wrong structure type.
1059func TestTypeMismatch(t *testing.T) {
1060 pb1 := initGoTest(true)
1061
1062 // Marshal
1063 o := old()
1064 o.Marshal(pb1)
1065
1066 // Now Unmarshal it to the wrong type.
1067 pb2 := initGoTestField()
1068 err := o.Unmarshal(pb2)
1069 switch err {
1070 case ErrWrongType:
1071 // fine
1072 case nil:
1073 t.Error("expected wrong type error, got no error")
1074 default:
1075 t.Error("expected wrong type error, got", err)
1076 }
1077}
1078
David Symonds5b7775e2010-12-01 10:09:04 +11001079func encodeDecode(t *testing.T, in, out interface{}, msg string) {
1080 buf, err := Marshal(in)
1081 if err != nil {
1082 t.Fatalf("failed marshaling %v: %v", msg, err)
1083 }
1084 if err := Unmarshal(buf, out); err != nil {
1085 t.Fatalf("failed unmarshaling %v: %v", msg, err)
1086 }
1087}
1088
1089func TestPackedNonPackedDecoderSwitching(t *testing.T) {
1090 np, p := new(NonPackedTest), new(PackedTest)
1091
1092 // non-packed -> packed
1093 np.A = []int32{0, 1, 1, 2, 3, 5}
1094 encodeDecode(t, np, p, "non-packed -> packed")
1095 if !reflect.DeepEqual(np.A, p.B) {
1096 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
1097 }
1098
1099 // packed -> non-packed
1100 np.Reset()
1101 p.B = []int32{3, 1, 4, 1, 5, 9}
1102 encodeDecode(t, p, np, "packed -> non-packed")
1103 if !reflect.DeepEqual(p.B, np.A) {
1104 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
1105 }
1106}
1107
Rob Pikeaaa3a622010-03-20 22:32:34 -07001108func TestProto1RepeatedGroup(t *testing.T) {
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001109 pb := &MessageList{
1110 Message: []*MessageList_Message{
1111 &MessageList_Message{
1112 Name: String("blah"),
1113 Count: Int32(7),
1114 },
1115 // NOTE: pb.Message[1] is a nil
1116 nil,
1117 },
1118 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001119
1120 o := old()
1121 if err := o.Marshal(pb); err != ErrRepeatedHasNil {
1122 t.Fatalf("unexpected or no error when marshaling: %v", err)
1123 }
1124}
1125
Rob Pike9caa5b92010-05-11 16:04:57 -07001126
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)
1132 pb.Foo = NewFOO(FOO_FOO1)
1133 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")
1159 } else if strings.Index(err.String(), "GoTestField") < 0 {
1160 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")
1170 } else if strings.Index(err.String(), "GoTestField") < 0 {
1171 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
1178func (nni nonNillableInt) Marshal() ([]byte, os.Error) {
1179 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
1191func (nm *nillableMessage) Marshal() ([]byte, os.Error) {
1192 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 Symonds7656e742011-07-22 14:54:17 +10001217// Check that passing a struct to Marshal returns a good error,
1218// rather than panicking.
1219func TestStructMarshaling(t *testing.T) {
1220 _, err := Marshal(OtherMessage{})
1221 if err != ErrNotPtr {
1222 t.Errorf("got %v, expected %v", err, ErrNotPtr)
1223 }
1224}
1225
David Symondsb79d99b2011-08-29 16:38:49 +10001226func TestAllSetDefaults(t *testing.T) {
1227 // Exercise SetDefaults with all scalar field types.
1228 m := &Defaults{
1229 // NaN != NaN, so override that here.
1230 F_Nan: Float32(1.7),
1231 }
1232 expected := &Defaults{
1233 F_Bool: Bool(true),
1234 F_Int32: Int32(32),
1235 F_Int64: Int64(64),
1236 F_Fixed32: Uint32(320),
1237 F_Fixed64: Uint64(640),
1238 F_Uint32: Uint32(3200),
1239 F_Uint64: Uint64(6400),
1240 F_Float: Float32(314159),
1241 F_Double: Float64(271828),
1242 F_String: String(`hello, "world!"` + "\n"),
1243 F_Bytes: []byte("Bignose"),
1244 F_Sint32: Int32(-32),
1245 F_Sint64: Int64(-64),
1246 F_Enum: NewDefaults_Color(Defaults_GREEN),
1247 F_Pinf: Float32(float32(math.Inf(1))),
1248 F_Ninf: Float32(float32(math.Inf(-1))),
1249 F_Nan: Float32(1.7),
1250 }
1251 SetDefaults(m)
1252 if !Equal(m, expected) {
1253 t.Errorf(" got %v\nwant %v", m, expected)
1254 }
1255}
1256
1257func TestSetDefaultsWithSetField(t *testing.T) {
1258 // Check that a set value is not overridden.
1259 m := &Defaults{
1260 F_Int32: Int32(12),
1261 }
1262 SetDefaults(m)
1263 if v := GetInt32(m.F_Int32); v != 12 {
1264 t.Errorf("m.FInt32 = %v, want 12", v)
1265 }
1266}
1267
1268func TestSetDefaultsWithSubMessage(t *testing.T) {
1269 m := &OtherMessage{
1270 Key: Int64(123),
1271 Inner: &InnerMessage{
1272 Host: String("gopher"),
1273 },
1274 }
1275 expected := &OtherMessage{
1276 Key: Int64(123),
1277 Inner: &InnerMessage{
1278 Host: String("gopher"),
1279 Port: Int32(4000),
1280 },
1281 }
1282 SetDefaults(m)
1283 if !Equal(m, expected) {
1284 t.Errorf(" got %v\nwant %v", m, expected)
1285 }
1286}
1287
David Symondsd73d7b12011-09-28 10:56:43 -07001288func TestMaximumTagNumber(t *testing.T) {
1289 m := &MaxTag{
1290 LastField: String("natural goat essence"),
1291 }
1292 buf, err := Marshal(m)
1293 if err != nil {
1294 t.Fatalf("proto.Marshal failed: %v", err)
1295 }
1296 m2 := new(MaxTag)
1297 if err := Unmarshal(buf, m2); err != nil {
1298 t.Fatalf("proto.Unmarshal failed: %v", err)
1299 }
1300 if got, want := GetString(m2.LastField), *m.LastField; got != want {
1301 t.Errorf("got %q, want %q", got, want)
1302 }
1303}
1304
David Symonds002ec402011-09-29 17:24:20 -07001305func TestJSON(t *testing.T) {
1306 m := &MyMessage{
1307 Count: Int32(4),
1308 Pet: []string{"bunny", "kitty"},
1309 Inner: &InnerMessage{
1310 Host: String("cauchy"),
1311 },
1312 }
1313 const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"}}`
1314
1315 b, err := json.Marshal(m)
1316 if err != nil {
1317 t.Fatalf("json.Marshal failed: %v", err)
1318 }
1319 s := string(b)
1320 if s != expected {
1321 t.Errorf("got %s\nwant %s", s, expected)
1322 }
1323}
1324
Rob Pikeaaa3a622010-03-20 22:32:34 -07001325func BenchmarkMarshal(b *testing.B) {
1326 b.StopTimer()
1327
1328 pb := initGoTest(true)
1329
1330 // Create an array
1331 const N = 1000 // Internally the library starts much smaller.
1332 pb.F_Int32Repeated = make([]int32, N)
David Symondsd9da6ba2011-08-30 14:41:30 +10001333 pb.F_DoubleRepeated = make([]float64, N)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001334
1335 // Fill in the array with some values.
1336 for i := 0; i < N; i++ {
1337 pb.F_Int32Repeated[i] = int32(i)
David Symondsd9da6ba2011-08-30 14:41:30 +10001338 pb.F_DoubleRepeated[i] = float64(i)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001339 }
David Symondsd9da6ba2011-08-30 14:41:30 +10001340
Rob Pikeaaa3a622010-03-20 22:32:34 -07001341 p := NewBuffer(nil)
1342
1343 b.StartTimer()
1344 for i := 0; i < b.N; i++ {
1345 p.Reset()
1346 p.Marshal(pb)
1347 }
1348}
1349
1350func BenchmarkUnmarshal(b *testing.B) {
1351 b.StopTimer()
1352
1353 pb := initGoTest(true)
1354
1355 // Create an array
1356 const N = 1000 // Internally the library starts much smaller.
1357 pb.F_Int32Repeated = make([]int32, N)
1358
1359 // Fill in the array with some values.
1360 for i := 0; i < N; i++ {
1361 pb.F_Int32Repeated[i] = int32(i)
1362 }
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001363 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001364 p := NewBuffer(nil)
1365 p.Marshal(pb)
1366 p2 := NewBuffer(nil)
1367
1368 b.StartTimer()
1369 for i := 0; i < b.N; i++ {
1370 p2.SetBuf(p.Bytes())
1371 p2.Unmarshal(pbd)
1372 }
1373}