codec_test.go 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. package codec
  4. import (
  5. "bufio"
  6. "bytes"
  7. "encoding/gob"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "math"
  13. "math/rand"
  14. "net"
  15. "net/rpc"
  16. "os"
  17. "os/exec"
  18. "path/filepath"
  19. "reflect"
  20. "runtime"
  21. "strconv"
  22. "strings"
  23. "sync/atomic"
  24. "testing"
  25. "time"
  26. )
  27. func init() {
  28. testPreInitFns = append(testPreInitFns, testInit)
  29. // fmt.Printf("sizeof: Decoder: %v, Encoder: %v, decNaked: %v\n",
  30. // reflect.TypeOf((*Decoder)(nil)).Elem().Size(),
  31. // reflect.TypeOf((*Encoder)(nil)).Elem().Size(),
  32. // reflect.TypeOf((*decNaked)(nil)).Elem().Size(),
  33. // )
  34. }
  35. type testCustomStringT string
  36. // make this a mapbyslice
  37. type testMbsT []interface{}
  38. func (testMbsT) MapBySlice() {}
  39. type testMbsCustStrT []testCustomStringT
  40. func (testMbsCustStrT) MapBySlice() {}
  41. // type testSelferRecur struct{}
  42. // func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) {
  43. // e.MustEncode(s)
  44. // }
  45. // func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) {
  46. // d.MustDecode(s)
  47. // }
  48. type testIntfMapI interface {
  49. GetIntfMapV() string
  50. }
  51. type testIntfMapT1 struct {
  52. IntfMapV string
  53. }
  54. func (x *testIntfMapT1) GetIntfMapV() string { return x.IntfMapV }
  55. type testIntfMapT2 struct {
  56. IntfMapV string
  57. }
  58. func (x testIntfMapT2) GetIntfMapV() string { return x.IntfMapV }
  59. var testErrWriterErr = errors.New("testErrWriterErr")
  60. type testErrWriter struct{}
  61. func (x *testErrWriter) Write(p []byte) (int, error) {
  62. return 0, testErrWriterErr
  63. }
  64. // ----
  65. type testVerifyFlag uint8
  66. const (
  67. _ testVerifyFlag = 1 << iota
  68. testVerifyMapTypeSame
  69. testVerifyMapTypeStrIntf
  70. testVerifyMapTypeIntfIntf
  71. // testVerifySliceIntf
  72. testVerifyForPython
  73. testVerifyDoNil
  74. testVerifyTimeAsInteger
  75. )
  76. func (f testVerifyFlag) isset(v testVerifyFlag) bool {
  77. return f&v == v
  78. }
  79. // const testSkipRPCTests = false
  80. var (
  81. testTableNumPrimitives int
  82. testTableIdxTime int
  83. testTableNumMaps int
  84. // set this when running using bufio, etc
  85. testSkipRPCTests = false
  86. )
  87. var (
  88. skipVerifyVal interface{} = &(struct{}{})
  89. testMapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  90. // For Go Time, do not use a descriptive timezone.
  91. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  92. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  93. timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8
  94. timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  95. timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  96. timeToCompare3 = time.Unix(0, 270).UTC() // use value that must be encoded as uint64 for nanoseconds (for cbor/msgpack comparison)
  97. //timeToCompare4 = time.Time{}.UTC() // does not work well with simple cbor time encoding (overflow)
  98. timeToCompare4 = time.Unix(-2013855848, 4223).UTC()
  99. table []interface{} // main items we encode
  100. // will encode a float32 as float64, or large int as uint
  101. testRpcInt = new(TestRpcInt)
  102. )
  103. var wrapInt64Typ = reflect.TypeOf(wrapInt64(0))
  104. var wrapBytesTyp = reflect.TypeOf(wrapBytes(nil))
  105. var testSelfExtTyp = reflect.TypeOf((*TestSelfExtImpl)(nil)).Elem()
  106. var testSelfExt2Typ = reflect.TypeOf((*TestSelfExtImpl2)(nil)).Elem()
  107. func testByteBuf(in []byte) *bytes.Buffer {
  108. return bytes.NewBuffer(in)
  109. }
  110. type TestABC struct {
  111. A, B, C string
  112. }
  113. func (x *TestABC) MarshalBinary() ([]byte, error) {
  114. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  115. }
  116. func (x *TestABC) MarshalText() ([]byte, error) {
  117. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  118. }
  119. func (x *TestABC) MarshalJSON() ([]byte, error) {
  120. return []byte(fmt.Sprintf(`"%s %s %s"`, x.A, x.B, x.C)), nil
  121. }
  122. func (x *TestABC) UnmarshalBinary(data []byte) (err error) {
  123. ss := strings.Split(string(data), " ")
  124. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  125. return
  126. }
  127. func (x *TestABC) UnmarshalText(data []byte) (err error) {
  128. return x.UnmarshalBinary(data)
  129. }
  130. func (x *TestABC) UnmarshalJSON(data []byte) (err error) {
  131. return x.UnmarshalBinary(data[1 : len(data)-1])
  132. }
  133. type TestABC2 struct {
  134. A, B, C string
  135. }
  136. func (x TestABC2) MarshalText() ([]byte, error) {
  137. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  138. }
  139. func (x *TestABC2) UnmarshalText(data []byte) (err error) {
  140. ss := strings.Split(string(data), " ")
  141. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  142. return
  143. // _, err = fmt.Sscanf(string(data), "%s %s %s", &x.A, &x.B, &x.C)
  144. }
  145. type TestSimplish struct {
  146. Ii int
  147. Ss string
  148. Ar [2]*TestSimplish
  149. Sl []*TestSimplish
  150. Mm map[string]*TestSimplish
  151. }
  152. type TestRpcABC struct {
  153. A, B, C string
  154. }
  155. type TestRpcInt struct {
  156. i int
  157. }
  158. func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil }
  159. func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil }
  160. func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil }
  161. func (r *TestRpcInt) EchoStruct(arg TestRpcABC, res *string) error {
  162. *res = fmt.Sprintf("%#v", arg)
  163. return nil
  164. }
  165. func (r *TestRpcInt) Echo123(args []string, res *string) error {
  166. *res = fmt.Sprintf("%#v", args)
  167. return nil
  168. }
  169. type TestRawValue struct {
  170. R Raw
  171. I int
  172. }
  173. // ----
  174. type testUnixNanoTimeExt struct {
  175. // keep timestamp here, so that do not incur interface-conversion costs
  176. // ts int64
  177. }
  178. func (x *testUnixNanoTimeExt) WriteExt(v interface{}) []byte {
  179. v2 := v.(*time.Time)
  180. bs := make([]byte, 8)
  181. bigen.PutUint64(bs, uint64(v2.UnixNano()))
  182. return bs
  183. }
  184. func (x *testUnixNanoTimeExt) ReadExt(v interface{}, bs []byte) {
  185. v2 := v.(*time.Time)
  186. ui := bigen.Uint64(bs)
  187. *v2 = time.Unix(0, int64(ui)).UTC()
  188. }
  189. func (x *testUnixNanoTimeExt) ConvertExt(v interface{}) interface{} {
  190. v2 := v.(*time.Time) // structs are encoded by passing the ptr
  191. return v2.UTC().UnixNano()
  192. }
  193. func (x *testUnixNanoTimeExt) UpdateExt(dest interface{}, v interface{}) {
  194. tt := dest.(*time.Time)
  195. switch v2 := v.(type) {
  196. case int64:
  197. *tt = time.Unix(0, v2).UTC()
  198. case uint64:
  199. *tt = time.Unix(0, int64(v2)).UTC()
  200. //case float64:
  201. //case string:
  202. default:
  203. panic(fmt.Sprintf("unsupported format for time conversion: expecting int64/uint64; got %T", v))
  204. }
  205. }
  206. // ----
  207. type wrapInt64Ext int64
  208. func (x *wrapInt64Ext) WriteExt(v interface{}) []byte {
  209. v2 := uint64(int64(v.(wrapInt64)))
  210. bs := make([]byte, 8)
  211. bigen.PutUint64(bs, v2)
  212. return bs
  213. }
  214. func (x *wrapInt64Ext) ReadExt(v interface{}, bs []byte) {
  215. v2 := v.(*wrapInt64)
  216. ui := bigen.Uint64(bs)
  217. *v2 = wrapInt64(int64(ui))
  218. }
  219. func (x *wrapInt64Ext) ConvertExt(v interface{}) interface{} {
  220. return int64(v.(wrapInt64))
  221. }
  222. func (x *wrapInt64Ext) UpdateExt(dest interface{}, v interface{}) {
  223. v2 := dest.(*wrapInt64)
  224. *v2 = wrapInt64(v.(int64))
  225. }
  226. // ----
  227. type wrapBytesExt struct{}
  228. func (x *wrapBytesExt) WriteExt(v interface{}) []byte {
  229. return ([]byte)(v.(wrapBytes))
  230. }
  231. func (x *wrapBytesExt) ReadExt(v interface{}, bs []byte) {
  232. v2 := v.(*wrapBytes)
  233. *v2 = wrapBytes(bs)
  234. }
  235. func (x *wrapBytesExt) ConvertExt(v interface{}) interface{} {
  236. return ([]byte)(v.(wrapBytes))
  237. }
  238. func (x *wrapBytesExt) UpdateExt(dest interface{}, v interface{}) {
  239. v2 := dest.(*wrapBytes)
  240. // some formats (e.g. json) cannot nakedly determine []byte from string, so expect both
  241. switch v3 := v.(type) {
  242. case []byte:
  243. *v2 = wrapBytes(v3)
  244. case string:
  245. *v2 = wrapBytes([]byte(v3))
  246. default:
  247. panic("UpdateExt for wrapBytesExt expects string or []byte")
  248. }
  249. // *v2 = wrapBytes(v.([]byte))
  250. }
  251. // ----
  252. // timeExt is an extension handler for time.Time, that uses binc model for encoding/decoding time.
  253. // we used binc model, as that is the only custom time representation that we designed ourselves.
  254. type timeExt struct{}
  255. func (x timeExt) WriteExt(v interface{}) (bs []byte) {
  256. switch v2 := v.(type) {
  257. case time.Time:
  258. bs = bincEncodeTime(v2)
  259. case *time.Time:
  260. bs = bincEncodeTime(*v2)
  261. default:
  262. panic(fmt.Errorf("unsupported format for time conversion: expecting time.Time; got %T", v2))
  263. }
  264. return
  265. }
  266. func (x timeExt) ReadExt(v interface{}, bs []byte) {
  267. tt, err := bincDecodeTime(bs)
  268. if err != nil {
  269. panic(err)
  270. }
  271. *(v.(*time.Time)) = tt
  272. }
  273. func (x timeExt) ConvertExt(v interface{}) interface{} {
  274. return x.WriteExt(v)
  275. }
  276. func (x timeExt) UpdateExt(v interface{}, src interface{}) {
  277. x.ReadExt(v, src.([]byte))
  278. }
  279. // ----
  280. func testCodecEncode(ts interface{}, bsIn []byte,
  281. fn func([]byte) *bytes.Buffer, h Handle) (bs []byte, err error) {
  282. return sTestCodecEncode(ts, bsIn, fn, h, basicHandle(h))
  283. }
  284. func testCodecDecode(bs []byte, ts interface{}, h Handle) (err error) {
  285. return sTestCodecDecode(bs, ts, h, basicHandle(h))
  286. }
  287. func checkErrT(t *testing.T, err error) {
  288. if err != nil {
  289. failT(t, err.Error())
  290. }
  291. }
  292. func checkEqualT(t *testing.T, v1 interface{}, v2 interface{}, desc string) {
  293. if err := deepEqual(v1, v2); err != nil {
  294. failT(t, "Not Equal: %s: %v. v1: %v, v2: %v", desc, err, v1, v2)
  295. }
  296. }
  297. func testInit() {
  298. gob.Register(new(TestStrucFlex))
  299. if testInitDebug {
  300. ts0 := newTestStrucFlex(2, testNumRepeatString, false, !testSkipIntf, testMapStringKeyOnly)
  301. logTv(nil, "====> depth: %v, ts: %#v\n", 2, ts0)
  302. }
  303. for _, v := range testHandles {
  304. bh := basicHandle(v)
  305. // pre-fill them first
  306. bh.EncodeOptions = testEncodeOptions
  307. bh.DecodeOptions = testDecodeOptions
  308. // bh.InterfaceReset = true
  309. // bh.PreferArrayOverSlice = true
  310. // modify from flag'ish things
  311. bh.MaxInitLen = testMaxInitLen
  312. }
  313. testMsgpackH.WriteExt = true
  314. var tTimeExt timeExt
  315. var tBytesExt wrapBytesExt
  316. var tI64Ext wrapInt64Ext
  317. // create legacy functions suitable for deprecated AddExt functionality,
  318. // and use on some places for testSimpleH e.g. for time.Time and wrapInt64
  319. var (
  320. myExtEncFn = func(x BytesExt, rv reflect.Value) (bs []byte, err error) {
  321. defer panicToErr(errDecoratorDef{}, &err)
  322. bs = x.WriteExt(rv.Interface())
  323. return
  324. }
  325. myExtDecFn = func(x BytesExt, rv reflect.Value, bs []byte) (err error) {
  326. defer panicToErr(errDecoratorDef{}, &err)
  327. x.ReadExt(rv.Interface(), bs)
  328. return
  329. }
  330. timeExtEncFn = func(rv reflect.Value) (bs []byte, err error) { return myExtEncFn(tTimeExt, rv) }
  331. timeExtDecFn = func(rv reflect.Value, bs []byte) (err error) { return myExtDecFn(tTimeExt, rv, bs) }
  332. wrapInt64ExtEncFn = func(rv reflect.Value) (bs []byte, err error) { return myExtEncFn(&tI64Ext, rv) }
  333. wrapInt64ExtDecFn = func(rv reflect.Value, bs []byte) (err error) { return myExtDecFn(&tI64Ext, rv, bs) }
  334. )
  335. chkErr := func(err error) {
  336. if err != nil {
  337. panic(err)
  338. }
  339. }
  340. // time.Time is a native type, so extensions will have no effect.
  341. // However, we add these here to ensure nothing happens.
  342. chkErr(testSimpleH.AddExt(timeTyp, 1, timeExtEncFn, timeExtDecFn))
  343. // testBincH.SetBytesExt(timeTyp, 1, timeExt{}) // time is builtin for binc
  344. chkErr(testMsgpackH.SetBytesExt(timeTyp, 1, timeExt{}))
  345. chkErr(testCborH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{}))
  346. // testJsonH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{})
  347. // Add extensions for the testSelfExt
  348. chkErr(testSimpleH.SetBytesExt(testSelfExtTyp, 78, SelfExt))
  349. chkErr(testMsgpackH.SetBytesExt(testSelfExtTyp, 78, SelfExt))
  350. chkErr(testBincH.SetBytesExt(testSelfExtTyp, 78, SelfExt))
  351. chkErr(testJsonH.SetInterfaceExt(testSelfExtTyp, 78, SelfExt))
  352. chkErr(testCborH.SetInterfaceExt(testSelfExtTyp, 78, SelfExt))
  353. chkErr(testSimpleH.SetBytesExt(testSelfExt2Typ, 79, SelfExt))
  354. chkErr(testMsgpackH.SetBytesExt(testSelfExt2Typ, 79, SelfExt))
  355. chkErr(testBincH.SetBytesExt(testSelfExt2Typ, 79, SelfExt))
  356. chkErr(testJsonH.SetInterfaceExt(testSelfExt2Typ, 79, SelfExt))
  357. chkErr(testCborH.SetInterfaceExt(testSelfExt2Typ, 79, SelfExt))
  358. // Now, add extensions for the type wrapInt64 and wrapBytes,
  359. // so we can execute the Encode/Decode Ext paths.
  360. chkErr(testSimpleH.SetBytesExt(wrapBytesTyp, 32, &tBytesExt))
  361. chkErr(testMsgpackH.SetBytesExt(wrapBytesTyp, 32, &tBytesExt))
  362. chkErr(testBincH.SetBytesExt(wrapBytesTyp, 32, &tBytesExt))
  363. chkErr(testJsonH.SetInterfaceExt(wrapBytesTyp, 32, &tBytesExt))
  364. chkErr(testCborH.SetInterfaceExt(wrapBytesTyp, 32, &tBytesExt))
  365. chkErr(testSimpleH.AddExt(wrapInt64Typ, 16, wrapInt64ExtEncFn, wrapInt64ExtDecFn))
  366. // chkErr(testSimpleH.SetBytesExt(wrapInt64Typ, 16, &tI64Ext))
  367. chkErr(testMsgpackH.SetBytesExt(wrapInt64Typ, 16, &tI64Ext))
  368. chkErr(testBincH.SetBytesExt(wrapInt64Typ, 16, &tI64Ext))
  369. chkErr(testJsonH.SetInterfaceExt(wrapInt64Typ, 16, &tI64Ext))
  370. chkErr(testCborH.SetInterfaceExt(wrapInt64Typ, 16, &tI64Ext))
  371. // primitives MUST be an even number, so it can be used as a mapBySlice also.
  372. primitives := []interface{}{
  373. int8(-8),
  374. int16(-1616),
  375. int32(-32323232),
  376. int64(-6464646464646464),
  377. uint8(192),
  378. uint16(1616),
  379. uint32(32323232),
  380. uint64(6464646464646464),
  381. byte(192),
  382. float32(-3232.0),
  383. float64(-6464646464.0),
  384. float32(3232.0),
  385. float64(6464.0),
  386. float64(6464646464.0),
  387. false,
  388. true,
  389. "null",
  390. nil,
  391. "some&day>some<day",
  392. timeToCompare1,
  393. "",
  394. timeToCompare2,
  395. "bytestring",
  396. timeToCompare3,
  397. "none",
  398. timeToCompare4,
  399. }
  400. maps := []interface{}{
  401. map[string]bool{
  402. "true": true,
  403. "false": false,
  404. },
  405. map[string]interface{}{
  406. "true": "True",
  407. "false": false,
  408. "uint16(1616)": uint16(1616),
  409. },
  410. //add a complex combo map in here. (map has list which has map)
  411. //note that after the first thing, everything else should be generic.
  412. map[string]interface{}{
  413. "list": []interface{}{
  414. int16(1616),
  415. int32(32323232),
  416. true,
  417. float32(-3232.0),
  418. map[string]interface{}{
  419. "TRUE": true,
  420. "FALSE": false,
  421. },
  422. []interface{}{true, false},
  423. },
  424. "int32": int32(32323232),
  425. "bool": true,
  426. "LONG STRING": `
  427. 1234567890 1234567890
  428. 1234567890 1234567890
  429. 1234567890 1234567890
  430. ABCDEDFGHIJKLMNOPQRSTUVWXYZ
  431. abcdedfghijklmnopqrstuvwxyz
  432. ABCDEDFGHIJKLMNOPQRSTUVWXYZ
  433. abcdedfghijklmnopqrstuvwxyz
  434. "ABCDEDFGHIJKLMNOPQRSTUVWXYZ"
  435. ' a tab '
  436. \a\b\c\d\e
  437. \b\f\n\r\t all literally
  438. ugorji
  439. `,
  440. "SHORT STRING": "1234567890",
  441. },
  442. map[interface{}]interface{}{
  443. true: "true",
  444. uint8(138): false,
  445. false: uint8(200),
  446. },
  447. }
  448. testTableNumPrimitives = len(primitives)
  449. testTableIdxTime = testTableNumPrimitives - 8
  450. testTableNumMaps = len(maps)
  451. table = []interface{}{}
  452. table = append(table, primitives...)
  453. table = append(table, primitives)
  454. table = append(table, testMbsT(primitives))
  455. table = append(table, maps...)
  456. table = append(table, newTestStrucFlex(0, testNumRepeatString, false, !testSkipIntf, testMapStringKeyOnly))
  457. // table = append(table, newTestStrucFlex(0, testNumRepeatString, true, !testSkipIntf, testMapStringKeyOnly))
  458. }
  459. func testTableVerify(f testVerifyFlag, h Handle) (av []interface{}) {
  460. av = make([]interface{}, len(table))
  461. lp := testTableNumPrimitives + 4
  462. // doNil := f & testVerifyDoNil == testVerifyDoNil
  463. // doPython := f & testVerifyForPython == testVerifyForPython
  464. switch {
  465. case f.isset(testVerifyForPython):
  466. for i, v := range table {
  467. if i == testTableNumPrimitives+1 || i > lp { // testTableNumPrimitives+1 is the mapBySlice
  468. av[i] = skipVerifyVal
  469. continue
  470. }
  471. av[i] = testVerifyVal(v, f, h)
  472. }
  473. // only do the python verify up to the maps, skipping the last 2 maps.
  474. av = av[:testTableNumPrimitives+2+testTableNumMaps-2]
  475. case f.isset(testVerifyDoNil):
  476. for i, v := range table {
  477. if i > lp {
  478. av[i] = skipVerifyVal
  479. continue
  480. }
  481. av[i] = testVerifyVal(v, f, h)
  482. }
  483. default:
  484. for i, v := range table {
  485. if i == lp {
  486. av[i] = skipVerifyVal
  487. continue
  488. }
  489. //av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  490. switch v.(type) {
  491. case []interface{}:
  492. av[i] = testVerifyVal(v, f, h)
  493. case testMbsT:
  494. av[i] = testVerifyVal(v, f, h)
  495. case map[string]interface{}:
  496. av[i] = testVerifyVal(v, f, h)
  497. case map[interface{}]interface{}:
  498. av[i] = testVerifyVal(v, f, h)
  499. case time.Time:
  500. av[i] = testVerifyVal(v, f, h)
  501. default:
  502. av[i] = v
  503. }
  504. }
  505. }
  506. return
  507. }
  508. func testVerifyValInt(v int64, isMsgp bool) (v2 interface{}) {
  509. if isMsgp {
  510. if v >= 0 && v <= 127 {
  511. v2 = uint64(v)
  512. } else {
  513. v2 = int64(v)
  514. }
  515. } else if v >= 0 {
  516. v2 = uint64(v)
  517. } else {
  518. v2 = int64(v)
  519. }
  520. return
  521. }
  522. func testVerifyVal(v interface{}, f testVerifyFlag, h Handle) (v2 interface{}) {
  523. //for python msgpack,
  524. // - all positive integers are unsigned 64-bit ints
  525. // - all floats are float64
  526. _, isMsgp := h.(*MsgpackHandle)
  527. _, isCbor := h.(*CborHandle)
  528. switch iv := v.(type) {
  529. case int8:
  530. v2 = testVerifyValInt(int64(iv), isMsgp)
  531. // fmt.Printf(">>>> is msgp: %v, v: %T, %v ==> v2: %T, %v\n", isMsgp, v, v, v2, v2)
  532. case int16:
  533. v2 = testVerifyValInt(int64(iv), isMsgp)
  534. case int32:
  535. v2 = testVerifyValInt(int64(iv), isMsgp)
  536. case int64:
  537. v2 = testVerifyValInt(int64(iv), isMsgp)
  538. case uint8:
  539. v2 = uint64(iv)
  540. case uint16:
  541. v2 = uint64(iv)
  542. case uint32:
  543. v2 = uint64(iv)
  544. case uint64:
  545. v2 = uint64(iv)
  546. case float32:
  547. v2 = float64(iv)
  548. case float64:
  549. v2 = float64(iv)
  550. case []interface{}:
  551. m2 := make([]interface{}, len(iv))
  552. for j, vj := range iv {
  553. m2[j] = testVerifyVal(vj, f, h)
  554. }
  555. v2 = m2
  556. case testMbsT:
  557. m2 := make([]interface{}, len(iv))
  558. for j, vj := range iv {
  559. m2[j] = testVerifyVal(vj, f, h)
  560. }
  561. v2 = testMbsT(m2)
  562. case map[string]bool:
  563. switch {
  564. case f.isset(testVerifyMapTypeSame):
  565. m2 := make(map[string]bool)
  566. for kj, kv := range iv {
  567. m2[kj] = kv
  568. }
  569. v2 = m2
  570. case f.isset(testVerifyMapTypeStrIntf):
  571. m2 := make(map[string]interface{})
  572. for kj, kv := range iv {
  573. m2[kj] = kv
  574. }
  575. v2 = m2
  576. case f.isset(testVerifyMapTypeIntfIntf):
  577. m2 := make(map[interface{}]interface{})
  578. for kj, kv := range iv {
  579. m2[kj] = kv
  580. }
  581. v2 = m2
  582. }
  583. case map[string]interface{}:
  584. switch {
  585. case f.isset(testVerifyMapTypeSame):
  586. m2 := make(map[string]interface{})
  587. for kj, kv := range iv {
  588. m2[kj] = testVerifyVal(kv, f, h)
  589. }
  590. v2 = m2
  591. case f.isset(testVerifyMapTypeStrIntf):
  592. m2 := make(map[string]interface{})
  593. for kj, kv := range iv {
  594. m2[kj] = testVerifyVal(kv, f, h)
  595. }
  596. v2 = m2
  597. case f.isset(testVerifyMapTypeIntfIntf):
  598. m2 := make(map[interface{}]interface{})
  599. for kj, kv := range iv {
  600. m2[kj] = testVerifyVal(kv, f, h)
  601. }
  602. v2 = m2
  603. }
  604. case map[interface{}]interface{}:
  605. m2 := make(map[interface{}]interface{})
  606. for kj, kv := range iv {
  607. m2[testVerifyVal(kj, f, h)] = testVerifyVal(kv, f, h)
  608. }
  609. v2 = m2
  610. case time.Time:
  611. switch {
  612. case f.isset(testVerifyTimeAsInteger):
  613. if iv2 := iv.UnixNano(); iv2 >= 0 {
  614. v2 = uint64(iv2)
  615. } else {
  616. v2 = int64(iv2)
  617. }
  618. case isMsgp:
  619. v2 = iv.UTC()
  620. case isCbor:
  621. // fmt.Printf("%%%% cbor verifier\n")
  622. v2 = iv.UTC().Round(time.Microsecond)
  623. default:
  624. v2 = v
  625. }
  626. default:
  627. v2 = v
  628. }
  629. return
  630. }
  631. func testUnmarshal(v interface{}, data []byte, h Handle) (err error) {
  632. return testCodecDecode(data, v, h)
  633. }
  634. func testMarshal(v interface{}, h Handle) (bs []byte, err error) {
  635. return testCodecEncode(v, nil, testByteBuf, h)
  636. }
  637. func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte) {
  638. t.Helper()
  639. bs, err := testMarshal(v, h)
  640. if err != nil {
  641. logT("%s: marshal failed: %v", name, err)
  642. failT(t, "Error encoding %s: %v, Err: %v", name, v, err)
  643. }
  644. return
  645. }
  646. func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) {
  647. t.Helper()
  648. if err := testUnmarshal(v, data, h); err != nil {
  649. logT("%s: unmarshal failed: %v", name, err)
  650. failTv(t, "Error Decoding into %s: %v, Err: %v", name, v, err)
  651. }
  652. }
  653. func testDeepEqualErr(v1, v2 interface{}, t *testing.T, name string) {
  654. t.Helper()
  655. if err := deepEqual(v1, v2); err == nil {
  656. logTv(t, "%s: values equal", name)
  657. } else {
  658. logT(t, "%s: values not equal: %v", name, err)
  659. failTv(t, "%s: values not equal: %v. 1: %#v, 2: %#v", name, err, v1, v2)
  660. }
  661. }
  662. func testReadWriteCloser(c io.ReadWriteCloser) io.ReadWriteCloser {
  663. if testRpcBufsize <= 0 && rand.Int63()%2 == 0 {
  664. return c
  665. }
  666. return struct {
  667. io.Closer
  668. *bufio.Reader
  669. *bufio.Writer
  670. }{c, bufio.NewReaderSize(c, testRpcBufsize), bufio.NewWriterSize(c, testRpcBufsize)}
  671. }
  672. // doTestCodecTableOne allows us test for different variations based on arguments passed.
  673. func doTestCodecTableOne(t *testing.T, testNil bool, h Handle,
  674. vs []interface{}, vsVerify []interface{}) {
  675. //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work.
  676. //Current setup allows us test (at least manually) the nil interface or typed interface.
  677. logTv(t, "================ TestNil: %v ================\n", testNil)
  678. for i, v0 := range vs {
  679. logTv(t, "..............................................")
  680. logTv(t, " Testing: #%d:, %T, %#v\n", i, v0, v0)
  681. // if a TestStrucFlex and we are doing a testNil,
  682. // ensure the fields which are not encodeable are set to nil appropriately
  683. // i.e. MstrUi64TSelf
  684. var mapMstrUi64TSelf map[stringUint64T]*stringUint64T
  685. var mapMsu2wss map[stringUint64T]wrapStringSlice
  686. tsflex, _ := v0.(*TestStrucFlex)
  687. if testNil && tsflex != nil {
  688. mapMstrUi64TSelf = tsflex.MstrUi64TSelf
  689. mapMsu2wss = tsflex.Msu2wss
  690. tsflex.MstrUi64TSelf = nil
  691. tsflex.Msu2wss = nil
  692. }
  693. b0 := testMarshalErr(v0, h, t, "v0")
  694. var b1 = b0
  695. if len(b1) > 256 {
  696. b1 = b1[:256]
  697. }
  698. if h.isBinary() {
  699. logTv(t, " Encoded bytes: len: %v, %v\n", len(b0), b1)
  700. } else {
  701. logTv(t, " Encoded string: len: %v, %s\n", len(b0), b0)
  702. // println("########### encoded string: " + string(b0))
  703. }
  704. var v1 interface{}
  705. var err error
  706. if testNil {
  707. err = testUnmarshal(&v1, b0, h)
  708. if tsflex != nil {
  709. tsflex.MstrUi64TSelf = mapMstrUi64TSelf
  710. tsflex.Msu2wss = mapMsu2wss
  711. }
  712. } else {
  713. if v0 != nil {
  714. v0rt := reflect.TypeOf(v0) // ptr
  715. if v0rt.Kind() == reflect.Ptr {
  716. err = testUnmarshal(v0, b0, h)
  717. v1 = v0
  718. } else {
  719. rv1 := reflect.New(v0rt)
  720. err = testUnmarshal(rv1.Interface(), b0, h)
  721. v1 = rv1.Elem().Interface()
  722. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  723. }
  724. }
  725. }
  726. logTv(t, " v1 returned: %T, %v %#v", v1, v1, v1)
  727. // if v1 != nil {
  728. // logT(t, " v1 returned: %T, %#v", v1, v1)
  729. // //we always indirect, because ptr to typed value may be passed (if not testNil)
  730. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  731. // }
  732. if err != nil {
  733. failT(t, "-------- Error: %v. Partial return: %v", err, v1)
  734. }
  735. v0check := vsVerify[i]
  736. if v0check == skipVerifyVal {
  737. logTv(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1)
  738. continue
  739. }
  740. if err = deepEqual(v0check, v1); err == nil {
  741. logTv(t, "++++++++ Before and After marshal matched\n")
  742. } else {
  743. // logT(t, "-------- Before and After marshal do not match: Error: %v"+
  744. // " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1)
  745. logT(t, "-------- FAIL: Before and After marshal do not match: Error: %v", err)
  746. logTv(t, " ....... GOLDEN: (%T) %v %#v", v0check, v0check, v0check)
  747. logTv(t, " ....... DECODED: (%T) %v %#v", v1, v1, v1)
  748. failT(t)
  749. }
  750. }
  751. }
  752. func testCodecTableOne(t *testing.T, h Handle) {
  753. testOnce.Do(testInitAll)
  754. // func TestMsgpackAllExperimental(t *testing.T) {
  755. // dopts := testDecOpts(nil, nil, false, true, true),
  756. numPrim, numMap, idxTime, idxMap := testTableNumPrimitives, testTableNumMaps, testTableIdxTime, testTableNumPrimitives+2
  757. //println("#################")
  758. tableVerify := testTableVerify(testVerifyMapTypeSame, h)
  759. tableTestNilVerify := testTableVerify(testVerifyDoNil|testVerifyMapTypeStrIntf, h)
  760. switch v := h.(type) {
  761. case *MsgpackHandle:
  762. var oldWriteExt bool
  763. _ = oldWriteExt
  764. oldWriteExt = v.WriteExt
  765. v.WriteExt = true
  766. doTestCodecTableOne(t, false, h, table, tableVerify)
  767. v.WriteExt = oldWriteExt
  768. case *JsonHandle:
  769. //skip []interface{} containing time.Time, as it encodes as a number, but cannot decode back to time.Time.
  770. //As there is no real support for extension tags in json, this must be skipped.
  771. doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  772. doTestCodecTableOne(t, false, h, table[idxMap:], tableVerify[idxMap:])
  773. default:
  774. doTestCodecTableOne(t, false, h, table, tableVerify)
  775. }
  776. // func TestMsgpackAll(t *testing.T) {
  777. // //skip []interface{} containing time.Time
  778. // doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  779. // doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:])
  780. // func TestMsgpackNilStringMap(t *testing.T) {
  781. var oldMapType reflect.Type
  782. v := basicHandle(h)
  783. oldMapType, v.MapType = v.MapType, testMapStrIntfTyp
  784. // defer func() { v.MapType = oldMapType }()
  785. //skip time.Time, []interface{} containing time.Time, last map, and newStruc
  786. doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime])
  787. doTestCodecTableOne(t, true, h, table[idxMap:idxMap+numMap-1], tableTestNilVerify[idxMap:idxMap+numMap-1]) // failing one for msgpack
  788. v.MapType = oldMapType
  789. // func TestMsgpackNilIntf(t *testing.T) {
  790. //do last map and newStruc
  791. idx2 := idxMap + numMap - 1
  792. doTestCodecTableOne(t, true, h, table[idx2:], tableTestNilVerify[idx2:])
  793. //TODO? What is this one?
  794. //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18])
  795. }
  796. func testCodecMiscOne(t *testing.T, h Handle) {
  797. var err error
  798. testOnce.Do(testInitAll)
  799. b := testMarshalErr(32, h, t, "32")
  800. // Cannot do this nil one, because faster type assertion decoding will panic
  801. // var i *int32
  802. // if err = testUnmarshal(b, i, nil); err == nil {
  803. // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr")
  804. // failT(t)
  805. // }
  806. var i2 int32
  807. testUnmarshalErr(&i2, b, h, t, "int32-ptr")
  808. if i2 != int32(32) {
  809. failT(t, "------- didn't unmarshal to 32: Received: %d", i2)
  810. }
  811. // func TestMsgpackDecodePtr(t *testing.T) {
  812. ts := newTestStrucFlex(testDepth, testNumRepeatString, false, !testSkipIntf, testMapStringKeyOnly)
  813. b = testMarshalErr(ts, h, t, "pointer-to-struct")
  814. if len(b) < 40 {
  815. failT(t, "------- Size must be > 40. Size: %d", len(b))
  816. }
  817. var b1 = b
  818. if len(b1) > 256 {
  819. b1 = b1[:256]
  820. }
  821. if h.isBinary() {
  822. logTv(t, "------- b: size: %v, value: %v", len(b), b1)
  823. } else {
  824. logTv(t, "------- b: size: %v, value: %s", len(b), b1)
  825. }
  826. ts2 := emptyTestStrucFlex()
  827. testUnmarshalErr(ts2, b, h, t, "pointer-to-struct")
  828. if ts2.I64 != math.MaxInt64*2/3 {
  829. failT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64)
  830. }
  831. // func TestMsgpackIntfDecode(t *testing.T) {
  832. m := map[string]int{"A": 2, "B": 3}
  833. p := []interface{}{m}
  834. bs := testMarshalErr(p, h, t, "p")
  835. m2 := map[string]int{}
  836. p2 := []interface{}{m2}
  837. testUnmarshalErr(&p2, bs, h, t, "&p2")
  838. if m2["A"] != 2 || m2["B"] != 3 {
  839. failT(t, "FAIL: m2 not as expected: expecting: %v, got: %v", m, m2)
  840. }
  841. // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2)
  842. checkEqualT(t, p, p2, "p=p2")
  843. checkEqualT(t, m, m2, "m=m2")
  844. if err = deepEqual(p, p2); err == nil {
  845. logTv(t, "p and p2 match")
  846. } else {
  847. failT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2)
  848. }
  849. if err = deepEqual(m, m2); err == nil {
  850. logTv(t, "m and m2 match")
  851. } else {
  852. failT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2)
  853. }
  854. // func TestMsgpackDecodeStructSubset(t *testing.T) {
  855. // test that we can decode a subset of the stream
  856. mm := map[string]interface{}{"A": 5, "B": 99, "C": 333}
  857. bs = testMarshalErr(mm, h, t, "mm")
  858. type ttt struct {
  859. A uint8
  860. C int32
  861. }
  862. var t2 ttt
  863. testUnmarshalErr(&t2, bs, h, t, "t2")
  864. t3 := ttt{5, 333}
  865. checkEqualT(t, t2, t3, "t2=t3")
  866. // println(">>>>>")
  867. // test simple arrays, non-addressable arrays, slices
  868. type tarr struct {
  869. A int64
  870. B [3]int64
  871. C []byte
  872. D [3]byte
  873. }
  874. var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}}
  875. // test both pointer and non-pointer (value)
  876. for _, tarr1 := range []interface{}{tarr0, &tarr0} {
  877. bs = testMarshalErr(tarr1, h, t, "tarr1")
  878. if _, ok := h.(*JsonHandle); ok {
  879. logTv(t, "Marshal as: %s", bs)
  880. }
  881. var tarr2 tarr
  882. testUnmarshalErr(&tarr2, bs, h, t, "tarr2")
  883. checkEqualT(t, tarr0, tarr2, "tarr0=tarr2")
  884. }
  885. // test byte array, even if empty (msgpack only)
  886. if h == testMsgpackH {
  887. type ystruct struct {
  888. Anarray []byte
  889. }
  890. var ya = ystruct{}
  891. testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya")
  892. }
  893. var tt1, tt2 time.Time
  894. tt2 = time.Now()
  895. bs = testMarshalErr(tt1, h, t, "zero-time-enc")
  896. testUnmarshalErr(&tt2, bs, h, t, "zero-time-dec")
  897. testDeepEqualErr(tt1, tt2, t, "zero-time-eq")
  898. // test encoding a slice of byte (but not []byte) and decoding into a []byte
  899. var sw = []wrapUint8{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}
  900. var bw []byte // ("ABCDEFGHIJ")
  901. bs = testMarshalErr(sw, h, t, "wrap-bytes-enc")
  902. testUnmarshalErr(&bw, bs, h, t, "wrap-bytes-dec")
  903. testDeepEqualErr(bw, []byte("ABCDEFGHIJ"), t, "wrap-bytes-eq")
  904. }
  905. func testCodecEmbeddedPointer(t *testing.T, h Handle) {
  906. testOnce.Do(testInitAll)
  907. type Z int
  908. type A struct {
  909. AnInt int
  910. }
  911. type B struct {
  912. *Z
  913. *A
  914. MoreInt int
  915. }
  916. var z Z = 4
  917. x1 := &B{&z, &A{5}, 6}
  918. bs := testMarshalErr(x1, h, t, "x1")
  919. var x2 = new(B)
  920. testUnmarshalErr(x2, bs, h, t, "x2")
  921. checkEqualT(t, x1, x2, "x1=x2")
  922. }
  923. func testCodecUnderlyingType(t *testing.T, h Handle) {
  924. testOnce.Do(testInitAll)
  925. // Manual Test.
  926. // Run by hand, with accompanying printf.statements in fast-path.go
  927. // to ensure that the fast functions are called.
  928. type T1 map[string]string
  929. v := T1{"1": "1s", "2": "2s"}
  930. var bs []byte
  931. var err error
  932. NewEncoderBytes(&bs, h).MustEncode(v)
  933. if err != nil {
  934. failT(t, "Error during encode: %v", err)
  935. }
  936. var v2 T1
  937. NewDecoderBytes(bs, h).MustDecode(&v2)
  938. if err != nil {
  939. failT(t, "Error during decode: %v", err)
  940. }
  941. }
  942. func testCodecChan(t *testing.T, h Handle) {
  943. testOnce.Do(testInitAll)
  944. // - send a slice []*int64 (sl1) into an chan (ch1) with cap > len(s1)
  945. // - encode ch1 as a stream array
  946. // - decode a chan (ch2), with cap > len(s1) from the stream array
  947. // - receive from ch2 into slice sl2
  948. // - compare sl1 and sl2
  949. // - do this for codecs: json, cbor (covers all types)
  950. if true {
  951. logTv(t, "*int64")
  952. sl1 := make([]*int64, 4)
  953. for i := range sl1 {
  954. var j int64 = int64(i)
  955. sl1[i] = &j
  956. }
  957. ch1 := make(chan *int64, 4)
  958. for _, j := range sl1 {
  959. ch1 <- j
  960. }
  961. var bs []byte
  962. NewEncoderBytes(&bs, h).MustEncode(ch1)
  963. ch2 := make(chan *int64, 8)
  964. NewDecoderBytes(bs, h).MustDecode(&ch2)
  965. close(ch2)
  966. var sl2 []*int64
  967. for j := range ch2 {
  968. sl2 = append(sl2, j)
  969. }
  970. if err := deepEqual(sl1, sl2); err != nil {
  971. failT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  972. }
  973. }
  974. if true {
  975. logTv(t, "testBytesT []byte - input []byte")
  976. type testBytesT []byte
  977. sl1 := make([]testBytesT, 4)
  978. for i := range sl1 {
  979. var j = []byte(strings.Repeat(strconv.FormatInt(int64(i), 10), i))
  980. sl1[i] = j
  981. }
  982. ch1 := make(chan testBytesT, 4)
  983. for _, j := range sl1 {
  984. ch1 <- j
  985. }
  986. var bs []byte
  987. NewEncoderBytes(&bs, h).MustEncode(ch1)
  988. ch2 := make(chan testBytesT, 8)
  989. NewDecoderBytes(bs, h).MustDecode(&ch2)
  990. close(ch2)
  991. var sl2 []testBytesT
  992. for j := range ch2 {
  993. // logTv(t, ">>>> from chan: is nil? %v, %v", j == nil, j)
  994. sl2 = append(sl2, j)
  995. }
  996. if err := deepEqual(sl1, sl2); err != nil {
  997. failT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  998. }
  999. }
  1000. if true {
  1001. logTv(t, "testBytesT byte - input string/testBytesT")
  1002. type testBytesT byte
  1003. sl1 := make([]testBytesT, 4)
  1004. for i := range sl1 {
  1005. var j = strconv.FormatInt(int64(i), 10)[0]
  1006. sl1[i] = testBytesT(j)
  1007. }
  1008. ch1 := make(chan testBytesT, 4)
  1009. for _, j := range sl1 {
  1010. ch1 <- j
  1011. }
  1012. var bs []byte
  1013. NewEncoderBytes(&bs, h).MustEncode(ch1)
  1014. ch2 := make(chan testBytesT, 8)
  1015. NewDecoderBytes(bs, h).MustDecode(&ch2)
  1016. close(ch2)
  1017. var sl2 []testBytesT
  1018. for j := range ch2 {
  1019. sl2 = append(sl2, j)
  1020. }
  1021. if err := deepEqual(sl1, sl2); err != nil {
  1022. failT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  1023. }
  1024. }
  1025. if true {
  1026. logTv(t, "*[]byte")
  1027. sl1 := make([]byte, 4)
  1028. for i := range sl1 {
  1029. var j = strconv.FormatInt(int64(i), 10)[0]
  1030. sl1[i] = byte(j)
  1031. }
  1032. ch1 := make(chan byte, 4)
  1033. for _, j := range sl1 {
  1034. ch1 <- j
  1035. }
  1036. var bs []byte
  1037. NewEncoderBytes(&bs, h).MustEncode(ch1)
  1038. ch2 := make(chan byte, 8)
  1039. NewDecoderBytes(bs, h).MustDecode(&ch2)
  1040. close(ch2)
  1041. var sl2 []byte
  1042. for j := range ch2 {
  1043. sl2 = append(sl2, j)
  1044. }
  1045. if err := deepEqual(sl1, sl2); err != nil {
  1046. failT(t, "FAIL: Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  1047. }
  1048. }
  1049. }
  1050. func testCodecRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration,
  1051. ) (port int) {
  1052. testOnce.Do(testInitAll)
  1053. if testSkipRPCTests {
  1054. return
  1055. }
  1056. // rpc needs EOF, which is sent via a panic, and so must be recovered.
  1057. if !recoverPanicToErr {
  1058. failT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF")
  1059. }
  1060. if jsonH, ok := h.(*JsonHandle); ok && !jsonH.TermWhitespace {
  1061. jsonH.TermWhitespace = true
  1062. defer func() { jsonH.TermWhitespace = false }()
  1063. }
  1064. srv := rpc.NewServer()
  1065. srv.Register(testRpcInt)
  1066. ln, err := net.Listen("tcp", "127.0.0.1:0") // listen on ipv4 localhost
  1067. logT(t, "connFn: addr: %v, network: %v, port: %v", ln.Addr(), ln.Addr().Network(), (ln.Addr().(*net.TCPAddr)).Port)
  1068. // log("listener: %v", ln.Addr())
  1069. checkErrT(t, err)
  1070. port = (ln.Addr().(*net.TCPAddr)).Port
  1071. // var opts *DecoderOptions
  1072. // opts := testDecOpts
  1073. // opts.MapType = mapStrIntfTyp
  1074. serverExitChan := make(chan bool, 1)
  1075. var serverExitFlag uint64
  1076. serverFn := func() {
  1077. for {
  1078. conn1, err1 := ln.Accept()
  1079. // if err1 != nil {
  1080. // //fmt.Printf("accept err1: %v\n", err1)
  1081. // continue
  1082. // }
  1083. if atomic.LoadUint64(&serverExitFlag) == 1 {
  1084. serverExitChan <- true
  1085. if conn1 != nil {
  1086. conn1.Close()
  1087. }
  1088. return // exit serverFn goroutine
  1089. }
  1090. if err1 == nil && conn1 != nil {
  1091. sc := rr.ServerCodec(testReadWriteCloser(conn1), h)
  1092. srv.ServeCodec(sc)
  1093. }
  1094. }
  1095. }
  1096. clientFn := func(cc rpc.ClientCodec) {
  1097. cl := rpc.NewClientWithCodec(cc)
  1098. defer cl.Close()
  1099. // defer func() { println("##### client closing"); cl.Close() }()
  1100. var up, sq, mult int
  1101. var rstr string
  1102. // log("Calling client")
  1103. checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
  1104. // log("Called TestRpcInt.Update")
  1105. checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5")
  1106. checkEqualT(t, up, 5, "up=5")
  1107. checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
  1108. checkEqualT(t, sq, 25, "sq=25")
  1109. checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
  1110. checkEqualT(t, mult, 100, "mult=100")
  1111. checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1112. checkEqualT(t, rstr, fmt.Sprintf("%#v", TestRpcABC{"Aa", "Bb", "Cc"}), "rstr=")
  1113. checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
  1114. checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=")
  1115. }
  1116. connFn := func() (bs net.Conn) {
  1117. // log("calling f1")
  1118. bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
  1119. checkErrT(t, err2)
  1120. return
  1121. }
  1122. exitFn := func() {
  1123. atomic.StoreUint64(&serverExitFlag, 1)
  1124. bs := connFn()
  1125. <-serverExitChan
  1126. bs.Close()
  1127. // serverExitChan <- true
  1128. }
  1129. go serverFn()
  1130. runtime.Gosched()
  1131. //time.Sleep(100 * time.Millisecond)
  1132. if exitSleepMs == 0 {
  1133. defer ln.Close()
  1134. defer exitFn()
  1135. }
  1136. if doRequest {
  1137. bs := connFn()
  1138. cc := rr.ClientCodec(testReadWriteCloser(bs), h)
  1139. clientFn(cc)
  1140. }
  1141. if exitSleepMs != 0 {
  1142. go func() {
  1143. defer ln.Close()
  1144. time.Sleep(exitSleepMs)
  1145. exitFn()
  1146. }()
  1147. }
  1148. return
  1149. }
  1150. func doTestMapEncodeForCanonical(t *testing.T, h Handle) {
  1151. testOnce.Do(testInitAll)
  1152. // println("doTestMapEncodeForCanonical")
  1153. v1 := map[stringUint64T]interface{}{
  1154. {"a", 1}: 1,
  1155. {"b", 2}: "hello",
  1156. {"c", 3}: map[string]interface{}{
  1157. "c/a": 1,
  1158. "c/b": "world",
  1159. "c/c": []int{1, 2, 3, 4},
  1160. "c/d": map[string]interface{}{
  1161. "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda",
  1162. "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa",
  1163. "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw",
  1164. "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag",
  1165. "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb",
  1166. "c/d/f": "",
  1167. },
  1168. "c/e": map[int]string{
  1169. 1: "1",
  1170. 22: "22",
  1171. 333: "333",
  1172. 4444: "4444",
  1173. 55555: "55555",
  1174. },
  1175. "c/f": map[string]int{
  1176. "1": 1,
  1177. "22": 22,
  1178. "333": 333,
  1179. "4444": 4444,
  1180. "55555": 55555,
  1181. },
  1182. "c/g": map[bool]int{
  1183. false: 0,
  1184. true: 1,
  1185. },
  1186. "c/t": map[time.Time]int64{
  1187. time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC): time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano(),
  1188. time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC): time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano(),
  1189. time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC): time.Date(2017, 1, 1, 0, 0, 0, 0, time.UTC).UnixNano(),
  1190. },
  1191. },
  1192. }
  1193. var v2 map[stringUint64T]interface{}
  1194. var b1, b2, b3 []byte
  1195. // encode v1 into b1, decode b1 into v2, encode v2 into b2, and compare b1 and b2.
  1196. // OR
  1197. // encode v1 into b1, decode b1 into v2, encode v2 into b2 and b3, and compare b2 and b3.
  1198. // e.g. when doing cbor indefinite, we may haveto use out-of-band encoding
  1199. // where each key is encoded as an indefinite length string, which makes it not the same
  1200. // order as the strings were lexicographically ordered before.
  1201. var cborIndef bool
  1202. if ch, ok := h.(*CborHandle); ok {
  1203. cborIndef = ch.IndefiniteLength
  1204. }
  1205. bh := basicHandle(h)
  1206. if !bh.Canonical {
  1207. bh.Canonical = true
  1208. defer func() { bh.Canonical = false }()
  1209. }
  1210. e1 := NewEncoderBytes(&b1, h)
  1211. e1.MustEncode(v1)
  1212. d1 := NewDecoderBytes(b1, h)
  1213. d1.MustDecode(&v2)
  1214. // testDeepEqualErr(v1, v2, t, "huh?")
  1215. e2 := NewEncoderBytes(&b2, h)
  1216. e2.MustEncode(v2)
  1217. var b1t, b2t = b1, b2
  1218. if cborIndef {
  1219. e2 = NewEncoderBytes(&b3, h)
  1220. e2.MustEncode(v2)
  1221. b1t, b2t = b2, b3
  1222. }
  1223. if !bytes.Equal(b1t, b2t) {
  1224. failT(t, "Unequal bytes: %v VS %v", b1t, b2t)
  1225. }
  1226. }
  1227. func doTestStdEncIntf(t *testing.T, h Handle) {
  1228. testOnce.Do(testInitAll)
  1229. args := [][2]interface{}{
  1230. {&TestABC{"A", "BB", "CCC"}, new(TestABC)},
  1231. {&TestABC2{"AAA", "BB", "C"}, new(TestABC2)},
  1232. }
  1233. for _, a := range args {
  1234. var b []byte
  1235. e := NewEncoderBytes(&b, h)
  1236. e.MustEncode(a[0])
  1237. d := NewDecoderBytes(b, h)
  1238. d.MustDecode(a[1])
  1239. if err := deepEqual(a[0], a[1]); err == nil {
  1240. logTv(t, "++++ Objects match")
  1241. } else {
  1242. failT(t, "---- FAIL: Objects do not match: y1: %v, err: %v", a[1], err)
  1243. }
  1244. }
  1245. }
  1246. func doTestEncCircularRef(t *testing.T, h Handle) {
  1247. testOnce.Do(testInitAll)
  1248. type T1 struct {
  1249. S string
  1250. B bool
  1251. T interface{}
  1252. }
  1253. type T2 struct {
  1254. S string
  1255. T *T1
  1256. }
  1257. type T3 struct {
  1258. S string
  1259. T *T2
  1260. }
  1261. t1 := T1{"t1", true, nil}
  1262. t2 := T2{"t2", &t1}
  1263. t3 := T3{"t3", &t2}
  1264. t1.T = &t3
  1265. var bs []byte
  1266. var err error
  1267. bh := basicHandle(h)
  1268. if !bh.CheckCircularRef {
  1269. bh.CheckCircularRef = true
  1270. defer func() { bh.CheckCircularRef = false }()
  1271. }
  1272. err = NewEncoderBytes(&bs, h).Encode(&t3)
  1273. if err == nil {
  1274. failT(t, "expecting error due to circular reference. found none")
  1275. }
  1276. if x := err.Error(); strings.Contains(x, "circular") || strings.Contains(x, "cyclic") {
  1277. logTv(t, "error detected as expected: %v", x)
  1278. } else {
  1279. failT(t, "FAIL: error detected was not as expected: %v", x)
  1280. }
  1281. }
  1282. // TestAnonCycleT{1,2,3} types are used to test anonymous cycles.
  1283. // They are top-level, so that they can have circular references.
  1284. type (
  1285. TestAnonCycleT1 struct {
  1286. S string
  1287. TestAnonCycleT2
  1288. }
  1289. TestAnonCycleT2 struct {
  1290. S2 string
  1291. TestAnonCycleT3
  1292. }
  1293. TestAnonCycleT3 struct {
  1294. *TestAnonCycleT1
  1295. }
  1296. )
  1297. func doTestAnonCycle(t *testing.T, h Handle) {
  1298. testOnce.Do(testInitAll)
  1299. var x TestAnonCycleT1
  1300. x.S = "hello"
  1301. x.TestAnonCycleT2.S2 = "hello.2"
  1302. x.TestAnonCycleT2.TestAnonCycleT3.TestAnonCycleT1 = &x
  1303. // just check that you can get typeInfo for T1
  1304. rt := reflect.TypeOf((*TestAnonCycleT1)(nil)).Elem()
  1305. rtid := rt2id(rt)
  1306. pti := basicHandle(h).getTypeInfo(rtid, rt)
  1307. logTv(t, "[%s] pti: %v", h.Name(), pti)
  1308. }
  1309. func doTestErrWriter(t *testing.T, h Handle) {
  1310. testOnce.Do(testInitAll)
  1311. name := h.Name()
  1312. var ew testErrWriter
  1313. w := bufio.NewWriterSize(&ew, 4)
  1314. enc := NewEncoder(w, h)
  1315. for i := 0; i < 4; i++ {
  1316. err := enc.Encode("ugorji")
  1317. if ev, ok := err.(encodeError); ok {
  1318. err = ev.Cause()
  1319. }
  1320. if err != testErrWriterErr {
  1321. failT(t, "%s: expecting err: %v, received: %v", name, testErrWriterErr, err)
  1322. }
  1323. }
  1324. }
  1325. func doTestJsonLargeInteger(t *testing.T, v interface{}, ias uint8) {
  1326. testOnce.Do(testInitAll)
  1327. logTv(t, "Running doTestJsonLargeInteger: v: %#v, ias: %c", v, ias)
  1328. oldIAS := testJsonH.IntegerAsString
  1329. defer func() { testJsonH.IntegerAsString = oldIAS }()
  1330. testJsonH.IntegerAsString = ias
  1331. var vu uint
  1332. var vi int
  1333. var vb bool
  1334. var b []byte
  1335. e := NewEncoderBytes(&b, testJsonH)
  1336. e.MustEncode(v)
  1337. e.MustEncode(true)
  1338. d := NewDecoderBytes(b, testJsonH)
  1339. // below, we validate that the json string or number was encoded,
  1340. // then decode, and validate that the correct value was decoded.
  1341. fnStrChk := func() {
  1342. // check that output started with ", and ended with " true
  1343. // if !(len(b) >= 7 && b[0] == '"' && string(b[len(b)-7:]) == `" true `) {
  1344. if !(len(b) >= 5 && b[0] == '"' && string(b[len(b)-5:]) == `"true`) {
  1345. failT(t, "Expecting a JSON string, got: '%s'", b)
  1346. }
  1347. }
  1348. switch ias {
  1349. case 'L':
  1350. switch v2 := v.(type) {
  1351. case int:
  1352. v2n := int64(v2) // done to work with 32-bit OS
  1353. if v2n > 1<<53 || (v2n < 0 && -v2n > 1<<53) {
  1354. fnStrChk()
  1355. }
  1356. case uint:
  1357. v2n := uint64(v2) // done to work with 32-bit OS
  1358. if v2n > 1<<53 {
  1359. fnStrChk()
  1360. }
  1361. }
  1362. case 'A':
  1363. fnStrChk()
  1364. default:
  1365. // check that output doesn't contain " at all
  1366. for _, i := range b {
  1367. if i == '"' {
  1368. failT(t, "Expecting a JSON Number without quotation: got: %s", b)
  1369. }
  1370. }
  1371. }
  1372. switch v2 := v.(type) {
  1373. case int:
  1374. d.MustDecode(&vi)
  1375. d.MustDecode(&vb)
  1376. // check that vb = true, and vi == v2
  1377. if !(vb && vi == v2) {
  1378. failT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vi)
  1379. }
  1380. case uint:
  1381. d.MustDecode(&vu)
  1382. d.MustDecode(&vb)
  1383. // check that vb = true, and vi == v2
  1384. if !(vb && vu == v2) {
  1385. failT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vu)
  1386. }
  1387. }
  1388. }
  1389. func doTestRawValue(t *testing.T, h Handle) {
  1390. testOnce.Do(testInitAll)
  1391. bh := basicHandle(h)
  1392. if !bh.Raw {
  1393. bh.Raw = true
  1394. defer func() { bh.Raw = false }()
  1395. }
  1396. var i, i2 int
  1397. var v, v2 TestRawValue
  1398. var bs, bs2 []byte
  1399. i = 1234 //1234567890
  1400. v = TestRawValue{I: i}
  1401. e := NewEncoderBytes(&bs, h)
  1402. e.MustEncode(v.I)
  1403. logTv(t, ">>> raw: %v\n", bs)
  1404. v.R = Raw(bs)
  1405. e.ResetBytes(&bs2)
  1406. e.MustEncode(v)
  1407. logTv(t, ">>> bs2: %v\n", bs2)
  1408. d := NewDecoderBytes(bs2, h)
  1409. d.MustDecode(&v2)
  1410. d.ResetBytes(v2.R)
  1411. logTv(t, ">>> v2.R: %v\n", ([]byte)(v2.R))
  1412. d.MustDecode(&i2)
  1413. logTv(t, ">>> Encoded %v, decoded %v\n", i, i2)
  1414. // logT(t, "Encoded %v, decoded %v", i, i2)
  1415. if i != i2 {
  1416. failT(t, "Error: encoded %v, decoded %v", i, i2)
  1417. }
  1418. }
  1419. // Comprehensive testing that generates data encoded from python handle (cbor, msgpack),
  1420. // and validates that our code can read and write it out accordingly.
  1421. // We keep this unexported here, and put actual test in ext_dep_test.go.
  1422. // This way, it can be excluded by excluding file completely.
  1423. func doTestPythonGenStreams(t *testing.T, h Handle) {
  1424. testOnce.Do(testInitAll)
  1425. name := h.Name()
  1426. logT(t, "TestPythonGenStreams-%v", name)
  1427. tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test")
  1428. if err != nil {
  1429. failT(t, "-------- Unable to create temp directory\n")
  1430. }
  1431. defer os.RemoveAll(tmpdir)
  1432. logTv(t, "tmpdir: %v", tmpdir)
  1433. cmd := exec.Command("python", "test.py", "testdata", tmpdir)
  1434. //cmd.Stdin = strings.NewReader("some input")
  1435. //cmd.Stdout = &out
  1436. var cmdout []byte
  1437. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1438. logT(t, "-------- Error running test.py testdata. Err: %v", err)
  1439. logT(t, " %v", string(cmdout))
  1440. failT(t)
  1441. }
  1442. bh := basicHandle(h)
  1443. oldMapType := bh.MapType
  1444. tablePythonVerify := testTableVerify(testVerifyForPython|testVerifyTimeAsInteger|testVerifyMapTypeStrIntf, h)
  1445. for i, v := range tablePythonVerify {
  1446. // if v == uint64(0) && h == testMsgpackH {
  1447. // v = int64(0)
  1448. // }
  1449. bh.MapType = oldMapType
  1450. //load up the golden file based on number
  1451. //decode it
  1452. //compare to in-mem object
  1453. //encode it again
  1454. //compare to output stream
  1455. logTv(t, "..............................................")
  1456. logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
  1457. var bss []byte
  1458. bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden"))
  1459. if err != nil {
  1460. failT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
  1461. continue
  1462. }
  1463. bh.MapType = testMapStrIntfTyp
  1464. var v1 interface{}
  1465. if err = testUnmarshal(&v1, bss, h); err != nil {
  1466. failT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
  1467. continue
  1468. }
  1469. if v == skipVerifyVal {
  1470. continue
  1471. }
  1472. //no need to indirect, because we pass a nil ptr, so we already have the value
  1473. //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
  1474. if err = deepEqual(v, v1); err == nil {
  1475. logTv(t, "++++++++ Objects match: %T, %v", v, v)
  1476. } else {
  1477. logT(t, "-------- FAIL: Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
  1478. logTv(t, "-------- GOLDEN: %#v", v)
  1479. // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1480. logTv(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1481. failT(t)
  1482. }
  1483. bsb, err := testMarshal(v1, h)
  1484. if err != nil {
  1485. failT(t, "Error encoding to stream: %d: Err: %v", i, err)
  1486. continue
  1487. }
  1488. if err = deepEqual(bsb, bss); err == nil {
  1489. logTv(t, "++++++++ Bytes match")
  1490. } else {
  1491. logT(t, "???????? FAIL: Bytes do not match. %v.", err)
  1492. xs := "--------"
  1493. if reflect.ValueOf(v).Kind() == reflect.Map {
  1494. xs = " "
  1495. logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
  1496. } else {
  1497. failT(t, "%s It's not a map. They should match.", xs)
  1498. }
  1499. logTv(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
  1500. logTv(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
  1501. }
  1502. }
  1503. bh.MapType = oldMapType
  1504. }
  1505. // To test MsgpackSpecRpc, we test 3 scenarios:
  1506. // - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
  1507. // - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
  1508. // - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
  1509. //
  1510. // This allows us test the different calling conventions
  1511. // - Go Service requires only one argument
  1512. // - Python Service allows multiple arguments
  1513. func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
  1514. if testSkipRPCTests {
  1515. return
  1516. }
  1517. testOnce.Do(testInitAll)
  1518. // openPorts are between 6700 and 6800
  1519. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  1520. openPort := strconv.FormatInt(6700+r.Int63n(99), 10)
  1521. // openPort := "6792"
  1522. cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4")
  1523. checkErrT(t, cmd.Start())
  1524. bs, err2 := net.Dial("tcp", ":"+openPort)
  1525. for i := 0; i < 10 && err2 != nil; i++ {
  1526. time.Sleep(50 * time.Millisecond) // time for python rpc server to start
  1527. bs, err2 = net.Dial("tcp", ":"+openPort)
  1528. }
  1529. checkErrT(t, err2)
  1530. cc := MsgpackSpecRpc.ClientCodec(testReadWriteCloser(bs), testMsgpackH)
  1531. cl := rpc.NewClientWithCodec(cc)
  1532. defer cl.Close()
  1533. var rstr string
  1534. checkErrT(t, cl.Call("EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1535. //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
  1536. var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
  1537. checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
  1538. checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
  1539. cmd.Process.Kill()
  1540. }
  1541. func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
  1542. if testSkipRPCTests {
  1543. return
  1544. }
  1545. testOnce.Do(testInitAll)
  1546. port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
  1547. //time.Sleep(1000 * time.Millisecond)
  1548. cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port))
  1549. var cmdout []byte
  1550. var err error
  1551. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1552. logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err)
  1553. logT(t, " %v", string(cmdout))
  1554. failT(t)
  1555. }
  1556. checkEqualT(t, string(cmdout),
  1557. fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestRpcABC{"Aa", "Bb", "Cc"}), "cmdout=")
  1558. }
  1559. func doTestSwallowAndZero(t *testing.T, h Handle) {
  1560. testOnce.Do(testInitAll)
  1561. v1 := newTestStrucFlex(testDepth, testNumRepeatString, false, false, testMapStringKeyOnly)
  1562. var b1 []byte
  1563. e1 := NewEncoderBytes(&b1, h)
  1564. e1.MustEncode(v1)
  1565. d1 := NewDecoderBytes(b1, h)
  1566. d1.swallow()
  1567. if d1.r().numread() != uint(len(b1)) {
  1568. failT(t, "swallow didn't consume all encoded bytes: %v out of %v", d1.r().numread(), len(b1))
  1569. }
  1570. setZero(v1)
  1571. testDeepEqualErr(v1, &TestStrucFlex{}, t, "filled-and-zeroed")
  1572. }
  1573. func doTestRawExt(t *testing.T, h Handle) {
  1574. testOnce.Do(testInitAll)
  1575. var b []byte
  1576. var v RawExt // interface{}
  1577. _, isJson := h.(*JsonHandle)
  1578. _, isCbor := h.(*CborHandle)
  1579. bh := basicHandle(h)
  1580. // isValuer := isJson || isCbor
  1581. // _ = isValuer
  1582. for _, r := range []RawExt{
  1583. {Tag: 99, Value: "9999", Data: []byte("9999")},
  1584. } {
  1585. e := NewEncoderBytes(&b, h)
  1586. e.MustEncode(&r)
  1587. // fmt.Printf(">>>> rawext: isnil? %v, %d - %v\n", b == nil, len(b), b)
  1588. d := NewDecoderBytes(b, h)
  1589. d.MustDecode(&v)
  1590. var r2 = r
  1591. switch {
  1592. case isJson:
  1593. r2.Tag = 0
  1594. r2.Data = nil
  1595. case isCbor:
  1596. r2.Data = nil
  1597. default:
  1598. r2.Value = nil
  1599. }
  1600. testDeepEqualErr(v, r2, t, "rawext-default")
  1601. // switch h.(type) {
  1602. // case *JsonHandle:
  1603. // testDeepEqualErr(r.Value, v, t, "rawext-json")
  1604. // default:
  1605. // var r2 = r
  1606. // if isValuer {
  1607. // r2.Data = nil
  1608. // } else {
  1609. // r2.Value = nil
  1610. // }
  1611. // testDeepEqualErr(v, r2, t, "rawext-default")
  1612. // }
  1613. }
  1614. // Add testing for Raw also
  1615. if b != nil {
  1616. b = b[:0]
  1617. }
  1618. oldRawMode := bh.Raw
  1619. defer func() { bh.Raw = oldRawMode }()
  1620. bh.Raw = true
  1621. var v2 Raw
  1622. for _, s := range []string{
  1623. "goodbye",
  1624. "hello",
  1625. } {
  1626. e := NewEncoderBytes(&b, h)
  1627. e.MustEncode(&s)
  1628. // fmt.Printf(">>>> rawext: isnil? %v, %d - %v\n", b == nil, len(b), b)
  1629. var r Raw = make([]byte, len(b))
  1630. copy(r, b)
  1631. d := NewDecoderBytes(b, h)
  1632. d.MustDecode(&v2)
  1633. testDeepEqualErr(v2, r, t, "raw-default")
  1634. }
  1635. }
  1636. // func doTestTimeExt(t *testing.T, h Handle) {
  1637. // var t = time.Now()
  1638. // // add time ext to the handle
  1639. // }
  1640. func doTestMapStructKey(t *testing.T, h Handle) {
  1641. testOnce.Do(testInitAll)
  1642. var b []byte
  1643. var v interface{} // map[stringUint64T]wrapUint64Slice // interface{}
  1644. bh := basicHandle(h)
  1645. m := map[stringUint64T]wrapUint64Slice{
  1646. {"55555", 55555}: []wrapUint64{12345},
  1647. {"333", 333}: []wrapUint64{123},
  1648. }
  1649. oldCanonical := bh.Canonical
  1650. oldMapType := bh.MapType
  1651. defer func() {
  1652. bh.Canonical = oldCanonical
  1653. bh.MapType = oldMapType
  1654. }()
  1655. bh.MapType = reflect.TypeOf((*map[stringUint64T]wrapUint64Slice)(nil)).Elem()
  1656. for _, bv := range [2]bool{true, false} {
  1657. b, v = nil, nil
  1658. bh.Canonical = bv
  1659. e := NewEncoderBytes(&b, h)
  1660. e.MustEncode(m)
  1661. d := NewDecoderBytes(b, h)
  1662. d.MustDecode(&v)
  1663. testDeepEqualErr(v, m, t, "map-structkey")
  1664. }
  1665. }
  1666. func doTestDecodeNilMapValue(t *testing.T, h Handle) {
  1667. testOnce.Do(testInitAll)
  1668. type Struct struct {
  1669. Field map[uint16]map[uint32]struct{}
  1670. }
  1671. bh := basicHandle(h)
  1672. oldMapType := bh.MapType
  1673. oldDeleteOnNilMapValue := bh.DeleteOnNilMapValue
  1674. defer func() {
  1675. bh.MapType = oldMapType
  1676. bh.DeleteOnNilMapValue = oldDeleteOnNilMapValue
  1677. }()
  1678. bh.MapType = reflect.TypeOf(map[interface{}]interface{}(nil))
  1679. bh.DeleteOnNilMapValue = false
  1680. _, isJsonHandle := h.(*JsonHandle)
  1681. toEncode := Struct{Field: map[uint16]map[uint32]struct{}{
  1682. 1: nil,
  1683. }}
  1684. bs, err := testMarshal(toEncode, h)
  1685. if err != nil {
  1686. failT(t, "Error encoding: %v, Err: %v", toEncode, err)
  1687. }
  1688. if isJsonHandle {
  1689. logT(t, "json encoded: %s\n", bs)
  1690. }
  1691. var decoded Struct
  1692. err = testUnmarshal(&decoded, bs, h)
  1693. if err != nil {
  1694. failT(t, "Error decoding: %v", err)
  1695. }
  1696. if !reflect.DeepEqual(decoded, toEncode) {
  1697. failT(t, "Decoded value %#v != %#v", decoded, toEncode)
  1698. }
  1699. }
  1700. func doTestEmbeddedFieldPrecedence(t *testing.T, h Handle) {
  1701. testOnce.Do(testInitAll)
  1702. type Embedded struct {
  1703. Field byte
  1704. }
  1705. type Struct struct {
  1706. Field byte
  1707. Embedded
  1708. }
  1709. toEncode := Struct{
  1710. Field: 1,
  1711. Embedded: Embedded{Field: 2},
  1712. }
  1713. _, isJsonHandle := h.(*JsonHandle)
  1714. handle := basicHandle(h)
  1715. oldMapType := handle.MapType
  1716. defer func() { handle.MapType = oldMapType }()
  1717. handle.MapType = reflect.TypeOf(map[interface{}]interface{}(nil))
  1718. bs, err := testMarshal(toEncode, h)
  1719. if err != nil {
  1720. failT(t, "Error encoding: %v, Err: %v", toEncode, err)
  1721. }
  1722. var decoded Struct
  1723. err = testUnmarshal(&decoded, bs, h)
  1724. if err != nil {
  1725. failT(t, "Error decoding: %v", err)
  1726. }
  1727. if decoded.Field != toEncode.Field {
  1728. logT(t, "Decoded result %v != %v", decoded.Field, toEncode.Field) // hex to look at what was encoded
  1729. if isJsonHandle {
  1730. logT(t, "JSON encoded as: %s", bs) // hex to look at what was encoded
  1731. }
  1732. failT(t)
  1733. }
  1734. }
  1735. func doTestLargeContainerLen(t *testing.T, h Handle) {
  1736. testOnce.Do(testInitAll)
  1737. m := make(map[int][]struct{})
  1738. for i := range []int{
  1739. 0, 1,
  1740. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1741. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1742. math.MaxInt32, math.MaxInt32 - 4,
  1743. // math.MaxInt32 + 4, // bombs on 32-bit
  1744. // math.MaxInt64, math.MaxInt64 - 4, // bombs on 32-bit
  1745. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1746. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1747. // math.MaxUint32, math.MaxUint32 + 4, math.MaxUint32 - 4, // bombs on 32-bit
  1748. } {
  1749. m[i] = make([]struct{}, i)
  1750. }
  1751. bs := testMarshalErr(m, h, t, "-")
  1752. var m2 = make(map[int][]struct{})
  1753. testUnmarshalErr(m2, bs, h, t, "-")
  1754. testDeepEqualErr(m, m2, t, "-")
  1755. // do same tests for large strings (encoded as symbols or not)
  1756. // skip if 32-bit or not using unsafe mode
  1757. if safeMode || (32<<(^uint(0)>>63)) < 64 {
  1758. return
  1759. }
  1760. // now, want to do tests for large strings, which
  1761. // could be encoded as symbols.
  1762. // to do this, we create a simple one-field struct,
  1763. // use use flags to switch from symbols to non-symbols
  1764. hbinc, okbinc := h.(*BincHandle)
  1765. if okbinc {
  1766. oldAsSymbols := hbinc.AsSymbols
  1767. defer func() { hbinc.AsSymbols = oldAsSymbols }()
  1768. }
  1769. var out []byte = make([]byte, 0, math.MaxUint16*3/2)
  1770. var in []byte = make([]byte, math.MaxUint16*3/2)
  1771. for i := range in {
  1772. in[i] = 'A'
  1773. }
  1774. e := NewEncoder(nil, h)
  1775. for _, i := range []int{
  1776. 0, 1, 4, 8, 12, 16, 28, 32, 36,
  1777. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1778. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1779. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1780. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1781. } {
  1782. var m1, m2 map[string]bool
  1783. m1 = make(map[string]bool, 1)
  1784. var s1 = stringView(in[:i])
  1785. // fmt.Printf("testcontainerlen: large string: i: %v, |%s|\n", i, s1)
  1786. m1[s1] = true
  1787. if okbinc {
  1788. hbinc.AsSymbols = 2
  1789. }
  1790. out = out[:0]
  1791. e.ResetBytes(&out)
  1792. e.MustEncode(m1)
  1793. // bs, _ = testMarshalErr(m1, h, t, "-")
  1794. m2 = make(map[string]bool, 1)
  1795. testUnmarshalErr(m2, out, h, t, "no-symbols")
  1796. testDeepEqualErr(m1, m2, t, "no-symbols")
  1797. if okbinc {
  1798. // now, do as symbols
  1799. hbinc.AsSymbols = 1
  1800. out = out[:0]
  1801. e.ResetBytes(&out)
  1802. e.MustEncode(m1)
  1803. // bs, _ = testMarshalErr(m1, h, t, "-")
  1804. m2 = make(map[string]bool, 1)
  1805. testUnmarshalErr(m2, out, h, t, "symbols")
  1806. testDeepEqualErr(m1, m2, t, "symbols")
  1807. }
  1808. }
  1809. }
  1810. func testRandomFillRV(v reflect.Value) {
  1811. testOnce.Do(testInitAll)
  1812. fneg := func() int64 {
  1813. i := rand.Intn(1)
  1814. if i == 1 {
  1815. return 1
  1816. }
  1817. return -1
  1818. }
  1819. switch v.Kind() {
  1820. case reflect.Invalid:
  1821. case reflect.Ptr:
  1822. if v.IsNil() {
  1823. v.Set(reflect.New(v.Type().Elem()))
  1824. }
  1825. testRandomFillRV(v.Elem())
  1826. case reflect.Interface:
  1827. if v.IsNil() {
  1828. v.Set(reflect.ValueOf("nothing"))
  1829. } else {
  1830. testRandomFillRV(v.Elem())
  1831. }
  1832. case reflect.Struct:
  1833. for i, n := 0, v.NumField(); i < n; i++ {
  1834. testRandomFillRV(v.Field(i))
  1835. }
  1836. case reflect.Slice:
  1837. if v.IsNil() {
  1838. v.Set(reflect.MakeSlice(v.Type(), 4, 4))
  1839. }
  1840. fallthrough
  1841. case reflect.Array:
  1842. for i, n := 0, v.Len(); i < n; i++ {
  1843. testRandomFillRV(v.Index(i))
  1844. }
  1845. case reflect.Map:
  1846. if v.IsNil() {
  1847. v.Set(reflect.MakeMap(v.Type()))
  1848. }
  1849. if v.Len() == 0 {
  1850. kt, vt := v.Type().Key(), v.Type().Elem()
  1851. for i := 0; i < 4; i++ {
  1852. k0 := reflect.New(kt).Elem()
  1853. v0 := reflect.New(vt).Elem()
  1854. testRandomFillRV(k0)
  1855. testRandomFillRV(v0)
  1856. v.SetMapIndex(k0, v0)
  1857. }
  1858. } else {
  1859. for _, k := range v.MapKeys() {
  1860. testRandomFillRV(v.MapIndex(k))
  1861. }
  1862. }
  1863. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1864. v.SetInt(fneg() * rand.Int63n(127))
  1865. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1866. v.SetUint(uint64(rand.Int63n(255)))
  1867. case reflect.Bool:
  1868. v.SetBool(fneg() == 1)
  1869. case reflect.Float32, reflect.Float64:
  1870. v.SetFloat(float64(fneg()) * float64(rand.Float32()))
  1871. case reflect.String:
  1872. // ensure this string can test the extent of json string decoding
  1873. v.SetString(strings.Repeat(strconv.FormatInt(rand.Int63n(99), 10), rand.Intn(8)) +
  1874. "- ABC \x41=\x42 \u2318 - \r \b \f - \u2028 and \u2029 .")
  1875. default:
  1876. panic(fmt.Errorf("testRandomFillRV: unsupported type: %v", v.Kind()))
  1877. }
  1878. }
  1879. func testMammoth(t *testing.T, h Handle) {
  1880. testOnce.Do(testInitAll)
  1881. name := h.Name()
  1882. var b []byte
  1883. var m, m2 TestMammoth
  1884. testRandomFillRV(reflect.ValueOf(&m).Elem())
  1885. b = testMarshalErr(&m, h, t, "mammoth-"+name)
  1886. // xdebugf("%s", b)
  1887. testUnmarshalErr(&m2, b, h, t, "mammoth-"+name)
  1888. testDeepEqualErr(&m, &m2, t, "mammoth-"+name)
  1889. var mm, mm2 TestMammoth2Wrapper
  1890. testRandomFillRV(reflect.ValueOf(&mm).Elem())
  1891. b = testMarshalErr(&mm, h, t, "mammoth2-"+name)
  1892. // os.Stderr.Write([]byte("\n\n\n\n" + string(b) + "\n\n\n\n"))
  1893. testUnmarshalErr(&mm2, b, h, t, "mammoth2-"+name)
  1894. testDeepEqualErr(&mm, &mm2, t, "mammoth2-"+name)
  1895. // testMammoth2(t, name, h)
  1896. }
  1897. func testTime(t *testing.T, h Handle) {
  1898. testOnce.Do(testInitAll)
  1899. name := h.Name()
  1900. // test time which uses the time.go implementation (ie Binc)
  1901. var tt, tt2 time.Time
  1902. // time in 1990
  1903. tt = time.Unix(20*366*24*60*60, 1000*900).In(time.FixedZone("UGO", -5*60*60))
  1904. // fmt.Printf("time tt: %v\n", tt)
  1905. b := testMarshalErr(tt, h, t, "time-"+name)
  1906. testUnmarshalErr(&tt2, b, h, t, "time-"+name)
  1907. // per go documentation, test time with .Equal not ==
  1908. if !tt2.Equal(tt) {
  1909. failT(t, "%s: values not equal: 1: %v, 2: %v", name, tt2, tt)
  1910. }
  1911. // testDeepEqualErr(tt.UTC(), tt2, t, "time-"+name)
  1912. }
  1913. func testUintToInt(t *testing.T, h Handle) {
  1914. testOnce.Do(testInitAll)
  1915. name := h.Name()
  1916. var golden = [...]int64{
  1917. 0, 1, 22, 333, 4444, 55555, 666666,
  1918. // msgpack ones
  1919. 24, 128,
  1920. // standard ones
  1921. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1922. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1923. math.MaxUint32, math.MaxUint32 + 4, math.MaxUint32 - 4,
  1924. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1925. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1926. math.MaxInt32, math.MaxInt32 + 4, math.MaxInt32 - 4,
  1927. math.MaxInt64, math.MaxInt64 - 4,
  1928. }
  1929. var ui uint64
  1930. var fi float64
  1931. var b []byte
  1932. for _, i := range golden {
  1933. ui = 0
  1934. b = testMarshalErr(i, h, t, "int2uint-"+name)
  1935. testUnmarshalErr(&ui, b, h, t, "int2uint-"+name)
  1936. if ui != uint64(i) {
  1937. failT(t, "%s: values not equal: %v, %v", name, ui, uint64(i))
  1938. }
  1939. i = 0
  1940. b = testMarshalErr(ui, h, t, "uint2int-"+name)
  1941. testUnmarshalErr(&i, b, h, t, "uint2int-"+name)
  1942. if i != int64(ui) {
  1943. failT(t, "%s: values not equal: %v, %v", name, i, int64(ui))
  1944. }
  1945. fi = 0
  1946. b = testMarshalErr(i, h, t, "int2float-"+name)
  1947. testUnmarshalErr(&fi, b, h, t, "int2float-"+name)
  1948. if fi != float64(i) {
  1949. failT(t, "%s: values not equal: %v, %v", name, fi, float64(i))
  1950. }
  1951. }
  1952. }
  1953. func doTestDifferentMapOrSliceType(t *testing.T, h Handle) {
  1954. testOnce.Do(testInitAll)
  1955. name := h.Name()
  1956. // - maptype, slicetype: diff from map[string]intf, map[intf]intf or []intf, etc
  1957. // include map[interface{}]string where some keys are []byte.
  1958. // To test, take a sequence of []byte and string, and decode into []string and []interface.
  1959. // Also, decode into map[string]string, map[string]interface{}, map[interface{}]string
  1960. bh := basicHandle(h)
  1961. oldM, oldS := bh.MapType, bh.SliceType
  1962. defer func() { bh.MapType, bh.SliceType = oldM, oldS }()
  1963. var b []byte
  1964. var vi = []interface{}{
  1965. "hello 1",
  1966. []byte("hello 2"),
  1967. "hello 3",
  1968. []byte("hello 4"),
  1969. "hello 5",
  1970. }
  1971. var vs []string
  1972. var v2i, v2s testMbsT
  1973. var v2ss testMbsCustStrT
  1974. // encode it as a map or as a slice
  1975. for i, v := range vi {
  1976. vv, ok := v.(string)
  1977. if !ok {
  1978. vv = string(v.([]byte))
  1979. }
  1980. vs = append(vs, vv)
  1981. v2i = append(v2i, v, strconv.FormatInt(int64(i+1), 10))
  1982. v2s = append(v2s, vv, strconv.FormatInt(int64(i+1), 10))
  1983. v2ss = append(v2ss, testCustomStringT(vv), testCustomStringT(strconv.FormatInt(int64(i+1), 10)))
  1984. }
  1985. var v2d interface{}
  1986. // encode vs as a list, and decode into a list and compare
  1987. var goldSliceS = []string{"hello 1", "hello 2", "hello 3", "hello 4", "hello 5"}
  1988. var goldSliceI = []interface{}{"hello 1", "hello 2", "hello 3", "hello 4", "hello 5"}
  1989. var goldSlice = []interface{}{goldSliceS, goldSliceI}
  1990. for j, g := range goldSlice {
  1991. bh.SliceType = reflect.TypeOf(g)
  1992. name := fmt.Sprintf("slice-%s-%v", name, j+1)
  1993. b = testMarshalErr(vs, h, t, name)
  1994. v2d = nil
  1995. // v2d = reflect.New(bh.SliceType).Elem().Interface()
  1996. testUnmarshalErr(&v2d, b, h, t, name)
  1997. testDeepEqualErr(v2d, goldSlice[j], t, name)
  1998. }
  1999. // to ensure that we do not use fast-path for map[intf]string, use a custom string type (for goldMapIS).
  2000. // this will allow us to test out the path that sees a []byte where a map has an interface{} type,
  2001. // and convert it to a string for the decoded map key.
  2002. // encode v2i as a map, and decode into a map and compare
  2003. var goldMapSS = map[string]string{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  2004. var goldMapSI = map[string]interface{}{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  2005. var goldMapIS = map[interface{}]testCustomStringT{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  2006. var goldMap = []interface{}{goldMapSS, goldMapSI, goldMapIS}
  2007. for j, g := range goldMap {
  2008. bh.MapType = reflect.TypeOf(g)
  2009. name := fmt.Sprintf("map-%s-%v", name, j+1)
  2010. // for formats that clearly differentiate binary from string, use v2i
  2011. // else use the v2s (with all strings, no []byte)
  2012. v2d = nil
  2013. // v2d = reflect.New(bh.MapType).Elem().Interface()
  2014. switch h.(type) {
  2015. case *MsgpackHandle, *BincHandle, *CborHandle:
  2016. b = testMarshalErr(v2i, h, t, name)
  2017. testUnmarshalErr(&v2d, b, h, t, name)
  2018. testDeepEqualErr(v2d, goldMap[j], t, name)
  2019. default:
  2020. b = testMarshalErr(v2s, h, t, name)
  2021. testUnmarshalErr(&v2d, b, h, t, name)
  2022. testDeepEqualErr(v2d, goldMap[j], t, name)
  2023. b = testMarshalErr(v2ss, h, t, name)
  2024. v2d = nil
  2025. testUnmarshalErr(&v2d, b, h, t, name)
  2026. testDeepEqualErr(v2d, goldMap[j], t, name)
  2027. }
  2028. }
  2029. }
  2030. func doTestScalars(t *testing.T, h Handle) {
  2031. testOnce.Do(testInitAll)
  2032. // for each scalar:
  2033. // - encode its ptr
  2034. // - encode it (non-ptr)
  2035. // - check that bytes are same
  2036. // - make a copy (using reflect)
  2037. // - check that same
  2038. // - set zero on it
  2039. // - check that its equal to 0 value
  2040. // - decode into new
  2041. // - compare to original
  2042. bh := basicHandle(h)
  2043. if !bh.Canonical {
  2044. bh.Canonical = true
  2045. defer func() { bh.Canonical = false }()
  2046. }
  2047. vi := []interface{}{
  2048. int(0),
  2049. int8(0),
  2050. int16(0),
  2051. int32(0),
  2052. int64(0),
  2053. uint(0),
  2054. uint8(0),
  2055. uint16(0),
  2056. uint32(0),
  2057. uint64(0),
  2058. uintptr(0),
  2059. float32(0),
  2060. float64(0),
  2061. bool(false),
  2062. string(""),
  2063. []byte(nil),
  2064. }
  2065. for _, v := range fastpathAV {
  2066. vi = append(vi, reflect.Zero(v.rt).Interface())
  2067. }
  2068. for _, v := range vi {
  2069. rv := reflect.New(reflect.TypeOf(v)).Elem()
  2070. testRandomFillRV(rv)
  2071. v = rv.Interface()
  2072. rv2 := reflect.New(rv.Type())
  2073. rv2.Elem().Set(rv)
  2074. vp := rv2.Interface()
  2075. var tname string
  2076. switch rv.Kind() {
  2077. case reflect.Map:
  2078. tname = "map[" + rv.Type().Key().Name() + "]" + rv.Type().Elem().Name()
  2079. case reflect.Slice:
  2080. tname = "[]" + rv.Type().Elem().Name()
  2081. default:
  2082. tname = rv.Type().Name()
  2083. }
  2084. var b, b1, b2 []byte
  2085. b1 = testMarshalErr(v, h, t, tname+"-enc")
  2086. // store b1 into b, as b1 slice is reused for next marshal
  2087. b = make([]byte, len(b1))
  2088. copy(b, b1)
  2089. b2 = testMarshalErr(vp, h, t, tname+"-enc-ptr")
  2090. testDeepEqualErr(b1, b2, t, tname+"-enc-eq")
  2091. setZero(vp)
  2092. testDeepEqualErr(rv2.Elem().Interface(), reflect.Zero(rv.Type()).Interface(), t, tname+"-enc-eq-zero-ref")
  2093. vp = rv2.Interface()
  2094. testUnmarshalErr(vp, b, h, t, tname+"-dec")
  2095. testDeepEqualErr(rv2.Elem().Interface(), v, t, tname+"-dec-eq")
  2096. }
  2097. }
  2098. func doTestIntfMapping(t *testing.T, h Handle) {
  2099. testOnce.Do(testInitAll)
  2100. name := h.Name()
  2101. rti := reflect.TypeOf((*testIntfMapI)(nil)).Elem()
  2102. defer func() { basicHandle(h).Intf2Impl(rti, nil) }()
  2103. type T9 struct {
  2104. I testIntfMapI
  2105. }
  2106. for i, v := range []testIntfMapI{
  2107. // Use a valid string to test some extents of json string decoding
  2108. &testIntfMapT1{"ABC \x41=\x42 \u2318 - \r \b \f - \u2028 and \u2029 ."},
  2109. testIntfMapT2{"DEF"},
  2110. } {
  2111. if err := basicHandle(h).Intf2Impl(rti, reflect.TypeOf(v)); err != nil {
  2112. failT(t, "Error mapping %v to %T", rti, v)
  2113. }
  2114. var v1, v2 T9
  2115. v1 = T9{v}
  2116. b := testMarshalErr(v1, h, t, name+"-enc-"+strconv.Itoa(i))
  2117. testUnmarshalErr(&v2, b, h, t, name+"-dec-"+strconv.Itoa(i))
  2118. testDeepEqualErr(v1, v2, t, name+"-dec-eq-"+strconv.Itoa(i))
  2119. }
  2120. }
  2121. func doTestOmitempty(t *testing.T, h Handle) {
  2122. testOnce.Do(testInitAll)
  2123. name := h.Name()
  2124. if basicHandle(h).StructToArray {
  2125. t.Skipf("Skipping OmitEmpty test when StructToArray=true")
  2126. }
  2127. type T1 struct {
  2128. A int `codec:"a"`
  2129. B *int `codec:"b,omitempty"`
  2130. C int `codec:"c,omitempty"`
  2131. }
  2132. type T2 struct {
  2133. A int `codec:"a"`
  2134. }
  2135. var v1 T1
  2136. var v2 T2
  2137. b1 := testMarshalErr(v1, h, t, name+"-omitempty")
  2138. b2 := testMarshalErr(v2, h, t, name+"-no-omitempty-trunc")
  2139. testDeepEqualErr(b1, b2, t, name+"-omitempty-cmp")
  2140. }
  2141. func doTestMissingFields(t *testing.T, h Handle) {
  2142. testOnce.Do(testInitAll)
  2143. name := h.Name()
  2144. if codecgen {
  2145. t.Skipf("Skipping Missing Fields tests as it is not honored by codecgen")
  2146. }
  2147. if basicHandle(h).StructToArray {
  2148. t.Skipf("Skipping Missing Fields test when StructToArray=true")
  2149. }
  2150. // encode missingFielderT2, decode into missingFielderT1, encode it out again, decode into new missingFielderT2, compare
  2151. v1 := missingFielderT2{S: "true seven eight", B: true, F: 777.0, I: -888}
  2152. b1 := testMarshalErr(v1, h, t, name+"-missing-enc-2")
  2153. // xdebugf("marshal into b1: %s", b1)
  2154. var v2 missingFielderT1
  2155. testUnmarshalErr(&v2, b1, h, t, name+"-missing-dec-1")
  2156. // xdebugf("unmarshal into v2: %v", v2)
  2157. b2 := testMarshalErr(&v2, h, t, name+"-missing-enc-1")
  2158. // xdebugf("marshal into b2: %s", b2)
  2159. var v3 missingFielderT2
  2160. testUnmarshalErr(&v3, b2, h, t, name+"-missing-dec-2")
  2161. // xdebugf("unmarshal into v3: %v", v3)
  2162. testDeepEqualErr(v1, v3, t, name+"-missing-cmp-2")
  2163. }
  2164. func doTestMaxDepth(t *testing.T, h Handle) {
  2165. testOnce.Do(testInitAll)
  2166. name := h.Name()
  2167. type T struct {
  2168. I interface{} // value to encode
  2169. M int16 // maxdepth
  2170. S bool // use swallow (decode into typed struct with only A1)
  2171. E interface{} // error to find
  2172. }
  2173. type T1 struct {
  2174. A1 *T1
  2175. }
  2176. var table []T
  2177. var sfunc = func(n int) (s [1]interface{}, s1 *[1]interface{}) {
  2178. s1 = &s
  2179. for i := 0; i < n; i++ {
  2180. var s0 [1]interface{}
  2181. s1[0] = &s0
  2182. s1 = &s0
  2183. }
  2184. // xdebugf("sfunc s: %v", s)
  2185. return
  2186. // var s []interface{}
  2187. // s = append(s, []interface{})
  2188. // s[0] = append(s[0], []interface{})
  2189. // s[0][0] = append(s[0][0], []interface{})
  2190. // s[0][0][0] = append(s[0][0][0], []interface{})
  2191. // s[0][0][0][0] = append(s[0][0][0][0], []interface{})
  2192. // return s
  2193. }
  2194. var mfunc = func(n int) (m map[string]interface{}, mlast map[string]interface{}) {
  2195. m = make(map[string]interface{})
  2196. mlast = make(map[string]interface{})
  2197. m["A0"] = mlast
  2198. for i := 1; i < n; i++ {
  2199. m0 := make(map[string]interface{})
  2200. mlast["A"+strconv.FormatInt(int64(i), 10)] = m0
  2201. mlast = m0
  2202. }
  2203. // xdebugf("mfunc m: %v", m)
  2204. return
  2205. }
  2206. s, s1 := sfunc(5)
  2207. m, _ := mfunc(5)
  2208. m99, _ := mfunc(99)
  2209. s1[0] = m
  2210. table = append(table, T{s, 0, false, nil})
  2211. table = append(table, T{s, 256, false, nil})
  2212. table = append(table, T{s, 7, false, errMaxDepthExceeded})
  2213. table = append(table, T{s, 15, false, nil})
  2214. table = append(table, T{m99, 15, true, errMaxDepthExceeded})
  2215. table = append(table, T{m99, 215, true, nil})
  2216. defer func(n int16, b bool) {
  2217. basicHandle(h).MaxDepth = n
  2218. testUseMust = b
  2219. }(basicHandle(h).MaxDepth, testUseMust)
  2220. testUseMust = false
  2221. for i, v := range table {
  2222. basicHandle(h).MaxDepth = v.M
  2223. b1 := testMarshalErr(v.I, h, t, name+"-maxdepth-enc"+strconv.FormatInt(int64(i), 10))
  2224. // xdebugf("b1: %s", b1)
  2225. var err error
  2226. if v.S {
  2227. var v2 T1
  2228. err = testUnmarshal(&v2, b1, h)
  2229. } else {
  2230. var v2 interface{}
  2231. err = testUnmarshal(&v2, b1, h)
  2232. }
  2233. if err1, ok := err.(decodeError); ok {
  2234. err = err1.codecError
  2235. }
  2236. var err0 interface{} = err
  2237. if err1, ok := err.(codecError); ok {
  2238. err0 = err1.err
  2239. }
  2240. if err0 != v.E {
  2241. failT(t, "Unexpected error testing max depth for depth %d: expected %v, received %v", v.M, v.E, err)
  2242. }
  2243. // decode into something that just triggers swallow
  2244. }
  2245. }
  2246. func doTestMultipleEncDec(t *testing.T, h Handle) {
  2247. testOnce.Do(testInitAll)
  2248. name := h.Name()
  2249. // encode a string multiple times.
  2250. // decode it multiple times.
  2251. // ensure we get the value each time
  2252. var s1 = "ugorji"
  2253. var s2 = "nwoke"
  2254. var s11, s21 string
  2255. var buf bytes.Buffer
  2256. e := NewEncoder(&buf, h)
  2257. e.MustEncode(s1)
  2258. e.MustEncode(s2)
  2259. d := NewDecoder(&buf, h)
  2260. d.MustDecode(&s11)
  2261. d.MustDecode(&s21)
  2262. testDeepEqualErr(s1, s11, t, name+"-multiple-encode")
  2263. testDeepEqualErr(s2, s21, t, name+"-multiple-encode")
  2264. }
  2265. func doTestSelfExt(t *testing.T, h Handle) {
  2266. testOnce.Do(testInitAll)
  2267. name := h.Name()
  2268. var ts TestSelfExtImpl
  2269. ts.S = "ugorji"
  2270. ts.I = 5678
  2271. ts.B = true
  2272. var ts2 TestSelfExtImpl
  2273. bs := testMarshalErr(&ts, h, t, name)
  2274. testUnmarshalErr(&ts2, bs, h, t, name)
  2275. testDeepEqualErr(&ts, &ts2, t, name)
  2276. }
  2277. func doTestBytesEncodedAsArray(t *testing.T, h Handle) {
  2278. testOnce.Do(testInitAll)
  2279. name := h.Name()
  2280. // Need to test edge case where bytes are encoded as an array
  2281. // (not using optimized []byte native format)
  2282. // encode []int8 (or int32 or any numeric type) with all positive numbers
  2283. // decode it into []uint8
  2284. var in = make([]int32, 128)
  2285. var un = make([]uint8, 128)
  2286. for i := range in {
  2287. in[i] = int32(i)
  2288. un[i] = uint8(i)
  2289. }
  2290. var out []byte
  2291. bs := testMarshalErr(&in, h, t, name)
  2292. testUnmarshalErr(&out, bs, h, t, name)
  2293. // xdebugf("in: %v", in)
  2294. // xdebug2f("out: %v\n", out)
  2295. testDeepEqualErr(un, out, t, name)
  2296. }
  2297. func doTestStrucEncDec(t *testing.T, h Handle) {
  2298. testOnce.Do(testInitAll)
  2299. name := h.Name()
  2300. {
  2301. var ts1 = newTestStruc(2, testNumRepeatString, false, !testSkipIntf, testMapStringKeyOnly)
  2302. var ts2 TestStruc
  2303. bs := testMarshalErr(ts1, h, t, name)
  2304. testUnmarshalErr(&ts2, bs, h, t, name)
  2305. testDeepEqualErr(ts1, &ts2, t, name)
  2306. }
  2307. // Note: We cannot use TestStrucFlex because it has omitempty values,
  2308. // Meaning that sometimes, encoded and decoded will not be same.
  2309. // {
  2310. // var ts1 = newTestStrucFlex(2, testNumRepeatString, false, !testSkipIntf, testMapStringKeyOnly)
  2311. // var ts2 TestStrucFlex
  2312. // bs := testMarshalErr(ts1, h, t, name)
  2313. // fmt.Printf("\n\n%s\n\n", bs)
  2314. // testUnmarshalErr(&ts2, bs, h, t, name)
  2315. // testDeepEqualErr(ts1, &ts2, t, name)
  2316. // }
  2317. }
  2318. func doTestStructKeyType(t *testing.T, h Handle) {
  2319. testOnce.Do(testInitAll)
  2320. name := h.Name()
  2321. mh, mok := h.(*MsgpackHandle)
  2322. bch, bcok := h.(*BincHandle)
  2323. bh := basicHandle(h)
  2324. s2a := bh.StructToArray
  2325. bh.StructToArray = false
  2326. var mfx bool
  2327. if mok {
  2328. mfx = mh.NoFixedNum
  2329. mh.NoFixedNum = false
  2330. }
  2331. var bcsym uint8
  2332. if bcok {
  2333. bcsym = bch.AsSymbols
  2334. bch.AsSymbols = 2 // TODO: should be 0 but binc symbols do not work well
  2335. }
  2336. defer func() {
  2337. bh.StructToArray = s2a
  2338. if mok {
  2339. mh.NoFixedNum = mfx
  2340. }
  2341. if bcok {
  2342. bch.AsSymbols = bcsym
  2343. }
  2344. }()
  2345. var bs1, bs2 []byte
  2346. var m = make(map[interface{}]interface{})
  2347. fn := func(v interface{}) {
  2348. bs1 = testMarshalErr(v, h, t, "")
  2349. bs2 = testMarshalErr(m, h, t, "")
  2350. // if _, ok := h.(*JsonHandle); ok {
  2351. // xdebugf("bs1: %s, bs2: %s", bs1, bs2)
  2352. // }
  2353. // if bcok {
  2354. // xdebug2f("-------------")
  2355. // xdebugf("v: %#v, m: %#v", v, m)
  2356. // xdebugf("bs1: %v", bs1)
  2357. // xdebugf("bs2: %v", bs2)
  2358. // xdebugf("bs1==bs2: %v", bytes.Equal(bs1, bs2))
  2359. // testDeepEqualErr(bs1, bs2, t, name+"")
  2360. // xdebug2f("-------------")
  2361. // return
  2362. // }
  2363. testDeepEqualErr(bs1, bs2, t, name+"")
  2364. }
  2365. fnclr := func() {
  2366. for k := range m {
  2367. delete(m, k)
  2368. }
  2369. }
  2370. m["F"] = 0
  2371. fn(testStrucKeyTypeT0{})
  2372. fnclr()
  2373. m["FFFF"] = 0
  2374. fn(testStrucKeyTypeT1{})
  2375. fnclr()
  2376. m[int64(-1)] = 0
  2377. fn(testStrucKeyTypeT2{})
  2378. fnclr()
  2379. m[int64(1)] = 0
  2380. fn(testStrucKeyTypeT3{})
  2381. fnclr()
  2382. m[float64(2.5)] = 0
  2383. fn(testStrucKeyTypeT4{})
  2384. fnclr()
  2385. }
  2386. func doTestRawToStringToRawEtc(t *testing.T, h Handle) {
  2387. testOnce.Do(testInitAll)
  2388. // name := h.Name()
  2389. // Tests:
  2390. // - RawToString
  2391. // - StringToRaw
  2392. // - MapValueReset
  2393. // - DeleteOnMapValue (skipped - no longer supported)
  2394. bh := basicHandle(h)
  2395. // xdebugf("[%s] maptype: %v, slice type: %v", name, bh.MapType, bh.SliceType)
  2396. r2s := bh.RawToString
  2397. s2r := bh.StringToRaw
  2398. can := bh.Canonical
  2399. mvr := bh.MapValueReset
  2400. var wext bool
  2401. mh, mok := h.(*MsgpackHandle)
  2402. if mok {
  2403. wext = mh.WriteExt
  2404. }
  2405. _, jok := h.(*JsonHandle)
  2406. defer func() {
  2407. bh.RawToString = r2s
  2408. bh.StringToRaw = s2r
  2409. bh.Canonical = can
  2410. bh.MapValueReset = mvr
  2411. if mok {
  2412. mh.WriteExt = wext
  2413. }
  2414. }()
  2415. bh.Canonical = false
  2416. var bs1, bs2 []byte
  2417. // encode: StringToRaw
  2418. // decode: RawToString
  2419. // compare encoded v1 to encoded v2, while setting StringToRaw to b
  2420. fne := func(v1, v2 interface{}, b bool) {
  2421. // xdebugf("[%s] fne: StringToRaw: %v, v1: %#v, v2: %#v", name, b, v1, v2)
  2422. bh.StringToRaw = b
  2423. bs1 = testMarshalErr(v1, h, t, "")
  2424. // bs1 = []byte(string(bs1))
  2425. bs2 = testMarshalErr(v2, h, t, "")
  2426. // if jok {
  2427. // xdebugf("[%s] fne: bh: %#v", name, bh.EncodeOptions)
  2428. // xdebugf("[%s] bs1: %s", name, bs1)
  2429. // xdebugf("[%s] bs2: %s", name, bs2)
  2430. // }
  2431. testDeepEqualErr(bs1, bs2, t, "")
  2432. }
  2433. // encoded v1, decode naked and compare to v2
  2434. fnd := func(v1, v2 interface{}, bs2r, br2s, bwext bool) {
  2435. bh.RawToString = br2s
  2436. bh.StringToRaw = bs2r
  2437. if mok {
  2438. mh.WriteExt = bwext
  2439. }
  2440. bs1 = testMarshalErr(v1, h, t, "")
  2441. var vn interface{}
  2442. testUnmarshalErr(&vn, bs1, h, t, "")
  2443. testDeepEqualErr(vn, v2, t, "")
  2444. }
  2445. sv0 := "value"
  2446. bv0 := []byte(sv0)
  2447. sv1 := sv0
  2448. bv1 := []byte(sv1)
  2449. m1 := map[string]*string{"key": &sv1}
  2450. m2 := map[string]*[]byte{"key": &bv1}
  2451. // m3 := map[[3]byte]string{[3]byte{'k', 'e', 'y'}: sv0}
  2452. m4 := map[[3]byte][]byte{[3]byte{'k', 'e', 'y'}: bv0}
  2453. m5 := map[string][]byte{"key": bv0}
  2454. // m6 := map[string]string{"key": sv0}
  2455. m7 := map[interface{}]interface{}{"key": sv0}
  2456. m8 := map[interface{}]interface{}{"key": bv0}
  2457. // StringToRaw=true
  2458. fne(m1, m4, true)
  2459. // StringToRaw=false
  2460. // compare encoded m2 to encoded m5
  2461. fne(m2, m5, false)
  2462. // json doesn't work well with StringToRaw and RawToString
  2463. // when dealing with interfaces, because it cannot decipher
  2464. // that a string should be treated as base64.
  2465. if jok {
  2466. goto MAP_VALUE_RESET
  2467. }
  2468. // if msgpack, always set WriteExt = RawToString
  2469. // StringToRaw=true (RawToString=true)
  2470. // encoded m1, decode naked and compare to m5
  2471. fnd(m2, m7, true, true, true)
  2472. // StringToRaw=true (RawToString=false)
  2473. // encoded m1, decode naked and compare to m6
  2474. fnd(m1, m8, true, false, false)
  2475. // StringToRaw=false, RawToString=true
  2476. // encode m1, decode naked, and compare to m6
  2477. fnd(m2, m7, false, true, true)
  2478. MAP_VALUE_RESET:
  2479. // set MapValueReset, and then decode i
  2480. sv2 := "value-new"
  2481. m9 := map[string]*string{"key": &sv2}
  2482. bs1 = testMarshalErr(m1, h, t, "")
  2483. bh.MapValueReset = false
  2484. testUnmarshalErr(&m9, bs1, h, t, "")
  2485. // if !(m9["key"] == m1["key"]
  2486. testDeepEqualErr(sv2, "value", t, "")
  2487. testDeepEqualErr(&sv2, m9["key"], t, "")
  2488. sv2 = "value-new"
  2489. m9["key"] = &sv2
  2490. bh.MapValueReset = true
  2491. testUnmarshalErr(&m9, bs1, h, t, "")
  2492. testDeepEqualErr(sv2, "value-new", t, "")
  2493. testDeepEqualErr("value", *(m9["key"]), t, "")
  2494. // t1 = struct {
  2495. // key string
  2496. // }{ key: sv0 }
  2497. // t2 := struct {
  2498. // key []byte
  2499. // }{ key: bv1 }
  2500. }
  2501. // -----------------
  2502. func TestJsonDecodeNonStringScalarInStringContext(t *testing.T) {
  2503. testOnce.Do(testInitAll)
  2504. var b = `{"s.true": "true", "b.true": true, "s.false": "false", "b.false": false, "s.10": "10", "i.10": 10, "i.-10": -10}`
  2505. var golden = map[string]string{"s.true": "true", "b.true": "true", "s.false": "false", "b.false": "false", "s.10": "10", "i.10": "10", "i.-10": "-10"}
  2506. var m map[string]string
  2507. d := NewDecoderBytes([]byte(b), testJsonH)
  2508. d.MustDecode(&m)
  2509. if err := deepEqual(golden, m); err == nil {
  2510. logTv(t, "++++ match: decoded: %#v", m)
  2511. } else {
  2512. failT(t, "---- mismatch: %v ==> golden: %#v, decoded: %#v", err, golden, m)
  2513. }
  2514. }
  2515. func TestJsonEncodeIndent(t *testing.T) {
  2516. testOnce.Do(testInitAll)
  2517. v := TestSimplish{
  2518. Ii: -794,
  2519. Ss: `A Man is
  2520. after the new line
  2521. after new line and tab
  2522. `,
  2523. }
  2524. v2 := v
  2525. v.Mm = make(map[string]*TestSimplish)
  2526. for i := 0; i < len(v.Ar); i++ {
  2527. v3 := v2
  2528. v3.Ii += (i * 4)
  2529. v3.Ss = fmt.Sprintf("%d - %s", v3.Ii, v3.Ss)
  2530. if i%2 == 0 {
  2531. v.Ar[i] = &v3
  2532. }
  2533. // v3 = v2
  2534. v.Sl = append(v.Sl, &v3)
  2535. v.Mm[strconv.FormatInt(int64(i), 10)] = &v3
  2536. }
  2537. oldcan := testJsonH.Canonical
  2538. oldIndent := testJsonH.Indent
  2539. oldS2A := testJsonH.StructToArray
  2540. defer func() {
  2541. testJsonH.Canonical = oldcan
  2542. testJsonH.Indent = oldIndent
  2543. testJsonH.StructToArray = oldS2A
  2544. }()
  2545. testJsonH.Canonical = true
  2546. testJsonH.Indent = -1
  2547. testJsonH.StructToArray = false
  2548. var bs []byte
  2549. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  2550. txt1Tab := string(bs)
  2551. bs = nil
  2552. testJsonH.Indent = 120
  2553. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  2554. txtSpaces := string(bs)
  2555. // fmt.Printf("\n-----------\n%s\n------------\n%s\n-------------\n", txt1Tab, txtSpaces)
  2556. goldenResultTab := `{
  2557. "Ar": [
  2558. {
  2559. "Ar": [
  2560. null,
  2561. null
  2562. ],
  2563. "Ii": -794,
  2564. "Mm": null,
  2565. "Sl": null,
  2566. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2567. },
  2568. null
  2569. ],
  2570. "Ii": -794,
  2571. "Mm": {
  2572. "0": {
  2573. "Ar": [
  2574. null,
  2575. null
  2576. ],
  2577. "Ii": -794,
  2578. "Mm": null,
  2579. "Sl": null,
  2580. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2581. },
  2582. "1": {
  2583. "Ar": [
  2584. null,
  2585. null
  2586. ],
  2587. "Ii": -790,
  2588. "Mm": null,
  2589. "Sl": null,
  2590. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2591. }
  2592. },
  2593. "Sl": [
  2594. {
  2595. "Ar": [
  2596. null,
  2597. null
  2598. ],
  2599. "Ii": -794,
  2600. "Mm": null,
  2601. "Sl": null,
  2602. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2603. },
  2604. {
  2605. "Ar": [
  2606. null,
  2607. null
  2608. ],
  2609. "Ii": -790,
  2610. "Mm": null,
  2611. "Sl": null,
  2612. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2613. }
  2614. ],
  2615. "Ss": "A Man is\nafter the new line\n\tafter new line and tab\n"
  2616. }`
  2617. if txt1Tab != goldenResultTab {
  2618. failT(t, "decoded indented with tabs != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txt1Tab)
  2619. }
  2620. if txtSpaces != strings.Replace(goldenResultTab, "\t", strings.Repeat(" ", 120), -1) {
  2621. failT(t, "decoded indented with spaces != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txtSpaces)
  2622. }
  2623. }
  2624. func TestBufioDecReader(t *testing.T) {
  2625. testOnce.Do(testInitAll)
  2626. // try to read 85 bytes in chunks of 7 at a time.
  2627. var s = strings.Repeat("01234'56789 ", 5)
  2628. // fmt.Printf("s: %s\n", s)
  2629. var r = strings.NewReader(s)
  2630. var br = &bufioDecReader{buf: make([]byte, 0, 13)}
  2631. br.r = r
  2632. b, err := ioutil.ReadAll(br.r)
  2633. if err != nil {
  2634. panic(err)
  2635. }
  2636. var s2 = string(b)
  2637. // fmt.Printf("s==s2: %v, len(s): %v, len(b): %v, len(s2): %v\n", s == s2, len(s), len(b), len(s2))
  2638. if s != s2 {
  2639. failT(t, "not equal: \ns: %s\ns2: %s", s, s2)
  2640. }
  2641. // Now, test search functions for skip, readTo and readUntil
  2642. // readUntil ', readTo ', skip whitespace. 3 times in a loop, each time compare the token and/or outs
  2643. // readUntil: see: 56789
  2644. var out []byte
  2645. var token byte
  2646. br = &bufioDecReader{buf: make([]byte, 0, 7)}
  2647. br.r = strings.NewReader(s)
  2648. // println()
  2649. for _, v2 := range [...]string{
  2650. `01234'`,
  2651. `56789 01234'`,
  2652. `56789 01234'`,
  2653. `56789 01234'`,
  2654. } {
  2655. out = br.readUntil(nil, '\'')
  2656. testDeepEqualErr(string(out), v2, t, "-")
  2657. // fmt.Printf("readUntil: out: `%s`\n", out)
  2658. }
  2659. br = &bufioDecReader{buf: make([]byte, 0, 7)}
  2660. br.r = strings.NewReader(s)
  2661. // println()
  2662. for range [4]struct{}{} {
  2663. out = br.readTo(nil, &jsonNumSet)
  2664. testDeepEqualErr(string(out), `01234`, t, "-")
  2665. // fmt.Printf("readTo: out: `%s`\n", out)
  2666. out = br.readUntil(nil, '\'')
  2667. testDeepEqualErr(string(out), "'", t, "-")
  2668. // fmt.Printf("readUntil: out: `%s`\n", out)
  2669. out = br.readTo(nil, &jsonNumSet)
  2670. testDeepEqualErr(string(out), `56789`, t, "-")
  2671. // fmt.Printf("readTo: out: `%s`\n", out)
  2672. out = br.readUntil(nil, '0')
  2673. testDeepEqualErr(string(out), ` 0`, t, "-")
  2674. // fmt.Printf("readUntil: out: `%s`\n", out)
  2675. br.unreadn1()
  2676. }
  2677. br = &bufioDecReader{buf: make([]byte, 0, 7)}
  2678. br.r = strings.NewReader(s)
  2679. // println()
  2680. for range [4]struct{}{} {
  2681. out = br.readUntil(nil, ' ')
  2682. testDeepEqualErr(string(out), `01234'56789 `, t, "-")
  2683. // fmt.Printf("readUntil: out: |%s|\n", out)
  2684. token = br.skip(&jsonCharWhitespaceSet)
  2685. testDeepEqualErr(token, byte('0'), t, "-")
  2686. // fmt.Printf("skip: token: '%c'\n", token)
  2687. br.unreadn1()
  2688. }
  2689. // println()
  2690. }
  2691. func TestAtomic(t *testing.T) {
  2692. testOnce.Do(testInitAll)
  2693. // load, store, load, confirm
  2694. if true {
  2695. var a atomicTypeInfoSlice
  2696. l := a.load()
  2697. if l != nil {
  2698. failT(t, "atomic fail: %T, expected load return nil, received: %v", a, l)
  2699. }
  2700. l = append(l, rtid2ti{})
  2701. a.store(l)
  2702. l = a.load()
  2703. if len(l) != 1 {
  2704. failT(t, "atomic fail: %T, expected load to have length 1, received: %d", a, len(l))
  2705. }
  2706. }
  2707. if true {
  2708. var a atomicRtidFnSlice
  2709. l := a.load()
  2710. if l != nil {
  2711. failT(t, "atomic fail: %T, expected load return nil, received: %v", a, l)
  2712. }
  2713. l = append(l, codecRtidFn{})
  2714. a.store(l)
  2715. l = a.load()
  2716. if len(l) != 1 {
  2717. failT(t, "atomic fail: %T, expected load to have length 1, received: %d", a, len(l))
  2718. }
  2719. }
  2720. if true {
  2721. var a atomicClsErr
  2722. l := a.load()
  2723. if l.errClosed != nil {
  2724. failT(t, "atomic fail: %T, expected load return clsErr = nil, received: %v", a, l.errClosed)
  2725. }
  2726. l.errClosed = io.EOF
  2727. a.store(l)
  2728. l = a.load()
  2729. if l.errClosed != io.EOF {
  2730. failT(t, "atomic fail: %T, expected clsErr = io.EOF, received: %v", a, l.errClosed)
  2731. }
  2732. }
  2733. }
  2734. // -----------
  2735. func TestJsonLargeInteger(t *testing.T) {
  2736. testOnce.Do(testInitAll)
  2737. for _, i := range []uint8{'L', 'A', 0} {
  2738. for _, j := range []interface{}{
  2739. int64(1 << 60),
  2740. -int64(1 << 60),
  2741. 0,
  2742. 1 << 20,
  2743. -(1 << 20),
  2744. uint64(1 << 60),
  2745. uint(0),
  2746. uint(1 << 20),
  2747. } {
  2748. doTestJsonLargeInteger(t, j, i)
  2749. }
  2750. }
  2751. }
  2752. func TestJsonInvalidUnicode(t *testing.T) {
  2753. testOnce.Do(testInitAll)
  2754. var m = map[string]string{
  2755. `"\udc49\u0430abc"`: "\uFFFDabc",
  2756. `"\udc49\u0430"`: "\uFFFD",
  2757. `"\udc49abc"`: "\uFFFDabc",
  2758. `"\udc49"`: "\uFFFD",
  2759. `"\udZ49\u0430abc"`: "\uFFFD\u0430abc",
  2760. `"\udcG9\u0430"`: "\uFFFD\u0430",
  2761. `"\uHc49abc"`: "\uFFFDabc",
  2762. `"\uKc49"`: "\uFFFD",
  2763. // ``: "",
  2764. }
  2765. for k, v := range m {
  2766. // println("k = ", k)
  2767. var s string
  2768. testUnmarshalErr(&s, []byte(k), testJsonH, t, "-")
  2769. if s != v {
  2770. failT(t, "not equal: %q, %q", v, s)
  2771. }
  2772. }
  2773. }
  2774. func TestMsgpackDecodeMapAndExtSizeMismatch(t *testing.T) {
  2775. fn := func(t *testing.T, b []byte, v interface{}) {
  2776. if err := NewDecoderBytes(b, testMsgpackH).Decode(v); err != io.EOF && err != io.ErrUnexpectedEOF {
  2777. t.Fatalf("expected EOF or ErrUnexpectedEOF, got %v", err)
  2778. }
  2779. }
  2780. // a map claiming to have 0x10eeeeee KV pairs, but only has 1.
  2781. var b = []byte{0xdf, 0x10, 0xee, 0xee, 0xee, 0x1, 0xa1, 0x1}
  2782. var m1 map[int]string
  2783. var m2 map[int][]byte
  2784. fn(t, b, &m1)
  2785. fn(t, b, &m2)
  2786. // an extension claiming to have 0x7fffffff bytes, but only has 1.
  2787. b = []byte{0xc9, 0x7f, 0xff, 0xff, 0xff, 0xda, 0x1}
  2788. var a interface{}
  2789. fn(t, b, &a)
  2790. // b = []byte{0x00}
  2791. // var s testSelferRecur
  2792. // fn(t, b, &s)
  2793. }
  2794. func TestMapRangeIndex(t *testing.T) {
  2795. // t.Skip()
  2796. type T struct {
  2797. I int
  2798. S string
  2799. B bool
  2800. M map[int]T
  2801. }
  2802. t1 := T{I: 1, B: true, S: "11", M: map[int]T{11: T{I: 11}}}
  2803. t2 := T{I: 1, B: true, S: "12", M: map[int]T{12: T{I: 12}}}
  2804. // ------
  2805. var m1 = map[string]*T{
  2806. "11": &t1,
  2807. "12": &t2,
  2808. }
  2809. var m1c = make(map[string]T)
  2810. for k, v := range m1 {
  2811. m1c[k] = *v
  2812. }
  2813. mt := reflect.TypeOf(m1)
  2814. it := mapRange(reflect.ValueOf(m1), mapAddressableRV(mt.Key()), mapAddressableRV(mt.Elem()), true)
  2815. for it.Next() {
  2816. k := it.Key().Interface().(string)
  2817. v := it.Value().Interface().(*T)
  2818. testDeepEqualErr(m1[k], v, t, "map-key-eq-it-key")
  2819. if _, ok := m1c[k]; ok {
  2820. delete(m1c, k)
  2821. } else {
  2822. failT(t, "unexpected key in map: %v", k)
  2823. }
  2824. }
  2825. testDeepEqualErr(len(m1c), 0, t, "all-keys-not-consumed")
  2826. // ------
  2827. var m2 = map[*T]T{
  2828. &t1: t1,
  2829. &t2: t2,
  2830. }
  2831. var m2c = make(map[*T]*T)
  2832. for k := range m2 {
  2833. m2c[k] = k
  2834. }
  2835. mt = reflect.TypeOf(m2)
  2836. it = mapRange(reflect.ValueOf(m2), mapAddressableRV(mt.Key()), mapAddressableRV(mt.Elem()), true)
  2837. for it.Next() {
  2838. k := it.Key().Interface().(*T)
  2839. v := it.Value().Interface().(T)
  2840. testDeepEqualErr(m2[k], v, t, "map-key-eq-it-key")
  2841. if _, ok := m2c[k]; ok {
  2842. delete(m2c, k)
  2843. } else {
  2844. failT(t, "unexpected key in map: %v", k)
  2845. }
  2846. }
  2847. testDeepEqualErr(len(m2c), 0, t, "all-keys-not-consumed")
  2848. // ---- test mapGet
  2849. fnTestMapIndex := func(mi ...interface{}) {
  2850. for _, m0 := range mi {
  2851. m := reflect.ValueOf(m0)
  2852. rvv := mapAddressableRV(m.Type().Elem())
  2853. for _, k := range m.MapKeys() {
  2854. testDeepEqualErr(m.MapIndex(k).Interface(), mapGet(m, k, rvv).Interface(), t, "map-index-eq")
  2855. }
  2856. }
  2857. }
  2858. fnTestMapIndex(m1, m1c, m2, m2c)
  2859. // var s string = "hello"
  2860. // var tt = &T{I: 3}
  2861. // ttTyp := reflect.TypeOf(tt)
  2862. // _, _ = tt, ttTyp
  2863. // mv := reflect.ValueOf(m)
  2864. // it := mapRange(mv, reflect.ValueOf(&s).Elem(), reflect.ValueOf(&tt).Elem(), true) //ok
  2865. // it := mapRange(mv, reflect.New(reflect.TypeOf(s)).Elem(), reflect.New(reflect.TypeOf(T{})).Elem(), true) // ok
  2866. // it := mapRange(mv, reflect.New(reflect.TypeOf(s)).Elem(), reflect.New(ttTyp.Elem()), true) // !ok
  2867. // it := mapRange(mv, reflect.New(reflect.TypeOf(s)).Elem(), reflect.New(reflect.TypeOf(T{})), true) !ok
  2868. // it := mapRange(mv, reflect.New(reflect.TypeOf(s)).Elem(), reflect.New(reflect.TypeOf(T{})).Elem(), true) // ok
  2869. // fmt.Printf("key: %#v\n", it.Key())
  2870. // fmt.Printf("exp: %#v\n", mv.MapIndex(it.Key()))
  2871. // fmt.Printf("val: %#v\n", it.Value())
  2872. // testDeepEqualErr(mv.MapIndex(it.Key()), it.Value().Interface()
  2873. }
  2874. // ----------
  2875. func TestBincCodecsTable(t *testing.T) {
  2876. testCodecTableOne(t, testBincH)
  2877. }
  2878. func TestBincCodecsMisc(t *testing.T) {
  2879. testCodecMiscOne(t, testBincH)
  2880. }
  2881. func TestBincCodecsEmbeddedPointer(t *testing.T) {
  2882. testCodecEmbeddedPointer(t, testBincH)
  2883. }
  2884. func TestBincStdEncIntf(t *testing.T) {
  2885. doTestStdEncIntf(t, testBincH)
  2886. }
  2887. func TestBincMammoth(t *testing.T) {
  2888. testMammoth(t, testBincH)
  2889. }
  2890. func TestSimpleCodecsTable(t *testing.T) {
  2891. testCodecTableOne(t, testSimpleH)
  2892. }
  2893. func TestSimpleCodecsMisc(t *testing.T) {
  2894. testCodecMiscOne(t, testSimpleH)
  2895. }
  2896. func TestSimpleCodecsEmbeddedPointer(t *testing.T) {
  2897. testCodecEmbeddedPointer(t, testSimpleH)
  2898. }
  2899. func TestSimpleStdEncIntf(t *testing.T) {
  2900. doTestStdEncIntf(t, testSimpleH)
  2901. }
  2902. func TestSimpleMammoth(t *testing.T) {
  2903. testMammoth(t, testSimpleH)
  2904. }
  2905. func TestMsgpackCodecsTable(t *testing.T) {
  2906. testCodecTableOne(t, testMsgpackH)
  2907. }
  2908. func TestMsgpackCodecsMisc(t *testing.T) {
  2909. testCodecMiscOne(t, testMsgpackH)
  2910. }
  2911. func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
  2912. testCodecEmbeddedPointer(t, testMsgpackH)
  2913. }
  2914. func TestMsgpackStdEncIntf(t *testing.T) {
  2915. doTestStdEncIntf(t, testMsgpackH)
  2916. }
  2917. func TestMsgpackMammoth(t *testing.T) {
  2918. testMammoth(t, testMsgpackH)
  2919. }
  2920. func TestCborCodecsTable(t *testing.T) {
  2921. testCodecTableOne(t, testCborH)
  2922. }
  2923. func TestCborCodecsMisc(t *testing.T) {
  2924. testCodecMiscOne(t, testCborH)
  2925. }
  2926. func TestCborCodecsEmbeddedPointer(t *testing.T) {
  2927. testCodecEmbeddedPointer(t, testCborH)
  2928. }
  2929. func TestCborCodecChan(t *testing.T) {
  2930. testCodecChan(t, testCborH)
  2931. }
  2932. func TestCborStdEncIntf(t *testing.T) {
  2933. doTestStdEncIntf(t, testCborH)
  2934. }
  2935. func TestCborMammoth(t *testing.T) {
  2936. testMammoth(t, testCborH)
  2937. }
  2938. func TestJsonCodecsTable(t *testing.T) {
  2939. testCodecTableOne(t, testJsonH)
  2940. }
  2941. func TestJsonCodecsMisc(t *testing.T) {
  2942. testCodecMiscOne(t, testJsonH)
  2943. }
  2944. func TestJsonCodecsEmbeddedPointer(t *testing.T) {
  2945. testCodecEmbeddedPointer(t, testJsonH)
  2946. }
  2947. func TestJsonCodecChan(t *testing.T) {
  2948. testCodecChan(t, testJsonH)
  2949. }
  2950. func TestJsonStdEncIntf(t *testing.T) {
  2951. doTestStdEncIntf(t, testJsonH)
  2952. }
  2953. func TestJsonMammoth(t *testing.T) {
  2954. testMammoth(t, testJsonH)
  2955. }
  2956. // ----- Raw ---------
  2957. func TestJsonRaw(t *testing.T) {
  2958. doTestRawValue(t, testJsonH)
  2959. }
  2960. func TestBincRaw(t *testing.T) {
  2961. doTestRawValue(t, testBincH)
  2962. }
  2963. func TestMsgpackRaw(t *testing.T) {
  2964. doTestRawValue(t, testMsgpackH)
  2965. }
  2966. func TestSimpleRaw(t *testing.T) {
  2967. doTestRawValue(t, testSimpleH)
  2968. }
  2969. func TestCborRaw(t *testing.T) {
  2970. doTestRawValue(t, testCborH)
  2971. }
  2972. // ----- ALL (framework based) -----
  2973. func TestAllEncCircularRef(t *testing.T) {
  2974. doTestEncCircularRef(t, testCborH)
  2975. }
  2976. func TestAllAnonCycle(t *testing.T) {
  2977. doTestAnonCycle(t, testCborH)
  2978. }
  2979. func TestAllErrWriter(t *testing.T) {
  2980. doTestErrWriter(t, testCborH)
  2981. doTestErrWriter(t, testJsonH)
  2982. }
  2983. // ----- RPC custom -----
  2984. func TestMsgpackRpcSpec(t *testing.T) {
  2985. testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
  2986. }
  2987. // ----- RPC -----
  2988. func TestBincRpcGo(t *testing.T) {
  2989. testCodecRpcOne(t, GoRpc, testBincH, true, 0)
  2990. }
  2991. func TestSimpleRpcGo(t *testing.T) {
  2992. testCodecRpcOne(t, GoRpc, testSimpleH, true, 0)
  2993. }
  2994. func TestMsgpackRpcGo(t *testing.T) {
  2995. testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0)
  2996. }
  2997. func TestCborRpcGo(t *testing.T) {
  2998. testCodecRpcOne(t, GoRpc, testCborH, true, 0)
  2999. }
  3000. func TestJsonRpcGo(t *testing.T) {
  3001. testCodecRpcOne(t, GoRpc, testJsonH, true, 0)
  3002. }
  3003. // ----- OTHERS -----
  3004. func TestBincMapEncodeForCanonical(t *testing.T) {
  3005. t.Skip() // TODO: testing fails??? Need to research
  3006. doTestMapEncodeForCanonical(t, testBincH)
  3007. }
  3008. func TestSimpleMapEncodeForCanonical(t *testing.T) {
  3009. doTestMapEncodeForCanonical(t, testSimpleH)
  3010. }
  3011. func TestMsgpackMapEncodeForCanonical(t *testing.T) {
  3012. doTestMapEncodeForCanonical(t, testMsgpackH)
  3013. }
  3014. func TestCborMapEncodeForCanonical(t *testing.T) {
  3015. doTestMapEncodeForCanonical(t, testCborH)
  3016. }
  3017. func TestJsonMapEncodeForCanonical(t *testing.T) {
  3018. doTestMapEncodeForCanonical(t, testJsonH)
  3019. }
  3020. func TestBincUnderlyingType(t *testing.T) {
  3021. testCodecUnderlyingType(t, testBincH)
  3022. }
  3023. func TestJsonSwallowAndZero(t *testing.T) {
  3024. doTestSwallowAndZero(t, testJsonH)
  3025. }
  3026. func TestCborSwallowAndZero(t *testing.T) {
  3027. doTestSwallowAndZero(t, testCborH)
  3028. }
  3029. func TestMsgpackSwallowAndZero(t *testing.T) {
  3030. doTestSwallowAndZero(t, testMsgpackH)
  3031. }
  3032. func TestBincSwallowAndZero(t *testing.T) {
  3033. doTestSwallowAndZero(t, testBincH)
  3034. }
  3035. func TestSimpleSwallowAndZero(t *testing.T) {
  3036. doTestSwallowAndZero(t, testSimpleH)
  3037. }
  3038. func TestJsonRawExt(t *testing.T) {
  3039. doTestRawExt(t, testJsonH)
  3040. }
  3041. func TestCborRawExt(t *testing.T) {
  3042. doTestRawExt(t, testCborH)
  3043. }
  3044. func TestMsgpackRawExt(t *testing.T) {
  3045. doTestRawExt(t, testMsgpackH)
  3046. }
  3047. func TestBincRawExt(t *testing.T) {
  3048. doTestRawExt(t, testBincH)
  3049. }
  3050. func TestSimpleRawExt(t *testing.T) {
  3051. doTestRawExt(t, testSimpleH)
  3052. }
  3053. func TestJsonMapStructKey(t *testing.T) {
  3054. doTestMapStructKey(t, testJsonH)
  3055. }
  3056. func TestCborMapStructKey(t *testing.T) {
  3057. doTestMapStructKey(t, testCborH)
  3058. }
  3059. func TestMsgpackMapStructKey(t *testing.T) {
  3060. doTestMapStructKey(t, testMsgpackH)
  3061. }
  3062. func TestBincMapStructKey(t *testing.T) {
  3063. doTestMapStructKey(t, testBincH)
  3064. }
  3065. func TestSimpleMapStructKey(t *testing.T) {
  3066. doTestMapStructKey(t, testSimpleH)
  3067. }
  3068. func TestJsonDecodeNilMapValue(t *testing.T) {
  3069. doTestDecodeNilMapValue(t, testJsonH)
  3070. }
  3071. func TestCborDecodeNilMapValue(t *testing.T) {
  3072. doTestDecodeNilMapValue(t, testCborH)
  3073. }
  3074. func TestMsgpackDecodeNilMapValue(t *testing.T) {
  3075. doTestDecodeNilMapValue(t, testMsgpackH)
  3076. }
  3077. func TestBincDecodeNilMapValue(t *testing.T) {
  3078. doTestDecodeNilMapValue(t, testBincH)
  3079. }
  3080. func TestSimpleDecodeNilMapValue(t *testing.T) {
  3081. doTestDecodeNilMapValue(t, testSimpleH)
  3082. }
  3083. func TestJsonEmbeddedFieldPrecedence(t *testing.T) {
  3084. doTestEmbeddedFieldPrecedence(t, testJsonH)
  3085. }
  3086. func TestCborEmbeddedFieldPrecedence(t *testing.T) {
  3087. doTestEmbeddedFieldPrecedence(t, testCborH)
  3088. }
  3089. func TestMsgpackEmbeddedFieldPrecedence(t *testing.T) {
  3090. doTestEmbeddedFieldPrecedence(t, testMsgpackH)
  3091. }
  3092. func TestBincEmbeddedFieldPrecedence(t *testing.T) {
  3093. doTestEmbeddedFieldPrecedence(t, testBincH)
  3094. }
  3095. func TestSimpleEmbeddedFieldPrecedence(t *testing.T) {
  3096. doTestEmbeddedFieldPrecedence(t, testSimpleH)
  3097. }
  3098. func TestJsonLargeContainerLen(t *testing.T) {
  3099. doTestLargeContainerLen(t, testJsonH)
  3100. }
  3101. func TestCborLargeContainerLen(t *testing.T) {
  3102. doTestLargeContainerLen(t, testCborH)
  3103. }
  3104. func TestMsgpackLargeContainerLen(t *testing.T) {
  3105. doTestLargeContainerLen(t, testMsgpackH)
  3106. }
  3107. func TestBincLargeContainerLen(t *testing.T) {
  3108. doTestLargeContainerLen(t, testBincH)
  3109. }
  3110. func TestSimpleLargeContainerLen(t *testing.T) {
  3111. doTestLargeContainerLen(t, testSimpleH)
  3112. }
  3113. func TestJsonMammothMapsAndSlices(t *testing.T) {
  3114. doTestMammothMapsAndSlices(t, testJsonH)
  3115. }
  3116. func TestCborMammothMapsAndSlices(t *testing.T) {
  3117. doTestMammothMapsAndSlices(t, testCborH)
  3118. }
  3119. func TestMsgpackMammothMapsAndSlices(t *testing.T) {
  3120. old1 := testMsgpackH.WriteExt
  3121. defer func() { testMsgpackH.WriteExt = old1 }()
  3122. testMsgpackH.WriteExt = true
  3123. doTestMammothMapsAndSlices(t, testMsgpackH)
  3124. }
  3125. func TestBincMammothMapsAndSlices(t *testing.T) {
  3126. doTestMammothMapsAndSlices(t, testBincH)
  3127. }
  3128. func TestSimpleMammothMapsAndSlices(t *testing.T) {
  3129. doTestMammothMapsAndSlices(t, testSimpleH)
  3130. }
  3131. func TestJsonTime(t *testing.T) {
  3132. testTime(t, testJsonH)
  3133. }
  3134. func TestCborTime(t *testing.T) {
  3135. testTime(t, testCborH)
  3136. }
  3137. func TestMsgpackTime(t *testing.T) {
  3138. testTime(t, testMsgpackH)
  3139. }
  3140. func TestBincTime(t *testing.T) {
  3141. testTime(t, testBincH)
  3142. }
  3143. func TestSimpleTime(t *testing.T) {
  3144. testTime(t, testSimpleH)
  3145. }
  3146. func TestJsonUintToInt(t *testing.T) {
  3147. testUintToInt(t, testJsonH)
  3148. }
  3149. func TestCborUintToInt(t *testing.T) {
  3150. testUintToInt(t, testCborH)
  3151. }
  3152. func TestMsgpackUintToInt(t *testing.T) {
  3153. testUintToInt(t, testMsgpackH)
  3154. }
  3155. func TestBincUintToInt(t *testing.T) {
  3156. testUintToInt(t, testBincH)
  3157. }
  3158. func TestSimpleUintToInt(t *testing.T) {
  3159. testUintToInt(t, testSimpleH)
  3160. }
  3161. func TestJsonDifferentMapOrSliceType(t *testing.T) {
  3162. doTestDifferentMapOrSliceType(t, testJsonH)
  3163. }
  3164. func TestCborDifferentMapOrSliceType(t *testing.T) {
  3165. doTestDifferentMapOrSliceType(t, testCborH)
  3166. }
  3167. func TestMsgpackDifferentMapOrSliceType(t *testing.T) {
  3168. doTestDifferentMapOrSliceType(t, testMsgpackH)
  3169. }
  3170. func TestBincDifferentMapOrSliceType(t *testing.T) {
  3171. doTestDifferentMapOrSliceType(t, testBincH)
  3172. }
  3173. func TestSimpleDifferentMapOrSliceType(t *testing.T) {
  3174. doTestDifferentMapOrSliceType(t, testSimpleH)
  3175. }
  3176. func TestJsonScalars(t *testing.T) {
  3177. doTestScalars(t, testJsonH)
  3178. }
  3179. func TestCborScalars(t *testing.T) {
  3180. doTestScalars(t, testCborH)
  3181. }
  3182. func TestMsgpackScalars(t *testing.T) {
  3183. doTestScalars(t, testMsgpackH)
  3184. }
  3185. func TestBincScalars(t *testing.T) {
  3186. doTestScalars(t, testBincH)
  3187. }
  3188. func TestSimpleScalars(t *testing.T) {
  3189. doTestScalars(t, testSimpleH)
  3190. }
  3191. func TestJsonOmitempty(t *testing.T) {
  3192. doTestOmitempty(t, testJsonH)
  3193. }
  3194. func TestCborOmitempty(t *testing.T) {
  3195. doTestOmitempty(t, testCborH)
  3196. }
  3197. func TestMsgpackOmitempty(t *testing.T) {
  3198. doTestOmitempty(t, testMsgpackH)
  3199. }
  3200. func TestBincOmitempty(t *testing.T) {
  3201. doTestOmitempty(t, testBincH)
  3202. }
  3203. func TestSimpleOmitempty(t *testing.T) {
  3204. doTestOmitempty(t, testSimpleH)
  3205. }
  3206. func TestJsonIntfMapping(t *testing.T) {
  3207. doTestIntfMapping(t, testJsonH)
  3208. }
  3209. func TestCborIntfMapping(t *testing.T) {
  3210. doTestIntfMapping(t, testCborH)
  3211. }
  3212. func TestMsgpackIntfMapping(t *testing.T) {
  3213. doTestIntfMapping(t, testMsgpackH)
  3214. }
  3215. func TestBincIntfMapping(t *testing.T) {
  3216. doTestIntfMapping(t, testBincH)
  3217. }
  3218. func TestSimpleIntfMapping(t *testing.T) {
  3219. doTestIntfMapping(t, testSimpleH)
  3220. }
  3221. func TestJsonMissingFields(t *testing.T) {
  3222. doTestMissingFields(t, testJsonH)
  3223. }
  3224. func TestCborMissingFields(t *testing.T) {
  3225. doTestMissingFields(t, testCborH)
  3226. }
  3227. func TestMsgpackMissingFields(t *testing.T) {
  3228. doTestMissingFields(t, testMsgpackH)
  3229. }
  3230. func TestBincMissingFields(t *testing.T) {
  3231. doTestMissingFields(t, testBincH)
  3232. }
  3233. func TestSimpleMissingFields(t *testing.T) {
  3234. doTestMissingFields(t, testSimpleH)
  3235. }
  3236. func TestJsonMaxDepth(t *testing.T) {
  3237. doTestMaxDepth(t, testJsonH)
  3238. }
  3239. func TestCborMaxDepth(t *testing.T) {
  3240. doTestMaxDepth(t, testCborH)
  3241. }
  3242. func TestMsgpackMaxDepth(t *testing.T) {
  3243. doTestMaxDepth(t, testMsgpackH)
  3244. }
  3245. func TestBincMaxDepth(t *testing.T) {
  3246. doTestMaxDepth(t, testBincH)
  3247. }
  3248. func TestSimpleMaxDepth(t *testing.T) {
  3249. doTestMaxDepth(t, testSimpleH)
  3250. }
  3251. func TestJsonSelfExt(t *testing.T) {
  3252. doTestSelfExt(t, testJsonH)
  3253. }
  3254. func TestCborSelfExt(t *testing.T) {
  3255. doTestSelfExt(t, testCborH)
  3256. }
  3257. func TestMsgpackSelfExt(t *testing.T) {
  3258. doTestSelfExt(t, testMsgpackH)
  3259. }
  3260. func TestBincSelfExt(t *testing.T) {
  3261. doTestSelfExt(t, testBincH)
  3262. }
  3263. func TestSimpleSelfExt(t *testing.T) {
  3264. doTestSelfExt(t, testSimpleH)
  3265. }
  3266. func TestJsonBytesEncodedAsArray(t *testing.T) {
  3267. doTestBytesEncodedAsArray(t, testJsonH)
  3268. }
  3269. func TestCborBytesEncodedAsArray(t *testing.T) {
  3270. doTestBytesEncodedAsArray(t, testCborH)
  3271. }
  3272. func TestMsgpackBytesEncodedAsArray(t *testing.T) {
  3273. doTestBytesEncodedAsArray(t, testMsgpackH)
  3274. }
  3275. func TestBincBytesEncodedAsArray(t *testing.T) {
  3276. doTestBytesEncodedAsArray(t, testBincH)
  3277. }
  3278. func TestSimpleBytesEncodedAsArray(t *testing.T) {
  3279. doTestBytesEncodedAsArray(t, testSimpleH)
  3280. }
  3281. func TestJsonStrucEncDec(t *testing.T) {
  3282. doTestStrucEncDec(t, testJsonH)
  3283. }
  3284. func TestCborStrucEncDec(t *testing.T) {
  3285. doTestStrucEncDec(t, testCborH)
  3286. }
  3287. func TestMsgpackStrucEncDec(t *testing.T) {
  3288. doTestStrucEncDec(t, testMsgpackH)
  3289. }
  3290. func TestBincStrucEncDec(t *testing.T) {
  3291. doTestStrucEncDec(t, testBincH)
  3292. }
  3293. func TestSimpleStrucEncDec(t *testing.T) {
  3294. doTestStrucEncDec(t, testSimpleH)
  3295. }
  3296. func TestJsonRawToStringToRawEtc(t *testing.T) {
  3297. doTestRawToStringToRawEtc(t, testJsonH)
  3298. }
  3299. func TestCborRawToStringToRawEtc(t *testing.T) {
  3300. doTestRawToStringToRawEtc(t, testCborH)
  3301. }
  3302. func TestMsgpackRawToStringToRawEtc(t *testing.T) {
  3303. doTestRawToStringToRawEtc(t, testMsgpackH)
  3304. }
  3305. func TestBincRawToStringToRawEtc(t *testing.T) {
  3306. doTestRawToStringToRawEtc(t, testBincH)
  3307. }
  3308. func TestSimpleRawToStringToRawEtc(t *testing.T) {
  3309. doTestRawToStringToRawEtc(t, testSimpleH)
  3310. }
  3311. func TestJsonStructKeyType(t *testing.T) {
  3312. doTestStructKeyType(t, testJsonH)
  3313. }
  3314. func TestCborStructKeyType(t *testing.T) {
  3315. doTestStructKeyType(t, testCborH)
  3316. }
  3317. func TestMsgpackStructKeyType(t *testing.T) {
  3318. doTestStructKeyType(t, testMsgpackH)
  3319. }
  3320. func TestBincStructKeyType(t *testing.T) {
  3321. doTestStructKeyType(t, testBincH)
  3322. }
  3323. func TestSimpleStructKeyType(t *testing.T) {
  3324. doTestStructKeyType(t, testSimpleH)
  3325. }
  3326. // --------
  3327. func TestMultipleEncDec(t *testing.T) {
  3328. doTestMultipleEncDec(t, testJsonH)
  3329. }
  3330. // TODO:
  3331. //
  3332. // Add Tests for the following:
  3333. // - struct tags: on anonymous fields, _struct (all fields), etc
  3334. // - chan to encode and decode (with support for codecgen also)
  3335. //
  3336. // Add negative tests for failure conditions:
  3337. // - bad input with large array length prefix
  3338. //
  3339. // Add tests for decode.go (standalone)
  3340. // - UnreadByte: only 2 states (z.ls = 2 and z.ls = 1) (0 --> 2 --> 1)
  3341. // - track: z.trb: track, stop track, check
  3342. // - PreferArrayOverSlice???
  3343. // - InterfaceReset
  3344. // - (chan byte) to decode []byte (with mapbyslice track)
  3345. // - decode slice of len 6, 16 into slice of (len 4, cap 8) and (len ) with maxinitlen=6, 8, 16
  3346. // - DeleteOnNilMapValue
  3347. // - decnaked: n.l == nil
  3348. // - ensureDecodeable (try to decode into a non-decodeable thing e.g. a nil interface{},
  3349. //
  3350. // Add tests for encode.go (standalone)
  3351. // - nil and 0-len slices and maps for non-fastpath things