codec_test.go 84 KB

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