codec_test.go 79 KB

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