all_test.go 66 KB

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