codec_test.go 88 KB

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