codecs_test.go 27 KB

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