codec_test.go 86 KB

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