codec_test.go 76 KB

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