codec_test.go 86 KB

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