codec_test.go 32 KB

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