codec_test.go 75 KB

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