codecs_test.go 26 KB

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