all_test.go 73 KB

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