codec_test.go 79 KB

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