codec_test.go 88 KB

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