codecs_test.go 30 KB

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