codec_test.go 30 KB

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