codec_test.go 102 KB

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