codec_test.go 108 KB

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