blob: 03f5369c6212adec462236b3d9a83ff3a8e8b108 [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
32// We need to compile the .pb.gos, which import this package, so
33// to run the test we must make install here and then make in the
34// testdata directory.
35// gotest: make install && cd testdata && make nuke && make
36
37package proto_test
38
39import (
40 "bytes"
41 "fmt"
David Symonds03c9d412010-08-26 14:23:18 +100042 "os"
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
117 pb.Kind = Int32(GoTest_TIME)
118 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)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700430 if o.Marshal(pb) != ErrRequiredNotSet {
431 t.Errorf("did not catch missing required fields")
432 }
433}
434
435// Check that all fields are nil.
436// Clearly silly, and a residue from a more interesting test with an earlier,
437// different initialization property, but it once caught a compiler bug so
438// it lives.
439func checkInitialized(pb *GoTest, t *testing.T) {
440 if pb.F_BoolDefaulted != nil {
441 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
442 }
443 if pb.F_Int32Defaulted != nil {
444 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
445 }
446 if pb.F_Int64Defaulted != nil {
447 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
448 }
449 if pb.F_Fixed32Defaulted != nil {
450 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
451 }
452 if pb.F_Fixed64Defaulted != nil {
453 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
454 }
455 if pb.F_Uint32Defaulted != nil {
456 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
457 }
458 if pb.F_Uint64Defaulted != nil {
459 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
460 }
461 if pb.F_FloatDefaulted != nil {
462 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
463 }
464 if pb.F_DoubleDefaulted != nil {
465 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
466 }
467 if pb.F_StringDefaulted != nil {
468 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
469 }
470 if pb.F_BytesDefaulted != nil {
471 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
472 }
473 if pb.F_Sint32Defaulted != nil {
474 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
475 }
476 if pb.F_Sint64Defaulted != nil {
477 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
478 }
479}
480
481// Does Reset() reset?
482func TestReset(t *testing.T) {
483 pb := initGoTest(true)
484 // muck with some values
485 pb.F_BoolDefaulted = Bool(false)
486 pb.F_Int32Defaulted = Int32(237)
487 pb.F_Int64Defaulted = Int64(12346)
488 pb.F_Fixed32Defaulted = Uint32(32000)
489 pb.F_Fixed64Defaulted = Uint64(666)
490 pb.F_Uint32Defaulted = Uint32(323232)
491 pb.F_Uint64Defaulted = nil
492 pb.F_FloatDefaulted = nil
493 pb.F_DoubleDefaulted = Float64(0)
494 pb.F_StringDefaulted = String("gotcha")
495 pb.F_BytesDefaulted = []byte("asdfasdf")
496 pb.F_Sint32Defaulted = Int32(123)
497 pb.F_Sint64Defaulted = Int64(789)
498 pb.Reset()
499 checkInitialized(pb, t)
500}
501
502// All required fields set, no defaults provided.
503func TestEncodeDecode1(t *testing.T) {
504 pb := initGoTest(false)
505 overify(t, pb,
506 "0807"+ // field 1, encoding 0, value 7
507 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
508 "5001"+ // field 10, encoding 0, value 1
509 "5803"+ // field 11, encoding 0, value 3
510 "6006"+ // field 12, encoding 0, value 6
511 "6d20000000"+ // field 13, encoding 5, value 0x20
512 "714000000000000000"+ // field 14, encoding 1, value 0x40
513 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
514 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
515 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
516 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
517 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
518 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
519 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
520 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
521 "b304"+ // field 70, encoding 3, start group
522 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
523 "b404") // field 70, encoding 4, end group
524}
525
526// All required fields set, defaults provided.
527func TestEncodeDecode2(t *testing.T) {
528 pb := initGoTest(true)
529 overify(t, pb,
530 "0807"+ // field 1, encoding 0, value 7
531 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
532 "5001"+ // field 10, encoding 0, value 1
533 "5803"+ // field 11, encoding 0, value 3
534 "6006"+ // field 12, encoding 0, value 6
535 "6d20000000"+ // field 13, encoding 5, value 32
536 "714000000000000000"+ // field 14, encoding 1, value 64
537 "78a019"+ // field 15, encoding 0, value 3232
538 "8001c032"+ // field 16, encoding 0, value 6464
539 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
540 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
541 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
542 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
543 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
544 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
545 "c00201"+ // field 40, encoding 0, value 1
546 "c80220"+ // field 41, encoding 0, value 32
547 "d00240"+ // field 42, encoding 0, value 64
548 "dd0240010000"+ // field 43, encoding 5, value 320
549 "e1028002000000000000"+ // field 44, encoding 1, value 640
550 "e8028019"+ // field 45, encoding 0, value 3200
551 "f0028032"+ // field 46, encoding 0, value 6400
552 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
553 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
554 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100555 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700556 "90193f"+ // field 402, encoding 0, value 63
557 "98197f"+ // field 403, encoding 0, value 127
558 "b304"+ // start group field 70 level 1
559 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
560 "b404") // end group field 70 level 1
561
562}
563
564// All default fields set to their default value by hand
565func TestEncodeDecode3(t *testing.T) {
566 pb := initGoTest(false)
567 pb.F_BoolDefaulted = Bool(true)
568 pb.F_Int32Defaulted = Int32(32)
569 pb.F_Int64Defaulted = Int64(64)
570 pb.F_Fixed32Defaulted = Uint32(320)
571 pb.F_Fixed64Defaulted = Uint64(640)
572 pb.F_Uint32Defaulted = Uint32(3200)
573 pb.F_Uint64Defaulted = Uint64(6400)
574 pb.F_FloatDefaulted = Float32(314159)
575 pb.F_DoubleDefaulted = Float64(271828)
576 pb.F_StringDefaulted = String("hello, \"world!\"\n")
577 pb.F_BytesDefaulted = []byte("Bignose")
578 pb.F_Sint32Defaulted = Int32(-32)
579 pb.F_Sint64Defaulted = Int64(-64)
580
581 overify(t, pb,
582 "0807"+ // field 1, encoding 0, value 7
583 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
584 "5001"+ // field 10, encoding 0, value 1
585 "5803"+ // field 11, encoding 0, value 3
586 "6006"+ // field 12, encoding 0, value 6
587 "6d20000000"+ // field 13, encoding 5, value 32
588 "714000000000000000"+ // field 14, encoding 1, value 64
589 "78a019"+ // field 15, encoding 0, value 3232
590 "8001c032"+ // field 16, encoding 0, value 6464
591 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
592 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
593 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
594 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
595 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
596 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
597 "c00201"+ // field 40, encoding 0, value 1
598 "c80220"+ // field 41, encoding 0, value 32
599 "d00240"+ // field 42, encoding 0, value 64
600 "dd0240010000"+ // field 43, encoding 5, value 320
601 "e1028002000000000000"+ // field 44, encoding 1, value 640
602 "e8028019"+ // field 45, encoding 0, value 3200
603 "f0028032"+ // field 46, encoding 0, value 6400
604 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
605 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
606 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100607 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700608 "90193f"+ // field 402, encoding 0, value 63
609 "98197f"+ // field 403, encoding 0, value 127
610 "b304"+ // start group field 70 level 1
611 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
612 "b404") // end group field 70 level 1
613
614}
615
616// All required fields set, defaults provided, all non-defaulted optional fields have values.
617func TestEncodeDecode4(t *testing.T) {
618 pb := initGoTest(true)
619 pb.Table = String("hello")
620 pb.Param = Int32(7)
621 pb.OptionalField = initGoTestField()
622 pb.F_BoolOptional = Bool(true)
623 pb.F_Int32Optional = Int32(32)
624 pb.F_Int64Optional = Int64(64)
625 pb.F_Fixed32Optional = Uint32(3232)
626 pb.F_Fixed64Optional = Uint64(6464)
627 pb.F_Uint32Optional = Uint32(323232)
628 pb.F_Uint64Optional = Uint64(646464)
629 pb.F_FloatOptional = Float32(32.)
630 pb.F_DoubleOptional = Float64(64.)
631 pb.F_StringOptional = String("hello")
632 pb.F_BytesOptional = []byte("Bignose")
633 pb.F_Sint32Optional = Int32(-32)
634 pb.F_Sint64Optional = Int64(-64)
635 pb.Optionalgroup = initGoTest_OptionalGroup()
636
637 overify(t, pb,
638 "0807"+ // field 1, encoding 0, value 7
639 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
640 "1807"+ // field 3, encoding 0, value 7
641 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
642 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
643 "5001"+ // field 10, encoding 0, value 1
644 "5803"+ // field 11, encoding 0, value 3
645 "6006"+ // field 12, encoding 0, value 6
646 "6d20000000"+ // field 13, encoding 5, value 32
647 "714000000000000000"+ // field 14, encoding 1, value 64
648 "78a019"+ // field 15, encoding 0, value 3232
649 "8001c032"+ // field 16, encoding 0, value 6464
650 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
651 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
652 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
653 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
654 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
655 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
656 "f00101"+ // field 30, encoding 0, value 1
657 "f80120"+ // field 31, encoding 0, value 32
658 "800240"+ // field 32, encoding 0, value 64
659 "8d02a00c0000"+ // field 33, encoding 5, value 3232
660 "91024019000000000000"+ // field 34, encoding 1, value 6464
661 "9802a0dd13"+ // field 35, encoding 0, value 323232
662 "a002c0ba27"+ // field 36, encoding 0, value 646464
663 "ad0200000042"+ // field 37, encoding 5, value 32.0
664 "b1020000000000005040"+ // field 38, encoding 1, value 64.0
665 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
666 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
667 "f0123f"+ // field 302, encoding 0, value 63
668 "f8127f"+ // field 303, encoding 0, value 127
669 "c00201"+ // field 40, encoding 0, value 1
670 "c80220"+ // field 41, encoding 0, value 32
671 "d00240"+ // field 42, encoding 0, value 64
672 "dd0240010000"+ // field 43, encoding 5, value 320
673 "e1028002000000000000"+ // field 44, encoding 1, value 640
674 "e8028019"+ // field 45, encoding 0, value 3200
675 "f0028032"+ // field 46, encoding 0, value 6400
676 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
677 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
678 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100679 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700680 "90193f"+ // field 402, encoding 0, value 63
681 "98197f"+ // field 403, encoding 0, value 127
682 "b304"+ // start group field 70 level 1
683 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
684 "b404"+ // end group field 70 level 1
685 "d305"+ // start group field 90 level 1
686 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
687 "d405") // end group field 90 level 1
688
689}
690
691// All required fields set, defaults provided, all repeated fields given two values.
692func TestEncodeDecode5(t *testing.T) {
693 pb := initGoTest(true)
694 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
695 pb.F_BoolRepeated = []bool{false, true}
696 pb.F_Int32Repeated = []int32{32, 33}
697 pb.F_Int64Repeated = []int64{64, 65}
698 pb.F_Fixed32Repeated = []uint32{3232, 3333}
699 pb.F_Fixed64Repeated = []uint64{6464, 6565}
700 pb.F_Uint32Repeated = []uint32{323232, 333333}
701 pb.F_Uint64Repeated = []uint64{646464, 656565}
702 pb.F_FloatRepeated = []float32{32., 33.}
703 pb.F_DoubleRepeated = []float64{64., 65.}
704 pb.F_StringRepeated = []string{"hello", "sailor"}
705 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
706 pb.F_Sint32Repeated = []int32{32, -32}
707 pb.F_Sint64Repeated = []int64{64, -64}
708 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
709
710 overify(t, pb,
711 "0807"+ // field 1, encoding 0, value 7
712 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
713 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
714 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
715 "5001"+ // field 10, encoding 0, value 1
716 "5803"+ // field 11, encoding 0, value 3
717 "6006"+ // field 12, encoding 0, value 6
718 "6d20000000"+ // field 13, encoding 5, value 32
719 "714000000000000000"+ // field 14, encoding 1, value 64
720 "78a019"+ // field 15, encoding 0, value 3232
721 "8001c032"+ // field 16, encoding 0, value 6464
722 "8d0100004a45"+ // field 17, encoding 5, value 3232.0
723 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
724 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
725 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
726 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
727 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
728 "a00100"+ // field 20, encoding 0, value 0
729 "a00101"+ // field 20, encoding 0, value 1
730 "a80120"+ // field 21, encoding 0, value 32
731 "a80121"+ // field 21, encoding 0, value 33
732 "b00140"+ // field 22, encoding 0, value 64
733 "b00141"+ // field 22, encoding 0, value 65
734 "bd01a00c0000"+ // field 23, encoding 5, value 3232
735 "bd01050d0000"+ // field 23, encoding 5, value 3333
736 "c1014019000000000000"+ // field 24, encoding 1, value 6464
737 "c101a519000000000000"+ // field 24, encoding 1, value 6565
738 "c801a0dd13"+ // field 25, encoding 0, value 323232
739 "c80195ac14"+ // field 25, encoding 0, value 333333
740 "d001c0ba27"+ // field 26, encoding 0, value 646464
741 "d001b58928"+ // field 26, encoding 0, value 656565
742 "dd0100000042"+ // field 27, encoding 5, value 32.0
743 "dd0100000442"+ // field 27, encoding 5, value 33.0
744 "e1010000000000005040"+ // field 28, encoding 1, value 64.0
745 "e1010000000000405040"+ // field 28, encoding 1, value 65.0
746 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
747 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
748 "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
749 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
750 "d00c40"+ // field 202, encoding 0, value 64
751 "d00c3f"+ // field 202, encoding 0, value 63
752 "d80c8001"+ // field 203, encoding 0, value 128
753 "d80c7f"+ // field 203, encoding 0, value 127
754 "c00201"+ // field 40, encoding 0, value 1
755 "c80220"+ // field 41, encoding 0, value 32
756 "d00240"+ // field 42, encoding 0, value 64
757 "dd0240010000"+ // field 43, encoding 5, value 320
758 "e1028002000000000000"+ // field 44, encoding 1, value 640
759 "e8028019"+ // field 45, encoding 0, value 3200
760 "f0028032"+ // field 46, encoding 0, value 6400
761 "fd02e0659948"+ // field 47, encoding 5, value 314159.0
762 "81030000000050971041"+ // field 48, encoding 1, value 271828.0
763 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
David Symonds5f7b9e02010-11-30 10:42:39 +1100764 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
Rob Pikeaaa3a622010-03-20 22:32:34 -0700765 "90193f"+ // field 402, encoding 0, value 63
766 "98197f"+ // field 403, encoding 0, value 127
767 "b304"+ // start group field 70 level 1
768 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
769 "b404"+ // end group field 70 level 1
770 "8305"+ // start group field 80 level 1
771 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
772 "8405"+ // end group field 80 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
777}
778
Mikkel Krautzdb488aa2010-11-29 14:15:51 -0800779// Test that we can encode empty bytes fields.
780func TestEncodeDecodeBytes1(t *testing.T) {
781 pb := initGoTest(false)
782
783 // Create our bytes
784 pb.F_BytesRequired = []byte{}
785 pb.F_BytesRepeated = [][]byte{ []byte{} }
786 pb.F_BytesOptional = []byte{}
787
788 d, err := Marshal(pb)
789 if err != nil {
790 t.Errorf(err.String())
791 }
792
793 pbd := new(GoTest)
794 if err := Unmarshal(d, pbd); err != nil {
795 t.Errorf(err.String())
796 }
797
798 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
799 t.Errorf("required empty bytes field is incorrect")
800 }
801 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
802 t.Errorf("repeated empty bytes field is incorrect")
803 }
804 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
805 t.Errorf("optional empty bytes field is incorrect")
806 }
807}
808
809// Test that we encode nil-valued fields of a repeated bytes field correctly.
810// Since entries in a repeated field cannot be nil, nil must mean empty value.
811func TestEncodeDecodeBytes2(t *testing.T) {
812 pb := initGoTest(false)
813
814 // Create our bytes
815 pb.F_BytesRepeated = [][]byte{ nil }
816
817 d, err := Marshal(pb)
818 if err != nil {
819 t.Errorf(err.String())
820 }
821
822 pbd := new(GoTest)
823 if err := Unmarshal(d, pbd); err != nil {
824 t.Errorf(err.String())
825 }
826
827 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
828 t.Errorf("Unexpected value for repeated bytes field")
829 }
830}
831
Rob Pikeaaa3a622010-03-20 22:32:34 -0700832// All required fields set, defaults provided, all repeated fields given two values.
833func TestSkippingUnrecognizedFields(t *testing.T) {
834 o := old()
835 pb := initGoTestField()
836
837 // Marshal it normally.
838 o.Marshal(pb)
839
840 // Now new a GoSkipTest record.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700841 skip := &GoSkipTest{
842 SkipInt32: Int32(32),
843 SkipFixed32: Uint32(3232),
844 SkipFixed64: Uint64(6464),
845 SkipString: String("skipper"),
846 Skipgroup: &GoSkipTest_SkipGroup{
847 GroupInt32: Int32(75),
848 GroupString: String("wxyz"),
849 },
850 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700851
852 // Marshal it into same buffer.
853 o.Marshal(skip)
854
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700855 pbd := new(GoTestField)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700856 o.Unmarshal(pbd)
857
858 // The __unrecognized field should be a marshaling of GoSkipTest
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700859 skipd := new(GoSkipTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700860
861 o.SetBuf(pbd.XXX_unrecognized)
862 o.Unmarshal(skipd)
863
864 if *skipd.SkipInt32 != *skip.SkipInt32 {
865 t.Error("skip int32", skipd.SkipInt32)
866 }
867 if *skipd.SkipFixed32 != *skip.SkipFixed32 {
868 t.Error("skip fixed32", skipd.SkipFixed32)
869 }
870 if *skipd.SkipFixed64 != *skip.SkipFixed64 {
871 t.Error("skip fixed64", skipd.SkipFixed64)
872 }
873 if *skipd.SkipString != *skip.SkipString {
874 t.Error("skip string", *skipd.SkipString)
875 }
876 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
877 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
878 }
879 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
880 t.Error("skip group string", *skipd.Skipgroup.GroupString)
881 }
882}
883
884// Check that we can grow an array (repeated field) to have many elements.
885// This test doesn't depend only on our encoding; for variety, it makes sure
886// we create, encode, and decode the correct contents explicitly. It's therefore
887// a bit messier.
888// This test also uses (and hence tests) the Marshal/Unmarshal functions
889// instead of the methods.
890func TestBigRepeated(t *testing.T) {
891 pb := initGoTest(true)
892
893 // Create the arrays
894 const N = 50 // Internally the library starts much smaller.
895 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
896 pb.F_Sint64Repeated = make([]int64, N)
897 pb.F_Sint32Repeated = make([]int32, N)
898 pb.F_BytesRepeated = make([][]byte, N)
899 pb.F_StringRepeated = make([]string, N)
900 pb.F_DoubleRepeated = make([]float64, N)
901 pb.F_FloatRepeated = make([]float32, N)
902 pb.F_Uint64Repeated = make([]uint64, N)
903 pb.F_Uint32Repeated = make([]uint32, N)
904 pb.F_Fixed64Repeated = make([]uint64, N)
905 pb.F_Fixed32Repeated = make([]uint32, N)
906 pb.F_Int64Repeated = make([]int64, N)
907 pb.F_Int32Repeated = make([]int32, N)
908 pb.F_BoolRepeated = make([]bool, N)
909 pb.RepeatedField = make([]*GoTestField, N)
910
911 // Fill in the arrays with checkable values.
912 igtf := initGoTestField()
913 igtrg := initGoTest_RepeatedGroup()
914 for i := 0; i < N; i++ {
915 pb.Repeatedgroup[i] = igtrg
916 pb.F_Sint64Repeated[i] = int64(i)
917 pb.F_Sint32Repeated[i] = int32(i)
918 s := fmt.Sprint(i)
919 pb.F_BytesRepeated[i] = []byte(s)
920 pb.F_StringRepeated[i] = s
921 pb.F_DoubleRepeated[i] = float64(i)
922 pb.F_FloatRepeated[i] = float32(i)
923 pb.F_Uint64Repeated[i] = uint64(i)
924 pb.F_Uint32Repeated[i] = uint32(i)
925 pb.F_Fixed64Repeated[i] = uint64(i)
926 pb.F_Fixed32Repeated[i] = uint32(i)
927 pb.F_Int64Repeated[i] = int64(i)
928 pb.F_Int32Repeated[i] = int32(i)
929 pb.F_BoolRepeated[i] = i%2 == 0
930 pb.RepeatedField[i] = igtf
931 }
932
933 // Marshal.
934 buf, _ := Marshal(pb)
935
936 // Now test Unmarshal by recreating the original buffer.
Rob Pikec6d8e4a2010-07-28 15:34:32 -0700937 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700938 Unmarshal(buf, pbd)
939
940 // Check the checkable values
941 for i := uint64(0); i < N; i++ {
942 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
943 t.Error("pbd.Repeatedgroup bad")
944 }
945 var x uint64
946 x = uint64(pbd.F_Sint64Repeated[i])
947 if x != i {
948 t.Error("pbd.F_Sint64Repeated bad", x, i)
949 }
950 x = uint64(pbd.F_Sint32Repeated[i])
951 if x != i {
952 t.Error("pbd.F_Sint32Repeated bad", x, i)
953 }
954 s := fmt.Sprint(i)
955 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
956 if pbd.F_StringRepeated[i] != s {
957 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
958 }
959 x = uint64(pbd.F_DoubleRepeated[i])
960 if x != i {
961 t.Error("pbd.F_DoubleRepeated bad", x, i)
962 }
963 x = uint64(pbd.F_FloatRepeated[i])
964 if x != i {
965 t.Error("pbd.F_FloatRepeated bad", x, i)
966 }
967 x = pbd.F_Uint64Repeated[i]
968 if x != i {
969 t.Error("pbd.F_Uint64Repeated bad", x, i)
970 }
971 x = uint64(pbd.F_Uint32Repeated[i])
972 if x != i {
973 t.Error("pbd.F_Uint32Repeated bad", x, i)
974 }
975 x = pbd.F_Fixed64Repeated[i]
976 if x != i {
977 t.Error("pbd.F_Fixed64Repeated bad", x, i)
978 }
979 x = uint64(pbd.F_Fixed32Repeated[i])
980 if x != i {
981 t.Error("pbd.F_Fixed32Repeated bad", x, i)
982 }
983 x = uint64(pbd.F_Int64Repeated[i])
984 if x != i {
985 t.Error("pbd.F_Int64Repeated bad", x, i)
986 }
987 x = uint64(pbd.F_Int32Repeated[i])
988 if x != i {
989 t.Error("pbd.F_Int32Repeated bad", x, i)
990 }
991 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
992 t.Error("pbd.F_BoolRepeated bad", x, i)
993 }
994 if pbd.RepeatedField[i] == nil { // TODO: more checking?
995 t.Error("pbd.RepeatedField bad")
996 }
997 }
998}
999
1000// Verify we give a useful message when decoding to the wrong structure type.
1001func TestTypeMismatch(t *testing.T) {
1002 pb1 := initGoTest(true)
1003
1004 // Marshal
1005 o := old()
1006 o.Marshal(pb1)
1007
1008 // Now Unmarshal it to the wrong type.
1009 pb2 := initGoTestField()
1010 err := o.Unmarshal(pb2)
1011 switch err {
1012 case ErrWrongType:
1013 // fine
1014 case nil:
1015 t.Error("expected wrong type error, got no error")
1016 default:
1017 t.Error("expected wrong type error, got", err)
1018 }
1019}
1020
1021func TestProto1RepeatedGroup(t *testing.T) {
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001022 pb := &MessageList{
1023 Message: []*MessageList_Message{
1024 &MessageList_Message{
1025 Name: String("blah"),
1026 Count: Int32(7),
1027 },
1028 // NOTE: pb.Message[1] is a nil
1029 nil,
1030 },
1031 }
Rob Pikeaaa3a622010-03-20 22:32:34 -07001032
1033 o := old()
1034 if err := o.Marshal(pb); err != ErrRepeatedHasNil {
1035 t.Fatalf("unexpected or no error when marshaling: %v", err)
1036 }
1037}
1038
Rob Pike9caa5b92010-05-11 16:04:57 -07001039
Rob Pikeaaa3a622010-03-20 22:32:34 -07001040// Test that enums work. Checks for a bug introduced by making enums
1041// named types instead of int32: newInt32FromUint64 would crash with
1042// a type mismatch in reflect.PointTo.
1043func TestEnum(t *testing.T) {
1044 pb := new(GoEnum)
1045 pb.Foo = NewFOO(FOO_FOO1)
1046 o := old()
1047 if err := o.Marshal(pb); err != nil {
1048 t.Fatalf("error encoding enum:", err)
1049 }
1050 pb1 := new(GoEnum)
1051 if err := o.Unmarshal(pb1); err != nil {
1052 t.Fatalf("error decoding enum:", err)
1053 }
1054 if *pb1.Foo != FOO_FOO1 {
1055 t.Errorf("expected 7 but got ", *pb1.Foo)
1056 }
1057}
1058
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001059// Verify that absent required fields cause Marshal/Unmarshal to return errors.
1060func TestRequiredFieldEnforcement(t *testing.T) {
1061 pb := new(GoTestField)
1062 _, err := Marshal(pb)
1063 if err == nil || err != ErrRequiredNotSet {
1064 t.Errorf("marshal: expected %q, got %q", ErrRequiredNotSet, err)
1065 }
1066
1067 // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
1068 // so simply counting the required fields is insufficient.
1069 // field 1, encoding 2, value "hi"
1070 buf := []byte("\x0A\x02hi\x0A\x02hi")
1071 err = Unmarshal(buf, pb)
1072 if err == nil || err != ErrRequiredNotSet {
1073 t.Errorf("unmarshal: expected %q, got %q", ErrRequiredNotSet, err)
1074 }
1075}
1076
David Symonds03c9d412010-08-26 14:23:18 +10001077// A type that implements the Marshaler interface, but is not nillable.
1078type nonNillableInt uint64
1079
1080func (nni nonNillableInt) Marshal() ([]byte, os.Error) {
1081 return EncodeVarint(uint64(nni)), nil
1082}
1083
1084type NNIMessage struct {
1085 nni nonNillableInt
1086}
1087
1088// A type that implements the Marshaler interface and is nillable.
1089type nillableMessage struct {
1090 x uint64
1091}
1092
1093func (nm *nillableMessage) Marshal() ([]byte, os.Error) {
1094 return EncodeVarint(nm.x), nil
1095}
1096
1097type NMMessage struct {
1098 nm *nillableMessage
1099}
1100
1101// Verify a type that uses the Marshaler interface, but has a nil pointer.
1102func TestNilMarshaler(t *testing.T) {
1103 // Try a struct with a Marshaler field that is nil.
1104 // It should be directly marshable.
1105 nmm := new(NMMessage)
1106 if _, err := Marshal(nmm); err != nil {
1107 t.Error("unexpected error marshaling nmm: ", err)
1108 }
1109
1110 // Try a struct with a Marshaler field that is not nillable.
1111 nnim := new(NNIMessage)
1112 nnim.nni = 7
1113 var _ Marshaler = nnim.nni // verify it is truly a Marshaler
1114 if _, err := Marshal(nnim); err != nil {
1115 t.Error("unexpected error marshaling nnim: ", err)
1116 }
1117}
1118
Rob Pikeaaa3a622010-03-20 22:32:34 -07001119func BenchmarkMarshal(b *testing.B) {
1120 b.StopTimer()
1121
1122 pb := initGoTest(true)
1123
1124 // Create an array
1125 const N = 1000 // Internally the library starts much smaller.
1126 pb.F_Int32Repeated = make([]int32, N)
1127
1128 // Fill in the array with some values.
1129 for i := 0; i < N; i++ {
1130 pb.F_Int32Repeated[i] = int32(i)
1131 }
1132 p := NewBuffer(nil)
1133
1134 b.StartTimer()
1135 for i := 0; i < b.N; i++ {
1136 p.Reset()
1137 p.Marshal(pb)
1138 }
1139}
1140
1141func BenchmarkUnmarshal(b *testing.B) {
1142 b.StopTimer()
1143
1144 pb := initGoTest(true)
1145
1146 // Create an array
1147 const N = 1000 // Internally the library starts much smaller.
1148 pb.F_Int32Repeated = make([]int32, N)
1149
1150 // Fill in the array with some values.
1151 for i := 0; i < N; i++ {
1152 pb.F_Int32Repeated[i] = int32(i)
1153 }
Rob Pikec6d8e4a2010-07-28 15:34:32 -07001154 pbd := new(GoTest)
Rob Pikeaaa3a622010-03-20 22:32:34 -07001155 p := NewBuffer(nil)
1156 p.Marshal(pb)
1157 p2 := NewBuffer(nil)
1158
1159 b.StartTimer()
1160 for i := 0; i < b.N; i++ {
1161 p2.SetBuf(p.Bytes())
1162 p2.Unmarshal(pbd)
1163 }
1164}