codec_test.go 65 KB

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