codec_test.go 71 KB

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