codec_test.go 71 KB

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