選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

2493 行
74 KiB

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