codecs_test.go 29 KB

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