codec_test.go 93 KB

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