codec_test.go 72 KB

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