codec_test.go 86 KB

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