codec_test.go 37 KB

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