codec_test.go 57 KB

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