codecs_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. // Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a BSD-style 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. // Some hints:
  17. // - python msgpack encodes positive numbers as uints, so use uints below
  18. // for positive numbers.
  19. // - flag mpEncodeUintAsFixnum allows uints be encoded as fixnums.
  20. // To accomodate it being true or false, ensure all unsigned values below are > 128.
  21. import (
  22. "bytes"
  23. "encoding/gob"
  24. "flag"
  25. "fmt"
  26. "io/ioutil"
  27. "math"
  28. "net"
  29. "net/rpc"
  30. "os"
  31. "os/exec"
  32. "path/filepath"
  33. "reflect"
  34. "runtime"
  35. "strconv"
  36. "sync/atomic"
  37. "testing"
  38. "time"
  39. )
  40. type testVerifyArg int
  41. const (
  42. testVerifyMapTypeSame testVerifyArg = iota
  43. testVerifyMapTypeStrIntf
  44. testVerifyMapTypeIntfIntf
  45. // testVerifySliceIntf
  46. testVerifyForPython
  47. )
  48. var (
  49. testInitDebug bool
  50. testUseIoEncDec bool
  51. testStructToArray bool
  52. testWriteNoSymbols bool
  53. _ = fmt.Printf
  54. skipVerifyVal interface{} = &(struct{}{})
  55. // For Go Time, do not use a descriptive timezone.
  56. // It's unnecessary, and makes it harder to do a reflect.DeepEqual.
  57. // The Offset already tells what the offset should be, if not on UTC and unknown zone name.
  58. timeLoc = time.FixedZone("", -8*60*60) // UTC-08:00 //time.UTC-8
  59. timeToCompare1 = time.Date(2012, 2, 2, 2, 2, 2, 2000, timeLoc)
  60. timeToCompare2 = time.Date(1900, 2, 2, 2, 2, 2, 2000, timeLoc)
  61. timeToCompare3 = time.Unix(0, 0).UTC()
  62. timeToCompare4 = time.Time{}.UTC()
  63. table []interface{} // main items we encode
  64. tableVerify []interface{} // we verify encoded things against this after decode
  65. tableTestNilVerify []interface{} // for nil interface, use this to verify (rules are different)
  66. tablePythonVerify []interface{} // for verifying for python, since Python sometimes
  67. // will encode a float32 as float64, or large int as uint
  68. testRpcInt = new(TestRpcInt)
  69. testMsgpackH = &MsgpackHandle{}
  70. testBincH = &BincHandle{}
  71. )
  72. func testInitFlags() {
  73. // delete(testDecOpts.ExtFuncs, timeTyp)
  74. flag.BoolVar(&testInitDebug, "tg", false, "Test Debug")
  75. flag.BoolVar(&testUseIoEncDec, "ti", false, "Use IO Reader/Writer for Marshal/Unmarshal")
  76. flag.BoolVar(&testStructToArray, "ts", false, "Set StructToArray option")
  77. flag.BoolVar(&testWriteNoSymbols, "tn", false, "Set NoSymbols option")
  78. }
  79. type AnonInTestStruc struct {
  80. AS string
  81. AI64 int64
  82. AI16 int16
  83. AUi64 uint64
  84. ASslice []string
  85. AI64slice []int64
  86. }
  87. type TestStruc struct {
  88. S string
  89. I64 int64
  90. I16 int16
  91. Ui64 uint64
  92. Ui8 uint8
  93. B bool
  94. By byte
  95. Sslice []string
  96. I64slice []int64
  97. I16slice []int16
  98. Ui64slice []uint64
  99. Ui8slice []uint8
  100. Bslice []bool
  101. Byslice []byte
  102. Islice []interface{}
  103. Iptrslice []*int64
  104. AnonInTestStruc
  105. //M map[interface{}]interface{} `json:"-",bson:"-"`
  106. Ms map[string]interface{}
  107. Msi64 map[string]int64
  108. Nintf interface{} //don't set this, so we can test for nil
  109. T time.Time
  110. Nmap map[string]bool //don't set this, so we can test for nil
  111. Nslice []byte //don't set this, so we can test for nil
  112. Nint64 *int64 //don't set this, so we can test for nil
  113. Mtsptr map[string]*TestStruc
  114. Mts map[string]TestStruc
  115. Its []*TestStruc
  116. Nteststruc *TestStruc
  117. }
  118. type TestABC struct {
  119. A, B, C string
  120. }
  121. type TestRpcInt struct {
  122. i int
  123. }
  124. func (r *TestRpcInt) Update(n int, res *int) error { r.i = n; *res = r.i; return nil }
  125. func (r *TestRpcInt) Square(ignore int, res *int) error { *res = r.i * r.i; return nil }
  126. func (r *TestRpcInt) Mult(n int, res *int) error { *res = r.i * n; return nil }
  127. func (r *TestRpcInt) EchoStruct(arg TestABC, res *string) error {
  128. *res = fmt.Sprintf("%#v", arg)
  129. return nil
  130. }
  131. func (r *TestRpcInt) Echo123(args []string, res *string) error {
  132. *res = fmt.Sprintf("%#v", args)
  133. return nil
  134. }
  135. func testVerifyVal(v interface{}, arg testVerifyArg) (v2 interface{}) {
  136. //for python msgpack,
  137. // - all positive integers are unsigned 64-bit ints
  138. // - all floats are float64
  139. switch iv := v.(type) {
  140. case int8:
  141. if arg == testVerifyForPython && iv > 0 {
  142. v2 = uint64(iv)
  143. } else {
  144. v2 = int64(iv)
  145. }
  146. case int16:
  147. if arg == testVerifyForPython && iv > 0 {
  148. v2 = uint64(iv)
  149. } else {
  150. v2 = int64(iv)
  151. }
  152. case int32:
  153. if arg == testVerifyForPython && iv > 0 {
  154. v2 = uint64(iv)
  155. } else {
  156. v2 = int64(iv)
  157. }
  158. case int64:
  159. if arg == testVerifyForPython && iv > 0 {
  160. v2 = uint64(iv)
  161. } else {
  162. v2 = int64(iv)
  163. }
  164. case uint8:
  165. v2 = uint64(iv)
  166. case uint16:
  167. v2 = uint64(iv)
  168. case uint32:
  169. v2 = uint64(iv)
  170. case uint64:
  171. v2 = uint64(iv)
  172. case float32:
  173. v2 = float64(iv)
  174. case float64:
  175. v2 = float64(iv)
  176. case []interface{}:
  177. m2 := make([]interface{}, len(iv))
  178. for j, vj := range iv {
  179. m2[j] = testVerifyVal(vj, arg)
  180. }
  181. v2 = m2
  182. case map[string]bool:
  183. switch arg {
  184. case testVerifyMapTypeSame:
  185. m2 := make(map[string]bool)
  186. for kj, kv := range iv {
  187. m2[kj] = kv
  188. }
  189. v2 = m2
  190. case testVerifyMapTypeStrIntf, testVerifyForPython:
  191. m2 := make(map[string]interface{})
  192. for kj, kv := range iv {
  193. m2[kj] = kv
  194. }
  195. v2 = m2
  196. case testVerifyMapTypeIntfIntf:
  197. m2 := make(map[interface{}]interface{})
  198. for kj, kv := range iv {
  199. m2[kj] = kv
  200. }
  201. v2 = m2
  202. }
  203. case map[string]interface{}:
  204. switch arg {
  205. case testVerifyMapTypeSame:
  206. m2 := make(map[string]interface{})
  207. for kj, kv := range iv {
  208. m2[kj] = testVerifyVal(kv, arg)
  209. }
  210. v2 = m2
  211. case testVerifyMapTypeStrIntf, testVerifyForPython:
  212. m2 := make(map[string]interface{})
  213. for kj, kv := range iv {
  214. m2[kj] = testVerifyVal(kv, arg)
  215. }
  216. v2 = m2
  217. case testVerifyMapTypeIntfIntf:
  218. m2 := make(map[interface{}]interface{})
  219. for kj, kv := range iv {
  220. m2[kj] = testVerifyVal(kv, arg)
  221. }
  222. v2 = m2
  223. }
  224. case map[interface{}]interface{}:
  225. m2 := make(map[interface{}]interface{})
  226. for kj, kv := range iv {
  227. m2[testVerifyVal(kj, arg)] = testVerifyVal(kv, arg)
  228. }
  229. v2 = m2
  230. case time.Time:
  231. switch arg {
  232. case testVerifyForPython:
  233. if iv2 := iv.UnixNano(); iv2 > 0 {
  234. v2 = uint64(iv2)
  235. } else {
  236. v2 = int64(iv2)
  237. }
  238. default:
  239. v2 = v
  240. }
  241. default:
  242. v2 = v
  243. }
  244. return
  245. }
  246. func testInit() {
  247. gob.Register(new(TestStruc))
  248. if testInitDebug {
  249. ts0 := newTestStruc(2, false)
  250. fmt.Printf("====> depth: %v, ts: %#v\n", 2, ts0)
  251. }
  252. testBincH.StructToArray = testStructToArray
  253. if testWriteNoSymbols {
  254. testBincH.AsSymbols = AsSymbolNone
  255. } else {
  256. testBincH.AsSymbols = AsSymbolAll
  257. }
  258. testMsgpackH.StructToArray = testStructToArray
  259. testMsgpackH.RawToString = true
  260. // testMsgpackH.AddExt(byteSliceTyp, 0, testMsgpackH.BinaryEncodeExt, testMsgpackH.BinaryDecodeExt)
  261. // testMsgpackH.AddExt(timeTyp, 1, testMsgpackH.TimeEncodeExt, testMsgpackH.TimeDecodeExt)
  262. testMsgpackH.AddExt(timeTyp, 1,
  263. func(rv reflect.Value) ([]byte, error) {
  264. return encodeTime(rv.Interface().(time.Time)), nil
  265. },
  266. func(rv reflect.Value, bs []byte) error {
  267. tt, err := decodeTime(bs)
  268. if err == nil {
  269. rv.Set(reflect.ValueOf(tt))
  270. }
  271. return err
  272. },
  273. )
  274. primitives := []interface{}{
  275. int8(-8),
  276. int16(-1616),
  277. int32(-32323232),
  278. int64(-6464646464646464),
  279. uint8(192),
  280. uint16(1616),
  281. uint32(32323232),
  282. uint64(6464646464646464),
  283. byte(192),
  284. float32(-3232.0),
  285. float64(-6464646464.0),
  286. float32(3232.0),
  287. float64(6464646464.0),
  288. false,
  289. true,
  290. nil,
  291. "someday",
  292. "",
  293. "bytestring",
  294. timeToCompare1,
  295. timeToCompare2,
  296. timeToCompare3,
  297. timeToCompare4,
  298. }
  299. mapsAndStrucs := []interface{}{
  300. map[string]bool{
  301. "true": true,
  302. "false": false,
  303. },
  304. map[string]interface{}{
  305. "true": "True",
  306. "false": false,
  307. "uint16(1616)": uint16(1616),
  308. },
  309. //add a complex combo map in here. (map has list which has map)
  310. //note that after the first thing, everything else should be generic.
  311. map[string]interface{}{
  312. "list": []interface{}{
  313. int16(1616),
  314. int32(32323232),
  315. true,
  316. float32(-3232.0),
  317. map[string]interface{}{
  318. "TRUE": true,
  319. "FALSE": false,
  320. },
  321. []interface{}{true, false},
  322. },
  323. "int32": int32(32323232),
  324. "bool": true,
  325. "LONG STRING": "123456789012345678901234567890123456789012345678901234567890",
  326. "SHORT STRING": "1234567890",
  327. },
  328. map[interface{}]interface{}{
  329. true: "true",
  330. uint8(138): false,
  331. "false": uint8(200),
  332. },
  333. newTestStruc(0, false),
  334. }
  335. table = []interface{}{}
  336. table = append(table, primitives...) //0-19 are primitives
  337. table = append(table, primitives) //20 is a list of primitives
  338. table = append(table, mapsAndStrucs...) //21-24 are maps. 25 is a *struct
  339. tableVerify = make([]interface{}, len(table))
  340. tableTestNilVerify = make([]interface{}, len(table))
  341. tablePythonVerify = make([]interface{}, len(table))
  342. lp := len(primitives)
  343. av := tableVerify
  344. for i, v := range table {
  345. if i == lp+3 {
  346. av[i] = skipVerifyVal
  347. continue
  348. }
  349. //av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  350. switch v.(type) {
  351. case []interface{}:
  352. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  353. case map[string]interface{}:
  354. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  355. case map[interface{}]interface{}:
  356. av[i] = testVerifyVal(v, testVerifyMapTypeSame)
  357. default:
  358. av[i] = v
  359. }
  360. }
  361. av = tableTestNilVerify
  362. for i, v := range table {
  363. if i > lp+3 {
  364. av[i] = skipVerifyVal
  365. continue
  366. }
  367. av[i] = testVerifyVal(v, testVerifyMapTypeStrIntf)
  368. }
  369. av = tablePythonVerify
  370. for i, v := range table {
  371. if i > lp+3 {
  372. av[i] = skipVerifyVal
  373. continue
  374. }
  375. av[i] = testVerifyVal(v, testVerifyForPython)
  376. }
  377. tablePythonVerify = tablePythonVerify[:24]
  378. }
  379. func testUnmarshal(v interface{}, data []byte, h Handle) error {
  380. if testUseIoEncDec {
  381. return NewDecoder(bytes.NewBuffer(data), h).Decode(v)
  382. }
  383. return NewDecoderBytes(data, h).Decode(v)
  384. }
  385. func testMarshal(v interface{}, h Handle) (bs []byte, err error) {
  386. if testUseIoEncDec {
  387. var buf bytes.Buffer
  388. err = NewEncoder(&buf, h).Encode(v)
  389. bs = buf.Bytes()
  390. return
  391. }
  392. err = NewEncoderBytes(&bs, h).Encode(v)
  393. return
  394. }
  395. func newTestStruc(depth int, bench bool) (ts *TestStruc) {
  396. var i64a, i64b, i64c, i64d int64 = 64, 6464, 646464, 64646464
  397. ts = &TestStruc{
  398. S: "some string",
  399. I64: math.MaxInt64 * 2 / 3, // 64,
  400. I16: 16,
  401. Ui64: uint64(int64(math.MaxInt64 * 2 / 3)), // 64, //don't use MaxUint64, as bson can't write it
  402. Ui8: 160,
  403. B: true,
  404. By: 5,
  405. Sslice: []string{"one", "two", "three"},
  406. I64slice: []int64{1, 2, 3},
  407. I16slice: []int16{4, 5, 6},
  408. Ui64slice: []uint64{137, 138, 139},
  409. Ui8slice: []uint8{210, 211, 212},
  410. Bslice: []bool{true, false, true, false},
  411. Byslice: []byte{13, 14, 15},
  412. Islice: []interface{}{"true", true, "no", false, uint64(288), float64(0.4)},
  413. Ms: map[string]interface{}{
  414. "true": "true",
  415. "int64(9)": false,
  416. },
  417. Msi64: map[string]int64{
  418. "one": 1,
  419. "two": 2,
  420. },
  421. T: timeToCompare1,
  422. AnonInTestStruc: AnonInTestStruc{
  423. AS: "A-String",
  424. AI64: 64,
  425. AI16: 16,
  426. AUi64: 64,
  427. ASslice: []string{"Aone", "Atwo", "Athree"},
  428. AI64slice: []int64{1, 2, 3},
  429. },
  430. }
  431. //For benchmarks, some things will not work.
  432. if !bench {
  433. //json and bson require string keys in maps
  434. //ts.M = map[interface{}]interface{}{
  435. // true: "true",
  436. // int8(9): false,
  437. //}
  438. //gob cannot encode nil in element in array (encodeArray: nil element)
  439. ts.Iptrslice = []*int64{nil, &i64a, nil, &i64b, nil, &i64c, nil, &i64d, nil}
  440. // ts.Iptrslice = nil
  441. }
  442. if depth > 0 {
  443. depth--
  444. if ts.Mtsptr == nil {
  445. ts.Mtsptr = make(map[string]*TestStruc)
  446. }
  447. if ts.Mts == nil {
  448. ts.Mts = make(map[string]TestStruc)
  449. }
  450. ts.Mtsptr["0"] = newTestStruc(depth, bench)
  451. ts.Mts["0"] = *(ts.Mtsptr["0"])
  452. ts.Its = append(ts.Its, ts.Mtsptr["0"])
  453. }
  454. return
  455. }
  456. // doTestCodecTableOne allows us test for different variations based on arguments passed.
  457. func doTestCodecTableOne(t *testing.T, testNil bool, h Handle,
  458. vs []interface{}, vsVerify []interface{}) {
  459. //if testNil, then just test for when a pointer to a nil interface{} is passed. It should work.
  460. //Current setup allows us test (at least manually) the nil interface or typed interface.
  461. logT(t, "================ TestNil: %v ================\n", testNil)
  462. for i, v0 := range vs {
  463. logT(t, "..............................................")
  464. logT(t, " Testing: #%d:, %T, %#v\n", i, v0, v0)
  465. b0, err := testMarshal(v0, h)
  466. if err != nil {
  467. logT(t, err.Error())
  468. failT(t)
  469. continue
  470. }
  471. logT(t, " Encoded bytes: len: %v, %v\n", len(b0), b0)
  472. var v1 interface{}
  473. if testNil {
  474. err = testUnmarshal(&v1, b0, h)
  475. } else {
  476. if v0 != nil {
  477. v0rt := reflect.TypeOf(v0) // ptr
  478. rv1 := reflect.New(v0rt)
  479. err = testUnmarshal(rv1.Interface(), b0, h)
  480. v1 = rv1.Elem().Interface()
  481. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  482. }
  483. }
  484. logT(t, " v1 returned: %T, %#v", v1, v1)
  485. // if v1 != nil {
  486. // logT(t, " v1 returned: %T, %#v", v1, v1)
  487. // //we always indirect, because ptr to typed value may be passed (if not testNil)
  488. // v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface()
  489. // }
  490. if err != nil {
  491. logT(t, "-------- Error: %v. Partial return: %v", err, v1)
  492. failT(t)
  493. continue
  494. }
  495. v0check := vsVerify[i]
  496. if v0check == skipVerifyVal {
  497. logT(t, " Nil Check skipped: Decoded: %T, %#v\n", v1, v1)
  498. continue
  499. }
  500. if err = deepEqual(v0check, v1); err == nil {
  501. logT(t, "++++++++ Before and After marshal matched\n")
  502. } else {
  503. logT(t, "-------- Before and After marshal do not match: Error: %v"+
  504. " ====> GOLDEN: (%T) %#v, DECODED: (%T) %#v\n", err, v0check, v0check, v1, v1)
  505. failT(t)
  506. }
  507. }
  508. }
  509. func testCodecTableOne(t *testing.T, h Handle) {
  510. // func TestMsgpackAllExperimental(t *testing.T) {
  511. // dopts := testDecOpts(nil, nil, false, true, true),
  512. var oldWriteExt, oldRawToString bool
  513. switch v := h.(type) {
  514. case *MsgpackHandle:
  515. oldWriteExt, v.WriteExt = v.WriteExt, true
  516. oldRawToString, v.RawToString = v.RawToString, true
  517. }
  518. doTestCodecTableOne(t, false, h, table, tableVerify)
  519. //if true { panic("") }
  520. switch v := h.(type) {
  521. case *MsgpackHandle:
  522. v.WriteExt, v.RawToString = oldWriteExt, oldRawToString
  523. }
  524. // func TestMsgpackAll(t *testing.T) {
  525. idxTime, numPrim, numMap := 19, 23, 4
  526. //skip []interface{} containing time.Time
  527. doTestCodecTableOne(t, false, h, table[:numPrim], tableVerify[:numPrim])
  528. doTestCodecTableOne(t, false, h, table[numPrim+1:], tableVerify[numPrim+1:])
  529. // func TestMsgpackNilStringMap(t *testing.T) {
  530. var oldMapType reflect.Type
  531. switch v := h.(type) {
  532. case *MsgpackHandle:
  533. oldMapType, v.MapType = v.MapType, mapStrIntfTyp
  534. case *BincHandle:
  535. oldMapType, v.MapType = v.MapType, mapStrIntfTyp
  536. }
  537. //skip time.Time, []interface{} containing time.Time, last map, and newStruc
  538. doTestCodecTableOne(t, true, h, table[:idxTime], tableTestNilVerify[:idxTime])
  539. doTestCodecTableOne(t, true, h, table[numPrim+1:numPrim+numMap], tableTestNilVerify[numPrim+1:numPrim+numMap])
  540. switch v := h.(type) {
  541. case *MsgpackHandle:
  542. v.MapType = oldMapType
  543. case *BincHandle:
  544. v.MapType = oldMapType
  545. }
  546. // func TestMsgpackNilIntf(t *testing.T) {
  547. //do newTestStruc and last element of map
  548. doTestCodecTableOne(t, true, h, table[numPrim+numMap:], tableTestNilVerify[numPrim+numMap:])
  549. //TODO? What is this one?
  550. //doTestCodecTableOne(t, true, h, table[17:18], tableTestNilVerify[17:18])
  551. }
  552. func testCodecMiscOne(t *testing.T, h Handle) {
  553. b, err := testMarshal(32, h)
  554. // Cannot do this nil one, because faster type assertion decoding will panic
  555. // var i *int32
  556. // if err = testUnmarshal(b, i, nil); err == nil {
  557. // logT(t, "------- Expecting error because we cannot unmarshal to int32 nil ptr")
  558. // t.FailNow()
  559. // }
  560. var i2 int32 = 0
  561. if err = testUnmarshal(&i2, b, h); err != nil {
  562. logT(t, "------- Cannot unmarshal to int32 ptr. Error: %v", err)
  563. t.FailNow()
  564. }
  565. if i2 != int32(32) {
  566. logT(t, "------- didn't unmarshal to 32: Received: %d", i2)
  567. t.FailNow()
  568. }
  569. // func TestMsgpackDecodePtr(t *testing.T) {
  570. ts := newTestStruc(0, false)
  571. b, err = testMarshal(ts, h)
  572. if err != nil {
  573. logT(t, "------- Cannot Marshal pointer to struct. Error: %v", err)
  574. t.FailNow()
  575. } else if len(b) < 40 {
  576. logT(t, "------- Size must be > 40. Size: %d", len(b))
  577. t.FailNow()
  578. }
  579. logT(t, "------- b: %v", b)
  580. ts2 := new(TestStruc)
  581. err = testUnmarshal(ts2, b, h)
  582. if err != nil {
  583. logT(t, "------- Cannot Unmarshal pointer to struct. Error: %v", err)
  584. t.FailNow()
  585. } else if ts2.I64 != math.MaxInt64*2/3 {
  586. logT(t, "------- Unmarshal wrong. Expect I64 = 64. Got: %v", ts2.I64)
  587. t.FailNow()
  588. }
  589. // func TestMsgpackIntfDecode(t *testing.T) {
  590. m := map[string]int{"A": 2, "B": 3}
  591. p := []interface{}{m}
  592. bs, err := testMarshal(p, h)
  593. if err != nil {
  594. logT(t, "Error marshalling p: %v, Err: %v", p, err)
  595. t.FailNow()
  596. }
  597. m2 := map[string]int{}
  598. p2 := []interface{}{m2}
  599. err = testUnmarshal(&p2, bs, h)
  600. if err != nil {
  601. logT(t, "Error unmarshalling into &p2: %v, Err: %v", p2, err)
  602. t.FailNow()
  603. }
  604. if m2["A"] != 2 || m2["B"] != 3 {
  605. logT(t, "m2 not as expected: expecting: %v, got: %v", m, m2)
  606. t.FailNow()
  607. }
  608. // log("m: %v, m2: %v, p: %v, p2: %v", m, m2, p, p2)
  609. if err = deepEqual(p, p2); err == nil {
  610. logT(t, "p and p2 match")
  611. } else {
  612. logT(t, "Not Equal: %v. p: %v, p2: %v", err, p, p2)
  613. t.FailNow()
  614. }
  615. if err = deepEqual(m, m2); err == nil {
  616. logT(t, "m and m2 match")
  617. } else {
  618. logT(t, "Not Equal: %v. m: %v, m2: %v", err, m, m2)
  619. t.FailNow()
  620. }
  621. // func TestMsgpackDecodeStructSubset(t *testing.T) {
  622. // test that we can decode a subset of the stream
  623. mm := map[string]interface{}{"A": 5, "B": 99, "C": 333}
  624. bs, err = testMarshal(mm, h)
  625. if err != nil {
  626. logT(t, "Error marshalling m: %v, Err: %v", mm, err)
  627. t.FailNow()
  628. }
  629. type ttt struct {
  630. A uint8
  631. C int32
  632. }
  633. var t2 ttt
  634. err = testUnmarshal(&t2, bs, h)
  635. if err != nil {
  636. logT(t, "Error unmarshalling into &t2: %v, Err: %v", t2, err)
  637. t.FailNow()
  638. }
  639. t3 := ttt{5, 333}
  640. if err = deepEqual(t2, t3); err != nil {
  641. logT(t, "Not Equal: %v. t2: %v, t3: %v", err, t2, t3)
  642. t.FailNow()
  643. }
  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 = testMarshal(tarr1, h)
  656. if err != nil {
  657. logT(t, "Error marshalling tarr: %v, Err: %v", tarr1, err)
  658. t.FailNow()
  659. }
  660. var tarr2 tarr
  661. err = testUnmarshal(&tarr2, bs, h)
  662. if err != nil {
  663. logT(t, "Error unmarshalling into &tarr2: %v, Err: %v", tarr2, err)
  664. t.FailNow()
  665. }
  666. if err = deepEqual(tarr0, tarr2); err != nil {
  667. logT(t, "Not Equal: %v. tarr1: %v, tarr2: %v", err, tarr0, tarr2)
  668. t.FailNow()
  669. }
  670. // fmt.Printf(">>>> err: %v. tarr1: %v, tarr2: %v\n", err, tarr0, tarr2)
  671. }
  672. // test byte array, even if empty (msgpack only)
  673. if h == testMsgpackH {
  674. type ystruct struct {
  675. Anarray []byte
  676. }
  677. var ya = ystruct{}
  678. err = testUnmarshal(&ya, []byte{0x91, 0x90}, h)
  679. if err != nil {
  680. logT(t, "Error unmarshalling into ystruct: %v, Err: %v", ya, err)
  681. t.FailNow()
  682. }
  683. }
  684. }
  685. func testCodecEmbeddedPointer(t *testing.T, h Handle) {
  686. type Z int
  687. type A struct {
  688. AnInt int
  689. }
  690. type B struct {
  691. *Z
  692. *A
  693. MoreInt int
  694. }
  695. var z Z = 4
  696. x1 := &B{&z, &A{5}, 6}
  697. bs, err := testMarshal(x1, h)
  698. if err != nil {
  699. logT(t, "Error encoding %v, Err: %v", x1, err)
  700. t.FailNow()
  701. }
  702. // fmt.Printf("buf: len(%v): %x\n", buf.Len(), buf.Bytes())
  703. var x2 = new(B)
  704. err = testUnmarshal(x2, bs, h)
  705. if err != nil {
  706. logT(t, "Error decoding into %v, Err: %v", x2, err)
  707. t.FailNow()
  708. }
  709. if !reflect.DeepEqual(x1, x2) {
  710. logT(t, "Error: NOT MATCH: x1: %v, x2: %v", x1, x2)
  711. t.FailNow()
  712. }
  713. }
  714. func doTestRpcOne(t *testing.T, rr Rpc, h Handle, doRequest bool, exitSleepMs time.Duration,
  715. ) (port int) {
  716. // rpc needs EOF, which is sent via a panic, and so must be recovered.
  717. if !recoverPanicToErr {
  718. logT(t, "EXPECTED. set recoverPanicToErr=true, since rpc needs EOF")
  719. t.FailNow()
  720. }
  721. srv := rpc.NewServer()
  722. srv.Register(testRpcInt)
  723. ln, err := net.Listen("tcp", "127.0.0.1:0")
  724. // log("listener: %v", ln.Addr())
  725. checkErrT(t, err)
  726. port = (ln.Addr().(*net.TCPAddr)).Port
  727. // var opts *DecoderOptions
  728. // opts := testDecOpts
  729. // opts.MapType = mapStrIntfTyp
  730. // opts.RawToString = false
  731. serverExitChan := make(chan bool, 1)
  732. var serverExitFlag uint64 = 0
  733. serverFn := func() {
  734. for {
  735. conn1, err1 := ln.Accept()
  736. if err1 != nil {
  737. //fmt.Printf("accept err1: %v\n", err1)
  738. continue
  739. }
  740. if atomic.LoadUint64(&serverExitFlag) == 1 {
  741. serverExitChan <- true
  742. conn1.Close()
  743. return // exit serverFn goroutine
  744. }
  745. var sc rpc.ServerCodec = rr.ServerCodec(conn1, h)
  746. srv.ServeCodec(sc)
  747. }
  748. }
  749. clientFn := func(cc rpc.ClientCodec) {
  750. cl := rpc.NewClientWithCodec(cc)
  751. defer cl.Close()
  752. var up, sq, mult int
  753. var rstr string
  754. // log("Calling client")
  755. checkErrT(t, cl.Call("TestRpcInt.Update", 5, &up))
  756. // log("Called TestRpcInt.Update")
  757. checkEqualT(t, testRpcInt.i, 5)
  758. checkEqualT(t, up, 5)
  759. checkErrT(t, cl.Call("TestRpcInt.Square", 1, &sq))
  760. checkEqualT(t, sq, 25)
  761. checkErrT(t, cl.Call("TestRpcInt.Mult", 20, &mult))
  762. checkEqualT(t, mult, 100)
  763. checkErrT(t, cl.Call("TestRpcInt.EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr))
  764. checkEqualT(t, rstr, fmt.Sprintf("%#v", TestABC{"Aa", "Bb", "Cc"}))
  765. checkErrT(t, cl.Call("TestRpcInt.Echo123", []string{"A1", "B2", "C3"}, &rstr))
  766. checkEqualT(t, rstr, fmt.Sprintf("%#v", []string{"A1", "B2", "C3"}))
  767. }
  768. connFn := func() (bs net.Conn) {
  769. // log("calling f1")
  770. bs, err2 := net.Dial(ln.Addr().Network(), ln.Addr().String())
  771. //fmt.Printf("f1. bs: %v, err2: %v\n", bs, err2)
  772. checkErrT(t, err2)
  773. return
  774. }
  775. exitFn := func() {
  776. atomic.StoreUint64(&serverExitFlag, 1)
  777. bs := connFn()
  778. <-serverExitChan
  779. bs.Close()
  780. // serverExitChan <- true
  781. }
  782. go serverFn()
  783. runtime.Gosched()
  784. //time.Sleep(100 * time.Millisecond)
  785. if exitSleepMs == 0 {
  786. defer ln.Close()
  787. defer exitFn()
  788. }
  789. if doRequest {
  790. bs := connFn()
  791. cc := rr.ClientCodec(bs, h)
  792. clientFn(cc)
  793. }
  794. if exitSleepMs != 0 {
  795. go func() {
  796. defer ln.Close()
  797. time.Sleep(exitSleepMs)
  798. exitFn()
  799. }()
  800. }
  801. return
  802. }
  803. // Comprehensive testing that generates data encoded from python msgpack,
  804. // and validates that our code can read and write it out accordingly.
  805. // We keep this unexported here, and put actual test in ext_dep_test.go.
  806. // This way, it can be excluded by excluding file completely.
  807. func doTestMsgpackPythonGenStreams(t *testing.T) {
  808. logT(t, "TestPythonGenStreams")
  809. tmpdir, err := ioutil.TempDir("", "golang-msgpack-test")
  810. if err != nil {
  811. logT(t, "-------- Unable to create temp directory\n")
  812. t.FailNow()
  813. }
  814. defer os.RemoveAll(tmpdir)
  815. logT(t, "tmpdir: %v", tmpdir)
  816. cmd := exec.Command("python", "msgpack_test.py", "testdata", tmpdir)
  817. //cmd.Stdin = strings.NewReader("some input")
  818. //cmd.Stdout = &out
  819. var cmdout []byte
  820. if cmdout, err = cmd.CombinedOutput(); err != nil {
  821. logT(t, "-------- Error running msgpack_test.py testdata. Err: %v", err)
  822. logT(t, " %v", string(cmdout))
  823. t.FailNow()
  824. }
  825. oldMapType := testMsgpackH.MapType
  826. for i, v := range tablePythonVerify {
  827. testMsgpackH.MapType = oldMapType
  828. //load up the golden file based on number
  829. //decode it
  830. //compare to in-mem object
  831. //encode it again
  832. //compare to output stream
  833. logT(t, "..............................................")
  834. logT(t, " Testing: #%d: %T, %#v\n", i, v, v)
  835. var bss []byte
  836. bss, err = ioutil.ReadFile(filepath.Join(tmpdir, strconv.Itoa(i)+".golden"))
  837. if err != nil {
  838. logT(t, "-------- Error reading golden file: %d. Err: %v", i, err)
  839. failT(t)
  840. continue
  841. }
  842. testMsgpackH.MapType = mapStrIntfTyp
  843. var v1 interface{}
  844. if err = testUnmarshal(&v1, bss, testMsgpackH); err != nil {
  845. logT(t, "-------- Error decoding stream: %d: Err: %v", i, err)
  846. failT(t)
  847. continue
  848. }
  849. if v == skipVerifyVal {
  850. continue
  851. }
  852. //no need to indirect, because we pass a nil ptr, so we already have the value
  853. //if v1 != nil { v1 = reflect.Indirect(reflect.ValueOf(v1)).Interface() }
  854. if err = deepEqual(v, v1); err == nil {
  855. logT(t, "++++++++ Objects match")
  856. } else {
  857. logT(t, "-------- Objects do not match: %v. Source: %T. Decoded: %T", err, v, v1)
  858. logT(t, "-------- AGAINST: %#v", v)
  859. logT(t, "-------- DECODED: %#v <====> %#v", v1, reflect.Indirect(reflect.ValueOf(v1)).Interface())
  860. failT(t)
  861. }
  862. bsb, err := testMarshal(v1, testMsgpackH)
  863. if err != nil {
  864. logT(t, "Error encoding to stream: %d: Err: %v", i, err)
  865. failT(t)
  866. continue
  867. }
  868. if err = deepEqual(bsb, bss); err == nil {
  869. logT(t, "++++++++ Bytes match")
  870. } else {
  871. logT(t, "???????? Bytes do not match. %v.", err)
  872. xs := "--------"
  873. if reflect.ValueOf(v).Kind() == reflect.Map {
  874. xs = " "
  875. logT(t, "%s It's a map. Ok that they don't match (dependent on ordering).", xs)
  876. } else {
  877. logT(t, "%s It's not a map. They should match.", xs)
  878. failT(t)
  879. }
  880. logT(t, "%s FROM_FILE: %4d] %v", xs, len(bss), bss)
  881. logT(t, "%s ENCODED: %4d] %v", xs, len(bsb), bsb)
  882. }
  883. }
  884. testMsgpackH.MapType = oldMapType
  885. }
  886. // To test MsgpackSpecRpc, we test 3 scenarios:
  887. // - Go Client to Go RPC Service (contained within TestMsgpackRpcSpec)
  888. // - Go client to Python RPC Service (contained within doTestMsgpackRpcSpecGoClientToPythonSvc)
  889. // - Python Client to Go RPC Service (contained within doTestMsgpackRpcSpecPythonClientToGoSvc)
  890. //
  891. // This allows us test the different calling conventions
  892. // - Go Service requires only one argument
  893. // - Python Service allows multiple arguments
  894. func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
  895. openPort := "6789"
  896. cmd := exec.Command("python", "msgpack_test.py", "rpc-server", openPort, "2")
  897. checkErrT(t, cmd.Start())
  898. time.Sleep(100 * time.Millisecond) // time for python rpc server to start
  899. bs, err2 := net.Dial("tcp", ":"+openPort)
  900. checkErrT(t, err2)
  901. cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH)
  902. cl := rpc.NewClientWithCodec(cc)
  903. defer cl.Close()
  904. var rstr string
  905. checkErrT(t, cl.Call("EchoStruct", TestABC{"Aa", "Bb", "Cc"}, &rstr))
  906. //checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
  907. var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
  908. checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
  909. checkEqualT(t, rstr, "1:A1 2:B2 3:C3")
  910. }
  911. func doTestMsgpackRpcSpecPythonClientToGoSvc(t *testing.T) {
  912. port := doTestRpcOne(t, MsgpackSpecRpc, testMsgpackH, false, 1*time.Second)
  913. //time.Sleep(1000 * time.Millisecond)
  914. cmd := exec.Command("python", "msgpack_test.py", "rpc-client-go-service", strconv.Itoa(port))
  915. var cmdout []byte
  916. var err error
  917. if cmdout, err = cmd.CombinedOutput(); err != nil {
  918. logT(t, "-------- Error running msgpack_test.py rpc-client-go-service. Err: %v", err)
  919. logT(t, " %v", string(cmdout))
  920. t.FailNow()
  921. }
  922. checkEqualT(t, string(cmdout),
  923. fmt.Sprintf("%#v\n%#v\n", []string{"A1", "B2", "C3"}, TestABC{"Aa", "Bb", "Cc"}))
  924. }
  925. func TestMsgpackCodecsTable(t *testing.T) {
  926. testCodecTableOne(t, testMsgpackH)
  927. }
  928. func TestMsgpackCodecsMisc(t *testing.T) {
  929. testCodecMiscOne(t, testMsgpackH)
  930. }
  931. func TestMsgpackCodecsEmbeddedPointer(t *testing.T) {
  932. testCodecEmbeddedPointer(t, testMsgpackH)
  933. }
  934. func TestBincCodecsTable(t *testing.T) {
  935. testCodecTableOne(t, testBincH)
  936. }
  937. func TestBincCodecsMisc(t *testing.T) {
  938. testCodecMiscOne(t, testBincH)
  939. }
  940. func TestBincCodecsEmbeddedPointer(t *testing.T) {
  941. testCodecEmbeddedPointer(t, testBincH)
  942. }
  943. func TestMsgpackRpcGo(t *testing.T) {
  944. doTestRpcOne(t, GoRpc, testMsgpackH, true, 0)
  945. }
  946. func TestMsgpackRpcSpec(t *testing.T) {
  947. doTestRpcOne(t, MsgpackSpecRpc, testMsgpackH, true, 0)
  948. }
  949. func TestBincRpcGo(t *testing.T) {
  950. doTestRpcOne(t, GoRpc, testBincH, true, 0)
  951. }
  952. // TODO:
  953. // Add Tests for:
  954. // - decoding empty list/map in stream into a nil slice/map
  955. // - binary(M|Unm)arsher support for time.Time