codec_test.go 41 KB

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