codec_test.go 76 KB

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