codecs_test.go 25 KB

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