codecs_test.go 27 KB

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