codecs_test.go 30 KB

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