codec_test.go 71 KB

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