codec_test.go 100 KB

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