all_test.go 71 KB

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