codec_test.go 38 KB

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