codec_test.go 76 KB

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