codecs_test.go 22 KB

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