codec_test.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  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. "flag"
  23. "fmt"
  24. "io/ioutil"
  25. "math"
  26. "math/rand"
  27. "net"
  28. "net/rpc"
  29. "os"
  30. "os/exec"
  31. "path/filepath"
  32. "reflect"
  33. "runtime"
  34. "strconv"
  35. "strings"
  36. "sync/atomic"
  37. "testing"
  38. "time"
  39. )
  40. func init() {
  41. testInitFlags()
  42. testPreInitFns = append(testPreInitFns, testInit)
  43. }
  44. // make this a mapbyslice
  45. type testMbsT []interface{}
  46. func (_ testMbsT) MapBySlice() {}
  47. type testVerifyArg int
  48. const (
  49. testVerifyMapTypeSame testVerifyArg = iota
  50. testVerifyMapTypeStrIntf
  51. testVerifyMapTypeIntfIntf
  52. // testVerifySliceIntf
  53. testVerifyForPython
  54. )
  55. const testSkipRPCTests = false
  56. var (
  57. testTableNumPrimitives int
  58. testTableIdxTime int
  59. testTableNumMaps int
  60. )
  61. var (
  62. skipVerifyVal interface{} = &(struct{}{})
  63. testMapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
  64. // For Go Time, do not use a descriptive timezone.
  65. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  66. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  67. timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8
  68. timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  69. timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc).UTC()
  70. timeToCompare3 = time.Unix(0, 270).UTC() // use value that must be encoded as uint64 for nanoseconds (for cbor/msgpack comparison)
  71. //timeToCompare4 = time.Time{}.UTC() // does not work well with simple cbor time encoding (overflow)
  72. timeToCompare4 = time.Unix(-2013855848, 4223).UTC()
  73. table []interface{} // main items we encode
  74. tableVerify []interface{} // we verify encoded things against this after decode
  75. tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different)
  76. tablePythonVerify []interface{} // for verifying for python, since Python sometimes
  77. // will encode a float32 as float64, or large int as uint
  78. testRpcInt = new(TestRpcInt)
  79. )
  80. func testInitFlags() {
  81. // delete(testDecOpts.ExtFuncs, timeTyp)
  82. flag.BoolVar(&testVerbose, "tv", false, "Test Verbose")
  83. flag.BoolVar(&testInitDebug, "tg", false, "Test Init Debug")
  84. flag.BoolVar(&testUseIoEncDec, "ti", false, "Use IO Reader/Writer for Marshal/Unmarshal")
  85. flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option")
  86. flag.BoolVar(&testWriteNoSymbols, "tn", false, "Set NoSymbols option")
  87. flag.BoolVar(&testCanonical, "tc", false, "Set Canonical option")
  88. flag.BoolVar(&testInternStr, "te", false, "Set InternStr option")
  89. flag.BoolVar(&testSkipIntf, "tf", false, "Skip Interfaces")
  90. flag.BoolVar(&testUseReset, "tr", false, "Use Reset")
  91. flag.IntVar(&testJsonIndent, "td", 0, "Use JSON Indent")
  92. flag.BoolVar(&testUseMust, "tm", true, "Use Must(En|De)code")
  93. flag.BoolVar(&testCheckCircRef, "tl", false, "Use Check Circular Ref")
  94. }
  95. func testByteBuf(in []byte) *bytes.Buffer {
  96. return bytes.NewBuffer(in)
  97. }
  98. type TestABC struct {
  99. A, B, C string
  100. }
  101. func (x *TestABC) MarshalBinary() ([]byte, error) {
  102. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  103. }
  104. func (x *TestABC) MarshalText() ([]byte, error) {
  105. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  106. }
  107. func (x *TestABC) MarshalJSON() ([]byte, error) {
  108. return []byte(fmt.Sprintf(`"%s %s %s"`, x.A, x.B, x.C)), nil
  109. }
  110. func (x *TestABC) UnmarshalBinary(data []byte) (err error) {
  111. ss := strings.Split(string(data), " ")
  112. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  113. return
  114. }
  115. func (x *TestABC) UnmarshalText(data []byte) (err error) {
  116. return x.UnmarshalBinary(data)
  117. }
  118. func (x *TestABC) UnmarshalJSON(data []byte) (err error) {
  119. return x.UnmarshalBinary(data[1 : len(data)-1])
  120. }
  121. type TestABC2 struct {
  122. A, B, C string
  123. }
  124. func (x TestABC2) MarshalText() ([]byte, error) {
  125. return []byte(fmt.Sprintf("%s %s %s", x.A, x.B, x.C)), nil
  126. }
  127. func (x *TestABC2) UnmarshalText(data []byte) (err error) {
  128. ss := strings.Split(string(data), " ")
  129. x.A, x.B, x.C = ss[0], ss[1], ss[2]
  130. return
  131. // _, err = fmt.Sscanf(string(data), "%s %s %s", &x.A, &x.B, &x.C)
  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. // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v\n", v)
  173. tt := dest.(*time.Time)
  174. switch v2 := v.(type) {
  175. case int64:
  176. *tt = time.Unix(0, v2).UTC()
  177. case *int64:
  178. *tt = time.Unix(0, *v2).UTC()
  179. case uint64:
  180. *tt = time.Unix(0, int64(v2)).UTC()
  181. case *uint64:
  182. *tt = time.Unix(0, int64(*v2)).UTC()
  183. //case float64:
  184. //case string:
  185. default:
  186. panic(fmt.Sprintf("unsupported format for time conversion: expecting int64/uint64; got %T", v))
  187. }
  188. // fmt.Printf("testUnixNanoTimeExt.UpdateExt: v: %v, tt: %#v\n", v, tt)
  189. }
  190. func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) {
  191. //for python msgpack,
  192. // - all positive integers are unsigned 64-bit ints
  193. // - all floats are float64
  194. switch iv := v.(type) {
  195. case int8:
  196. if iv >= 0 {
  197. v2 = uint64(iv)
  198. } else {
  199. v2 = int64(iv)
  200. }
  201. case int16:
  202. if iv >= 0 {
  203. v2 = uint64(iv)
  204. } else {
  205. v2 = int64(iv)
  206. }
  207. case int32:
  208. if iv >= 0 {
  209. v2 = uint64(iv)
  210. } else {
  211. v2 = int64(iv)
  212. }
  213. case int64:
  214. if iv >= 0 {
  215. v2 = uint64(iv)
  216. } else {
  217. v2 = int64(iv)
  218. }
  219. case uint8:
  220. v2 = uint64(iv)
  221. case uint16:
  222. v2 = uint64(iv)
  223. case uint32:
  224. v2 = uint64(iv)
  225. case uint64:
  226. v2 = uint64(iv)
  227. case float32:
  228. v2 = float64(iv)
  229. case float64:
  230. v2 = float64(iv)
  231. case []interface{}:
  232. m2 := make([]interface{}, len(iv))
  233. for j, vj := range iv {
  234. m2[j] = testVerifyVal(vj, arg)
  235. }
  236. v2 = m2
  237. case testMbsT:
  238. m2 := make([]interface{}, len(iv))
  239. for j, vj := range iv {
  240. m2[j] = testVerifyVal(vj, arg)
  241. }
  242. v2 = testMbsT(m2)
  243. case map[string]bool:
  244. switch arg {
  245. case testVerifyMapTypeSame:
  246. m2 := make(map[string]bool)
  247. for kj, kv := range iv {
  248. m2[kj] = kv
  249. }
  250. v2 = m2
  251. case testVerifyMapTypeStrIntf, testVerifyForPython:
  252. m2 := make(map[string]interface{})
  253. for kj, kv := range iv {
  254. m2[kj] = kv
  255. }
  256. v2 = m2
  257. case testVerifyMapTypeIntfIntf:
  258. m2 := make(map[interface{}]interface{})
  259. for kj, kv := range iv {
  260. m2[kj] = kv
  261. }
  262. v2 = m2
  263. }
  264. case map[string]interface{}:
  265. switch arg {
  266. case testVerifyMapTypeSame:
  267. m2 := make(map[string]interface{})
  268. for kj, kv := range iv {
  269. m2[kj] = testVerifyVal(kv, arg)
  270. }
  271. v2 = m2
  272. case testVerifyMapTypeStrIntf, testVerifyForPython:
  273. m2 := make(map[string]interface{})
  274. for kj, kv := range iv {
  275. m2[kj] = testVerifyVal(kv, arg)
  276. }
  277. v2 = m2
  278. case testVerifyMapTypeIntfIntf:
  279. m2 := make(map[interface{}]interface{})
  280. for kj, kv := range iv {
  281. m2[kj] = testVerifyVal(kv, arg)
  282. }
  283. v2 = m2
  284. }
  285. case map[interface{}]interface{}:
  286. m2 := make(map[interface{}]interface{})
  287. for kj, kv := range iv {
  288. m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg)
  289. }
  290. v2 = m2
  291. case time.Time:
  292. switch arg {
  293. case testVerifyForPython:
  294. if iv2 := iv.UnixNano(); iv2 >= 0 {
  295. v2 = uint64(iv2)
  296. } else {
  297. v2 = int64(iv2)
  298. }
  299. default:
  300. v2 = v
  301. }
  302. default:
  303. v2 = v
  304. }
  305. return
  306. }
  307. func testInit() {
  308. gob.Register(new(TestStruc))
  309. if testInitDebug {
  310. ts0 := newTestStruc(2, false, !testSkipIntf, false)
  311. fmt.Printf("====> depth: %v, ts: %#v\n", 2, ts0)
  312. }
  313. for _, v := range testHandles {
  314. bh := v.getBasicHandle()
  315. bh.InternString = testInternStr
  316. bh.Canonical = testCanonical
  317. bh.CheckCircularRef = testCheckCircRef
  318. bh.StructToArray = testStructToArray
  319. // mostly doing this for binc
  320. if testWriteNoSymbols {
  321. bh.AsSymbols = AsSymbolNone
  322. } else {
  323. bh.AsSymbols = AsSymbolAll
  324. }
  325. }
  326. testJsonH.Indent = int8(testJsonIndent)
  327. testMsgpackH.RawToString = true
  328. // testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt)
  329. // testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt)
  330. // add extensions for msgpack, simple for time.Time, so we can encode/decode same way.
  331. // use different flavors of XXXExt calls, including deprecated ones.
  332. // NOTE:
  333. // DO NOT set extensions for JsonH, so we can test json(M|Unm)arshal support.
  334. testSimpleH.AddExt(timeTyp, 1, timeExtEncFn, timeExtDecFn)
  335. testMsgpackH.SetBytesExt(timeTyp, 1, timeExt{})
  336. testCborH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{})
  337. // testJsonH.SetInterfaceExt(timeTyp, 1, &testUnixNanoTimeExt{})
  338. // primitives MUST be an even number, so it can be used as a mapBySlice also.
  339. primitives := []interface{}{
  340. int8(-8),
  341. int16(-1616),
  342. int32(-32323232),
  343. int64(-6464646464646464),
  344. uint8(192),
  345. uint16(1616),
  346. uint32(32323232),
  347. uint64(6464646464646464),
  348. byte(192),
  349. float32(-3232.0),
  350. float64(-6464646464.0),
  351. float32(3232.0),
  352. float64(6464.0),
  353. float64(6464646464.0),
  354. false,
  355. true,
  356. "null",
  357. nil,
  358. "someday",
  359. timeToCompare1,
  360. "",
  361. timeToCompare2,
  362. "bytestring",
  363. timeToCompare3,
  364. "none",
  365. timeToCompare4,
  366. }
  367. maps := []interface{}{
  368. map[string]bool{
  369. "true": true,
  370. "false": false,
  371. },
  372. map[string]interface{}{
  373. "true": "True",
  374. "false": false,
  375. "uint16(1616)": uint16(1616),
  376. },
  377. //add a complex combo map in here. (map has list which has map)
  378. //note that after the first thing, everything else should be generic.
  379. map[string]interface{}{
  380. "list": []interface{}{
  381. int16(1616),
  382. int32(32323232),
  383. true,
  384. float32(-3232.0),
  385. map[string]interface{}{
  386. "TRUE": true,
  387. "FALSE": false,
  388. },
  389. []interface{}{true, false},
  390. },
  391. "int32": int32(32323232),
  392. "bool": true,
  393. "LONG STRING": "123456789012345678901234567890123456789012345678901234567890",
  394. "SHORT STRING": "1234567890",
  395. },
  396. map[interface{}]interface{}{
  397. true: "true",
  398. uint8(138): false,
  399. "false": uint8(200),
  400. },
  401. }
  402. testTableNumPrimitives = len(primitives)
  403. testTableIdxTime = testTableNumPrimitives - 8
  404. testTableNumMaps = len(maps)
  405. table = []interface{}{}
  406. table = append(table, primitives...)
  407. table = append(table, primitives)
  408. table = append(table, testMbsT(primitives))
  409. table = append(table, maps...)
  410. table = append(table, newTestStruc(0, false, !testSkipIntf, false))
  411. tableVerify = make([]interface{}, len(table))
  412. tableTestNilVerify = make([]interface{}, len(table))
  413. tablePythonVerify = make([]interface{}, len(table))
  414. lp := testTableNumPrimitives + 4
  415. av := tableVerify
  416. for i, v := range table {
  417. if i == lp {
  418. av[i] = skipVerifyVal
  419. continue
  420. }
  421. //av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  422. switch v.(type) {
  423. case []interface{}:
  424. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  425. case testMbsT:
  426. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  427. case map[string]interface{}:
  428. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  429. case map[interface{}]interface{}:
  430. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  431. default:
  432. av[i] = v
  433. }
  434. }
  435. av = tableTestNilVerify
  436. for i, v := range table {
  437. if i > lp {
  438. av[i] = skipVerifyVal
  439. continue
  440. }
  441. av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf)
  442. }
  443. av = tablePythonVerify
  444. for i, v := range table {
  445. if i == testTableNumPrimitives+1 || i > lp { // testTableNumPrimitives+1 is the mapBySlice
  446. av[i] = skipVerifyVal
  447. continue
  448. }
  449. av[i] = testVerifyVal(v, testVerifyForPython)
  450. }
  451. // only do the python verify up to the maps, skipping the last 2 maps.
  452. tablePythonVerify = tablePythonVerify[:testTableNumPrimitives+2+testTableNumMaps-2]
  453. }
  454. func testUnmarshal(v interface{}, data []byte, h Handle) (err error) {
  455. return testCodecDecode(data, v, h)
  456. }
  457. func testMarshal(v interface{}, h Handle) (bs []byte, err error) {
  458. return testCodecEncode(v, nil, testByteBuf, h)
  459. }
  460. func testMarshalErr(v interface{}, h Handle, t *testing.T, name string) (bs []byte, err error) {
  461. if bs, err = testMarshal(v, h); err != nil {
  462. logT(t, "Error encoding %s: %v, Err: %v", name, v, err)
  463. t.FailNow()
  464. }
  465. return
  466. }
  467. func testUnmarshalErr(v interface{}, data []byte, h Handle, t *testing.T, name string) (err error) {
  468. if err = testUnmarshal(v, data, h); err != nil {
  469. logT(t, "Error Decoding into %s: %v, Err: %v", name, v, err)
  470. t.FailNow()
  471. }
  472. return
  473. }
  474. // doTestCodecTableOne allows us test for different variations based on arguments passed.
  475. func doTestCodecTableOne(t *testing.T, testNil bool, h Handle,
  476. vs []interface{}, vsVerify []interface{}) {
  477. //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work.
  478. //Current setup allows us test (at least manually) the nil interface or typed interface.
  479. logT(t, "================ TestNil: %v ================\n", testNil)
  480. for i, v0 := range vs {
  481. logT(t, "..............................................")
  482. logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0)
  483. b0, err := testMarshalErr(v0, h, t, "v0")
  484. if err != nil {
  485. continue
  486. }
  487. if h.isBinary() {
  488. logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b0)
  489. } else {
  490. logT(t, " Encoded string: len: %v, %v\n", len(string(b0)), string(b0))
  491. // println("########### encoded string: " + string(b0))
  492. }
  493. var v1 interface{}
  494. if testNil {
  495. err = testUnmarshal(&v1, b0, h)
  496. } else {
  497. if v0 != nil {
  498. v0rt := reflect.TypeOf(v0) // ptr
  499. rv1 := reflect.New(v0rt)
  500. err = testUnmarshal(rv1.Interface(), b0, h)
  501. v1 = rv1.Elem().Interface()
  502. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  503. }
  504. }
  505. logT(t, " v1 returned: %T, %#v", v1, v1)
  506. // if v1 != nil {
  507. // logT(t, " v1 returned: %T, %#v", v1, v1)
  508. // //we always indirect, because ptr to typed value may be passed (if not testNil)
  509. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  510. // }
  511. if err != nil {
  512. logT(t, "-------- Error: %v. Partial return: %v", err, v1)
  513. failT(t)
  514. continue
  515. }
  516. v0check := vsVerify[i]
  517. if v0check == skipVerifyVal {
  518. logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1)
  519. continue
  520. }
  521. if err = deepEqual(v0check, v1); err == nil {
  522. logT(t, "++++++++ Before and After marshal matched\n")
  523. } else {
  524. // logT(t, "-------- Before and After marshal do not match: Error: %v"+
  525. // " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1)
  526. logT(t, "-------- Before and After marshal do not match: Error: %v", err)
  527. logT(t, " ....... GOLDEN: (%T) %#v", v0check, v0check)
  528. logT(t, " ....... DECODED: (%T) %#v", v1, v1)
  529. failT(t)
  530. }
  531. }
  532. }
  533. func testCodecTableOne(t *testing.T, h Handle) {
  534. testOnce.Do(testInitAll)
  535. // func TestMsgpackAllExperimental(t *testing.T) {
  536. // dopts := testDecOpts(nil, nil, false, true, true),
  537. numPrim, numMap, idxTime, idxMap := testTableNumPrimitives, testTableNumMaps, testTableIdxTime, testTableNumPrimitives+2
  538. //println("#################")
  539. switch v := h.(type) {
  540. case *MsgpackHandle:
  541. var oldWriteExt, oldRawToString bool
  542. oldWriteExt, v.WriteExt = v.WriteExt, true
  543. oldRawToString, v.RawToString = v.RawToString, true
  544. doTestCodecTableOne(t, false, h, table, tableVerify)
  545. v.WriteExt, v.RawToString = oldWriteExt, oldRawToString
  546. case *JsonHandle:
  547. //skip []interface{} containing time.Time, as it encodes as a number, but cannot decode back to time.Time.
  548. //As there is no real support for extension tags in json, this must be skipped.
  549. doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  550. doTestCodecTableOne(t, false, h, table[idxMap:], tableVerify[idxMap:])
  551. default:
  552. doTestCodecTableOne(t, false, h, table, tableVerify)
  553. }
  554. // func TestMsgpackAll(t *testing.T) {
  555. // //skip []interface{} containing time.Time
  556. // doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  557. // doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:])
  558. // func TestMsgpackNilStringMap(t *testing.T) {
  559. var oldMapType reflect.Type
  560. v := h.getBasicHandle()
  561. oldMapType, v.MapType = v.MapType, testMapStrIntfTyp
  562. //skip time.Time, []interface{} containing time.Time, last map, and newStruc
  563. doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime])
  564. doTestCodecTableOne(t, true, h, table[idxMap:idxMap+numMap-1], tableTestNilVerify[idxMap:idxMap+numMap-1])
  565. v.MapType = oldMapType
  566. // func TestMsgpackNilIntf(t *testing.T) {
  567. //do last map and newStruc
  568. idx2 := idxMap + numMap - 1
  569. doTestCodecTableOne(t, true, h, table[idx2:], tableTestNilVerify[idx2:])
  570. //TODO? What is this one?
  571. //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18])
  572. }
  573. func testCodecMiscOne(t *testing.T, h Handle) {
  574. testOnce.Do(testInitAll)
  575. b, err := testMarshalErr(32, h, t, "32")
  576. // Cannot do this nil one, because faster type assertion decoding will panic
  577. // var i *int32
  578. // if err = testUnmarshal(b, i, nil); err == nil {
  579. // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr")
  580. // t.FailNow()
  581. // }
  582. var i2 int32 = 0
  583. err = testUnmarshalErr(&i2, b, h, t, "int32-ptr")
  584. if i2 != int32(32) {
  585. logT(t, "------- didn't unmarshal to 32: Received: %d", i2)
  586. t.FailNow()
  587. }
  588. // func TestMsgpackDecodePtr(t *testing.T) {
  589. ts := newTestStruc(0, false, !testSkipIntf, false)
  590. b, err = testMarshalErr(ts, h, t, "pointer-to-struct")
  591. if len(b) < 40 {
  592. logT(t, "------- Size must be > 40. Size: %d", len(b))
  593. t.FailNow()
  594. }
  595. if h.isBinary() {
  596. logT(t, "------- b: %v", b)
  597. } else {
  598. logT(t, "------- b: %s", b)
  599. }
  600. ts2 := new(TestStruc)
  601. err = testUnmarshalErr(ts2, b, h, t, "pointer-to-struct")
  602. if ts2.I64 != math.MaxInt64*2/3 {
  603. logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64)
  604. t.FailNow()
  605. }
  606. // func TestMsgpackIntfDecode(t *testing.T) {
  607. m := map[string]int{"A": 2, "B": 3}
  608. p := []interface{}{m}
  609. bs, err := testMarshalErr(p, h, t, "p")
  610. m2 := map[string]int{}
  611. p2 := []interface{}{m2}
  612. err = testUnmarshalErr(&p2, bs, h, t, "&p2")
  613. if m2["A"] != 2 || m2["B"] != 3 {
  614. logT(t, "m2 not as expected: expecting: %v, got: %v", m, m2)
  615. t.FailNow()
  616. }
  617. // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2)
  618. checkEqualT(t, p, p2, "p=p2")
  619. checkEqualT(t, m, m2, "m=m2")
  620. if err = deepEqual(p, p2); err == nil {
  621. logT(t, "p and p2 match")
  622. } else {
  623. logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2)
  624. t.FailNow()
  625. }
  626. if err = deepEqual(m, m2); err == nil {
  627. logT(t, "m and m2 match")
  628. } else {
  629. logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2)
  630. t.FailNow()
  631. }
  632. // func TestMsgpackDecodeStructSubset(t *testing.T) {
  633. // test that we can decode a subset of the stream
  634. mm := map[string]interface{}{"A": 5, "B": 99, "C": 333}
  635. bs, err = testMarshalErr(mm, h, t, "mm")
  636. type ttt struct {
  637. A uint8
  638. C int32
  639. }
  640. var t2 ttt
  641. testUnmarshalErr(&t2, bs, h, t, "t2")
  642. t3 := ttt{5, 333}
  643. checkEqualT(t, t2, t3, "t2=t3")
  644. // println(">>>>>")
  645. // test simple arrays, non-addressable arrays, slices
  646. type tarr struct {
  647. A int64
  648. B [3]int64
  649. C []byte
  650. D [3]byte
  651. }
  652. var tarr0 = tarr{1, [3]int64{2, 3, 4}, []byte{4, 5, 6}, [3]byte{7, 8, 9}}
  653. // test both pointer and non-pointer (value)
  654. for _, tarr1 := range []interface{}{tarr0, &tarr0} {
  655. bs, err = testMarshalErr(tarr1, h, t, "tarr1")
  656. if err != nil {
  657. logT(t, "Error marshalling: %v", err)
  658. t.FailNow()
  659. }
  660. if _, ok := h.(*JsonHandle); ok {
  661. logT(t, "Marshal as: %s", bs)
  662. }
  663. var tarr2 tarr
  664. testUnmarshalErr(&tarr2, bs, h, t, "tarr2")
  665. checkEqualT(t, tarr0, tarr2, "tarr0=tarr2")
  666. // fmt.Printf(">>>> err: %v. tarr1: %v, tarr2: %v\n", err, tarr0, tarr2)
  667. }
  668. // test byte array, even if empty (msgpack only)
  669. if h == testMsgpackH {
  670. type ystruct struct {
  671. Anarray []byte
  672. }
  673. var ya = ystruct{}
  674. testUnmarshalErr(&ya, []byte{0x91, 0x90}, h, t, "ya")
  675. }
  676. }
  677. func testCodecEmbeddedPointer(t *testing.T, h Handle) {
  678. testOnce.Do(testInitAll)
  679. type Z int
  680. type A struct {
  681. AnInt int
  682. }
  683. type B struct {
  684. *Z
  685. *A
  686. MoreInt int
  687. }
  688. var z Z = 4
  689. x1 := &B{&z, &A{5}, 6}
  690. bs, err := testMarshalErr(x1, h, t, "x1")
  691. // fmt.Printf("buf: len(%v): %x\n", buf.Len(), buf.Bytes())
  692. var x2 = new(B)
  693. err = testUnmarshalErr(x2, bs, h, t, "x2")
  694. err = checkEqualT(t, x1, x2, "x1=x2")
  695. _ = err
  696. }
  697. func testCodecUnderlyingType(t *testing.T, h Handle) {
  698. testOnce.Do(testInitAll)
  699. // Manual Test.
  700. // Run by hand, with accompanying print statements in fast-path.go
  701. // to ensure that the fast functions are called.
  702. type T1 map[string]string
  703. v := T1{"1": "1s", "2": "2s"}
  704. var bs []byte
  705. var err error
  706. NewEncoderBytes(&bs, h).MustEncode(v)
  707. if err != nil {
  708. logT(t, "Error during encode: %v", err)
  709. failT(t)
  710. }
  711. var v2 T1
  712. NewDecoderBytes(bs, h).MustDecode(&v2)
  713. if err != nil {
  714. logT(t, "Error during decode: %v", err)
  715. failT(t)
  716. }
  717. }
  718. func testCodecChan(t *testing.T, h Handle) {
  719. // - send a slice []*int64 (sl1) into an chan (ch1) with cap > len(s1)
  720. // - encode ch1 as a stream array
  721. // - decode a chan (ch2), with cap > len(s1) from the stream array
  722. // - receive from ch2 into slice sl2
  723. // - compare sl1 and sl2
  724. // - do this for codecs: json, cbor (covers all types)
  725. sl1 := make([]*int64, 4)
  726. for i := range sl1 {
  727. var j int64 = int64(i)
  728. sl1[i] = &j
  729. }
  730. ch1 := make(chan *int64, 4)
  731. for _, j := range sl1 {
  732. ch1 <- j
  733. }
  734. var bs []byte
  735. NewEncoderBytes(&bs, h).MustEncode(ch1)
  736. // if !h.isBinary() {
  737. // fmt.Printf("before: len(ch1): %v, bs: %s\n", len(ch1), bs)
  738. // }
  739. // var ch2 chan *int64 // this will block if json, etc.
  740. ch2 := make(chan *int64, 8)
  741. NewDecoderBytes(bs, h).MustDecode(&ch2)
  742. // logT(t, "Len(ch2): %v", len(ch2))
  743. // fmt.Printf("after: len(ch2): %v, ch2: %v\n", len(ch2), ch2)
  744. close(ch2)
  745. var sl2 []*int64
  746. for j := range ch2 {
  747. sl2 = append(sl2, j)
  748. }
  749. if err := deepEqual(sl1, sl2); err != nil {
  750. logT(t, "Not Match: %v; len: %v, %v", err, len(sl1), len(sl2))
  751. failT(t)
  752. }
  753. }
  754. func testCodecRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration,
  755. ) (port int) {
  756. testOnce.Do(testInitAll)
  757. if testSkipRPCTests {
  758. return
  759. }
  760. // rpc needs EOF, which is sent via a panic, and so must be recovered.
  761. if !recoverPanicToErr {
  762. logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF")
  763. t.FailNow()
  764. }
  765. srv := rpc.NewServer()
  766. srv.Register(testRpcInt)
  767. ln, err := net.Listen("tcp", "127.0.0.1:0")
  768. // log("listener: %v", ln.Addr())
  769. checkErrT(t, err)
  770. port = (ln.Addr().(*net.TCPAddr)).Port
  771. // var opts *DecoderOptions
  772. // opts := testDecOpts
  773. // opts.MapType = mapStrIntfTyp
  774. // opts.RawToString = false
  775. serverExitChan := make(chan bool, 1)
  776. var serverExitFlag uint64 = 0
  777. serverFn := func() {
  778. for {
  779. conn1, err1 := ln.Accept()
  780. // if err1 != nil {
  781. // //fmt.Printf("accept err1: %v\n", err1)
  782. // continue
  783. // }
  784. if atomic.LoadUint64(&serverExitFlag) == 1 {
  785. serverExitChan <- true
  786. conn1.Close()
  787. return // exit serverFn goroutine
  788. }
  789. if err1 == nil {
  790. var sc rpc.ServerCodec = rr.ServerCodec(conn1, h)
  791. srv.ServeCodec(sc)
  792. }
  793. }
  794. }
  795. clientFn := func(cc rpc.ClientCodec) {
  796. cl := rpc.NewClientWithCodec(cc)
  797. defer cl.Close()
  798. // defer func() { println("##### client closing"); cl.Close() }()
  799. var up, sq, mult int
  800. var rstr string
  801. // log("Calling client")
  802. checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
  803. // log("Called TestRpcInt.Update")
  804. checkEqualT(t, testRpcInt.i, 5, "testRpcInt.i=5")
  805. checkEqualT(t, up, 5, "up=5")
  806. checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
  807. checkEqualT(t, sq, 25, "sq=25")
  808. checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
  809. checkEqualT(t, mult, 100, "mult=100")
  810. checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  811. checkEqualT(t, rstr, fmt.Sprintf("%#v", TestRpcABC{"Aa", "Bb", "Cc"}), "rstr=")
  812. checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
  813. checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}), "rstr=")
  814. }
  815. connFn := func() (bs net.Conn) {
  816. // log("calling f1")
  817. bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
  818. //fmt.Printf("f1. bs: %v, err2: %v\n", bs, err2)
  819. checkErrT(t, err2)
  820. return
  821. }
  822. exitFn := func() {
  823. atomic.StoreUint64(&serverExitFlag, 1)
  824. bs := connFn()
  825. <-serverExitChan
  826. bs.Close()
  827. // serverExitChan <- true
  828. }
  829. go serverFn()
  830. runtime.Gosched()
  831. //time.Sleep(100 * time.Millisecond)
  832. if exitSleepMs == 0 {
  833. defer ln.Close()
  834. defer exitFn()
  835. }
  836. if doRequest {
  837. bs := connFn()
  838. cc := rr.ClientCodec(bs, h)
  839. clientFn(cc)
  840. }
  841. if exitSleepMs != 0 {
  842. go func() {
  843. defer ln.Close()
  844. time.Sleep(exitSleepMs)
  845. exitFn()
  846. }()
  847. }
  848. return
  849. }
  850. func doTestMapEncodeForCanonical(t *testing.T, name string, h Handle) {
  851. v1 := map[string]interface{}{
  852. "a": 1,
  853. "b": "hello",
  854. "c": map[string]interface{}{
  855. "c/a": 1,
  856. "c/b": "world",
  857. "c/c": []int{1, 2, 3, 4},
  858. "c/d": map[string]interface{}{
  859. "c/d/a": "fdisajfoidsajfopdjsaopfjdsapofda",
  860. "c/d/b": "fdsafjdposakfodpsakfopdsakfpodsakfpodksaopfkdsopafkdopsa",
  861. "c/d/c": "poir02 ir30qif4p03qir0pogjfpoaerfgjp ofke[padfk[ewapf kdp[afep[aw",
  862. "c/d/d": "fdsopafkd[sa f-32qor-=4qeof -afo-erfo r-eafo 4e- o r4-qwo ag",
  863. "c/d/e": "kfep[a sfkr0[paf[a foe-[wq ewpfao-q ro3-q ro-4qof4-qor 3-e orfkropzjbvoisdb",
  864. "c/d/f": "",
  865. },
  866. "c/e": map[int]string{
  867. 1: "1",
  868. 22: "22",
  869. 333: "333",
  870. 4444: "4444",
  871. 55555: "55555",
  872. },
  873. "c/f": map[string]int{
  874. "1": 1,
  875. "22": 22,
  876. "333": 333,
  877. "4444": 4444,
  878. "55555": 55555,
  879. },
  880. },
  881. }
  882. var v2 map[string]interface{}
  883. var b1, b2 []byte
  884. // encode v1 into b1, decode b1 into v2, encode v2 into b2, compare b1 and b2
  885. bh := h.getBasicHandle()
  886. if !bh.Canonical {
  887. bh.Canonical = true
  888. defer func() { bh.Canonical = false }()
  889. }
  890. e1 := NewEncoderBytes(&b1, h)
  891. e1.MustEncode(v1)
  892. d1 := NewDecoderBytes(b1, h)
  893. d1.MustDecode(&v2)
  894. e2 := NewEncoderBytes(&b2, h)
  895. e2.MustEncode(v2)
  896. if !bytes.Equal(b1, b2) {
  897. logT(t, "Unequal bytes: %v VS %v", b1, b2)
  898. t.FailNow()
  899. }
  900. }
  901. func doTestStdEncIntf(t *testing.T, name string, h Handle) {
  902. args := [][2]interface{}{
  903. {&TestABC{"A", "BB", "CCC"}, new(TestABC)},
  904. {&TestABC2{"AAA", "BB", "C"}, new(TestABC2)},
  905. }
  906. for _, a := range args {
  907. var b []byte
  908. e := NewEncoderBytes(&b, h)
  909. e.MustEncode(a[0])
  910. d := NewDecoderBytes(b, h)
  911. d.MustDecode(a[1])
  912. if err := deepEqual(a[0], a[1]); err == nil {
  913. logT(t, "++++ Objects match")
  914. } else {
  915. logT(t, "---- Objects do not match: y1: %v, err: %v", a[1], err)
  916. failT(t)
  917. }
  918. }
  919. }
  920. func doTestEncCircularRef(t *testing.T, name string, h Handle) {
  921. type T1 struct {
  922. S string
  923. B bool
  924. T interface{}
  925. }
  926. type T2 struct {
  927. S string
  928. T *T1
  929. }
  930. type T3 struct {
  931. S string
  932. T *T2
  933. }
  934. t1 := T1{"t1", true, nil}
  935. t2 := T2{"t2", &t1}
  936. t3 := T3{"t3", &t2}
  937. t1.T = &t3
  938. var bs []byte
  939. var err error
  940. bh := h.getBasicHandle()
  941. if !bh.CheckCircularRef {
  942. bh.CheckCircularRef = true
  943. defer func() { bh.CheckCircularRef = false }()
  944. }
  945. err = NewEncoderBytes(&bs, h).Encode(&t3)
  946. if err == nil {
  947. logT(t, "expecting error due to circular reference. found none")
  948. t.FailNow()
  949. }
  950. if x := err.Error(); strings.Contains(x, "circular") || strings.Contains(x, "cyclic") {
  951. logT(t, "error detected as expected: %v", x)
  952. } else {
  953. logT(t, "error detected was not as expected: %v", x)
  954. t.FailNow()
  955. }
  956. }
  957. // TestAnonCycleT{1,2,3} types are used to test anonymous cycles.
  958. // They are top-level, so that they can have circular references.
  959. type (
  960. TestAnonCycleT1 struct {
  961. S string
  962. TestAnonCycleT2
  963. }
  964. TestAnonCycleT2 struct {
  965. S2 string
  966. TestAnonCycleT3
  967. }
  968. TestAnonCycleT3 struct {
  969. *TestAnonCycleT1
  970. }
  971. )
  972. func doTestAnonCycle(t *testing.T, name string, h Handle) {
  973. var x TestAnonCycleT1
  974. x.S = "hello"
  975. x.TestAnonCycleT2.S2 = "hello.2"
  976. x.TestAnonCycleT2.TestAnonCycleT3.TestAnonCycleT1 = &x
  977. // just check that you can get typeInfo for T1
  978. rt := reflect.TypeOf((*TestAnonCycleT1)(nil)).Elem()
  979. rtid := reflect.ValueOf(rt).Pointer()
  980. pti := h.getBasicHandle().getTypeInfo(rtid, rt)
  981. logT(t, "pti: %v", pti)
  982. }
  983. func doTestJsonLargeInteger(t *testing.T, v interface{}, ias uint8) {
  984. logT(t, "Running doTestJsonLargeInteger: v: %#v, ias: %c", v, ias)
  985. oldIAS := testJsonH.IntegerAsString
  986. defer func() { testJsonH.IntegerAsString = oldIAS }()
  987. testJsonH.IntegerAsString = ias
  988. var vu uint
  989. var vi int
  990. var vb bool
  991. var b []byte
  992. e := NewEncoderBytes(&b, testJsonH)
  993. e.MustEncode(v)
  994. e.MustEncode(true)
  995. d := NewDecoderBytes(b, testJsonH)
  996. // below, we validate that the json string or number was encoded,
  997. // then decode, and validate that the correct value was decoded.
  998. fnStrChk := func() {
  999. // check that output started with ", and ended with "true
  1000. if !(b[0] == '"' && string(b[len(b)-5:]) == `"true`) {
  1001. logT(t, "Expecting a JSON string, got: %s", b)
  1002. failT(t)
  1003. }
  1004. }
  1005. switch ias {
  1006. case 'L':
  1007. switch v2 := v.(type) {
  1008. case int:
  1009. v2n := int64(v2) // done to work with 32-bit OS
  1010. if v2n > 1<<53 || (v2n < 0 && -v2n > 1<<53) {
  1011. fnStrChk()
  1012. }
  1013. case uint:
  1014. v2n := uint64(v2) // done to work with 32-bit OS
  1015. if v2n > 1<<53 {
  1016. fnStrChk()
  1017. }
  1018. }
  1019. case 'A':
  1020. fnStrChk()
  1021. default:
  1022. // check that output doesn't contain " at all
  1023. for _, i := range b {
  1024. if i == '"' {
  1025. logT(t, "Expecting a JSON Number without quotation: got: %s", b)
  1026. failT(t)
  1027. }
  1028. }
  1029. }
  1030. switch v2 := v.(type) {
  1031. case int:
  1032. d.MustDecode(&vi)
  1033. d.MustDecode(&vb)
  1034. // check that vb = true, and vi == v2
  1035. if !(vb && vi == v2) {
  1036. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vi)
  1037. failT(t)
  1038. }
  1039. case uint:
  1040. d.MustDecode(&vu)
  1041. d.MustDecode(&vb)
  1042. // check that vb = true, and vi == v2
  1043. if !(vb && vu == v2) {
  1044. logT(t, "Expecting equal values from %s: got golden: %v, decoded: %v", b, v2, vu)
  1045. failT(t)
  1046. }
  1047. // fmt.Printf("%v: %s, decode: %d, bool: %v, equal_on_decode: %v\n", v, b, vu, vb, vu == v.(uint))
  1048. }
  1049. }
  1050. func doTestRawValue(t *testing.T, name string, h Handle) {
  1051. bh := h.getBasicHandle()
  1052. if !bh.Raw {
  1053. bh.Raw = true
  1054. defer func() { bh.Raw = false }()
  1055. }
  1056. var i, i2 int
  1057. var v, v2 TestRawValue
  1058. var bs, bs2 []byte
  1059. i = 1234 //1234567890
  1060. v = TestRawValue{I: i}
  1061. e := NewEncoderBytes(&bs, h)
  1062. e.MustEncode(v.I)
  1063. logT(t, ">>> raw: %v\n", bs)
  1064. v.R = Raw(bs)
  1065. e.ResetBytes(&bs2)
  1066. e.MustEncode(v)
  1067. logT(t, ">>> bs2: %v\n", bs2)
  1068. d := NewDecoderBytes(bs2, h)
  1069. d.MustDecode(&v2)
  1070. d.ResetBytes(v2.R)
  1071. logT(t, ">>> v2.R: %v\n", ([]byte)(v2.R))
  1072. d.MustDecode(&i2)
  1073. logT(t, ">>> Encoded %v, decoded %v\n", i, i2)
  1074. // logT(t, "Encoded %v, decoded %v", i, i2)
  1075. if i != i2 {
  1076. logT(t, "Error: encoded %v, decoded %v", i, i2)
  1077. t.FailNow()
  1078. }
  1079. }
  1080. // Comprehensive testing that generates data encoded from python handle (cbor, msgpack),
  1081. // and validates that our code can read and write it out accordingly.
  1082. // We keep this unexported here, and put actual test in ext_dep_test.go.
  1083. // This way, it can be excluded by excluding file completely.
  1084. func doTestPythonGenStreams(t *testing.T, name string, h Handle) {
  1085. logT(t, "TestPythonGenStreams-%v", name)
  1086. tmpdir, err := ioutil.TempDir("", "golang-"+name+"-test")
  1087. if err != nil {
  1088. logT(t, "-------- Unable to create temp directory\n")
  1089. t.FailNow()
  1090. }
  1091. defer os.RemoveAll(tmpdir)
  1092. logT(t, "tmpdir: %v", tmpdir)
  1093. cmd := exec.Command("python", "test.py", "testdata", tmpdir)
  1094. //cmd.Stdin = strings.NewReader("some input")
  1095. //cmd.Stdout = &out
  1096. var cmdout []byte
  1097. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1098. logT(t, "-------- Error running test.py testdata. Err: %v", err)
  1099. logT(t, " %v", string(cmdout))
  1100. t.FailNow()
  1101. }
  1102. bh := h.getBasicHandle()
  1103. oldMapType := bh.MapType
  1104. for i, v := range tablePythonVerify {
  1105. // if v == uint64(0) && h == testMsgpackH {
  1106. // v = int64(0)
  1107. // }
  1108. bh.MapType = oldMapType
  1109. //load up the golden file based on number
  1110. //decode it
  1111. //compare to in-mem object
  1112. //encode it again
  1113. //compare to output stream
  1114. logT(t, "..............................................")
  1115. logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
  1116. var bss []byte
  1117. bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+"."+name+".golden"))
  1118. if err != nil {
  1119. logT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
  1120. failT(t)
  1121. continue
  1122. }
  1123. bh.MapType = testMapStrIntfTyp
  1124. var v1 interface{}
  1125. if err = testUnmarshal(&v1, bss, h); err != nil {
  1126. logT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
  1127. failT(t)
  1128. continue
  1129. }
  1130. if v == skipVerifyVal {
  1131. continue
  1132. }
  1133. //no need to indirect, because we pass a nil ptr, so we already have the value
  1134. //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
  1135. if err = deepEqual(v, v1); err == nil {
  1136. logT(t, "++++++++ Objects match: %T, %v", v, v)
  1137. } else {
  1138. logT(t, "-------- Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
  1139. logT(t, "-------- GOLDEN: %#v", v)
  1140. // logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1141. logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  1142. failT(t)
  1143. }
  1144. bsb, err := testMarshal(v1, h)
  1145. if err != nil {
  1146. logT(t, "Error encoding to stream: %d: Err: %v", i, err)
  1147. failT(t)
  1148. continue
  1149. }
  1150. if err = deepEqual(bsb, bss); err == nil {
  1151. logT(t, "++++++++ Bytes match")
  1152. } else {
  1153. logT(t, "???????? Bytes do not match. %v.", err)
  1154. xs := "--------"
  1155. if reflect.ValueOf(v).Kind() == reflect.Map {
  1156. xs = " "
  1157. logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
  1158. } else {
  1159. logT(t, "%s It's not a map. They should match.", xs)
  1160. failT(t)
  1161. }
  1162. logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
  1163. logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
  1164. }
  1165. }
  1166. bh.MapType = oldMapType
  1167. }
  1168. // To test MsgpackSpecRpc, we test 3 scenarios:
  1169. // - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
  1170. // - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
  1171. // - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
  1172. //
  1173. // This allows us test the different calling conventions
  1174. // - Go Service requires only one argument
  1175. // - Python Service allows multiple arguments
  1176. func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
  1177. if testSkipRPCTests {
  1178. return
  1179. }
  1180. // openPorts are between 6700 and 6800
  1181. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  1182. openPort := strconv.FormatInt(6700+r.Int63n(99), 10)
  1183. // openPort := "6792"
  1184. cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4")
  1185. checkErrT(t, cmd.Start())
  1186. bs, err2 := net.Dial("tcp", ":"+openPort)
  1187. for i := 0; i < 10 && err2 != nil; i++ {
  1188. time.Sleep(50 * time.Millisecond) // time for python rpc server to start
  1189. bs, err2 = net.Dial("tcp", ":"+openPort)
  1190. }
  1191. checkErrT(t, err2)
  1192. cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH)
  1193. cl := rpc.NewClientWithCodec(cc)
  1194. defer cl.Close()
  1195. var rstr string
  1196. checkErrT(t, cl.Call("EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
  1197. //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
  1198. var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
  1199. checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
  1200. checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
  1201. cmd.Process.Kill()
  1202. }
  1203. func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
  1204. if testSkipRPCTests {
  1205. return
  1206. }
  1207. port := testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
  1208. //time.Sleep(1000 * time.Millisecond)
  1209. cmd := exec.Command("python", "test.py", "rpc-client-go-service", strconv.Itoa(port))
  1210. var cmdout []byte
  1211. var err error
  1212. if cmdout, err = cmd.CombinedOutput(); err != nil {
  1213. logT(t, "-------- Error running test.py rpc-client-go-service. Err: %v", err)
  1214. logT(t, " %v", string(cmdout))
  1215. t.FailNow()
  1216. }
  1217. checkEqualT(t, string(cmdout),
  1218. fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestRpcABC{"Aa", "Bb", "Cc"}), "cmdout=")
  1219. }
  1220. func TestBincCodecsTable(t *testing.T) {
  1221. testCodecTableOne(t, testBincH)
  1222. }
  1223. func TestBincCodecsMisc(t *testing.T) {
  1224. testCodecMiscOne(t, testBincH)
  1225. }
  1226. func TestBincCodecsEmbeddedPointer(t *testing.T) {
  1227. testCodecEmbeddedPointer(t, testBincH)
  1228. }
  1229. func TestBincStdEncIntf(t *testing.T) {
  1230. doTestStdEncIntf(t, "binc", testBincH)
  1231. }
  1232. func TestSimpleCodecsTable(t *testing.T) {
  1233. testCodecTableOne(t, testSimpleH)
  1234. }
  1235. func TestSimpleCodecsMisc(t *testing.T) {
  1236. testCodecMiscOne(t, testSimpleH)
  1237. }
  1238. func TestSimpleCodecsEmbeddedPointer(t *testing.T) {
  1239. testCodecEmbeddedPointer(t, testSimpleH)
  1240. }
  1241. func TestSimpleStdEncIntf(t *testing.T) {
  1242. doTestStdEncIntf(t, "simple", testSimpleH)
  1243. }
  1244. func TestMsgpackCodecsTable(t *testing.T) {
  1245. testCodecTableOne(t, testMsgpackH)
  1246. }
  1247. func TestMsgpackCodecsMisc(t *testing.T) {
  1248. testCodecMiscOne(t, testMsgpackH)
  1249. }
  1250. func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
  1251. testCodecEmbeddedPointer(t, testMsgpackH)
  1252. }
  1253. func TestMsgpackStdEncIntf(t *testing.T) {
  1254. doTestStdEncIntf(t, "msgpack", testMsgpackH)
  1255. }
  1256. func TestCborCodecsTable(t *testing.T) {
  1257. testCodecTableOne(t, testCborH)
  1258. }
  1259. func TestCborCodecsMisc(t *testing.T) {
  1260. testCodecMiscOne(t, testCborH)
  1261. }
  1262. func TestCborCodecsEmbeddedPointer(t *testing.T) {
  1263. testCodecEmbeddedPointer(t, testCborH)
  1264. }
  1265. func TestCborMapEncodeForCanonical(t *testing.T) {
  1266. doTestMapEncodeForCanonical(t, "cbor", testCborH)
  1267. }
  1268. func TestCborCodecChan(t *testing.T) {
  1269. testCodecChan(t, testCborH)
  1270. }
  1271. func TestCborStdEncIntf(t *testing.T) {
  1272. doTestStdEncIntf(t, "cbor", testCborH)
  1273. }
  1274. func TestJsonCodecsTable(t *testing.T) {
  1275. testCodecTableOne(t, testJsonH)
  1276. }
  1277. func TestJsonCodecsMisc(t *testing.T) {
  1278. testCodecMiscOne(t, testJsonH)
  1279. }
  1280. func TestJsonCodecsEmbeddedPointer(t *testing.T) {
  1281. testCodecEmbeddedPointer(t, testJsonH)
  1282. }
  1283. func TestJsonCodecChan(t *testing.T) {
  1284. testCodecChan(t, testJsonH)
  1285. }
  1286. func TestJsonStdEncIntf(t *testing.T) {
  1287. doTestStdEncIntf(t, "json", testJsonH)
  1288. }
  1289. // ----- Raw ---------
  1290. func TestJsonRaw(t *testing.T) {
  1291. doTestRawValue(t, "json", testJsonH)
  1292. }
  1293. func TestBincRaw(t *testing.T) {
  1294. doTestRawValue(t, "binc", testBincH)
  1295. }
  1296. func TestMsgpackRaw(t *testing.T) {
  1297. doTestRawValue(t, "msgpack", testMsgpackH)
  1298. }
  1299. func TestSimpleRaw(t *testing.T) {
  1300. doTestRawValue(t, "simple", testSimpleH)
  1301. }
  1302. func TestCborRaw(t *testing.T) {
  1303. doTestRawValue(t, "cbor", testCborH)
  1304. }
  1305. // ----- ALL (framework based) -----
  1306. func TestAllEncCircularRef(t *testing.T) {
  1307. doTestEncCircularRef(t, "cbor", testCborH)
  1308. }
  1309. func TestAllAnonCycle(t *testing.T) {
  1310. doTestAnonCycle(t, "cbor", testCborH)
  1311. }
  1312. // ----- RPC -----
  1313. func TestBincRpcGo(t *testing.T) {
  1314. testCodecRpcOne(t, GoRpc, testBincH, true, 0)
  1315. }
  1316. func TestSimpleRpcGo(t *testing.T) {
  1317. testCodecRpcOne(t, GoRpc, testSimpleH, true, 0)
  1318. }
  1319. func TestMsgpackRpcGo(t *testing.T) {
  1320. testCodecRpcOne(t, GoRpc, testMsgpackH, true, 0)
  1321. }
  1322. func TestCborRpcGo(t *testing.T) {
  1323. testCodecRpcOne(t, GoRpc, testCborH, true, 0)
  1324. }
  1325. func TestJsonRpcGo(t *testing.T) {
  1326. testCodecRpcOne(t, GoRpc, testJsonH, true, 0)
  1327. }
  1328. func TestMsgpackRpcSpec(t *testing.T) {
  1329. testCodecRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
  1330. }
  1331. func TestBincUnderlyingType(t *testing.T) {
  1332. testCodecUnderlyingType(t, testBincH)
  1333. }
  1334. func TestJsonLargeInteger(t *testing.T) {
  1335. for _, i := range []uint8{'L', 'A', 0} {
  1336. for _, j := range []interface{}{
  1337. int64(1 << 60),
  1338. -int64(1 << 60),
  1339. 0,
  1340. 1 << 20,
  1341. -(1 << 20),
  1342. uint64(1 << 60),
  1343. uint(0),
  1344. uint(1 << 20),
  1345. } {
  1346. doTestJsonLargeInteger(t, j, i)
  1347. }
  1348. }
  1349. }
  1350. // TODO:
  1351. // Add Tests for:
  1352. // - decoding empty list/map in stream into a nil slice/map
  1353. // - binary(M|Unm)arsher support for time.Time (e.g. cbor encoding)
  1354. // - text(M|Unm)arshaler support for time.Time (e.g. json encoding)
  1355. // - non fast-path scenarios e.g. map[string]uint16, []customStruct.
  1356. // Expand cbor to include indefinite length stuff for this non-fast-path types.
  1357. // This may not be necessary, since we have the manual tests (fastpathEnabled=false) to test/validate with.
  1358. // - CodecSelfer
  1359. // Ensure it is called when (en|de)coding interface{} or reflect.Value (2 different codepaths).
  1360. // - interfaces: textMarshaler, binaryMarshaler, codecSelfer
  1361. // - struct tags:
  1362. // on anonymous fields, _struct (all fields), etc
  1363. // - codecgen of struct containing channels.
  1364. // - bad input with large array length prefix
  1365. //
  1366. // Cleanup tests:
  1367. // - The are brittle in their handling of validation and skipping