codec_test.go 87 KB

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