github.com/schwarzm/garden-linux@v0.0.0-20150507151835-33bca2147c47/Godeps/_workspace/src/code.google.com/p/gogoprotobuf/proto/all_test.go (about) 1 // Go support for Protocol Buffers - Google's data interchange format 2 // 3 // Copyright 2010 The Go Authors. 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 package proto_test 33 34 import ( 35 "bytes" 36 "encoding/json" 37 "errors" 38 "fmt" 39 "math" 40 "math/rand" 41 "reflect" 42 "runtime/debug" 43 "strings" 44 "testing" 45 "time" 46 47 . "./testdata" 48 . "code.google.com/p/gogoprotobuf/proto" 49 ) 50 51 var globalO *Buffer 52 53 func old() *Buffer { 54 if globalO == nil { 55 globalO = NewBuffer(nil) 56 } 57 globalO.Reset() 58 return globalO 59 } 60 61 func equalbytes(b1, b2 []byte, t *testing.T) { 62 if len(b1) != len(b2) { 63 t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) 64 return 65 } 66 for i := 0; i < len(b1); i++ { 67 if b1[i] != b2[i] { 68 t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) 69 } 70 } 71 } 72 73 func initGoTestField() *GoTestField { 74 f := new(GoTestField) 75 f.Label = String("label") 76 f.Type = String("type") 77 return f 78 } 79 80 // These are all structurally equivalent but the tag numbers differ. 81 // (It's remarkable that required, optional, and repeated all have 82 // 8 letters.) 83 func initGoTest_RequiredGroup() *GoTest_RequiredGroup { 84 return &GoTest_RequiredGroup{ 85 RequiredField: String("required"), 86 } 87 } 88 89 func initGoTest_OptionalGroup() *GoTest_OptionalGroup { 90 return &GoTest_OptionalGroup{ 91 RequiredField: String("optional"), 92 } 93 } 94 95 func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { 96 return &GoTest_RepeatedGroup{ 97 RequiredField: String("repeated"), 98 } 99 } 100 101 func initGoTest(setdefaults bool) *GoTest { 102 pb := new(GoTest) 103 if setdefaults { 104 pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) 105 pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) 106 pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) 107 pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) 108 pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) 109 pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) 110 pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) 111 pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) 112 pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) 113 pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) 114 pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted 115 pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) 116 pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) 117 } 118 119 pb.Kind = GoTest_TIME.Enum() 120 pb.RequiredField = initGoTestField() 121 pb.F_BoolRequired = Bool(true) 122 pb.F_Int32Required = Int32(3) 123 pb.F_Int64Required = Int64(6) 124 pb.F_Fixed32Required = Uint32(32) 125 pb.F_Fixed64Required = Uint64(64) 126 pb.F_Uint32Required = Uint32(3232) 127 pb.F_Uint64Required = Uint64(6464) 128 pb.F_FloatRequired = Float32(3232) 129 pb.F_DoubleRequired = Float64(6464) 130 pb.F_StringRequired = String("string") 131 pb.F_BytesRequired = []byte("bytes") 132 pb.F_Sint32Required = Int32(-32) 133 pb.F_Sint64Required = Int64(-64) 134 pb.Requiredgroup = initGoTest_RequiredGroup() 135 136 return pb 137 } 138 139 func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { 140 data := b.Bytes() 141 ld := len(data) 142 ls := len(s) / 2 143 144 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) 145 146 // find the interesting spot - n 147 n := ls 148 if ld < ls { 149 n = ld 150 } 151 j := 0 152 for i := 0; i < n; i++ { 153 bs := hex(s[j])*16 + hex(s[j+1]) 154 j += 2 155 if data[i] == bs { 156 continue 157 } 158 n = i 159 break 160 } 161 l := n - 10 162 if l < 0 { 163 l = 0 164 } 165 h := n + 10 166 167 // find the interesting spot - n 168 fmt.Printf("is[%d]:", l) 169 for i := l; i < h; i++ { 170 if i >= ld { 171 fmt.Printf(" --") 172 continue 173 } 174 fmt.Printf(" %.2x", data[i]) 175 } 176 fmt.Printf("\n") 177 178 fmt.Printf("sb[%d]:", l) 179 for i := l; i < h; i++ { 180 if i >= ls { 181 fmt.Printf(" --") 182 continue 183 } 184 bs := hex(s[j])*16 + hex(s[j+1]) 185 j += 2 186 fmt.Printf(" %.2x", bs) 187 } 188 fmt.Printf("\n") 189 190 t.Fail() 191 192 // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) 193 // Print the output in a partially-decoded format; can 194 // be helpful when updating the test. It produces the output 195 // that is pasted, with minor edits, into the argument to verify(). 196 // data := b.Bytes() 197 // nesting := 0 198 // for b.Len() > 0 { 199 // start := len(data) - b.Len() 200 // var u uint64 201 // u, err := DecodeVarint(b) 202 // if err != nil { 203 // fmt.Printf("decode error on varint:", err) 204 // return 205 // } 206 // wire := u & 0x7 207 // tag := u >> 3 208 // switch wire { 209 // case WireVarint: 210 // v, err := DecodeVarint(b) 211 // if err != nil { 212 // fmt.Printf("decode error on varint:", err) 213 // return 214 // } 215 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", 216 // data[start:len(data)-b.Len()], tag, wire, v) 217 // case WireFixed32: 218 // v, err := DecodeFixed32(b) 219 // if err != nil { 220 // fmt.Printf("decode error on fixed32:", err) 221 // return 222 // } 223 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", 224 // data[start:len(data)-b.Len()], tag, wire, v) 225 // case WireFixed64: 226 // v, err := DecodeFixed64(b) 227 // if err != nil { 228 // fmt.Printf("decode error on fixed64:", err) 229 // return 230 // } 231 // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", 232 // data[start:len(data)-b.Len()], tag, wire, v) 233 // case WireBytes: 234 // nb, err := DecodeVarint(b) 235 // if err != nil { 236 // fmt.Printf("decode error on bytes:", err) 237 // return 238 // } 239 // after_tag := len(data) - b.Len() 240 // str := make([]byte, nb) 241 // _, err = b.Read(str) 242 // if err != nil { 243 // fmt.Printf("decode error on bytes:", err) 244 // return 245 // } 246 // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", 247 // data[start:after_tag], str, tag, wire) 248 // case WireStartGroup: 249 // nesting++ 250 // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", 251 // data[start:len(data)-b.Len()], tag, nesting) 252 // case WireEndGroup: 253 // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", 254 // data[start:len(data)-b.Len()], tag, nesting) 255 // nesting-- 256 // default: 257 // fmt.Printf("unrecognized wire type %d\n", wire) 258 // return 259 // } 260 // } 261 } 262 263 func hex(c uint8) uint8 { 264 if '0' <= c && c <= '9' { 265 return c - '0' 266 } 267 if 'a' <= c && c <= 'f' { 268 return 10 + c - 'a' 269 } 270 if 'A' <= c && c <= 'F' { 271 return 10 + c - 'A' 272 } 273 return 0 274 } 275 276 func equal(b []byte, s string, t *testing.T) bool { 277 if 2*len(b) != len(s) { 278 // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) 279 fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) 280 return false 281 } 282 for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { 283 x := hex(s[j])*16 + hex(s[j+1]) 284 if b[i] != x { 285 // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) 286 fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) 287 return false 288 } 289 } 290 return true 291 } 292 293 func overify(t *testing.T, pb *GoTest, expected string) { 294 o := old() 295 err := o.Marshal(pb) 296 if err != nil { 297 fmt.Printf("overify marshal-1 err = %v", err) 298 o.DebugPrint("", o.Bytes()) 299 t.Fatalf("expected = %s", expected) 300 } 301 if !equal(o.Bytes(), expected, t) { 302 o.DebugPrint("overify neq 1", o.Bytes()) 303 t.Fatalf("expected = %s", expected) 304 } 305 306 // Now test Unmarshal by recreating the original buffer. 307 pbd := new(GoTest) 308 err = o.Unmarshal(pbd) 309 if err != nil { 310 t.Fatalf("overify unmarshal err = %v", err) 311 o.DebugPrint("", o.Bytes()) 312 t.Fatalf("string = %s", expected) 313 } 314 o.Reset() 315 err = o.Marshal(pbd) 316 if err != nil { 317 t.Errorf("overify marshal-2 err = %v", err) 318 o.DebugPrint("", o.Bytes()) 319 t.Fatalf("string = %s", expected) 320 } 321 if !equal(o.Bytes(), expected, t) { 322 o.DebugPrint("overify neq 2", o.Bytes()) 323 t.Fatalf("string = %s", expected) 324 } 325 } 326 327 // Simple tests for numeric encode/decode primitives (varint, etc.) 328 func TestNumericPrimitives(t *testing.T) { 329 for i := uint64(0); i < 1e6; i += 111 { 330 o := old() 331 if o.EncodeVarint(i) != nil { 332 t.Error("EncodeVarint") 333 break 334 } 335 x, e := o.DecodeVarint() 336 if e != nil { 337 t.Fatal("DecodeVarint") 338 } 339 if x != i { 340 t.Fatal("varint decode fail:", i, x) 341 } 342 343 o = old() 344 if o.EncodeFixed32(i) != nil { 345 t.Fatal("encFixed32") 346 } 347 x, e = o.DecodeFixed32() 348 if e != nil { 349 t.Fatal("decFixed32") 350 } 351 if x != i { 352 t.Fatal("fixed32 decode fail:", i, x) 353 } 354 355 o = old() 356 if o.EncodeFixed64(i*1234567) != nil { 357 t.Error("encFixed64") 358 break 359 } 360 x, e = o.DecodeFixed64() 361 if e != nil { 362 t.Error("decFixed64") 363 break 364 } 365 if x != i*1234567 { 366 t.Error("fixed64 decode fail:", i*1234567, x) 367 break 368 } 369 370 o = old() 371 i32 := int32(i - 12345) 372 if o.EncodeZigzag32(uint64(i32)) != nil { 373 t.Fatal("EncodeZigzag32") 374 } 375 x, e = o.DecodeZigzag32() 376 if e != nil { 377 t.Fatal("DecodeZigzag32") 378 } 379 if x != uint64(uint32(i32)) { 380 t.Fatal("zigzag32 decode fail:", i32, x) 381 } 382 383 o = old() 384 i64 := int64(i - 12345) 385 if o.EncodeZigzag64(uint64(i64)) != nil { 386 t.Fatal("EncodeZigzag64") 387 } 388 x, e = o.DecodeZigzag64() 389 if e != nil { 390 t.Fatal("DecodeZigzag64") 391 } 392 if x != uint64(i64) { 393 t.Fatal("zigzag64 decode fail:", i64, x) 394 } 395 } 396 } 397 398 // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. 399 type fakeMarshaler struct { 400 b []byte 401 err error 402 } 403 404 func (f fakeMarshaler) Marshal() ([]byte, error) { 405 return f.b, f.err 406 } 407 408 func (f fakeMarshaler) String() string { 409 return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) 410 } 411 412 func (f fakeMarshaler) ProtoMessage() {} 413 414 func (f fakeMarshaler) Reset() {} 415 416 // Simple tests for proto messages that implement the Marshaler interface. 417 func TestMarshalerEncoding(t *testing.T) { 418 tests := []struct { 419 name string 420 m Message 421 want []byte 422 wantErr error 423 }{ 424 { 425 name: "Marshaler that fails", 426 m: fakeMarshaler{ 427 err: errors.New("some marshal err"), 428 b: []byte{5, 6, 7}, 429 }, 430 // Since there's an error, nothing should be written to buffer. 431 want: nil, 432 wantErr: errors.New("some marshal err"), 433 }, 434 { 435 name: "Marshaler that succeeds", 436 m: fakeMarshaler{ 437 b: []byte{0, 1, 2, 3, 4, 127, 255}, 438 }, 439 want: []byte{0, 1, 2, 3, 4, 127, 255}, 440 wantErr: nil, 441 }, 442 } 443 for _, test := range tests { 444 b := NewBuffer(nil) 445 err := b.Marshal(test.m) 446 if !reflect.DeepEqual(test.wantErr, err) { 447 t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) 448 } 449 if !reflect.DeepEqual(test.want, b.Bytes()) { 450 t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) 451 } 452 } 453 } 454 455 // Simple tests for bytes 456 func TestBytesPrimitives(t *testing.T) { 457 o := old() 458 bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} 459 if o.EncodeRawBytes(bytes) != nil { 460 t.Error("EncodeRawBytes") 461 } 462 decb, e := o.DecodeRawBytes(false) 463 if e != nil { 464 t.Error("DecodeRawBytes") 465 } 466 equalbytes(bytes, decb, t) 467 } 468 469 // Simple tests for strings 470 func TestStringPrimitives(t *testing.T) { 471 o := old() 472 s := "now is the time" 473 if o.EncodeStringBytes(s) != nil { 474 t.Error("enc_string") 475 } 476 decs, e := o.DecodeStringBytes() 477 if e != nil { 478 t.Error("dec_string") 479 } 480 if s != decs { 481 t.Error("string encode/decode fail:", s, decs) 482 } 483 } 484 485 // Do we catch the "required bit not set" case? 486 func TestRequiredBit(t *testing.T) { 487 o := old() 488 pb := new(GoTest) 489 err := o.Marshal(pb) 490 if err == nil { 491 t.Error("did not catch missing required fields") 492 } else if strings.Index(err.Error(), "Kind") < 0 { 493 t.Error("wrong error type:", err) 494 } 495 } 496 497 // Check that all fields are nil. 498 // Clearly silly, and a residue from a more interesting test with an earlier, 499 // different initialization property, but it once caught a compiler bug so 500 // it lives. 501 func checkInitialized(pb *GoTest, t *testing.T) { 502 if pb.F_BoolDefaulted != nil { 503 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) 504 } 505 if pb.F_Int32Defaulted != nil { 506 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) 507 } 508 if pb.F_Int64Defaulted != nil { 509 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) 510 } 511 if pb.F_Fixed32Defaulted != nil { 512 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) 513 } 514 if pb.F_Fixed64Defaulted != nil { 515 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) 516 } 517 if pb.F_Uint32Defaulted != nil { 518 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) 519 } 520 if pb.F_Uint64Defaulted != nil { 521 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) 522 } 523 if pb.F_FloatDefaulted != nil { 524 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) 525 } 526 if pb.F_DoubleDefaulted != nil { 527 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) 528 } 529 if pb.F_StringDefaulted != nil { 530 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) 531 } 532 if pb.F_BytesDefaulted != nil { 533 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) 534 } 535 if pb.F_Sint32Defaulted != nil { 536 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) 537 } 538 if pb.F_Sint64Defaulted != nil { 539 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) 540 } 541 } 542 543 // Does Reset() reset? 544 func TestReset(t *testing.T) { 545 pb := initGoTest(true) 546 // muck with some values 547 pb.F_BoolDefaulted = Bool(false) 548 pb.F_Int32Defaulted = Int32(237) 549 pb.F_Int64Defaulted = Int64(12346) 550 pb.F_Fixed32Defaulted = Uint32(32000) 551 pb.F_Fixed64Defaulted = Uint64(666) 552 pb.F_Uint32Defaulted = Uint32(323232) 553 pb.F_Uint64Defaulted = nil 554 pb.F_FloatDefaulted = nil 555 pb.F_DoubleDefaulted = Float64(0) 556 pb.F_StringDefaulted = String("gotcha") 557 pb.F_BytesDefaulted = []byte("asdfasdf") 558 pb.F_Sint32Defaulted = Int32(123) 559 pb.F_Sint64Defaulted = Int64(789) 560 pb.Reset() 561 checkInitialized(pb, t) 562 } 563 564 // All required fields set, no defaults provided. 565 func TestEncodeDecode1(t *testing.T) { 566 pb := initGoTest(false) 567 overify(t, pb, 568 "0807"+ // field 1, encoding 0, value 7 569 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) 570 "5001"+ // field 10, encoding 0, value 1 571 "5803"+ // field 11, encoding 0, value 3 572 "6006"+ // field 12, encoding 0, value 6 573 "6d20000000"+ // field 13, encoding 5, value 0x20 574 "714000000000000000"+ // field 14, encoding 1, value 0x40 575 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 576 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 577 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 578 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 579 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" 580 "b304"+ // field 70, encoding 3, start group 581 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 582 "b404"+ // field 70, encoding 4, end group 583 "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" 584 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 585 "b8067f") // field 103, encoding 0, 0x7f zigzag64 586 } 587 588 // All required fields set, defaults provided. 589 func TestEncodeDecode2(t *testing.T) { 590 pb := initGoTest(true) 591 overify(t, pb, 592 "0807"+ // field 1, encoding 0, value 7 593 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) 594 "5001"+ // field 10, encoding 0, value 1 595 "5803"+ // field 11, encoding 0, value 3 596 "6006"+ // field 12, encoding 0, value 6 597 "6d20000000"+ // field 13, encoding 5, value 32 598 "714000000000000000"+ // field 14, encoding 1, value 64 599 "78a019"+ // field 15, encoding 0, value 3232 600 "8001c032"+ // field 16, encoding 0, value 6464 601 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 602 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 603 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" 604 "c00201"+ // field 40, encoding 0, value 1 605 "c80220"+ // field 41, encoding 0, value 32 606 "d00240"+ // field 42, encoding 0, value 64 607 "dd0240010000"+ // field 43, encoding 5, value 320 608 "e1028002000000000000"+ // field 44, encoding 1, value 640 609 "e8028019"+ // field 45, encoding 0, value 3200 610 "f0028032"+ // field 46, encoding 0, value 6400 611 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 612 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 613 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" 614 "b304"+ // start group field 70 level 1 615 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 616 "b404"+ // end group field 70 level 1 617 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" 618 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 619 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 620 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" 621 "90193f"+ // field 402, encoding 0, value 63 622 "98197f") // field 403, encoding 0, value 127 623 624 } 625 626 // All default fields set to their default value by hand 627 func TestEncodeDecode3(t *testing.T) { 628 pb := initGoTest(false) 629 pb.F_BoolDefaulted = Bool(true) 630 pb.F_Int32Defaulted = Int32(32) 631 pb.F_Int64Defaulted = Int64(64) 632 pb.F_Fixed32Defaulted = Uint32(320) 633 pb.F_Fixed64Defaulted = Uint64(640) 634 pb.F_Uint32Defaulted = Uint32(3200) 635 pb.F_Uint64Defaulted = Uint64(6400) 636 pb.F_FloatDefaulted = Float32(314159) 637 pb.F_DoubleDefaulted = Float64(271828) 638 pb.F_StringDefaulted = String("hello, \"world!\"\n") 639 pb.F_BytesDefaulted = []byte("Bignose") 640 pb.F_Sint32Defaulted = Int32(-32) 641 pb.F_Sint64Defaulted = Int64(-64) 642 643 overify(t, pb, 644 "0807"+ // field 1, encoding 0, value 7 645 "220d"+"0a056c6162656c120474797065"+ // field 4, 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 "c00201"+ // field 40, encoding 0, value 1 657 "c80220"+ // field 41, encoding 0, value 32 658 "d00240"+ // field 42, encoding 0, value 64 659 "dd0240010000"+ // field 43, encoding 5, value 320 660 "e1028002000000000000"+ // field 44, encoding 1, value 640 661 "e8028019"+ // field 45, encoding 0, value 3200 662 "f0028032"+ // field 46, encoding 0, value 6400 663 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 664 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 665 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" 666 "b304"+ // start group field 70 level 1 667 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 668 "b404"+ // end group field 70 level 1 669 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" 670 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 671 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 672 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" 673 "90193f"+ // field 402, encoding 0, value 63 674 "98197f") // field 403, encoding 0, value 127 675 676 } 677 678 // All required fields set, defaults provided, all non-defaulted optional fields have values. 679 func TestEncodeDecode4(t *testing.T) { 680 pb := initGoTest(true) 681 pb.Table = String("hello") 682 pb.Param = Int32(7) 683 pb.OptionalField = initGoTestField() 684 pb.F_BoolOptional = Bool(true) 685 pb.F_Int32Optional = Int32(32) 686 pb.F_Int64Optional = Int64(64) 687 pb.F_Fixed32Optional = Uint32(3232) 688 pb.F_Fixed64Optional = Uint64(6464) 689 pb.F_Uint32Optional = Uint32(323232) 690 pb.F_Uint64Optional = Uint64(646464) 691 pb.F_FloatOptional = Float32(32.) 692 pb.F_DoubleOptional = Float64(64.) 693 pb.F_StringOptional = String("hello") 694 pb.F_BytesOptional = []byte("Bignose") 695 pb.F_Sint32Optional = Int32(-32) 696 pb.F_Sint64Optional = Int64(-64) 697 pb.Optionalgroup = initGoTest_OptionalGroup() 698 699 overify(t, pb, 700 "0807"+ // field 1, encoding 0, value 7 701 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" 702 "1807"+ // field 3, encoding 0, value 7 703 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) 704 "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) 705 "5001"+ // field 10, encoding 0, value 1 706 "5803"+ // field 11, encoding 0, value 3 707 "6006"+ // field 12, encoding 0, value 6 708 "6d20000000"+ // field 13, encoding 5, value 32 709 "714000000000000000"+ // field 14, encoding 1, value 64 710 "78a019"+ // field 15, encoding 0, value 3232 711 "8001c032"+ // field 16, encoding 0, value 6464 712 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 713 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 714 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" 715 "f00101"+ // field 30, encoding 0, value 1 716 "f80120"+ // field 31, encoding 0, value 32 717 "800240"+ // field 32, encoding 0, value 64 718 "8d02a00c0000"+ // field 33, encoding 5, value 3232 719 "91024019000000000000"+ // field 34, encoding 1, value 6464 720 "9802a0dd13"+ // field 35, encoding 0, value 323232 721 "a002c0ba27"+ // field 36, encoding 0, value 646464 722 "ad0200000042"+ // field 37, encoding 5, value 32.0 723 "b1020000000000005040"+ // field 38, encoding 1, value 64.0 724 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" 725 "c00201"+ // field 40, encoding 0, value 1 726 "c80220"+ // field 41, encoding 0, value 32 727 "d00240"+ // field 42, encoding 0, value 64 728 "dd0240010000"+ // field 43, encoding 5, value 320 729 "e1028002000000000000"+ // field 44, encoding 1, value 640 730 "e8028019"+ // field 45, encoding 0, value 3200 731 "f0028032"+ // field 46, encoding 0, value 6400 732 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 733 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 734 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" 735 "b304"+ // start group field 70 level 1 736 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 737 "b404"+ // end group field 70 level 1 738 "d305"+ // start group field 90 level 1 739 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" 740 "d405"+ // end group field 90 level 1 741 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" 742 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 743 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 744 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" 745 "f0123f"+ // field 302, encoding 0, value 63 746 "f8127f"+ // field 303, encoding 0, value 127 747 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" 748 "90193f"+ // field 402, encoding 0, value 63 749 "98197f") // field 403, encoding 0, value 127 750 751 } 752 753 // All required fields set, defaults provided, all repeated fields given two values. 754 func TestEncodeDecode5(t *testing.T) { 755 pb := initGoTest(true) 756 pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} 757 pb.F_BoolRepeated = []bool{false, true} 758 pb.F_Int32Repeated = []int32{32, 33} 759 pb.F_Int64Repeated = []int64{64, 65} 760 pb.F_Fixed32Repeated = []uint32{3232, 3333} 761 pb.F_Fixed64Repeated = []uint64{6464, 6565} 762 pb.F_Uint32Repeated = []uint32{323232, 333333} 763 pb.F_Uint64Repeated = []uint64{646464, 656565} 764 pb.F_FloatRepeated = []float32{32., 33.} 765 pb.F_DoubleRepeated = []float64{64., 65.} 766 pb.F_StringRepeated = []string{"hello", "sailor"} 767 pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} 768 pb.F_Sint32Repeated = []int32{32, -32} 769 pb.F_Sint64Repeated = []int64{64, -64} 770 pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} 771 772 overify(t, pb, 773 "0807"+ // field 1, encoding 0, value 7 774 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) 775 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) 776 "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) 777 "5001"+ // field 10, encoding 0, value 1 778 "5803"+ // field 11, encoding 0, value 3 779 "6006"+ // field 12, encoding 0, value 6 780 "6d20000000"+ // field 13, encoding 5, value 32 781 "714000000000000000"+ // field 14, encoding 1, value 64 782 "78a019"+ // field 15, encoding 0, value 3232 783 "8001c032"+ // field 16, encoding 0, value 6464 784 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 785 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 786 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" 787 "a00100"+ // field 20, encoding 0, value 0 788 "a00101"+ // field 20, encoding 0, value 1 789 "a80120"+ // field 21, encoding 0, value 32 790 "a80121"+ // field 21, encoding 0, value 33 791 "b00140"+ // field 22, encoding 0, value 64 792 "b00141"+ // field 22, encoding 0, value 65 793 "bd01a00c0000"+ // field 23, encoding 5, value 3232 794 "bd01050d0000"+ // field 23, encoding 5, value 3333 795 "c1014019000000000000"+ // field 24, encoding 1, value 6464 796 "c101a519000000000000"+ // field 24, encoding 1, value 6565 797 "c801a0dd13"+ // field 25, encoding 0, value 323232 798 "c80195ac14"+ // field 25, encoding 0, value 333333 799 "d001c0ba27"+ // field 26, encoding 0, value 646464 800 "d001b58928"+ // field 26, encoding 0, value 656565 801 "dd0100000042"+ // field 27, encoding 5, value 32.0 802 "dd0100000442"+ // field 27, encoding 5, value 33.0 803 "e1010000000000005040"+ // field 28, encoding 1, value 64.0 804 "e1010000000000405040"+ // field 28, encoding 1, value 65.0 805 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" 806 "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" 807 "c00201"+ // field 40, encoding 0, value 1 808 "c80220"+ // field 41, encoding 0, value 32 809 "d00240"+ // field 42, encoding 0, value 64 810 "dd0240010000"+ // field 43, encoding 5, value 320 811 "e1028002000000000000"+ // field 44, encoding 1, value 640 812 "e8028019"+ // field 45, encoding 0, value 3200 813 "f0028032"+ // field 46, encoding 0, value 6400 814 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 815 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 816 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" 817 "b304"+ // start group field 70 level 1 818 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 819 "b404"+ // end group field 70 level 1 820 "8305"+ // start group field 80 level 1 821 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" 822 "8405"+ // end group field 80 level 1 823 "8305"+ // start group field 80 level 1 824 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" 825 "8405"+ // end group field 80 level 1 826 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" 827 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 828 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 829 "ca0c03"+"626967"+ // field 201, encoding 2, string "big" 830 "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" 831 "d00c40"+ // field 202, encoding 0, value 32 832 "d00c3f"+ // field 202, encoding 0, value -32 833 "d80c8001"+ // field 203, encoding 0, value 64 834 "d80c7f"+ // field 203, encoding 0, value -64 835 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" 836 "90193f"+ // field 402, encoding 0, value 63 837 "98197f") // field 403, encoding 0, value 127 838 839 } 840 841 // All required fields set, all packed repeated fields given two values. 842 func TestEncodeDecode6(t *testing.T) { 843 pb := initGoTest(false) 844 pb.F_BoolRepeatedPacked = []bool{false, true} 845 pb.F_Int32RepeatedPacked = []int32{32, 33} 846 pb.F_Int64RepeatedPacked = []int64{64, 65} 847 pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} 848 pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} 849 pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} 850 pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} 851 pb.F_FloatRepeatedPacked = []float32{32., 33.} 852 pb.F_DoubleRepeatedPacked = []float64{64., 65.} 853 pb.F_Sint32RepeatedPacked = []int32{32, -32} 854 pb.F_Sint64RepeatedPacked = []int64{64, -64} 855 856 overify(t, pb, 857 "0807"+ // field 1, encoding 0, value 7 858 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) 859 "5001"+ // field 10, encoding 0, value 1 860 "5803"+ // field 11, encoding 0, value 3 861 "6006"+ // field 12, encoding 0, value 6 862 "6d20000000"+ // field 13, encoding 5, value 32 863 "714000000000000000"+ // field 14, encoding 1, value 64 864 "78a019"+ // field 15, encoding 0, value 3232 865 "8001c032"+ // field 16, encoding 0, value 6464 866 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 867 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 868 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" 869 "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 870 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 871 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 872 "aa0308"+ // field 53, encoding 2, 8 bytes 873 "a00c0000050d0000"+ // value 3232, value 3333 874 "b20310"+ // field 54, encoding 2, 16 bytes 875 "4019000000000000a519000000000000"+ // value 6464, value 6565 876 "ba0306"+ // field 55, encoding 2, 6 bytes 877 "a0dd1395ac14"+ // value 323232, value 333333 878 "c20306"+ // field 56, encoding 2, 6 bytes 879 "c0ba27b58928"+ // value 646464, value 656565 880 "ca0308"+ // field 57, encoding 2, 8 bytes 881 "0000004200000442"+ // value 32.0, value 33.0 882 "d20310"+ // field 58, encoding 2, 16 bytes 883 "00000000000050400000000000405040"+ // value 64.0, value 65.0 884 "b304"+ // start group field 70 level 1 885 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" 886 "b404"+ // end group field 70 level 1 887 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" 888 "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 889 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 890 "b21f02"+ // field 502, encoding 2, 2 bytes 891 "403f"+ // value 32, value -32 892 "ba1f03"+ // field 503, encoding 2, 3 bytes 893 "80017f") // value 64, value -64 894 } 895 896 // Test that we can encode empty bytes fields. 897 func TestEncodeDecodeBytes1(t *testing.T) { 898 pb := initGoTest(false) 899 900 // Create our bytes 901 pb.F_BytesRequired = []byte{} 902 pb.F_BytesRepeated = [][]byte{{}} 903 pb.F_BytesOptional = []byte{} 904 905 d, err := Marshal(pb) 906 if err != nil { 907 t.Error(err) 908 } 909 910 pbd := new(GoTest) 911 if err := Unmarshal(d, pbd); err != nil { 912 t.Error(err) 913 } 914 915 if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { 916 t.Error("required empty bytes field is incorrect") 917 } 918 if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { 919 t.Error("repeated empty bytes field is incorrect") 920 } 921 if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { 922 t.Error("optional empty bytes field is incorrect") 923 } 924 } 925 926 // Test that we encode nil-valued fields of a repeated bytes field correctly. 927 // Since entries in a repeated field cannot be nil, nil must mean empty value. 928 func TestEncodeDecodeBytes2(t *testing.T) { 929 pb := initGoTest(false) 930 931 // Create our bytes 932 pb.F_BytesRepeated = [][]byte{nil} 933 934 d, err := Marshal(pb) 935 if err != nil { 936 t.Error(err) 937 } 938 939 pbd := new(GoTest) 940 if err := Unmarshal(d, pbd); err != nil { 941 t.Error(err) 942 } 943 944 if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { 945 t.Error("Unexpected value for repeated bytes field") 946 } 947 } 948 949 // All required fields set, defaults provided, all repeated fields given two values. 950 func TestSkippingUnrecognizedFields(t *testing.T) { 951 o := old() 952 pb := initGoTestField() 953 954 // Marshal it normally. 955 o.Marshal(pb) 956 957 // Now new a GoSkipTest record. 958 skip := &GoSkipTest{ 959 SkipInt32: Int32(32), 960 SkipFixed32: Uint32(3232), 961 SkipFixed64: Uint64(6464), 962 SkipString: String("skipper"), 963 Skipgroup: &GoSkipTest_SkipGroup{ 964 GroupInt32: Int32(75), 965 GroupString: String("wxyz"), 966 }, 967 } 968 969 // Marshal it into same buffer. 970 o.Marshal(skip) 971 972 pbd := new(GoTestField) 973 o.Unmarshal(pbd) 974 975 // The __unrecognized field should be a marshaling of GoSkipTest 976 skipd := new(GoSkipTest) 977 978 o.SetBuf(pbd.XXX_unrecognized) 979 o.Unmarshal(skipd) 980 981 if *skipd.SkipInt32 != *skip.SkipInt32 { 982 t.Error("skip int32", skipd.SkipInt32) 983 } 984 if *skipd.SkipFixed32 != *skip.SkipFixed32 { 985 t.Error("skip fixed32", skipd.SkipFixed32) 986 } 987 if *skipd.SkipFixed64 != *skip.SkipFixed64 { 988 t.Error("skip fixed64", skipd.SkipFixed64) 989 } 990 if *skipd.SkipString != *skip.SkipString { 991 t.Error("skip string", *skipd.SkipString) 992 } 993 if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { 994 t.Error("skip group int32", skipd.Skipgroup.GroupInt32) 995 } 996 if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { 997 t.Error("skip group string", *skipd.Skipgroup.GroupString) 998 } 999 } 1000 1001 // Check that unrecognized fields of a submessage are preserved. 1002 func TestSubmessageUnrecognizedFields(t *testing.T) { 1003 nm := &NewMessage{ 1004 Nested: &NewMessage_Nested{ 1005 Name: String("Nigel"), 1006 FoodGroup: String("carbs"), 1007 }, 1008 } 1009 b, err := Marshal(nm) 1010 if err != nil { 1011 t.Fatalf("Marshal of NewMessage: %v", err) 1012 } 1013 1014 // Unmarshal into an OldMessage. 1015 om := new(OldMessage) 1016 if err := Unmarshal(b, om); err != nil { 1017 t.Fatalf("Unmarshal to OldMessage: %v", err) 1018 } 1019 exp := &OldMessage{ 1020 Nested: &OldMessage_Nested{ 1021 Name: String("Nigel"), 1022 // normal protocol buffer users should not do this 1023 XXX_unrecognized: []byte("\x12\x05carbs"), 1024 }, 1025 } 1026 if !Equal(om, exp) { 1027 t.Errorf("om = %v, want %v", om, exp) 1028 } 1029 1030 // Clone the OldMessage. 1031 om = Clone(om).(*OldMessage) 1032 if !Equal(om, exp) { 1033 t.Errorf("Clone(om) = %v, want %v", om, exp) 1034 } 1035 1036 // Marshal the OldMessage, then unmarshal it into an empty NewMessage. 1037 if b, err = Marshal(om); err != nil { 1038 t.Fatalf("Marshal of OldMessage: %v", err) 1039 } 1040 t.Logf("Marshal(%v) -> %q", om, b) 1041 nm2 := new(NewMessage) 1042 if err := Unmarshal(b, nm2); err != nil { 1043 t.Fatalf("Unmarshal to NewMessage: %v", err) 1044 } 1045 if !Equal(nm, nm2) { 1046 t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) 1047 } 1048 } 1049 1050 // Check that we can grow an array (repeated field) to have many elements. 1051 // This test doesn't depend only on our encoding; for variety, it makes sure 1052 // we create, encode, and decode the correct contents explicitly. It's therefore 1053 // a bit messier. 1054 // This test also uses (and hence tests) the Marshal/Unmarshal functions 1055 // instead of the methods. 1056 func TestBigRepeated(t *testing.T) { 1057 pb := initGoTest(true) 1058 1059 // Create the arrays 1060 const N = 50 // Internally the library starts much smaller. 1061 pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) 1062 pb.F_Sint64Repeated = make([]int64, N) 1063 pb.F_Sint32Repeated = make([]int32, N) 1064 pb.F_BytesRepeated = make([][]byte, N) 1065 pb.F_StringRepeated = make([]string, N) 1066 pb.F_DoubleRepeated = make([]float64, N) 1067 pb.F_FloatRepeated = make([]float32, N) 1068 pb.F_Uint64Repeated = make([]uint64, N) 1069 pb.F_Uint32Repeated = make([]uint32, N) 1070 pb.F_Fixed64Repeated = make([]uint64, N) 1071 pb.F_Fixed32Repeated = make([]uint32, N) 1072 pb.F_Int64Repeated = make([]int64, N) 1073 pb.F_Int32Repeated = make([]int32, N) 1074 pb.F_BoolRepeated = make([]bool, N) 1075 pb.RepeatedField = make([]*GoTestField, N) 1076 1077 // Fill in the arrays with checkable values. 1078 igtf := initGoTestField() 1079 igtrg := initGoTest_RepeatedGroup() 1080 for i := 0; i < N; i++ { 1081 pb.Repeatedgroup[i] = igtrg 1082 pb.F_Sint64Repeated[i] = int64(i) 1083 pb.F_Sint32Repeated[i] = int32(i) 1084 s := fmt.Sprint(i) 1085 pb.F_BytesRepeated[i] = []byte(s) 1086 pb.F_StringRepeated[i] = s 1087 pb.F_DoubleRepeated[i] = float64(i) 1088 pb.F_FloatRepeated[i] = float32(i) 1089 pb.F_Uint64Repeated[i] = uint64(i) 1090 pb.F_Uint32Repeated[i] = uint32(i) 1091 pb.F_Fixed64Repeated[i] = uint64(i) 1092 pb.F_Fixed32Repeated[i] = uint32(i) 1093 pb.F_Int64Repeated[i] = int64(i) 1094 pb.F_Int32Repeated[i] = int32(i) 1095 pb.F_BoolRepeated[i] = i%2 == 0 1096 pb.RepeatedField[i] = igtf 1097 } 1098 1099 // Marshal. 1100 buf, _ := Marshal(pb) 1101 1102 // Now test Unmarshal by recreating the original buffer. 1103 pbd := new(GoTest) 1104 Unmarshal(buf, pbd) 1105 1106 // Check the checkable values 1107 for i := uint64(0); i < N; i++ { 1108 if pbd.Repeatedgroup[i] == nil { // TODO: more checking? 1109 t.Error("pbd.Repeatedgroup bad") 1110 } 1111 var x uint64 1112 x = uint64(pbd.F_Sint64Repeated[i]) 1113 if x != i { 1114 t.Error("pbd.F_Sint64Repeated bad", x, i) 1115 } 1116 x = uint64(pbd.F_Sint32Repeated[i]) 1117 if x != i { 1118 t.Error("pbd.F_Sint32Repeated bad", x, i) 1119 } 1120 s := fmt.Sprint(i) 1121 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) 1122 if pbd.F_StringRepeated[i] != s { 1123 t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) 1124 } 1125 x = uint64(pbd.F_DoubleRepeated[i]) 1126 if x != i { 1127 t.Error("pbd.F_DoubleRepeated bad", x, i) 1128 } 1129 x = uint64(pbd.F_FloatRepeated[i]) 1130 if x != i { 1131 t.Error("pbd.F_FloatRepeated bad", x, i) 1132 } 1133 x = pbd.F_Uint64Repeated[i] 1134 if x != i { 1135 t.Error("pbd.F_Uint64Repeated bad", x, i) 1136 } 1137 x = uint64(pbd.F_Uint32Repeated[i]) 1138 if x != i { 1139 t.Error("pbd.F_Uint32Repeated bad", x, i) 1140 } 1141 x = pbd.F_Fixed64Repeated[i] 1142 if x != i { 1143 t.Error("pbd.F_Fixed64Repeated bad", x, i) 1144 } 1145 x = uint64(pbd.F_Fixed32Repeated[i]) 1146 if x != i { 1147 t.Error("pbd.F_Fixed32Repeated bad", x, i) 1148 } 1149 x = uint64(pbd.F_Int64Repeated[i]) 1150 if x != i { 1151 t.Error("pbd.F_Int64Repeated bad", x, i) 1152 } 1153 x = uint64(pbd.F_Int32Repeated[i]) 1154 if x != i { 1155 t.Error("pbd.F_Int32Repeated bad", x, i) 1156 } 1157 if pbd.F_BoolRepeated[i] != (i%2 == 0) { 1158 t.Error("pbd.F_BoolRepeated bad", x, i) 1159 } 1160 if pbd.RepeatedField[i] == nil { // TODO: more checking? 1161 t.Error("pbd.RepeatedField bad") 1162 } 1163 } 1164 } 1165 1166 // Verify we give a useful message when decoding to the wrong structure type. 1167 func TestTypeMismatch(t *testing.T) { 1168 pb1 := initGoTest(true) 1169 1170 // Marshal 1171 o := old() 1172 o.Marshal(pb1) 1173 1174 // Now Unmarshal it to the wrong type. 1175 pb2 := initGoTestField() 1176 err := o.Unmarshal(pb2) 1177 if err == nil { 1178 t.Error("expected error, got no error") 1179 } else if !strings.Contains(err.Error(), "bad wiretype") { 1180 t.Error("expected bad wiretype error, got", err) 1181 } 1182 } 1183 1184 func encodeDecode(t *testing.T, in, out Message, msg string) { 1185 buf, err := Marshal(in) 1186 if err != nil { 1187 t.Fatalf("failed marshaling %v: %v", msg, err) 1188 } 1189 if err := Unmarshal(buf, out); err != nil { 1190 t.Fatalf("failed unmarshaling %v: %v", msg, err) 1191 } 1192 } 1193 1194 func TestPackedNonPackedDecoderSwitching(t *testing.T) { 1195 np, p := new(NonPackedTest), new(PackedTest) 1196 1197 // non-packed -> packed 1198 np.A = []int32{0, 1, 1, 2, 3, 5} 1199 encodeDecode(t, np, p, "non-packed -> packed") 1200 if !reflect.DeepEqual(np.A, p.B) { 1201 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) 1202 } 1203 1204 // packed -> non-packed 1205 np.Reset() 1206 p.B = []int32{3, 1, 4, 1, 5, 9} 1207 encodeDecode(t, p, np, "packed -> non-packed") 1208 if !reflect.DeepEqual(p.B, np.A) { 1209 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) 1210 } 1211 } 1212 1213 func TestProto1RepeatedGroup(t *testing.T) { 1214 pb := &MessageList{ 1215 Message: []*MessageList_Message{ 1216 { 1217 Name: String("blah"), 1218 Count: Int32(7), 1219 }, 1220 // NOTE: pb.Message[1] is a nil 1221 nil, 1222 }, 1223 } 1224 1225 o := old() 1226 if err := o.Marshal(pb); err != ErrRepeatedHasNil { 1227 t.Fatalf("unexpected or no error when marshaling: %v", err) 1228 } 1229 } 1230 1231 // Test that enums work. Checks for a bug introduced by making enums 1232 // named types instead of int32: newInt32FromUint64 would crash with 1233 // a type mismatch in reflect.PointTo. 1234 func TestEnum(t *testing.T) { 1235 pb := new(GoEnum) 1236 pb.Foo = FOO_FOO1.Enum() 1237 o := old() 1238 if err := o.Marshal(pb); err != nil { 1239 t.Fatal("error encoding enum:", err) 1240 } 1241 pb1 := new(GoEnum) 1242 if err := o.Unmarshal(pb1); err != nil { 1243 t.Fatal("error decoding enum:", err) 1244 } 1245 if *pb1.Foo != FOO_FOO1 { 1246 t.Error("expected 7 but got ", *pb1.Foo) 1247 } 1248 } 1249 1250 // Enum types have String methods. Check that enum fields can be printed. 1251 // We don't care what the value actually is, just as long as it doesn't crash. 1252 func TestPrintingNilEnumFields(t *testing.T) { 1253 pb := new(GoEnum) 1254 fmt.Sprintf("%+v", pb) 1255 } 1256 1257 // Verify that absent required fields cause Marshal/Unmarshal to return errors. 1258 func TestRequiredFieldEnforcement(t *testing.T) { 1259 pb := new(GoTestField) 1260 _, err := Marshal(pb) 1261 if err == nil { 1262 t.Error("marshal: expected error, got nil") 1263 } else if strings.Index(err.Error(), "Label") < 0 { 1264 t.Errorf("marshal: bad error type: %v", err) 1265 } 1266 1267 // A slightly sneaky, yet valid, proto. It encodes the same required field twice, 1268 // so simply counting the required fields is insufficient. 1269 // field 1, encoding 2, value "hi" 1270 buf := []byte("\x0A\x02hi\x0A\x02hi") 1271 err = Unmarshal(buf, pb) 1272 if err == nil { 1273 t.Error("unmarshal: expected error, got nil") 1274 } else if strings.Index(err.Error(), "{Unknown}") < 0 { 1275 t.Errorf("unmarshal: bad error type: %v", err) 1276 } 1277 } 1278 1279 func TestTypedNilMarshal(t *testing.T) { 1280 // A typed nil should return ErrNil and not crash. 1281 _, err := Marshal((*GoEnum)(nil)) 1282 if err != ErrNil { 1283 t.Errorf("Marshal: got err %v, want ErrNil", err) 1284 } 1285 } 1286 1287 // A type that implements the Marshaler interface, but is not nillable. 1288 type nonNillableInt uint64 1289 1290 func (nni nonNillableInt) Marshal() ([]byte, error) { 1291 return EncodeVarint(uint64(nni)), nil 1292 } 1293 1294 type NNIMessage struct { 1295 nni nonNillableInt 1296 } 1297 1298 func (*NNIMessage) Reset() {} 1299 func (*NNIMessage) String() string { return "" } 1300 func (*NNIMessage) ProtoMessage() {} 1301 1302 // A type that implements the Marshaler interface and is nillable. 1303 type nillableMessage struct { 1304 x uint64 1305 } 1306 1307 func (nm *nillableMessage) Marshal() ([]byte, error) { 1308 return EncodeVarint(nm.x), nil 1309 } 1310 1311 type NMMessage struct { 1312 nm *nillableMessage 1313 } 1314 1315 func (*NMMessage) Reset() {} 1316 func (*NMMessage) String() string { return "" } 1317 func (*NMMessage) ProtoMessage() {} 1318 1319 // Verify a type that uses the Marshaler interface, but has a nil pointer. 1320 func TestNilMarshaler(t *testing.T) { 1321 // Try a struct with a Marshaler field that is nil. 1322 // It should be directly marshable. 1323 nmm := new(NMMessage) 1324 if _, err := Marshal(nmm); err != nil { 1325 t.Error("unexpected error marshaling nmm: ", err) 1326 } 1327 1328 // Try a struct with a Marshaler field that is not nillable. 1329 nnim := new(NNIMessage) 1330 nnim.nni = 7 1331 var _ Marshaler = nnim.nni // verify it is truly a Marshaler 1332 if _, err := Marshal(nnim); err != nil { 1333 t.Error("unexpected error marshaling nnim: ", err) 1334 } 1335 } 1336 1337 func TestAllSetDefaults(t *testing.T) { 1338 // Exercise SetDefaults with all scalar field types. 1339 m := &Defaults{ 1340 // NaN != NaN, so override that here. 1341 F_Nan: Float32(1.7), 1342 } 1343 expected := &Defaults{ 1344 F_Bool: Bool(true), 1345 F_Int32: Int32(32), 1346 F_Int64: Int64(64), 1347 F_Fixed32: Uint32(320), 1348 F_Fixed64: Uint64(640), 1349 F_Uint32: Uint32(3200), 1350 F_Uint64: Uint64(6400), 1351 F_Float: Float32(314159), 1352 F_Double: Float64(271828), 1353 F_String: String(`hello, "world!"` + "\n"), 1354 F_Bytes: []byte("Bignose"), 1355 F_Sint32: Int32(-32), 1356 F_Sint64: Int64(-64), 1357 F_Enum: Defaults_GREEN.Enum(), 1358 F_Pinf: Float32(float32(math.Inf(1))), 1359 F_Ninf: Float32(float32(math.Inf(-1))), 1360 F_Nan: Float32(1.7), 1361 } 1362 SetDefaults(m) 1363 if !Equal(m, expected) { 1364 t.Errorf(" got %v\nwant %v", m, expected) 1365 } 1366 } 1367 1368 func TestSetDefaultsWithSetField(t *testing.T) { 1369 // Check that a set value is not overridden. 1370 m := &Defaults{ 1371 F_Int32: Int32(12), 1372 } 1373 SetDefaults(m) 1374 if v := m.GetF_Int32(); v != 12 { 1375 t.Errorf("m.FInt32 = %v, want 12", v) 1376 } 1377 } 1378 1379 func TestSetDefaultsWithSubMessage(t *testing.T) { 1380 m := &OtherMessage{ 1381 Key: Int64(123), 1382 Inner: &InnerMessage{ 1383 Host: String("gopher"), 1384 }, 1385 } 1386 expected := &OtherMessage{ 1387 Key: Int64(123), 1388 Inner: &InnerMessage{ 1389 Host: String("gopher"), 1390 Port: Int32(4000), 1391 }, 1392 } 1393 SetDefaults(m) 1394 if !Equal(m, expected) { 1395 t.Errorf("\n got %v\nwant %v", m, expected) 1396 } 1397 } 1398 1399 func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { 1400 m := &MyMessage{ 1401 RepInner: []*InnerMessage{{}}, 1402 } 1403 expected := &MyMessage{ 1404 RepInner: []*InnerMessage{{ 1405 Port: Int32(4000), 1406 }}, 1407 } 1408 SetDefaults(m) 1409 if !Equal(m, expected) { 1410 t.Errorf("\n got %v\nwant %v", m, expected) 1411 } 1412 } 1413 1414 func TestMaximumTagNumber(t *testing.T) { 1415 m := &MaxTag{ 1416 LastField: String("natural goat essence"), 1417 } 1418 buf, err := Marshal(m) 1419 if err != nil { 1420 t.Fatalf("proto.Marshal failed: %v", err) 1421 } 1422 m2 := new(MaxTag) 1423 if err := Unmarshal(buf, m2); err != nil { 1424 t.Fatalf("proto.Unmarshal failed: %v", err) 1425 } 1426 if got, want := m2.GetLastField(), *m.LastField; got != want { 1427 t.Errorf("got %q, want %q", got, want) 1428 } 1429 } 1430 1431 func TestJSON(t *testing.T) { 1432 m := &MyMessage{ 1433 Count: Int32(4), 1434 Pet: []string{"bunny", "kitty"}, 1435 Inner: &InnerMessage{ 1436 Host: String("cauchy"), 1437 }, 1438 Bikeshed: MyMessage_GREEN.Enum(), 1439 } 1440 const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` 1441 1442 b, err := json.Marshal(m) 1443 if err != nil { 1444 t.Fatalf("json.Marshal failed: %v", err) 1445 } 1446 s := string(b) 1447 if s != expected { 1448 t.Errorf("got %s\nwant %s", s, expected) 1449 } 1450 1451 received := new(MyMessage) 1452 if err := json.Unmarshal(b, received); err != nil { 1453 t.Fatalf("json.Unmarshal failed: %v", err) 1454 } 1455 if !Equal(received, m) { 1456 t.Fatalf("got %s, want %s", received, m) 1457 } 1458 1459 // Test unmarshalling of JSON with symbolic enum name. 1460 const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` 1461 received.Reset() 1462 if err := json.Unmarshal([]byte(old), received); err != nil { 1463 t.Fatalf("json.Unmarshal failed: %v", err) 1464 } 1465 if !Equal(received, m) { 1466 t.Fatalf("got %s, want %s", received, m) 1467 } 1468 } 1469 1470 func TestBadWireType(t *testing.T) { 1471 b := []byte{7<<3 | 6} // field 7, wire type 6 1472 pb := new(OtherMessage) 1473 if err := Unmarshal(b, pb); err == nil { 1474 t.Errorf("Unmarshal did not fail") 1475 } else if !strings.Contains(err.Error(), "unknown wire type") { 1476 t.Errorf("wrong error: %v", err) 1477 } 1478 } 1479 1480 func TestBytesWithInvalidLength(t *testing.T) { 1481 // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. 1482 b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} 1483 Unmarshal(b, new(MyMessage)) 1484 } 1485 1486 func TestLengthOverflow(t *testing.T) { 1487 // Overflowing a length should not panic. 1488 b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} 1489 Unmarshal(b, new(MyMessage)) 1490 } 1491 1492 func TestVarintOverflow(t *testing.T) { 1493 // Overflowing a 64-bit length should not be allowed. 1494 b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} 1495 if err := Unmarshal(b, new(MyMessage)); err == nil { 1496 t.Fatalf("Overflowed uint64 length without error") 1497 } 1498 } 1499 1500 func TestUnmarshalFuzz(t *testing.T) { 1501 const N = 1000 1502 seed := time.Now().UnixNano() 1503 t.Logf("RNG seed is %d", seed) 1504 rng := rand.New(rand.NewSource(seed)) 1505 buf := make([]byte, 20) 1506 for i := 0; i < N; i++ { 1507 for j := range buf { 1508 buf[j] = byte(rng.Intn(256)) 1509 } 1510 fuzzUnmarshal(t, buf) 1511 } 1512 } 1513 1514 func TestMergeMessages(t *testing.T) { 1515 pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} 1516 data, err := Marshal(pb) 1517 if err != nil { 1518 t.Fatalf("Marshal: %v", err) 1519 } 1520 1521 pb1 := new(MessageList) 1522 if err := Unmarshal(data, pb1); err != nil { 1523 t.Fatalf("first Unmarshal: %v", err) 1524 } 1525 if err := Unmarshal(data, pb1); err != nil { 1526 t.Fatalf("second Unmarshal: %v", err) 1527 } 1528 if len(pb1.Message) != 1 { 1529 t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) 1530 } 1531 1532 pb2 := new(MessageList) 1533 if err := UnmarshalMerge(data, pb2); err != nil { 1534 t.Fatalf("first UnmarshalMerge: %v", err) 1535 } 1536 if err := UnmarshalMerge(data, pb2); err != nil { 1537 t.Fatalf("second UnmarshalMerge: %v", err) 1538 } 1539 if len(pb2.Message) != 2 { 1540 t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) 1541 } 1542 } 1543 1544 func TestExtensionMarshalOrder(t *testing.T) { 1545 m := &MyMessage{Count: Int(123)} 1546 if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { 1547 t.Fatalf("SetExtension: %v", err) 1548 } 1549 if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { 1550 t.Fatalf("SetExtension: %v", err) 1551 } 1552 if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { 1553 t.Fatalf("SetExtension: %v", err) 1554 } 1555 1556 // Serialize m several times, and check we get the same bytes each time. 1557 var orig []byte 1558 for i := 0; i < 100; i++ { 1559 b, err := Marshal(m) 1560 if err != nil { 1561 t.Fatalf("Marshal: %v", err) 1562 } 1563 if i == 0 { 1564 orig = b 1565 continue 1566 } 1567 if !bytes.Equal(b, orig) { 1568 t.Errorf("Bytes differ on attempt #%d", i) 1569 } 1570 } 1571 } 1572 1573 // Many extensions, because small maps might not iterate differently on each iteration. 1574 var exts = []*ExtensionDesc{ 1575 E_X201, 1576 E_X202, 1577 E_X203, 1578 E_X204, 1579 E_X205, 1580 E_X206, 1581 E_X207, 1582 E_X208, 1583 E_X209, 1584 E_X210, 1585 E_X211, 1586 E_X212, 1587 E_X213, 1588 E_X214, 1589 E_X215, 1590 E_X216, 1591 E_X217, 1592 E_X218, 1593 E_X219, 1594 E_X220, 1595 E_X221, 1596 E_X222, 1597 E_X223, 1598 E_X224, 1599 E_X225, 1600 E_X226, 1601 E_X227, 1602 E_X228, 1603 E_X229, 1604 E_X230, 1605 E_X231, 1606 E_X232, 1607 E_X233, 1608 E_X234, 1609 E_X235, 1610 E_X236, 1611 E_X237, 1612 E_X238, 1613 E_X239, 1614 E_X240, 1615 E_X241, 1616 E_X242, 1617 E_X243, 1618 E_X244, 1619 E_X245, 1620 E_X246, 1621 E_X247, 1622 E_X248, 1623 E_X249, 1624 E_X250, 1625 } 1626 1627 func TestMessageSetMarshalOrder(t *testing.T) { 1628 m := &MyMessageSet{} 1629 for _, x := range exts { 1630 if err := SetExtension(m, x, &Empty{}); err != nil { 1631 t.Fatalf("SetExtension: %v", err) 1632 } 1633 } 1634 1635 buf, err := Marshal(m) 1636 if err != nil { 1637 t.Fatalf("Marshal: %v", err) 1638 } 1639 1640 // Serialize m several times, and check we get the same bytes each time. 1641 for i := 0; i < 10; i++ { 1642 b1, err := Marshal(m) 1643 if err != nil { 1644 t.Fatalf("Marshal: %v", err) 1645 } 1646 if !bytes.Equal(b1, buf) { 1647 t.Errorf("Bytes differ on re-Marshal #%d", i) 1648 } 1649 1650 m2 := &MyMessageSet{} 1651 if err := Unmarshal(buf, m2); err != nil { 1652 t.Errorf("Unmarshal: %v", err) 1653 } 1654 b2, err := Marshal(m2) 1655 if err != nil { 1656 t.Errorf("re-Marshal: %v", err) 1657 } 1658 if !bytes.Equal(b2, buf) { 1659 t.Errorf("Bytes differ on round-trip #%d", i) 1660 } 1661 } 1662 } 1663 1664 func TestUnmarshalMergesMessages(t *testing.T) { 1665 // If a nested message occurs twice in the input, 1666 // the fields should be merged when decoding. 1667 a := &OtherMessage{ 1668 Key: Int64(123), 1669 Inner: &InnerMessage{ 1670 Host: String("polhode"), 1671 Port: Int32(1234), 1672 }, 1673 } 1674 aData, err := Marshal(a) 1675 if err != nil { 1676 t.Fatalf("Marshal(a): %v", err) 1677 } 1678 b := &OtherMessage{ 1679 Weight: Float32(1.2), 1680 Inner: &InnerMessage{ 1681 Host: String("herpolhode"), 1682 Connected: Bool(true), 1683 }, 1684 } 1685 bData, err := Marshal(b) 1686 if err != nil { 1687 t.Fatalf("Marshal(b): %v", err) 1688 } 1689 want := &OtherMessage{ 1690 Key: Int64(123), 1691 Weight: Float32(1.2), 1692 Inner: &InnerMessage{ 1693 Host: String("herpolhode"), 1694 Port: Int32(1234), 1695 Connected: Bool(true), 1696 }, 1697 } 1698 got := new(OtherMessage) 1699 if err := Unmarshal(append(aData, bData...), got); err != nil { 1700 t.Fatalf("Unmarshal: %v", err) 1701 } 1702 if !Equal(got, want) { 1703 t.Errorf("\n got %v\nwant %v", got, want) 1704 } 1705 } 1706 1707 func TestEncodingSizes(t *testing.T) { 1708 tests := []struct { 1709 m Message 1710 n int 1711 }{ 1712 {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, 1713 {&Defaults{F_Int32: Int32(math.MinInt32)}, 6}, 1714 {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, 1715 } 1716 for _, test := range tests { 1717 b, err := Marshal(test.m) 1718 if err != nil { 1719 t.Errorf("Marshal(%v): %v", test.m, err) 1720 continue 1721 } 1722 if len(b) != test.n { 1723 t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) 1724 } 1725 } 1726 } 1727 1728 func TestRequiredNotSetError(t *testing.T) { 1729 pb := initGoTest(false) 1730 pb.RequiredField.Label = nil 1731 pb.F_Int32Required = nil 1732 pb.F_Int64Required = nil 1733 1734 expected := "0807" + // field 1, encoding 0, value 7 1735 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) 1736 "5001" + // field 10, encoding 0, value 1 1737 "6d20000000" + // field 13, encoding 5, value 0x20 1738 "714000000000000000" + // field 14, encoding 1, value 0x40 1739 "78a019" + // field 15, encoding 0, value 0xca0 = 3232 1740 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 1741 "8d0100004a45" + // field 17, encoding 5, value 3232.0 1742 "9101000000000040b940" + // field 18, encoding 1, value 6464.0 1743 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" 1744 "b304" + // field 70, encoding 3, start group 1745 "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" 1746 "b404" + // field 70, encoding 4, end group 1747 "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" 1748 "b0063f" + // field 102, encoding 0, 0x3f zigzag32 1749 "b8067f" // field 103, encoding 0, 0x7f zigzag64 1750 1751 o := old() 1752 bytes, err := Marshal(pb) 1753 if _, ok := err.(*RequiredNotSetError); !ok { 1754 fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) 1755 o.DebugPrint("", bytes) 1756 t.Fatalf("expected = %s", expected) 1757 } 1758 if strings.Index(err.Error(), "RequiredField.Label") < 0 { 1759 t.Errorf("marshal-1 wrong err msg: %v", err) 1760 } 1761 if !equal(bytes, expected, t) { 1762 o.DebugPrint("neq 1", bytes) 1763 t.Fatalf("expected = %s", expected) 1764 } 1765 1766 // Now test Unmarshal by recreating the original buffer. 1767 pbd := new(GoTest) 1768 err = Unmarshal(bytes, pbd) 1769 if _, ok := err.(*RequiredNotSetError); !ok { 1770 t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) 1771 o.DebugPrint("", bytes) 1772 t.Fatalf("string = %s", expected) 1773 } 1774 if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { 1775 t.Errorf("unmarshal wrong err msg: %v", err) 1776 } 1777 bytes, err = Marshal(pbd) 1778 if _, ok := err.(*RequiredNotSetError); !ok { 1779 t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) 1780 o.DebugPrint("", bytes) 1781 t.Fatalf("string = %s", expected) 1782 } 1783 if strings.Index(err.Error(), "RequiredField.Label") < 0 { 1784 t.Errorf("marshal-2 wrong err msg: %v", err) 1785 } 1786 if !equal(bytes, expected, t) { 1787 o.DebugPrint("neq 2", bytes) 1788 t.Fatalf("string = %s", expected) 1789 } 1790 } 1791 1792 func fuzzUnmarshal(t *testing.T, data []byte) { 1793 defer func() { 1794 if e := recover(); e != nil { 1795 t.Errorf("These bytes caused a panic: %+v", data) 1796 t.Logf("Stack:\n%s", debug.Stack()) 1797 t.FailNow() 1798 } 1799 }() 1800 1801 pb := new(MyMessage) 1802 Unmarshal(data, pb) 1803 } 1804 1805 // Benchmarks 1806 1807 func testMsg() *GoTest { 1808 pb := initGoTest(true) 1809 const N = 1000 // Internally the library starts much smaller. 1810 pb.F_Int32Repeated = make([]int32, N) 1811 pb.F_DoubleRepeated = make([]float64, N) 1812 for i := 0; i < N; i++ { 1813 pb.F_Int32Repeated[i] = int32(i) 1814 pb.F_DoubleRepeated[i] = float64(i) 1815 } 1816 return pb 1817 } 1818 1819 func bytesMsg() *GoTest { 1820 pb := initGoTest(true) 1821 buf := make([]byte, 4000) 1822 for i := range buf { 1823 buf[i] = byte(i) 1824 } 1825 pb.F_BytesDefaulted = buf 1826 return pb 1827 } 1828 1829 func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { 1830 d, _ := marshal(pb) 1831 b.SetBytes(int64(len(d))) 1832 b.ResetTimer() 1833 for i := 0; i < b.N; i++ { 1834 marshal(pb) 1835 } 1836 } 1837 1838 func benchmarkBufferMarshal(b *testing.B, pb Message) { 1839 p := NewBuffer(nil) 1840 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { 1841 p.Reset() 1842 err := p.Marshal(pb0) 1843 return p.Bytes(), err 1844 }) 1845 } 1846 1847 func benchmarkSize(b *testing.B, pb Message) { 1848 benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { 1849 Size(pb) 1850 return nil, nil 1851 }) 1852 } 1853 1854 func newOf(pb Message) Message { 1855 in := reflect.ValueOf(pb) 1856 if in.IsNil() { 1857 return pb 1858 } 1859 return reflect.New(in.Type().Elem()).Interface().(Message) 1860 } 1861 1862 func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { 1863 d, _ := Marshal(pb) 1864 b.SetBytes(int64(len(d))) 1865 pbd := newOf(pb) 1866 1867 b.ResetTimer() 1868 for i := 0; i < b.N; i++ { 1869 unmarshal(d, pbd) 1870 } 1871 } 1872 1873 func benchmarkBufferUnmarshal(b *testing.B, pb Message) { 1874 p := NewBuffer(nil) 1875 benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { 1876 p.SetBuf(d) 1877 return p.Unmarshal(pb0) 1878 }) 1879 } 1880 1881 // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} 1882 1883 func BenchmarkMarshal(b *testing.B) { 1884 benchmarkMarshal(b, testMsg(), Marshal) 1885 } 1886 1887 func BenchmarkBufferMarshal(b *testing.B) { 1888 benchmarkBufferMarshal(b, testMsg()) 1889 } 1890 1891 func BenchmarkSize(b *testing.B) { 1892 benchmarkSize(b, testMsg()) 1893 } 1894 1895 func BenchmarkUnmarshal(b *testing.B) { 1896 benchmarkUnmarshal(b, testMsg(), Unmarshal) 1897 } 1898 1899 func BenchmarkBufferUnmarshal(b *testing.B) { 1900 benchmarkBufferUnmarshal(b, testMsg()) 1901 } 1902 1903 func BenchmarkMarshalBytes(b *testing.B) { 1904 benchmarkMarshal(b, bytesMsg(), Marshal) 1905 } 1906 1907 func BenchmarkBufferMarshalBytes(b *testing.B) { 1908 benchmarkBufferMarshal(b, bytesMsg()) 1909 } 1910 1911 func BenchmarkSizeBytes(b *testing.B) { 1912 benchmarkSize(b, bytesMsg()) 1913 } 1914 1915 func BenchmarkUnmarshalBytes(b *testing.B) { 1916 benchmarkUnmarshal(b, bytesMsg(), Unmarshal) 1917 } 1918 1919 func BenchmarkBufferUnmarshalBytes(b *testing.B) { 1920 benchmarkBufferUnmarshal(b, bytesMsg()) 1921 } 1922 1923 func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { 1924 b.StopTimer() 1925 pb := initGoTestField() 1926 skip := &GoSkipTest{ 1927 SkipInt32: Int32(32), 1928 SkipFixed32: Uint32(3232), 1929 SkipFixed64: Uint64(6464), 1930 SkipString: String("skipper"), 1931 Skipgroup: &GoSkipTest_SkipGroup{ 1932 GroupInt32: Int32(75), 1933 GroupString: String("wxyz"), 1934 }, 1935 } 1936 1937 pbd := new(GoTestField) 1938 p := NewBuffer(nil) 1939 p.Marshal(pb) 1940 p.Marshal(skip) 1941 p2 := NewBuffer(nil) 1942 1943 b.StartTimer() 1944 for i := 0; i < b.N; i++ { 1945 p2.SetBuf(p.Bytes()) 1946 p2.Unmarshal(pbd) 1947 } 1948 }