codec_test.go 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179
  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(errDecoratorDef{}, &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(errDecoratorDef{}, &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") // listen on ipv4 localhost
  1045. logT(t, "connFn: addr: %v, network: %v, port: %v", ln.Addr(), ln.Addr().Network(), (ln.Addr().(*net.TCPAddr)).Port)
  1046. // log("listener: %v", ln.Addr())
  1047. checkErrT(t, err)
  1048. port = (ln.Addr().(*net.TCPAddr)).Port
  1049. // var opts *DecoderOptions
  1050. // opts := testDecOpts
  1051. // opts.MapType = mapStrIntfTyp
  1052. // opts.RawToString = false
  1053. serverExitChan := make(chan bool, 1)
  1054. var serverExitFlag uint64
  1055. serverFn := func() {
  1056. for {
  1057. conn1, err1 := ln.Accept()
  1058. // if err1 != nil {
  1059. // //fmt.Printf("accept err1: %v\n", err1)
  1060. // continue
  1061. // }
  1062. if atomic.LoadUint64(&serverExitFlag) == 1 {
  1063. serverExitChan <- true
  1064. if conn1 != nil {
  1065. conn1.Close()
  1066. }
  1067. return // exit serverFn goroutine
  1068. }
  1069. if err1 == nil && conn1 != nil {
  1070. sc := rr.ServerCodec(testReadWriteCloser(conn1), h)
  1071. srv.ServeCodec(sc)
  1072. }
  1073. }
  1074. }
  1075. clientFn := func(cc rpc.ClientCodec) {
  1076. cl := rpc.NewClientWithCodec(cc)
  1077. defer cl.Close()
  1078. // defer func() { println("##### client closing"); cl.Close() }()
  1079. var up, sq, mult int
  1080. var rstr string
  1081. // log("Calling client")
  1082. checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
  1083. // log("Called TestRpcInt.Update")
  1084. checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5")
  1085. checkEqualT(t, up, 5, "up=5")
  1086. checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
  1087. checkEqualT(t, sq, 25, "sq=25")
  1088. checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
  1089. checkEqualT(t, mult, 100, "mult=100")
  1090. checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1091. checkEqualT(t, rstr, fmt.Sprintf("%#v", TestRpcABC{"Aa", "Bb", "Cc"}), "rstr=")
  1092. checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
  1093. checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=")
  1094. }
  1095. connFn := func() (bs net.Conn) {
  1096. // log("calling f1")
  1097. bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
  1098. checkErrT(t, err2)
  1099. return
  1100. }
  1101. exitFn := func() {
  1102. atomic.StoreUint64(&serverExitFlag, 1)
  1103. bs := connFn()
  1104. <-serverExitChan
  1105. bs.Close()
  1106. // serverExitChan <- true
  1107. }
  1108. go serverFn()
  1109. runtime.Gosched()
  1110. //time.Sleep(100 * time.Millisecond)
  1111. if exitSleepMs == 0 {
  1112. defer ln.Close()
  1113. defer exitFn()
  1114. }
  1115. if doRequest {
  1116. bs := connFn()
  1117. cc := rr.ClientCodec(testReadWriteCloser(bs), h)
  1118. clientFn(cc)
  1119. }
  1120. if exitSleepMs != 0 {
  1121. go func() {
  1122. defer ln.Close()
  1123. time.Sleep(exitSleepMs)
  1124. exitFn()
  1125. }()
  1126. }
  1127. return
  1128. }
  1129. func doTestMapEncodeForCanonical(t *testing.T, name string, h Handle) {
  1130. testOnce.Do(testInitAll)
  1131. // println("doTestMapEncodeForCanonical")
  1132. v1 := map[stringUint64T]interface{}{
  1133. {"a", 1}: 1,
  1134. {"b", 2}: "hello",
  1135. {"c", 3}: map[string]interface{}{
  1136. "c/a": 1,
  1137. "c/b": "world",
  1138. "c/c": []int{1, 2, 3, 4},
  1139. "c/d": map[string]interface{}{
  1140. "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda",
  1141. "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa",
  1142. "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw",
  1143. "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag",
  1144. "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb",
  1145. "c/d/f": "",
  1146. },
  1147. "c/e": map[int]string{
  1148. 1: "1",
  1149. 22: "22",
  1150. 333: "333",
  1151. 4444: "4444",
  1152. 55555: "55555",
  1153. },
  1154. "c/f": map[string]int{
  1155. "1": 1,
  1156. "22": 22,
  1157. "333": 333,
  1158. "4444": 4444,
  1159. "55555": 55555,
  1160. },
  1161. "c/g": map[bool]int{
  1162. false: 0,
  1163. true: 1,
  1164. },
  1165. },
  1166. }
  1167. var v2 map[stringUint64T]interface{}
  1168. var b1, b2, b3 []byte
  1169. // encode v1 into b1, decode b1 into v2, encode v2 into b2, and compare b1 and b2.
  1170. // OR
  1171. // encode v1 into b1, decode b1 into v2, encode v2 into b2 and b3, and compare b2 and b3.
  1172. // e.g. when doing cbor indefinite, we may haveto use out-of-band encoding
  1173. // where each key is encoded as an indefinite length string, which makes it not the same
  1174. // order as the strings were lexicographically ordered before.
  1175. var cborIndef bool
  1176. if ch, ok := h.(*CborHandle); ok {
  1177. cborIndef = ch.IndefiniteLength
  1178. }
  1179. bh := h.getBasicHandle()
  1180. if !bh.Canonical {
  1181. bh.Canonical = true
  1182. defer func() { bh.Canonical = false }()
  1183. }
  1184. e1 := NewEncoderBytes(&b1, h)
  1185. e1.MustEncode(v1)
  1186. d1 := NewDecoderBytes(b1, h)
  1187. d1.MustDecode(&v2)
  1188. // testDeepEqualErr(v1, v2, t, "huh?")
  1189. e2 := NewEncoderBytes(&b2, h)
  1190. e2.MustEncode(v2)
  1191. var b1t, b2t = b1, b2
  1192. if cborIndef {
  1193. e2 = NewEncoderBytes(&b3, h)
  1194. e2.MustEncode(v2)
  1195. b1t, b2t = b2, b3
  1196. }
  1197. if !bytes.Equal(b1t, b2t) {
  1198. logT(t, "Unequal bytes: %v VS %v", b1t, b2t)
  1199. failT(t)
  1200. }
  1201. }
  1202. func doTestStdEncIntf(t *testing.T, name string, h Handle) {
  1203. testOnce.Do(testInitAll)
  1204. args := [][2]interface{}{
  1205. {&TestABC{"A", "BB", "CCC"}, new(TestABC)},
  1206. {&TestABC2{"AAA", "BB", "C"}, new(TestABC2)},
  1207. }
  1208. for _, a := range args {
  1209. var b []byte
  1210. e := NewEncoderBytes(&b, h)
  1211. e.MustEncode(a[0])
  1212. d := NewDecoderBytes(b, h)
  1213. d.MustDecode(a[1])
  1214. if err := deepEqual(a[0], a[1]); err == nil {
  1215. logT(t, "++++ Objects match")
  1216. } else {
  1217. logT(t, "---- FAIL: Objects do not match: y1: %v, err: %v", a[1], err)
  1218. failT(t)
  1219. }
  1220. }
  1221. }
  1222. func doTestEncCircularRef(t *testing.T, name string, h Handle) {
  1223. testOnce.Do(testInitAll)
  1224. type T1 struct {
  1225. S string
  1226. B bool
  1227. T interface{}
  1228. }
  1229. type T2 struct {
  1230. S string
  1231. T *T1
  1232. }
  1233. type T3 struct {
  1234. S string
  1235. T *T2
  1236. }
  1237. t1 := T1{"t1", true, nil}
  1238. t2 := T2{"t2", &t1}
  1239. t3 := T3{"t3", &t2}
  1240. t1.T = &t3
  1241. var bs []byte
  1242. var err error
  1243. bh := h.getBasicHandle()
  1244. if !bh.CheckCircularRef {
  1245. bh.CheckCircularRef = true
  1246. defer func() { bh.CheckCircularRef = false }()
  1247. }
  1248. err = NewEncoderBytes(&bs, h).Encode(&t3)
  1249. if err == nil {
  1250. logT(t, "expecting error due to circular reference. found none")
  1251. failT(t)
  1252. }
  1253. if x := err.Error(); strings.Contains(x, "circular") || strings.Contains(x, "cyclic") {
  1254. logT(t, "error detected as expected: %v", x)
  1255. } else {
  1256. logT(t, "FAIL: error detected was not as expected: %v", x)
  1257. failT(t)
  1258. }
  1259. }
  1260. // TestAnonCycleT{1,2,3} types are used to test anonymous cycles.
  1261. // They are top-level, so that they can have circular references.
  1262. type (
  1263. TestAnonCycleT1 struct {
  1264. S string
  1265. TestAnonCycleT2
  1266. }
  1267. TestAnonCycleT2 struct {
  1268. S2 string
  1269. TestAnonCycleT3
  1270. }
  1271. TestAnonCycleT3 struct {
  1272. *TestAnonCycleT1
  1273. }
  1274. )
  1275. func doTestAnonCycle(t *testing.T, name string, h Handle) {
  1276. testOnce.Do(testInitAll)
  1277. var x TestAnonCycleT1
  1278. x.S = "hello"
  1279. x.TestAnonCycleT2.S2 = "hello.2"
  1280. x.TestAnonCycleT2.TestAnonCycleT3.TestAnonCycleT1 = &x
  1281. // just check that you can get typeInfo for T1
  1282. rt := reflect.TypeOf((*TestAnonCycleT1)(nil)).Elem()
  1283. rtid := rt2id(rt)
  1284. pti := h.getBasicHandle().getTypeInfo(rtid, rt)
  1285. logT(t, "pti: %v", pti)
  1286. }
  1287. func doTestJsonLargeInteger(t *testing.T, v interface{}, ias uint8) {
  1288. testOnce.Do(testInitAll)
  1289. logT(t, "Running doTestJsonLargeInteger: v: %#v, ias: %c", v, ias)
  1290. oldIAS := testJsonH.IntegerAsString
  1291. defer func() { testJsonH.IntegerAsString = oldIAS }()
  1292. testJsonH.IntegerAsString = ias
  1293. var vu uint
  1294. var vi int
  1295. var vb bool
  1296. var b []byte
  1297. e := NewEncoderBytes(&b, testJsonH)
  1298. e.MustEncode(v)
  1299. e.MustEncode(true)
  1300. d := NewDecoderBytes(b, testJsonH)
  1301. // below, we validate that the json string or number was encoded,
  1302. // then decode, and validate that the correct value was decoded.
  1303. fnStrChk := func() {
  1304. // check that output started with ", and ended with "true
  1305. if !(b[0] == '"' && string(b[len(b)-5:]) == `"true`) {
  1306. logT(t, "Expecting a JSON string, got: %s", b)
  1307. failT(t)
  1308. }
  1309. }
  1310. switch ias {
  1311. case 'L':
  1312. switch v2 := v.(type) {
  1313. case int:
  1314. v2n := int64(v2) // done to work with 32-bit OS
  1315. if v2n > 1<<53 || (v2n < 0 && -v2n > 1<<53) {
  1316. fnStrChk()
  1317. }
  1318. case uint:
  1319. v2n := uint64(v2) // done to work with 32-bit OS
  1320. if v2n > 1<<53 {
  1321. fnStrChk()
  1322. }
  1323. }
  1324. case 'A':
  1325. fnStrChk()
  1326. default:
  1327. // check that output doesn't contain " at all
  1328. for _, i := range b {
  1329. if i == '"' {
  1330. logT(t, "Expecting a JSON Number without quotation: got: %s", b)
  1331. failT(t)
  1332. }
  1333. }
  1334. }
  1335. switch v2 := v.(type) {
  1336. case int:
  1337. d.MustDecode(&vi)
  1338. d.MustDecode(&vb)
  1339. // check that vb = true, and vi == v2
  1340. if !(vb && vi == v2) {
  1341. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vi)
  1342. failT(t)
  1343. }
  1344. case uint:
  1345. d.MustDecode(&vu)
  1346. d.MustDecode(&vb)
  1347. // check that vb = true, and vi == v2
  1348. if !(vb && vu == v2) {
  1349. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vu)
  1350. failT(t)
  1351. }
  1352. }
  1353. }
  1354. func doTestRawValue(t *testing.T, name string, h Handle) {
  1355. testOnce.Do(testInitAll)
  1356. bh := h.getBasicHandle()
  1357. if !bh.Raw {
  1358. bh.Raw = true
  1359. defer func() { bh.Raw = false }()
  1360. }
  1361. var i, i2 int
  1362. var v, v2 TestRawValue
  1363. var bs, bs2 []byte
  1364. i = 1234 //1234567890
  1365. v = TestRawValue{I: i}
  1366. e := NewEncoderBytes(&bs, h)
  1367. e.MustEncode(v.I)
  1368. logT(t, ">>> raw: %v\n", bs)
  1369. v.R = Raw(bs)
  1370. e.ResetBytes(&bs2)
  1371. e.MustEncode(v)
  1372. logT(t, ">>> bs2: %v\n", bs2)
  1373. d := NewDecoderBytes(bs2, h)
  1374. d.MustDecode(&v2)
  1375. d.ResetBytes(v2.R)
  1376. logT(t, ">>> v2.R: %v\n", ([]byte)(v2.R))
  1377. d.MustDecode(&i2)
  1378. logT(t, ">>> Encoded %v, decoded %v\n", i, i2)
  1379. // logT(t, "Encoded %v, decoded %v", i, i2)
  1380. if i != i2 {
  1381. logT(t, "Error: encoded %v, decoded %v", i, i2)
  1382. failT(t)
  1383. }
  1384. }
  1385. // Comprehensive testing that generates data encoded from python handle (cbor, msgpack),
  1386. // and validates that our code can read and write it out accordingly.
  1387. // We keep this unexported here, and put actual test in ext_dep_test.go.
  1388. // This way, it can be excluded by excluding file completely.
  1389. func doTestPythonGenStreams(t *testing.T, name string, h Handle) {
  1390. testOnce.Do(testInitAll)
  1391. logT(t, "TestPythonGenStreams-%v", name)
  1392. tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test")
  1393. if err != nil {
  1394. logT(t, "-------- Unable to create temp directory\n")
  1395. failT(t)
  1396. }
  1397. defer os.RemoveAll(tmpdir)
  1398. logT(t, "tmpdir: %v", tmpdir)
  1399. cmd := exec.Command("python", "test.py", "testdata", tmpdir)
  1400. //cmd.Stdin = strings.NewReader("some input")
  1401. //cmd.Stdout = &out
  1402. var cmdout []byte
  1403. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1404. logT(t, "-------- Error running test.py testdata. Err: %v", err)
  1405. logT(t, " %v", string(cmdout))
  1406. failT(t)
  1407. }
  1408. bh := h.getBasicHandle()
  1409. oldMapType := bh.MapType
  1410. tablePythonVerify := testTableVerify(testVerifyForPython|testVerifyTimeAsInteger|testVerifyMapTypeStrIntf, h)
  1411. for i, v := range tablePythonVerify {
  1412. // if v == uint64(0) && h == testMsgpackH {
  1413. // v = int64(0)
  1414. // }
  1415. bh.MapType = oldMapType
  1416. //load up the golden file based on number
  1417. //decode it
  1418. //compare to in-mem object
  1419. //encode it again
  1420. //compare to output stream
  1421. logT(t, "..............................................")
  1422. logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
  1423. var bss []byte
  1424. bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden"))
  1425. if err != nil {
  1426. logT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
  1427. failT(t)
  1428. continue
  1429. }
  1430. bh.MapType = testMapStrIntfTyp
  1431. var v1 interface{}
  1432. if err = testUnmarshal(&v1, bss, h); err != nil {
  1433. logT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
  1434. failT(t)
  1435. continue
  1436. }
  1437. if v == skipVerifyVal {
  1438. continue
  1439. }
  1440. //no need to indirect, because we pass a nil ptr, so we already have the value
  1441. //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
  1442. if err = deepEqual(v, v1); err == nil {
  1443. logT(t, "++++++++ Objects match: %T, %v", v, v)
  1444. } else {
  1445. logT(t, "-------- FAIL: Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
  1446. logT(t, "-------- GOLDEN: %#v", v)
  1447. // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1448. logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1449. failT(t)
  1450. }
  1451. bsb, err := testMarshal(v1, h)
  1452. if err != nil {
  1453. logT(t, "Error encoding to stream: %d: Err: %v", i, err)
  1454. failT(t)
  1455. continue
  1456. }
  1457. if err = deepEqual(bsb, bss); err == nil {
  1458. logT(t, "++++++++ Bytes match")
  1459. } else {
  1460. logT(t, "???????? FAIL: Bytes do not match. %v.", err)
  1461. xs := "--------"
  1462. if reflect.ValueOf(v).Kind() == reflect.Map {
  1463. xs = " "
  1464. logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
  1465. } else {
  1466. logT(t, "%s It's not a map. They should match.", xs)
  1467. failT(t)
  1468. }
  1469. logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
  1470. logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
  1471. }
  1472. }
  1473. bh.MapType = oldMapType
  1474. }
  1475. // To test MsgpackSpecRpc, we test 3 scenarios:
  1476. // - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
  1477. // - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
  1478. // - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
  1479. //
  1480. // This allows us test the different calling conventions
  1481. // - Go Service requires only one argument
  1482. // - Python Service allows multiple arguments
  1483. func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
  1484. if testSkipRPCTests {
  1485. return
  1486. }
  1487. testOnce.Do(testInitAll)
  1488. // openPorts are between 6700 and 6800
  1489. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  1490. openPort := strconv.FormatInt(6700+r.Int63n(99), 10)
  1491. // openPort := "6792"
  1492. cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4")
  1493. checkErrT(t, cmd.Start())
  1494. bs, err2 := net.Dial("tcp", ":"+openPort)
  1495. for i := 0; i < 10 && err2 != nil; i++ {
  1496. time.Sleep(50 * time.Millisecond) // time for python rpc server to start
  1497. bs, err2 = net.Dial("tcp", ":"+openPort)
  1498. }
  1499. checkErrT(t, err2)
  1500. cc := MsgpackSpecRpc.ClientCodec(testReadWriteCloser(bs), testMsgpackH)
  1501. cl := rpc.NewClientWithCodec(cc)
  1502. defer cl.Close()
  1503. var rstr string
  1504. checkErrT(t, cl.Call("EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1505. //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
  1506. var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
  1507. checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
  1508. checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
  1509. cmd.Process.Kill()
  1510. }
  1511. func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
  1512. if testSkipRPCTests {
  1513. return
  1514. }
  1515. testOnce.Do(testInitAll)
  1516. port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
  1517. //time.Sleep(1000 * time.Millisecond)
  1518. cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port))
  1519. var cmdout []byte
  1520. var err error
  1521. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1522. logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err)
  1523. logT(t, " %v", string(cmdout))
  1524. failT(t)
  1525. }
  1526. checkEqualT(t, string(cmdout),
  1527. fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestRpcABC{"Aa", "Bb", "Cc"}), "cmdout=")
  1528. }
  1529. func doTestSwallowAndZero(t *testing.T, h Handle) {
  1530. testOnce.Do(testInitAll)
  1531. v1 := newTestStrucFlex(testDepth, testNumRepeatString, false, false, false)
  1532. var b1 []byte
  1533. e1 := NewEncoderBytes(&b1, h)
  1534. e1.MustEncode(v1)
  1535. d1 := NewDecoderBytes(b1, h)
  1536. d1.swallow()
  1537. if d1.r.numread() != len(b1) {
  1538. logT(t, "swallow didn't consume all encoded bytes: %v out of %v", d1.r.numread(), len(b1))
  1539. failT(t)
  1540. }
  1541. setZero(v1)
  1542. testDeepEqualErr(v1, &TestStrucFlex{}, t, "filled-and-zeroed")
  1543. }
  1544. func doTestRawExt(t *testing.T, h Handle) {
  1545. testOnce.Do(testInitAll)
  1546. var b []byte
  1547. var v RawExt // interface{}
  1548. _, isJson := h.(*JsonHandle)
  1549. _, isCbor := h.(*CborHandle)
  1550. bh := h.getBasicHandle()
  1551. // isValuer := isJson || isCbor
  1552. // _ = isValuer
  1553. for _, r := range []RawExt{
  1554. {Tag: 99, Value: "9999", Data: []byte("9999")},
  1555. } {
  1556. e := NewEncoderBytes(&b, h)
  1557. e.MustEncode(&r)
  1558. // fmt.Printf(">>>> rawext: isnil? %v, %d - %v\n", b == nil, len(b), b)
  1559. d := NewDecoderBytes(b, h)
  1560. d.MustDecode(&v)
  1561. var r2 = r
  1562. switch {
  1563. case isJson:
  1564. r2.Tag = 0
  1565. r2.Data = nil
  1566. case isCbor:
  1567. r2.Data = nil
  1568. default:
  1569. r2.Value = nil
  1570. }
  1571. testDeepEqualErr(v, r2, t, "rawext-default")
  1572. // switch h.(type) {
  1573. // case *JsonHandle:
  1574. // testDeepEqualErr(r.Value, v, t, "rawext-json")
  1575. // default:
  1576. // var r2 = r
  1577. // if isValuer {
  1578. // r2.Data = nil
  1579. // } else {
  1580. // r2.Value = nil
  1581. // }
  1582. // testDeepEqualErr(v, r2, t, "rawext-default")
  1583. // }
  1584. }
  1585. // Add testing for Raw also
  1586. if b != nil {
  1587. b = b[:0]
  1588. }
  1589. oldRawMode := bh.Raw
  1590. defer func() { bh.Raw = oldRawMode }()
  1591. bh.Raw = true
  1592. var v2 Raw
  1593. for _, s := range []string{
  1594. "goodbye",
  1595. "hello",
  1596. } {
  1597. e := NewEncoderBytes(&b, h)
  1598. e.MustEncode(&s)
  1599. // fmt.Printf(">>>> rawext: isnil? %v, %d - %v\n", b == nil, len(b), b)
  1600. var r Raw = make([]byte, len(b))
  1601. copy(r, b)
  1602. d := NewDecoderBytes(b, h)
  1603. d.MustDecode(&v2)
  1604. testDeepEqualErr(v2, r, t, "raw-default")
  1605. }
  1606. }
  1607. // func doTestTimeExt(t *testing.T, h Handle) {
  1608. // var t = time.Now()
  1609. // // add time ext to the handle
  1610. // }
  1611. func doTestMapStructKey(t *testing.T, h Handle) {
  1612. testOnce.Do(testInitAll)
  1613. var b []byte
  1614. var v interface{} // map[stringUint64T]wrapUint64Slice // interface{}
  1615. bh := h.getBasicHandle()
  1616. m := map[stringUint64T]wrapUint64Slice{
  1617. {"55555", 55555}: []wrapUint64{12345},
  1618. {"333", 333}: []wrapUint64{123},
  1619. }
  1620. oldCanonical := bh.Canonical
  1621. oldMapType := bh.MapType
  1622. defer func() {
  1623. bh.Canonical = oldCanonical
  1624. bh.MapType = oldMapType
  1625. }()
  1626. bh.MapType = reflect.TypeOf((*map[stringUint64T]wrapUint64Slice)(nil)).Elem()
  1627. for _, bv := range [2]bool{true, false} {
  1628. b, v = nil, nil
  1629. bh.Canonical = bv
  1630. e := NewEncoderBytes(&b, h)
  1631. e.MustEncode(m)
  1632. d := NewDecoderBytes(b, h)
  1633. d.MustDecode(&v)
  1634. testDeepEqualErr(v, m, t, "map-structkey")
  1635. }
  1636. }
  1637. func doTestDecodeNilMapValue(t *testing.T, handle Handle) {
  1638. testOnce.Do(testInitAll)
  1639. type Struct struct {
  1640. Field map[uint16]map[uint32]struct{}
  1641. }
  1642. bh := handle.getBasicHandle()
  1643. oldMapType := bh.MapType
  1644. oldDeleteOnNilMapValue := bh.DeleteOnNilMapValue
  1645. defer func() {
  1646. bh.MapType = oldMapType
  1647. bh.DeleteOnNilMapValue = oldDeleteOnNilMapValue
  1648. }()
  1649. bh.MapType = reflect.TypeOf(map[interface{}]interface{}(nil))
  1650. bh.DeleteOnNilMapValue = false
  1651. _, isJsonHandle := handle.(*JsonHandle)
  1652. toEncode := Struct{Field: map[uint16]map[uint32]struct{}{
  1653. 1: nil,
  1654. }}
  1655. bs, err := testMarshal(toEncode, handle)
  1656. if err != nil {
  1657. logT(t, "Error encoding: %v, Err: %v", toEncode, err)
  1658. failT(t)
  1659. }
  1660. if isJsonHandle {
  1661. logT(t, "json encoded: %s\n", bs)
  1662. }
  1663. var decoded Struct
  1664. err = testUnmarshal(&decoded, bs, handle)
  1665. if err != nil {
  1666. logT(t, "Error decoding: %v", err)
  1667. failT(t)
  1668. }
  1669. if !reflect.DeepEqual(decoded, toEncode) {
  1670. logT(t, "Decoded value %#v != %#v", decoded, toEncode)
  1671. failT(t)
  1672. }
  1673. }
  1674. func doTestEmbeddedFieldPrecedence(t *testing.T, h Handle) {
  1675. testOnce.Do(testInitAll)
  1676. type Embedded struct {
  1677. Field byte
  1678. }
  1679. type Struct struct {
  1680. Field byte
  1681. Embedded
  1682. }
  1683. toEncode := Struct{
  1684. Field: 1,
  1685. Embedded: Embedded{Field: 2},
  1686. }
  1687. _, isJsonHandle := h.(*JsonHandle)
  1688. handle := h.getBasicHandle()
  1689. oldMapType := handle.MapType
  1690. defer func() { handle.MapType = oldMapType }()
  1691. handle.MapType = reflect.TypeOf(map[interface{}]interface{}(nil))
  1692. bs, err := testMarshal(toEncode, h)
  1693. if err != nil {
  1694. logT(t, "Error encoding: %v, Err: %v", toEncode, err)
  1695. failT(t)
  1696. }
  1697. var decoded Struct
  1698. err = testUnmarshal(&decoded, bs, h)
  1699. if err != nil {
  1700. logT(t, "Error decoding: %v", err)
  1701. failT(t)
  1702. }
  1703. if decoded.Field != toEncode.Field {
  1704. logT(t, "Decoded result %v != %v", decoded.Field, toEncode.Field) // hex to look at what was encoded
  1705. if isJsonHandle {
  1706. logT(t, "JSON encoded as: %s", bs) // hex to look at what was encoded
  1707. }
  1708. failT(t)
  1709. }
  1710. }
  1711. func doTestLargeContainerLen(t *testing.T, h Handle) {
  1712. testOnce.Do(testInitAll)
  1713. m := make(map[int][]struct{})
  1714. for i := range []int{
  1715. 0, 1,
  1716. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1717. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1718. math.MaxInt32, math.MaxInt32 - 4,
  1719. // math.MaxInt32 + 4, // bombs on 32-bit
  1720. // math.MaxInt64, math.MaxInt64 - 4, // bombs on 32-bit
  1721. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1722. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1723. // math.MaxUint32, math.MaxUint32 + 4, math.MaxUint32 - 4, // bombs on 32-bit
  1724. } {
  1725. m[i] = make([]struct{}, i)
  1726. }
  1727. bs := testMarshalErr(m, h, t, "-")
  1728. var m2 = make(map[int][]struct{})
  1729. testUnmarshalErr(m2, bs, h, t, "-")
  1730. testDeepEqualErr(m, m2, t, "-")
  1731. // do same tests for large strings (encoded as symbols or not)
  1732. // skip if 32-bit or not using unsafe mode
  1733. if safeMode || (32<<(^uint(0)>>63)) < 64 {
  1734. return
  1735. }
  1736. // now, want to do tests for large strings, which
  1737. // could be encoded as symbols.
  1738. // to do this, we create a simple one-field struct,
  1739. // use use flags to switch from symbols to non-symbols
  1740. hbinc, okbinc := h.(*BincHandle)
  1741. if okbinc {
  1742. oldAsSymbols := hbinc.AsSymbols
  1743. defer func() { hbinc.AsSymbols = oldAsSymbols }()
  1744. }
  1745. var out []byte = make([]byte, 0, math.MaxUint16*3/2)
  1746. var in []byte = make([]byte, math.MaxUint16*3/2)
  1747. for i := range in {
  1748. in[i] = 'A'
  1749. }
  1750. e := NewEncoder(nil, h)
  1751. for _, i := range []int{
  1752. 0, 1, 4, 8, 12, 16, 28, 32, 36,
  1753. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1754. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1755. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1756. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1757. } {
  1758. var m1, m2 map[string]bool
  1759. m1 = make(map[string]bool, 1)
  1760. var s1 = stringView(in[:i])
  1761. // fmt.Printf("testcontainerlen: large string: i: %v, |%s|\n", i, s1)
  1762. m1[s1] = true
  1763. if okbinc {
  1764. hbinc.AsSymbols = 2
  1765. }
  1766. out = out[:0]
  1767. e.ResetBytes(&out)
  1768. e.MustEncode(m1)
  1769. // bs, _ = testMarshalErr(m1, h, t, "-")
  1770. m2 = make(map[string]bool, 1)
  1771. testUnmarshalErr(m2, out, h, t, "no-symbols")
  1772. testDeepEqualErr(m1, m2, t, "no-symbols")
  1773. if okbinc {
  1774. // now, do as symbols
  1775. hbinc.AsSymbols = 1
  1776. out = out[:0]
  1777. e.ResetBytes(&out)
  1778. e.MustEncode(m1)
  1779. // bs, _ = testMarshalErr(m1, h, t, "-")
  1780. m2 = make(map[string]bool, 1)
  1781. testUnmarshalErr(m2, out, h, t, "symbols")
  1782. testDeepEqualErr(m1, m2, t, "symbols")
  1783. }
  1784. }
  1785. }
  1786. func testRandomFillRV(v reflect.Value) {
  1787. testOnce.Do(testInitAll)
  1788. fneg := func() int64 {
  1789. i := rand.Intn(1)
  1790. if i == 1 {
  1791. return 1
  1792. }
  1793. return -1
  1794. }
  1795. switch v.Kind() {
  1796. case reflect.Invalid:
  1797. case reflect.Ptr:
  1798. if v.IsNil() {
  1799. v.Set(reflect.New(v.Type().Elem()))
  1800. }
  1801. testRandomFillRV(v.Elem())
  1802. case reflect.Interface:
  1803. if v.IsNil() {
  1804. v.Set(reflect.ValueOf("nothing"))
  1805. } else {
  1806. testRandomFillRV(v.Elem())
  1807. }
  1808. case reflect.Struct:
  1809. for i, n := 0, v.NumField(); i < n; i++ {
  1810. testRandomFillRV(v.Field(i))
  1811. }
  1812. case reflect.Slice:
  1813. if v.IsNil() {
  1814. v.Set(reflect.MakeSlice(v.Type(), 4, 4))
  1815. }
  1816. fallthrough
  1817. case reflect.Array:
  1818. for i, n := 0, v.Len(); i < n; i++ {
  1819. testRandomFillRV(v.Index(i))
  1820. }
  1821. case reflect.Map:
  1822. if v.IsNil() {
  1823. v.Set(reflect.MakeMap(v.Type()))
  1824. }
  1825. if v.Len() == 0 {
  1826. kt, vt := v.Type().Key(), v.Type().Elem()
  1827. for i := 0; i < 4; i++ {
  1828. k0 := reflect.New(kt).Elem()
  1829. v0 := reflect.New(vt).Elem()
  1830. testRandomFillRV(k0)
  1831. testRandomFillRV(v0)
  1832. v.SetMapIndex(k0, v0)
  1833. }
  1834. } else {
  1835. for _, k := range v.MapKeys() {
  1836. testRandomFillRV(v.MapIndex(k))
  1837. }
  1838. }
  1839. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1840. v.SetInt(fneg() * rand.Int63n(127))
  1841. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1842. v.SetUint(uint64(rand.Int63n(255)))
  1843. case reflect.Bool:
  1844. v.SetBool(fneg() == 1)
  1845. case reflect.Float32, reflect.Float64:
  1846. v.SetFloat(float64(fneg()) * float64(rand.Float32()))
  1847. case reflect.String:
  1848. // ensure this string can test the extent of json string decoding
  1849. v.SetString(strings.Repeat(strconv.FormatInt(rand.Int63n(99), 10), rand.Intn(8)) +
  1850. "- ABC \x41=\x42 \u2318 - \r \b \f - \u2028 and \u2029 .")
  1851. default:
  1852. panic(fmt.Errorf("testRandomFillRV: unsupported type: %v", v.Kind()))
  1853. }
  1854. }
  1855. func testMammoth(t *testing.T, name string, h Handle) {
  1856. testOnce.Do(testInitAll)
  1857. var b []byte
  1858. var m, m2 TestMammoth
  1859. testRandomFillRV(reflect.ValueOf(&m).Elem())
  1860. b = testMarshalErr(&m, h, t, "mammoth-"+name)
  1861. testUnmarshalErr(&m2, b, h, t, "mammoth-"+name)
  1862. testDeepEqualErr(&m, &m2, t, "mammoth-"+name)
  1863. var mm, mm2 TestMammoth2Wrapper
  1864. testRandomFillRV(reflect.ValueOf(&mm).Elem())
  1865. b = testMarshalErr(&mm, h, t, "mammoth2-"+name)
  1866. testUnmarshalErr(&mm2, b, h, t, "mammoth2-"+name)
  1867. testDeepEqualErr(&mm, &mm2, t, "mammoth2-"+name)
  1868. // testMammoth2(t, name, h)
  1869. }
  1870. func testTime(t *testing.T, name string, h Handle) {
  1871. testOnce.Do(testInitAll)
  1872. // test time which uses the time.go implementation (ie Binc)
  1873. var tt, tt2 time.Time
  1874. // time in 1990
  1875. tt = time.Unix(20*366*24*60*60, 1000*900).In(time.FixedZone("UGO", -5*60*60))
  1876. // fmt.Printf("time tt: %v\n", tt)
  1877. b := testMarshalErr(tt, h, t, "time-"+name)
  1878. testUnmarshalErr(&tt2, b, h, t, "time-"+name)
  1879. // per go documentation, test time with .Equal not ==
  1880. if !tt2.Equal(tt) {
  1881. logT(t, "%s: values not equal: 1: %v, 2: %v", name, tt2, tt)
  1882. failT(t)
  1883. }
  1884. // testDeepEqualErr(tt.UTC(), tt2, t, "time-"+name)
  1885. }
  1886. func testUintToInt(t *testing.T, name string, h Handle) {
  1887. testOnce.Do(testInitAll)
  1888. var golden = [...]int64{
  1889. 0, 1, 22, 333, 4444, 55555, 666666,
  1890. // msgpack ones
  1891. 24, 128,
  1892. // standard ones
  1893. math.MaxUint8, math.MaxUint8 + 4, math.MaxUint8 - 4,
  1894. math.MaxUint16, math.MaxUint16 + 4, math.MaxUint16 - 4,
  1895. math.MaxUint32, math.MaxUint32 + 4, math.MaxUint32 - 4,
  1896. math.MaxInt8, math.MaxInt8 + 4, math.MaxInt8 - 4,
  1897. math.MaxInt16, math.MaxInt16 + 4, math.MaxInt16 - 4,
  1898. math.MaxInt32, math.MaxInt32 + 4, math.MaxInt32 - 4,
  1899. math.MaxInt64, math.MaxInt64 - 4,
  1900. }
  1901. var ui uint64
  1902. var fi float64
  1903. var b []byte
  1904. for _, i := range golden {
  1905. ui = 0
  1906. b = testMarshalErr(i, h, t, "int2uint-"+name)
  1907. testUnmarshalErr(&ui, b, h, t, "int2uint-"+name)
  1908. if ui != uint64(i) {
  1909. logT(t, "%s: values not equal: %v, %v", name, ui, uint64(i))
  1910. failT(t)
  1911. }
  1912. i = 0
  1913. b = testMarshalErr(ui, h, t, "uint2int-"+name)
  1914. testUnmarshalErr(&i, b, h, t, "uint2int-"+name)
  1915. if i != int64(ui) {
  1916. logT(t, "%s: values not equal: %v, %v", name, i, int64(ui))
  1917. failT(t)
  1918. }
  1919. fi = 0
  1920. b = testMarshalErr(i, h, t, "int2float-"+name)
  1921. testUnmarshalErr(&fi, b, h, t, "int2float-"+name)
  1922. if fi != float64(i) {
  1923. logT(t, "%s: values not equal: %v, %v", name, fi, float64(i))
  1924. failT(t)
  1925. }
  1926. }
  1927. }
  1928. func doTestDifferentMapOrSliceType(t *testing.T, name string, h Handle) {
  1929. testOnce.Do(testInitAll)
  1930. // - maptype, slicetype: diff from map[string]intf, map[intf]intf or []intf, etc
  1931. // include map[interface{}]string where some keys are []byte.
  1932. // To test, take a sequence of []byte and string, and decode into []string and []interface.
  1933. // Also, decode into map[string]string, map[string]interface{}, map[interface{}]string
  1934. bh := h.getBasicHandle()
  1935. oldM, oldS := bh.MapType, bh.SliceType
  1936. defer func() { bh.MapType, bh.SliceType = oldM, oldS }()
  1937. var b []byte
  1938. var vi = []interface{}{
  1939. "hello 1",
  1940. []byte("hello 2"),
  1941. "hello 3",
  1942. []byte("hello 4"),
  1943. "hello 5",
  1944. }
  1945. var vs []string
  1946. var v2i, v2s testMbsT
  1947. var v2ss testMbsCustStrT
  1948. // encode it as a map or as a slice
  1949. for i, v := range vi {
  1950. vv, ok := v.(string)
  1951. if !ok {
  1952. vv = string(v.([]byte))
  1953. }
  1954. vs = append(vs, vv)
  1955. v2i = append(v2i, v, strconv.FormatInt(int64(i+1), 10))
  1956. v2s = append(v2s, vv, strconv.FormatInt(int64(i+1), 10))
  1957. v2ss = append(v2ss, testCustomStringT(vv), testCustomStringT(strconv.FormatInt(int64(i+1), 10)))
  1958. }
  1959. var v2d interface{}
  1960. // encode vs as a list, and decode into a list and compare
  1961. var goldSliceS = []string{"hello 1", "hello 2", "hello 3", "hello 4", "hello 5"}
  1962. var goldSliceI = []interface{}{"hello 1", "hello 2", "hello 3", "hello 4", "hello 5"}
  1963. var goldSlice = []interface{}{goldSliceS, goldSliceI}
  1964. for j, g := range goldSlice {
  1965. bh.SliceType = reflect.TypeOf(g)
  1966. name := fmt.Sprintf("slice-%s-%v", name, j+1)
  1967. b = testMarshalErr(vs, h, t, name)
  1968. v2d = nil
  1969. // v2d = reflect.New(bh.SliceType).Elem().Interface()
  1970. testUnmarshalErr(&v2d, b, h, t, name)
  1971. testDeepEqualErr(v2d, goldSlice[j], t, name)
  1972. }
  1973. // to ensure that we do not use fast-path for map[intf]string, use a custom string type (for goldMapIS).
  1974. // this will allow us to test out the path that sees a []byte where a map has an interface{} type,
  1975. // and convert it to a string for the decoded map key.
  1976. // encode v2i as a map, and decode into a map and compare
  1977. var goldMapSS = map[string]string{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  1978. var goldMapSI = map[string]interface{}{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  1979. var goldMapIS = map[interface{}]testCustomStringT{"hello 1": "1", "hello 2": "2", "hello 3": "3", "hello 4": "4", "hello 5": "5"}
  1980. var goldMap = []interface{}{goldMapSS, goldMapSI, goldMapIS}
  1981. for j, g := range goldMap {
  1982. bh.MapType = reflect.TypeOf(g)
  1983. name := fmt.Sprintf("map-%s-%v", name, j+1)
  1984. // for formats that clearly differentiate binary from string, use v2i
  1985. // else use the v2s (with all strings, no []byte)
  1986. v2d = nil
  1987. // v2d = reflect.New(bh.MapType).Elem().Interface()
  1988. switch h.(type) {
  1989. case *MsgpackHandle, *BincHandle, *CborHandle:
  1990. b = testMarshalErr(v2i, h, t, name)
  1991. testUnmarshalErr(&v2d, b, h, t, name)
  1992. testDeepEqualErr(v2d, goldMap[j], t, name)
  1993. default:
  1994. b = testMarshalErr(v2s, h, t, name)
  1995. testUnmarshalErr(&v2d, b, h, t, name)
  1996. testDeepEqualErr(v2d, goldMap[j], t, name)
  1997. b = testMarshalErr(v2ss, h, t, name)
  1998. v2d = nil
  1999. testUnmarshalErr(&v2d, b, h, t, name)
  2000. testDeepEqualErr(v2d, goldMap[j], t, name)
  2001. }
  2002. }
  2003. }
  2004. func doTestScalars(t *testing.T, name string, h Handle) {
  2005. testOnce.Do(testInitAll)
  2006. // for each scalar:
  2007. // - encode its ptr
  2008. // - encode it (non-ptr)
  2009. // - check that bytes are same
  2010. // - make a copy (using reflect)
  2011. // - check that same
  2012. // - set zero on it
  2013. // - check that its equal to 0 value
  2014. // - decode into new
  2015. // - compare to original
  2016. bh := h.getBasicHandle()
  2017. if !bh.Canonical {
  2018. bh.Canonical = true
  2019. defer func() { bh.Canonical = false }()
  2020. }
  2021. vi := []interface{}{
  2022. int(0),
  2023. int8(0),
  2024. int16(0),
  2025. int32(0),
  2026. int64(0),
  2027. uint(0),
  2028. uint8(0),
  2029. uint16(0),
  2030. uint32(0),
  2031. uint64(0),
  2032. uintptr(0),
  2033. float32(0),
  2034. float64(0),
  2035. bool(false),
  2036. string(""),
  2037. []byte(nil),
  2038. }
  2039. for _, v := range fastpathAV {
  2040. vi = append(vi, reflect.Zero(v.rt).Interface())
  2041. }
  2042. for _, v := range vi {
  2043. rv := reflect.New(reflect.TypeOf(v)).Elem()
  2044. testRandomFillRV(rv)
  2045. v = rv.Interface()
  2046. rv2 := reflect.New(rv.Type())
  2047. rv2.Elem().Set(rv)
  2048. vp := rv2.Interface()
  2049. var tname string
  2050. switch rv.Kind() {
  2051. case reflect.Map:
  2052. tname = "map[" + rv.Type().Key().Name() + "]" + rv.Type().Elem().Name()
  2053. case reflect.Slice:
  2054. tname = "[]" + rv.Type().Elem().Name()
  2055. default:
  2056. tname = rv.Type().Name()
  2057. }
  2058. var b, b1, b2 []byte
  2059. b1 = testMarshalErr(v, h, t, tname+"-enc")
  2060. // store b1 into b, as b1 slice is reused for next marshal
  2061. b = make([]byte, len(b1))
  2062. copy(b, b1)
  2063. b2 = testMarshalErr(vp, h, t, tname+"-enc-ptr")
  2064. testDeepEqualErr(b1, b2, t, tname+"-enc-eq")
  2065. setZero(vp)
  2066. testDeepEqualErr(rv2.Elem().Interface(), reflect.Zero(rv.Type()).Interface(), t, tname+"-enc-eq-zero-ref")
  2067. vp = rv2.Interface()
  2068. testUnmarshalErr(vp, b, h, t, tname+"-dec")
  2069. testDeepEqualErr(rv2.Elem().Interface(), v, t, tname+"-dec-eq")
  2070. }
  2071. }
  2072. func doTestIntfMapping(t *testing.T, name string, h Handle) {
  2073. testOnce.Do(testInitAll)
  2074. rti := reflect.TypeOf((*testIntfMapI)(nil)).Elem()
  2075. defer func() { h.getBasicHandle().Intf2Impl(rti, nil) }()
  2076. type T9 struct {
  2077. I testIntfMapI
  2078. }
  2079. for i, v := range []testIntfMapI{
  2080. // Use a valid string to test some extents of json string decoding
  2081. &testIntfMapT1{"ABC \x41=\x42 \u2318 - \r \b \f - \u2028 and \u2029 ."},
  2082. testIntfMapT2{"DEF"},
  2083. } {
  2084. if err := h.getBasicHandle().Intf2Impl(rti, reflect.TypeOf(v)); err != nil {
  2085. failT(t, "Error mapping %v to %T", rti, v)
  2086. }
  2087. var v1, v2 T9
  2088. v1 = T9{v}
  2089. b := testMarshalErr(v1, h, t, name+"-enc-"+strconv.Itoa(i))
  2090. testUnmarshalErr(&v2, b, h, t, name+"-dec-"+strconv.Itoa(i))
  2091. testDeepEqualErr(v1, v2, t, name+"-dec-eq-"+strconv.Itoa(i))
  2092. }
  2093. }
  2094. func doTestOmitempty(t *testing.T, name string, h Handle) {
  2095. testOnce.Do(testInitAll)
  2096. if h.getBasicHandle().StructToArray {
  2097. t.Skipf("Skipping OmitEmpty test when StructToArray=true")
  2098. }
  2099. type T1 struct {
  2100. A int `codec:"a"`
  2101. B *int `codec:"b,omitempty"`
  2102. C int `codec:"c,omitempty"`
  2103. }
  2104. type T2 struct {
  2105. A int `codec:"a"`
  2106. }
  2107. var v1 T1
  2108. var v2 T2
  2109. b1 := testMarshalErr(v1, h, t, name+"-omitempty")
  2110. b2 := testMarshalErr(v2, h, t, name+"-no-omitempty-trunc")
  2111. testDeepEqualErr(b1, b2, t, name+"-omitempty-cmp")
  2112. }
  2113. func doTestMissingFields(t *testing.T, name string, h Handle) {
  2114. testOnce.Do(testInitAll)
  2115. if codecgen {
  2116. t.Skipf("Skipping Missing Fields tests as it is not honored by codecgen")
  2117. }
  2118. if h.getBasicHandle().StructToArray {
  2119. t.Skipf("Skipping Missing Fields test when StructToArray=true")
  2120. }
  2121. // encode missingFielderT2, decode into missingFielderT1, encode it out again, decode into new missingFielderT2, compare
  2122. v1 := missingFielderT2{S: "true seven eight", B: true, F: 777.0, I: -888}
  2123. b1 := testMarshalErr(v1, h, t, name+"-missing-enc-2")
  2124. // xdebugf("b1: %s", b1)
  2125. var v2 missingFielderT1
  2126. testUnmarshalErr(&v2, b1, h, t, name+"-missing-dec-1")
  2127. // xdebugf("unmarshal worked")
  2128. b2 := testMarshalErr(&v2, h, t, name+"-missing-enc-1")
  2129. var v3 missingFielderT2
  2130. testUnmarshalErr(&v3, b2, h, t, name+"-missing-dec-2")
  2131. testDeepEqualErr(v1, v3, t, name+"-missing-cmp-2")
  2132. }
  2133. func doTestMaxDepth(t *testing.T, name string, h Handle) {
  2134. testOnce.Do(testInitAll)
  2135. type T struct {
  2136. I interface{} // value to encode
  2137. M int16 // maxdepth
  2138. S bool // use swallow (decode into typed struct with only A1)
  2139. E interface{} // error to find
  2140. }
  2141. type T1 struct {
  2142. A1 *T1
  2143. }
  2144. var table []T
  2145. var sfunc = func(n int) (s [1]interface{}, s1 *[1]interface{}) {
  2146. s1 = &s
  2147. for i := 0; i < n; i++ {
  2148. var s0 [1]interface{}
  2149. s1[0] = &s0
  2150. s1 = &s0
  2151. }
  2152. // xdebugf("sfunc s: %v", s)
  2153. return
  2154. // var s []interface{}
  2155. // s = append(s, []interface{})
  2156. // s[0] = append(s[0], []interface{})
  2157. // s[0][0] = append(s[0][0], []interface{})
  2158. // s[0][0][0] = append(s[0][0][0], []interface{})
  2159. // s[0][0][0][0] = append(s[0][0][0][0], []interface{})
  2160. // return s
  2161. }
  2162. var mfunc = func(n int) (m map[string]interface{}, mlast map[string]interface{}) {
  2163. m = make(map[string]interface{})
  2164. mlast = make(map[string]interface{})
  2165. m["A0"] = mlast
  2166. for i := 1; i < n; i++ {
  2167. m0 := make(map[string]interface{})
  2168. mlast["A"+strconv.FormatInt(int64(i), 10)] = m0
  2169. mlast = m0
  2170. }
  2171. // xdebugf("mfunc m: %v", m)
  2172. return
  2173. }
  2174. s, s1 := sfunc(5)
  2175. m, _ := mfunc(5)
  2176. m99, _ := mfunc(99)
  2177. s1[0] = m
  2178. table = append(table, T{s, 0, false, nil})
  2179. table = append(table, T{s, 256, false, nil})
  2180. table = append(table, T{s, 7, false, errMaxDepthExceeded})
  2181. table = append(table, T{s, 15, false, nil})
  2182. table = append(table, T{m99, 15, true, errMaxDepthExceeded})
  2183. table = append(table, T{m99, 215, true, nil})
  2184. defer func(n int16, b bool) {
  2185. h.getBasicHandle().MaxDepth = n
  2186. testUseMust = b
  2187. }(h.getBasicHandle().MaxDepth, testUseMust)
  2188. testUseMust = false
  2189. for i, v := range table {
  2190. h.getBasicHandle().MaxDepth = v.M
  2191. b1 := testMarshalErr(v.I, h, t, name+"-maxdepth-enc"+strconv.FormatInt(int64(i), 10))
  2192. // xdebugf("b1: %s", b1)
  2193. var err error
  2194. if v.S {
  2195. var v2 T1
  2196. err = testUnmarshal(&v2, b1, h)
  2197. } else {
  2198. var v2 interface{}
  2199. err = testUnmarshal(&v2, b1, h)
  2200. }
  2201. if err1, ok := err.(decodeError); ok {
  2202. err = err1.codecError
  2203. }
  2204. var err0 interface{} = err
  2205. if err1, ok := err.(codecError); ok {
  2206. err0 = err1.err
  2207. }
  2208. if err0 != v.E {
  2209. failT(t, "Unexpected error testing max depth for depth %d: expected %v, received %v", v.M, v.E, err)
  2210. }
  2211. // decode into something that just triggers swallow
  2212. }
  2213. }
  2214. // -----------------
  2215. func TestJsonDecodeNonStringScalarInStringContext(t *testing.T) {
  2216. testOnce.Do(testInitAll)
  2217. var b = `{"s.true": "true", "b.true": true, "s.false": "false", "b.false": false, "s.10": "10", "i.10": 10, "i.-10": -10}`
  2218. 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"}
  2219. var m map[string]string
  2220. d := NewDecoderBytes([]byte(b), testJsonH)
  2221. d.MustDecode(&m)
  2222. if err := deepEqual(golden, m); err == nil {
  2223. logT(t, "++++ match: decoded: %#v", m)
  2224. } else {
  2225. logT(t, "---- mismatch: %v ==> golden: %#v, decoded: %#v", err, golden, m)
  2226. failT(t)
  2227. }
  2228. }
  2229. func TestJsonEncodeIndent(t *testing.T) {
  2230. testOnce.Do(testInitAll)
  2231. v := TestSimplish{
  2232. Ii: -794,
  2233. Ss: `A Man is
  2234. after the new line
  2235. after new line and tab
  2236. `,
  2237. }
  2238. v2 := v
  2239. v.Mm = make(map[string]*TestSimplish)
  2240. for i := 0; i < len(v.Ar); i++ {
  2241. v3 := v2
  2242. v3.Ii += (i * 4)
  2243. v3.Ss = fmt.Sprintf("%d - %s", v3.Ii, v3.Ss)
  2244. if i%2 == 0 {
  2245. v.Ar[i] = &v3
  2246. }
  2247. // v3 = v2
  2248. v.Sl = append(v.Sl, &v3)
  2249. v.Mm[strconv.FormatInt(int64(i), 10)] = &v3
  2250. }
  2251. oldcan := testJsonH.Canonical
  2252. oldIndent := testJsonH.Indent
  2253. oldS2A := testJsonH.StructToArray
  2254. defer func() {
  2255. testJsonH.Canonical = oldcan
  2256. testJsonH.Indent = oldIndent
  2257. testJsonH.StructToArray = oldS2A
  2258. }()
  2259. testJsonH.Canonical = true
  2260. testJsonH.Indent = -1
  2261. testJsonH.StructToArray = false
  2262. var bs []byte
  2263. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  2264. txt1Tab := string(bs)
  2265. bs = nil
  2266. testJsonH.Indent = 120
  2267. NewEncoderBytes(&bs, testJsonH).MustEncode(&v)
  2268. txtSpaces := string(bs)
  2269. // fmt.Printf("\n-----------\n%s\n------------\n%s\n-------------\n", txt1Tab, txtSpaces)
  2270. goldenResultTab := `{
  2271. "Ar": [
  2272. {
  2273. "Ar": [
  2274. null,
  2275. null
  2276. ],
  2277. "Ii": -794,
  2278. "Mm": null,
  2279. "Sl": null,
  2280. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2281. },
  2282. null
  2283. ],
  2284. "Ii": -794,
  2285. "Mm": {
  2286. "0": {
  2287. "Ar": [
  2288. null,
  2289. null
  2290. ],
  2291. "Ii": -794,
  2292. "Mm": null,
  2293. "Sl": null,
  2294. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2295. },
  2296. "1": {
  2297. "Ar": [
  2298. null,
  2299. null
  2300. ],
  2301. "Ii": -790,
  2302. "Mm": null,
  2303. "Sl": null,
  2304. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2305. }
  2306. },
  2307. "Sl": [
  2308. {
  2309. "Ar": [
  2310. null,
  2311. null
  2312. ],
  2313. "Ii": -794,
  2314. "Mm": null,
  2315. "Sl": null,
  2316. "Ss": "-794 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2317. },
  2318. {
  2319. "Ar": [
  2320. null,
  2321. null
  2322. ],
  2323. "Ii": -790,
  2324. "Mm": null,
  2325. "Sl": null,
  2326. "Ss": "-790 - A Man is\nafter the new line\n\tafter new line and tab\n"
  2327. }
  2328. ],
  2329. "Ss": "A Man is\nafter the new line\n\tafter new line and tab\n"
  2330. }`
  2331. if txt1Tab != goldenResultTab {
  2332. logT(t, "decoded indented with tabs != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txt1Tab)
  2333. failT(t)
  2334. }
  2335. if txtSpaces != strings.Replace(goldenResultTab, "\t", strings.Repeat(" ", 120), -1) {
  2336. logT(t, "decoded indented with spaces != expected: \nexpected: %s\nencoded: %s", goldenResultTab, txtSpaces)
  2337. failT(t)
  2338. }
  2339. }
  2340. func TestBufioDecReader(t *testing.T) {
  2341. testOnce.Do(testInitAll)
  2342. // try to read 85 bytes in chunks of 7 at a time.
  2343. var s = strings.Repeat("01234'56789 ", 5)
  2344. // fmt.Printf("s: %s\n", s)
  2345. var r = strings.NewReader(s)
  2346. var br = &bufioDecReader{r: r, buf: make([]byte, 0, 13)}
  2347. b, err := ioutil.ReadAll(br)
  2348. if err != nil {
  2349. panic(err)
  2350. }
  2351. var s2 = string(b)
  2352. // fmt.Printf("s==s2: %v, len(s): %v, len(b): %v, len(s2): %v\n", s == s2, len(s), len(b), len(s2))
  2353. if s != s2 {
  2354. logT(t, "not equal: \ns: %s\ns2: %s", s, s2)
  2355. failT(t)
  2356. }
  2357. // Now, test search functions for skip, readTo and readUntil
  2358. // readUntil ', readTo ', skip whitespace. 3 times in a loop, each time compare the token and/or outs
  2359. // readUntil: see: 56789
  2360. var out []byte
  2361. var token byte
  2362. br = &bufioDecReader{r: strings.NewReader(s), buf: make([]byte, 0, 7)}
  2363. // println()
  2364. for _, v2 := range [...]string{
  2365. `01234'`,
  2366. `56789 01234'`,
  2367. `56789 01234'`,
  2368. `56789 01234'`,
  2369. } {
  2370. out = br.readUntil(nil, '\'')
  2371. testDeepEqualErr(string(out), v2, t, "-")
  2372. // fmt.Printf("readUntil: out: `%s`\n", out)
  2373. }
  2374. br = &bufioDecReader{r: strings.NewReader(s), buf: make([]byte, 0, 7)}
  2375. // println()
  2376. for range [4]struct{}{} {
  2377. out = br.readTo(nil, &jsonNumSet)
  2378. testDeepEqualErr(string(out), `01234`, t, "-")
  2379. // fmt.Printf("readTo: out: `%s`\n", out)
  2380. out = br.readUntil(nil, '\'')
  2381. testDeepEqualErr(string(out), "'", t, "-")
  2382. // fmt.Printf("readUntil: out: `%s`\n", out)
  2383. out = br.readTo(nil, &jsonNumSet)
  2384. testDeepEqualErr(string(out), `56789`, t, "-")
  2385. // fmt.Printf("readTo: out: `%s`\n", out)
  2386. out = br.readUntil(nil, '0')
  2387. testDeepEqualErr(string(out), ` 0`, t, "-")
  2388. // fmt.Printf("readUntil: out: `%s`\n", out)
  2389. br.UnreadByte()
  2390. }
  2391. br = &bufioDecReader{r: strings.NewReader(s), buf: make([]byte, 0, 7)}
  2392. // println()
  2393. for range [4]struct{}{} {
  2394. out = br.readUntil(nil, ' ')
  2395. testDeepEqualErr(string(out), `01234'56789 `, t, "-")
  2396. // fmt.Printf("readUntil: out: |%s|\n", out)
  2397. token = br.skip(&jsonCharWhitespaceSet)
  2398. testDeepEqualErr(token, byte('0'), t, "-")
  2399. // fmt.Printf("skip: token: '%c'\n", token)
  2400. br.UnreadByte()
  2401. }
  2402. // println()
  2403. }
  2404. // -----------
  2405. func TestJsonLargeInteger(t *testing.T) {
  2406. testOnce.Do(testInitAll)
  2407. for _, i := range []uint8{'L', 'A', 0} {
  2408. for _, j := range []interface{}{
  2409. int64(1 << 60),
  2410. -int64(1 << 60),
  2411. 0,
  2412. 1 << 20,
  2413. -(1 << 20),
  2414. uint64(1 << 60),
  2415. uint(0),
  2416. uint(1 << 20),
  2417. } {
  2418. doTestJsonLargeInteger(t, j, i)
  2419. }
  2420. }
  2421. }
  2422. func TestJsonInvalidUnicode(t *testing.T) {
  2423. testOnce.Do(testInitAll)
  2424. var m = map[string]string{
  2425. `"\udc49\u0430abc"`: "\uFFFDabc",
  2426. `"\udc49\u0430"`: "\uFFFD",
  2427. `"\udc49abc"`: "\uFFFDabc",
  2428. `"\udc49"`: "\uFFFD",
  2429. `"\udZ49\u0430abc"`: "\uFFFD\u0430abc",
  2430. `"\udcG9\u0430"`: "\uFFFD\u0430",
  2431. `"\uHc49abc"`: "\uFFFDabc",
  2432. `"\uKc49"`: "\uFFFD",
  2433. // ``: "",
  2434. }
  2435. for k, v := range m {
  2436. // println("k = ", k)
  2437. var s string
  2438. testUnmarshalErr(&s, []byte(k), testJsonH, t, "-")
  2439. if s != v {
  2440. logT(t, "not equal: %q, %q", v, s)
  2441. failT(t)
  2442. }
  2443. }
  2444. }
  2445. func TestMsgpackDecodeMapAndExtSizeMismatch(t *testing.T) {
  2446. fn := func(t *testing.T, b []byte, v interface{}) {
  2447. if err := NewDecoderBytes(b, testMsgpackH).Decode(v); err != io.EOF && err != io.ErrUnexpectedEOF {
  2448. t.Fatalf("expected EOF or ErrUnexpectedEOF, got %v", err)
  2449. }
  2450. }
  2451. // a map claiming to have 0x10eeeeee KV pairs, but only has 1.
  2452. var b = []byte{0xdf, 0x10, 0xee, 0xee, 0xee, 0x1, 0xa1, 0x1}
  2453. var m1 map[int]string
  2454. var m2 map[int][]byte
  2455. fn(t, b, &m1)
  2456. fn(t, b, &m2)
  2457. // an extension claiming to have 0x7fffffff bytes, but only has 1.
  2458. b = []byte{0xc9, 0x7f, 0xff, 0xff, 0xff, 0xda, 0x1}
  2459. var a interface{}
  2460. fn(t, b, &a)
  2461. }
  2462. // ----------
  2463. func TestBincCodecsTable(t *testing.T) {
  2464. testCodecTableOne(t, testBincH)
  2465. }
  2466. func TestBincCodecsMisc(t *testing.T) {
  2467. testCodecMiscOne(t, testBincH)
  2468. }
  2469. func TestBincCodecsEmbeddedPointer(t *testing.T) {
  2470. testCodecEmbeddedPointer(t, testBincH)
  2471. }
  2472. func TestBincStdEncIntf(t *testing.T) {
  2473. doTestStdEncIntf(t, "binc", testBincH)
  2474. }
  2475. func TestBincMammoth(t *testing.T) {
  2476. testMammoth(t, "binc", testBincH)
  2477. }
  2478. func TestSimpleCodecsTable(t *testing.T) {
  2479. testCodecTableOne(t, testSimpleH)
  2480. }
  2481. func TestSimpleCodecsMisc(t *testing.T) {
  2482. testCodecMiscOne(t, testSimpleH)
  2483. }
  2484. func TestSimpleCodecsEmbeddedPointer(t *testing.T) {
  2485. testCodecEmbeddedPointer(t, testSimpleH)
  2486. }
  2487. func TestSimpleStdEncIntf(t *testing.T) {
  2488. doTestStdEncIntf(t, "simple", testSimpleH)
  2489. }
  2490. func TestSimpleMammoth(t *testing.T) {
  2491. testMammoth(t, "simple", testSimpleH)
  2492. }
  2493. func TestMsgpackCodecsTable(t *testing.T) {
  2494. testCodecTableOne(t, testMsgpackH)
  2495. }
  2496. func TestMsgpackCodecsMisc(t *testing.T) {
  2497. testCodecMiscOne(t, testMsgpackH)
  2498. }
  2499. func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
  2500. testCodecEmbeddedPointer(t, testMsgpackH)
  2501. }
  2502. func TestMsgpackStdEncIntf(t *testing.T) {
  2503. doTestStdEncIntf(t, "msgpack", testMsgpackH)
  2504. }
  2505. func TestMsgpackMammoth(t *testing.T) {
  2506. testMammoth(t, "msgpack", testMsgpackH)
  2507. }
  2508. func TestCborCodecsTable(t *testing.T) {
  2509. testCodecTableOne(t, testCborH)
  2510. }
  2511. func TestCborCodecsMisc(t *testing.T) {
  2512. testCodecMiscOne(t, testCborH)
  2513. }
  2514. func TestCborCodecsEmbeddedPointer(t *testing.T) {
  2515. testCodecEmbeddedPointer(t, testCborH)
  2516. }
  2517. func TestCborMapEncodeForCanonical(t *testing.T) {
  2518. doTestMapEncodeForCanonical(t, "cbor", testCborH)
  2519. }
  2520. func TestCborCodecChan(t *testing.T) {
  2521. testCodecChan(t, testCborH)
  2522. }
  2523. func TestCborStdEncIntf(t *testing.T) {
  2524. doTestStdEncIntf(t, "cbor", testCborH)
  2525. }
  2526. func TestCborMammoth(t *testing.T) {
  2527. testMammoth(t, "cbor", testCborH)
  2528. }
  2529. func TestJsonCodecsTable(t *testing.T) {
  2530. testCodecTableOne(t, testJsonH)
  2531. }
  2532. func TestJsonCodecsMisc(t *testing.T) {
  2533. testCodecMiscOne(t, testJsonH)
  2534. }
  2535. func TestJsonCodecsEmbeddedPointer(t *testing.T) {
  2536. testCodecEmbeddedPointer(t, testJsonH)
  2537. }
  2538. func TestJsonCodecChan(t *testing.T) {
  2539. testCodecChan(t, testJsonH)
  2540. }
  2541. func TestJsonStdEncIntf(t *testing.T) {
  2542. doTestStdEncIntf(t, "json", testJsonH)
  2543. }
  2544. func TestJsonMammoth(t *testing.T) {
  2545. testMammoth(t, "json", testJsonH)
  2546. }
  2547. // ----- Raw ---------
  2548. func TestJsonRaw(t *testing.T) {
  2549. doTestRawValue(t, "json", testJsonH)
  2550. }
  2551. func TestBincRaw(t *testing.T) {
  2552. doTestRawValue(t, "binc", testBincH)
  2553. }
  2554. func TestMsgpackRaw(t *testing.T) {
  2555. doTestRawValue(t, "msgpack", testMsgpackH)
  2556. }
  2557. func TestSimpleRaw(t *testing.T) {
  2558. doTestRawValue(t, "simple", testSimpleH)
  2559. }
  2560. func TestCborRaw(t *testing.T) {
  2561. doTestRawValue(t, "cbor", testCborH)
  2562. }
  2563. // ----- ALL (framework based) -----
  2564. func TestAllEncCircularRef(t *testing.T) {
  2565. doTestEncCircularRef(t, "cbor", testCborH)
  2566. }
  2567. func TestAllAnonCycle(t *testing.T) {
  2568. doTestAnonCycle(t, "cbor", testCborH)
  2569. }
  2570. // ----- RPC -----
  2571. func TestBincRpcGo(t *testing.T) {
  2572. testCodecRpcOne(t, GoRpc, testBincH, true, 0)
  2573. }
  2574. func TestSimpleRpcGo(t *testing.T) {
  2575. testCodecRpcOne(t, GoRpc, testSimpleH, true, 0)
  2576. }
  2577. func TestMsgpackRpcGo(t *testing.T) {
  2578. testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0)
  2579. }
  2580. func TestCborRpcGo(t *testing.T) {
  2581. testCodecRpcOne(t, GoRpc, testCborH, true, 0)
  2582. }
  2583. func TestJsonRpcGo(t *testing.T) {
  2584. testCodecRpcOne(t, GoRpc, testJsonH, true, 0)
  2585. }
  2586. func TestMsgpackRpcSpec(t *testing.T) {
  2587. testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
  2588. }
  2589. func TestBincUnderlyingType(t *testing.T) {
  2590. testCodecUnderlyingType(t, testBincH)
  2591. }
  2592. func TestJsonSwallowAndZero(t *testing.T) {
  2593. doTestSwallowAndZero(t, testJsonH)
  2594. }
  2595. func TestCborSwallowAndZero(t *testing.T) {
  2596. doTestSwallowAndZero(t, testCborH)
  2597. }
  2598. func TestMsgpackSwallowAndZero(t *testing.T) {
  2599. doTestSwallowAndZero(t, testMsgpackH)
  2600. }
  2601. func TestBincSwallowAndZero(t *testing.T) {
  2602. doTestSwallowAndZero(t, testBincH)
  2603. }
  2604. func TestSimpleSwallowAndZero(t *testing.T) {
  2605. doTestSwallowAndZero(t, testSimpleH)
  2606. }
  2607. func TestJsonRawExt(t *testing.T) {
  2608. doTestRawExt(t, testJsonH)
  2609. }
  2610. func TestCborRawExt(t *testing.T) {
  2611. doTestRawExt(t, testCborH)
  2612. }
  2613. func TestMsgpackRawExt(t *testing.T) {
  2614. doTestRawExt(t, testMsgpackH)
  2615. }
  2616. func TestBincRawExt(t *testing.T) {
  2617. doTestRawExt(t, testBincH)
  2618. }
  2619. func TestSimpleRawExt(t *testing.T) {
  2620. doTestRawExt(t, testSimpleH)
  2621. }
  2622. func TestJsonMapStructKey(t *testing.T) {
  2623. doTestMapStructKey(t, testJsonH)
  2624. }
  2625. func TestCborMapStructKey(t *testing.T) {
  2626. doTestMapStructKey(t, testCborH)
  2627. }
  2628. func TestMsgpackMapStructKey(t *testing.T) {
  2629. doTestMapStructKey(t, testMsgpackH)
  2630. }
  2631. func TestBincMapStructKey(t *testing.T) {
  2632. doTestMapStructKey(t, testBincH)
  2633. }
  2634. func TestSimpleMapStructKey(t *testing.T) {
  2635. doTestMapStructKey(t, testSimpleH)
  2636. }
  2637. func TestJsonDecodeNilMapValue(t *testing.T) {
  2638. doTestDecodeNilMapValue(t, testJsonH)
  2639. }
  2640. func TestCborDecodeNilMapValue(t *testing.T) {
  2641. doTestDecodeNilMapValue(t, testCborH)
  2642. }
  2643. func TestMsgpackDecodeNilMapValue(t *testing.T) {
  2644. doTestDecodeNilMapValue(t, testMsgpackH)
  2645. }
  2646. func TestBincDecodeNilMapValue(t *testing.T) {
  2647. doTestDecodeNilMapValue(t, testBincH)
  2648. }
  2649. func TestSimpleDecodeNilMapValue(t *testing.T) {
  2650. doTestDecodeNilMapValue(t, testSimpleH)
  2651. }
  2652. func TestJsonEmbeddedFieldPrecedence(t *testing.T) {
  2653. doTestEmbeddedFieldPrecedence(t, testJsonH)
  2654. }
  2655. func TestCborEmbeddedFieldPrecedence(t *testing.T) {
  2656. doTestEmbeddedFieldPrecedence(t, testCborH)
  2657. }
  2658. func TestMsgpackEmbeddedFieldPrecedence(t *testing.T) {
  2659. doTestEmbeddedFieldPrecedence(t, testMsgpackH)
  2660. }
  2661. func TestBincEmbeddedFieldPrecedence(t *testing.T) {
  2662. doTestEmbeddedFieldPrecedence(t, testBincH)
  2663. }
  2664. func TestSimpleEmbeddedFieldPrecedence(t *testing.T) {
  2665. doTestEmbeddedFieldPrecedence(t, testSimpleH)
  2666. }
  2667. func TestJsonLargeContainerLen(t *testing.T) {
  2668. doTestLargeContainerLen(t, testJsonH)
  2669. }
  2670. func TestCborLargeContainerLen(t *testing.T) {
  2671. doTestLargeContainerLen(t, testCborH)
  2672. }
  2673. func TestMsgpackLargeContainerLen(t *testing.T) {
  2674. doTestLargeContainerLen(t, testMsgpackH)
  2675. }
  2676. func TestBincLargeContainerLen(t *testing.T) {
  2677. doTestLargeContainerLen(t, testBincH)
  2678. }
  2679. func TestSimpleLargeContainerLen(t *testing.T) {
  2680. doTestLargeContainerLen(t, testSimpleH)
  2681. }
  2682. func TestJsonMammothMapsAndSlices(t *testing.T) {
  2683. doTestMammothMapsAndSlices(t, testJsonH)
  2684. }
  2685. func TestCborMammothMapsAndSlices(t *testing.T) {
  2686. doTestMammothMapsAndSlices(t, testCborH)
  2687. }
  2688. func TestMsgpackMammothMapsAndSlices(t *testing.T) {
  2689. old1, old2 := testMsgpackH.RawToString, testMsgpackH.WriteExt
  2690. defer func() { testMsgpackH.RawToString, testMsgpackH.WriteExt = old1, old2 }()
  2691. testMsgpackH.RawToString = true
  2692. testMsgpackH.WriteExt = true
  2693. doTestMammothMapsAndSlices(t, testMsgpackH)
  2694. }
  2695. func TestBincMammothMapsAndSlices(t *testing.T) {
  2696. doTestMammothMapsAndSlices(t, testBincH)
  2697. }
  2698. func TestSimpleMammothMapsAndSlices(t *testing.T) {
  2699. doTestMammothMapsAndSlices(t, testSimpleH)
  2700. }
  2701. func TestJsonTime(t *testing.T) {
  2702. testTime(t, "json", testJsonH)
  2703. }
  2704. func TestCborTime(t *testing.T) {
  2705. testTime(t, "cbor", testCborH)
  2706. }
  2707. func TestMsgpackTime(t *testing.T) {
  2708. testTime(t, "msgpack", testMsgpackH)
  2709. }
  2710. func TestBincTime(t *testing.T) {
  2711. testTime(t, "binc", testBincH)
  2712. }
  2713. func TestSimpleTime(t *testing.T) {
  2714. testTime(t, "simple", testSimpleH)
  2715. }
  2716. func TestJsonUintToInt(t *testing.T) {
  2717. testUintToInt(t, "json", testJsonH)
  2718. }
  2719. func TestCborUintToInt(t *testing.T) {
  2720. testUintToInt(t, "cbor", testCborH)
  2721. }
  2722. func TestMsgpackUintToInt(t *testing.T) {
  2723. testUintToInt(t, "msgpack", testMsgpackH)
  2724. }
  2725. func TestBincUintToInt(t *testing.T) {
  2726. testUintToInt(t, "binc", testBincH)
  2727. }
  2728. func TestSimpleUintToInt(t *testing.T) {
  2729. testUintToInt(t, "simple", testSimpleH)
  2730. }
  2731. func TestJsonDifferentMapOrSliceType(t *testing.T) {
  2732. doTestDifferentMapOrSliceType(t, "json", testJsonH)
  2733. }
  2734. func TestCborDifferentMapOrSliceType(t *testing.T) {
  2735. doTestDifferentMapOrSliceType(t, "cbor", testCborH)
  2736. }
  2737. func TestMsgpackDifferentMapOrSliceType(t *testing.T) {
  2738. doTestDifferentMapOrSliceType(t, "msgpack", testMsgpackH)
  2739. }
  2740. func TestBincDifferentMapOrSliceType(t *testing.T) {
  2741. doTestDifferentMapOrSliceType(t, "binc", testBincH)
  2742. }
  2743. func TestSimpleDifferentMapOrSliceType(t *testing.T) {
  2744. doTestDifferentMapOrSliceType(t, "simple", testSimpleH)
  2745. }
  2746. func TestJsonScalars(t *testing.T) {
  2747. doTestScalars(t, "json", testJsonH)
  2748. }
  2749. func TestCborScalars(t *testing.T) {
  2750. doTestScalars(t, "cbor", testCborH)
  2751. }
  2752. func TestMsgpackScalars(t *testing.T) {
  2753. doTestScalars(t, "msgpack", testMsgpackH)
  2754. }
  2755. func TestBincScalars(t *testing.T) {
  2756. doTestScalars(t, "binc", testBincH)
  2757. }
  2758. func TestSimpleScalars(t *testing.T) {
  2759. doTestScalars(t, "simple", testSimpleH)
  2760. }
  2761. func TestJsonOmitempty(t *testing.T) {
  2762. doTestOmitempty(t, "json", testJsonH)
  2763. }
  2764. func TestCborOmitempty(t *testing.T) {
  2765. doTestOmitempty(t, "cbor", testCborH)
  2766. }
  2767. func TestMsgpackOmitempty(t *testing.T) {
  2768. doTestOmitempty(t, "msgpack", testMsgpackH)
  2769. }
  2770. func TestBincOmitempty(t *testing.T) {
  2771. doTestOmitempty(t, "binc", testBincH)
  2772. }
  2773. func TestSimpleOmitempty(t *testing.T) {
  2774. doTestOmitempty(t, "simple", testSimpleH)
  2775. }
  2776. func TestJsonIntfMapping(t *testing.T) {
  2777. doTestIntfMapping(t, "json", testJsonH)
  2778. }
  2779. func TestCborIntfMapping(t *testing.T) {
  2780. doTestIntfMapping(t, "cbor", testCborH)
  2781. }
  2782. func TestMsgpackIntfMapping(t *testing.T) {
  2783. doTestIntfMapping(t, "msgpack", testMsgpackH)
  2784. }
  2785. func TestBincIntfMapping(t *testing.T) {
  2786. doTestIntfMapping(t, "binc", testBincH)
  2787. }
  2788. func TestSimpleIntfMapping(t *testing.T) {
  2789. doTestIntfMapping(t, "simple", testSimpleH)
  2790. }
  2791. func TestJsonMissingFields(t *testing.T) {
  2792. doTestMissingFields(t, "json", testJsonH)
  2793. }
  2794. func TestCborMissingFields(t *testing.T) {
  2795. doTestMissingFields(t, "cbor", testCborH)
  2796. }
  2797. func TestMsgpackMissingFields(t *testing.T) {
  2798. doTestMissingFields(t, "msgpack", testMsgpackH)
  2799. }
  2800. func TestBincMissingFields(t *testing.T) {
  2801. doTestMissingFields(t, "binc", testBincH)
  2802. }
  2803. func TestSimpleMissingFields(t *testing.T) {
  2804. doTestMissingFields(t, "simple", testSimpleH)
  2805. }
  2806. func TestJsonMaxDepth(t *testing.T) {
  2807. doTestMaxDepth(t, "json", testJsonH)
  2808. }
  2809. func TestCborMaxDepth(t *testing.T) {
  2810. doTestMaxDepth(t, "cbor", testCborH)
  2811. }
  2812. func TestMsgpackMaxDepth(t *testing.T) {
  2813. doTestMaxDepth(t, "msgpack", testMsgpackH)
  2814. }
  2815. func TestBincMaxDepth(t *testing.T) {
  2816. doTestMaxDepth(t, "binc", testBincH)
  2817. }
  2818. func TestSimpleMaxDepth(t *testing.T) {
  2819. doTestMaxDepth(t, "simple", testSimpleH)
  2820. }
  2821. // TODO:
  2822. //
  2823. // Add Tests for:
  2824. // - struct tags: on anonymous fields, _struct (all fields), etc
  2825. // - chan to encode and decode (with support for codecgen also)
  2826. //
  2827. // Add negative tests for failure conditions:
  2828. // - bad input with large array length prefix
  2829. //
  2830. // decode.go (standalone)
  2831. // - UnreadByte: only 2 states (z.ls = 2 and z.ls = 1) (0 --> 2 --> 1)
  2832. // - track: z.trb: track, stop track, check
  2833. // - PreferArrayOverSlice???
  2834. // - InterfaceReset
  2835. // - (chan byte) to decode []byte (with mapbyslice track)
  2836. // - decode slice of len 6, 16 into slice of (len 4, cap 8) and (len ) with maxinitlen=6, 8, 16
  2837. // - DeleteOnNilMapValue
  2838. // - decnaked: n.l == nil
  2839. // - ensureDecodeable (try to decode into a non-decodeable thing e.g. a nil interface{},
  2840. //
  2841. // encode.go (standalone)
  2842. // - nil and 0-len slices and maps for non-fastpath things