codec_test.go 92 KB

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