codecs_test.go 27 KB

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